diff --git a/docs/reference.md b/docs/reference.md index ef673ca35..2a89f45c0 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -66,7 +66,10 @@ line; agents connected to magpie lose it when it quits. doesn't list is named as the other providers serving it name it, so glm-5-turbo reads GLM-5-Turbo under Zhipu as under ZCode; an Azure deployment keeps its own name), and refreshes itself in the - background once it goes stale. Choose which models each provider exposes, + background once it goes stale. Where models.dev can't be reached, the + last copy fetched keeps answering, a first run answers from the copy + magpie ships with, and a failed fetch is tried again within minutes, + through the proxy set in Settings. Choose which models each provider exposes, or expose them all — a model released this morning is in the picker on the next refresh. - **Each agent's own model list.** Under an agent's name on the Agents page, diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index fdeb4a1f8..514c1d88d 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -75,6 +75,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | A plugin's own price | A model no catalog prices (models.dev has no vendor's own model: Devin's SWE-2 and SWE-1.7 Lightning, Cursor's auto, Qoder's efficient) is priced at what its plugin lists it at (`ListPrice` → `pluginListPrice`, `plugin.Model.Cost`, read by `pluginPrice`: an input or output above 0, OpenCode's 0 being none), else at $0 when the plugin says the plan serves it free (`pluginFree`, `plugin.Model.Free`: Devin's Free cost tier, Qoder's and WorkBuddy's x0). Both come after every catalog, so a price a catalog gives is kept over the plugin's. Devin's plugin (0.1.18) lists each paid model at the price Devin's GetCliModelConfigs gives it (input, cached input and output per 1M tokens); a moved Devin user's calls on Devin's own models had no cost on Usage before (太陽と向日葵 on Discord, `TestPluginFreeModelCostsNothing`). A plugin that gives no price and doesn't say free leaves the model unpriced. | [`models.go`](../../internal/provider/models.go), [`plugins.go`](../../internal/provider/plugins.go), [`providers.go`](../../internal/plugin/providers.go) | | Codex's free auto-review | OpenAI made Codex's Auto-review free for users signed in through a ChatGPT account (silverzhou on Discord), so a `codex-auto-review` call through the Codex subscription is priced at nothing (`ListPrice` → `codexReviewFree`, `provider.ChatGPTReviewFree`), not at GPT-5.6 Luna's price (`pricedNames`), and the Requests list names no model it is priced as (`PricedNameFor`). Not on a Free plan, where it spends the allowance (cybercaius), read from the plan Codex is signed in to now; a Codex signed out since counts as a paid plan, as the gateway's caps take it (`freeOnChatGPT`). The same model through an API key, the ChatGPT API subscription or a relay, and a review that followed the session to another model, keep their price; a price the user set wins. Every call is priced as it is read, so rows logged before are free too; the price views' cache keys on each account's plan (`usagePriceCacheKey`). Guarded by `TestAutoReviewFreeOnChatGPTSignIn` and `usage.TestAutoReviewFreeOnChatGPT`. | | A lab's models | models.dev keeps two catalogs: `api.json`, each provider's models with that host's prices, and `models.json`, each lab's models with only what is the model's on every host (name, window, reply limit, thinking, inputs, release), no price. `Sync` keeps the second beside the first as `labs.json` (`LabsPath`, `syncLabs`: best effort, through a rename, a failed fetch keeping the last; a catalog with none beside it is `Stale` once a process, so it comes at the next look). A model only a lab lists, no provider (models.dev took the gated Claude Mythos 5.1 out of anthropic's list in #11327 and kept its lab file), is voted into the same tables as a listed one (`loadGen`, `labs`), so `ContextOf`, `OutputOf`, `NameOf`, `Thinks`, `SeesImages` and every entry built on them know it wherever a vendor's or an account's list has it; a thinking one with no levels takes the levels of the newest of its family a provider gives them (`labKinEfforts`: Mythos 5.1 takes Mythos 5's). A model a provider lists keeps what providers say of it. `catalog.Describe` builds a model from these for a list that names an id alone. `TestLabOnlyModelIsKnown`, `TestLabsLeaveListedModels`, `TestSyncKeepsLabs`, `TestAnthropicKeyGatedModelDescribed` (iebb on Discord). | [`labs.go`](../../internal/catalog/labs.go), [`catalog.go`](../../internal/catalog/catalog.go) | +| models.dev unreachable | The catalog (`CachePath`, `models.json`) is written whole through a rename (`writeWhole`), so a reader never sees it half written and a fetch that fails (refused, hanging past `fetchBound`, a page that isn't the catalog) keeps the last good copy. `loadGen` reads magpie's copy, then OpenCode's, then the copy the binary ships with (`bundled/api.json.gz`, `bundledAt`), passing over one it can't parse. `Seed` (the app's backend, `magpie serve`, the plugin host) writes the shipped copy into `CachePath` dated `bundledAt` when there is no catalog file or the one there is older, so the plugin host's `mdev` reads it too and `Stale` still has the real one fetched. The app's backend fetches beside the vendors' lists rather than before them, and `KeepFresh` tries a failed fetch again after `retryFirst` (2 minutes), doubling up to the hour (`nextRetry`). The fetch goes through `http.DefaultClient`, so through the proxy in Settings, `*_PROXY` or the system's (`netproxy.Install`). A test binary has the shipped copy off (`bundledOn`). Refresh it with `go generate ./internal/catalog` and set `bundledAt` (creeksuen on X). `TestFailedSyncKeepsLastGood`, `TestFirstRunOfflineAnswersFromShippedCopy`, `TestUnreadableCacheFallsBackToShippedCopy`, `TestSeed`, `TestSyncWritesThroughRename`, `TestFailedFetchRetriedSoon`. | [`bundled.go`](../../internal/catalog/bundled.go), [`fresh.go`](../../internal/catalog/fresh.go), [`catalog.go`](../../internal/catalog/catalog.go), [`backend.go`](../../internal/gui/backend.go) | | A Claude account's models | magpie never asks Anthropic with a Claude sign-in, so a Claude account's list is models.dev's anthropic list and what Anthropic told the account's Claude Code beyond it. Claude Code keeps that in its `.claude.json` from its own bootstrap: `additionalModelOptionsCache` (models its /model picker offers beyond its own; a `null` value or a `disabled` one is not a model), `modelAccessCache` (`entitled` per API id) and `additionalModelCostsCache` (Anthropic's prices). `claudeModels` reads the file of Claude Code's own sign-in (`claudeProfilePath`) and of each saved account's directory (`claudeAccountDir`), through `filememo`, and adds each model none of them lists, described by `catalog.Describe` and priced as Anthropic told it. `Account.Lists` for a Claude account goes by its own file (`claudeLists`: the saved directory's, or Claude Code's own when its `oauthAccount` is that account, the one Anthropic answered last): a model it isn't entitled to is out, so routing tries the accounts entitled to a gated model first; with no file, every model is taken to be in, as before. `ListPrice` of a provider whose catalogs include anthropic falls back to that price after every catalog (`claudeCodePrice`). The agent's own Claude Code model picker (`claudeOwn`) offers what `ClaudeCodeModels` gives for the account signed in here; a WSL distro's keeps the catalog's. A fetch of the list in the app or `magpie serve` (Fetch models, the accounts' relist) fetches models.dev's catalog first when it is older than `askedAfter` (10 minutes) and wasn't tried in that time (`catalog.Asked`), only in a process that keeps the catalog fresh: the daily sync alone left a model launched since off the list the user had just fetched, while Claude Code's own /model, built from the catalog baked into its binary (`latest_per_family`), had it (hhdaxia on X: Fable 5.2, `TestClaudeFetchAsksModelsDevForANewModel`). Not done: a Claude Code that never started on a saved account has no file, so its gated models show only once it has run there. `TestClaudeAccountListsGatedModels`. | [`claude_code_models.go`](../../internal/provider/claude_code_models.go), [`account.go`](../../internal/provider/account.go), [`codex_models.go`](../../internal/provider/codex_models.go), [`claude.go`](../../internal/agent/claude.go), [`fresh.go`](../../internal/catalog/fresh.go) | | A key's own windows | A sub2api key given a spending limit per 5 hours, day or 7 days answers its `/v1/usage` with `rate_limits` and no `remaining` (`readSub2APIKeyLimits`). With the Balance URL set to it, the key's card shows them as the windows *5 hours*, *1 day*, *7 days*, in USD, beside a balance field the user wrote; *Check balance* and `magpie provider show` give what its fullest window has left (`Balance`). A Balance URL at an account query left without its token (a sub2api panel's `/api/v1/user/profile`, new-api's `/api/user/self`, after the token was removed) asks the same panel's query for the key instead, the saved URL untouched (`keyQueryOf`, `BalanceQuery`), unless the user's Headers carry an Authorization or Cookie of their own. A Balance URL of the user's own is asked with GET, or with POST and no body when the provider's `BalanceMethod` says so (#2368: an endpoint that answers only a POST; the editor's GET/POST beside the URL, `balance.method=` on the command line); any other method is refused before anything is sent (`balanceMethodOf`). `KeyAllowance` gives routing the same windows: never waited for, read in the background at most once a minute, a failed read keeping the last, and seeded from the card's last reading (`quotas.json`) after a restart. A key bought as a plan (Kimi Code, GLM Coding Plan and Z.ai, MiniMax Coding Plan, OpenCode Go, Command Code, Ollama Cloud, Mistral: `planQuotaSourceOf`) gives routing its card's windows the same way (`planKeyWindows`, Zhipu's team quota behind a key with none of its own); the Usage page's read of its card is taken at once (`noteKeyAllowance`), and a key there that turns out pay-as-you-go, with no windows, is asked again only every 30 minutes (`keyNoWindowsAge`). Kimi Code's `/usages` (`readKimiCode`) is read as kimi-cli and kimi-code read it: the week's `usage` and each `limits[]` window as counts, and the shares in `usages` (`limit_5h`, `limit_7d`, and `limit_month_total` as a *Month* window renewing at its `reset_time`, lidazi2016 on Discord); a window told both ways is the share's, and `limit_month_code`, the part of the month code used, is no window. `TestReadKimiCode`, `TestReadKimiCodeMonth`. A Command Code plan's key has its month of credits as a *Credits* window beside the 5-hour and weekly ones, as the signed-in subscription's card has (`cmdKeyWindows`, #2451): billing/credits leaves the plan out, so it is the key's billing/subscriptions plan, asked at most every ten minutes and the last one kept while it can't be read; the same reply's period end is the Credits window's reset, left off once it has passed (#2454); a key whose plan was never read has its two windows alone. On Go, GOAT and Pro the month is counted in Command Code's usage-value credits, not dollars (GOAT's 70 are $100 of a model like DeepSeek V4.1 Flash, $70 of GLM-5.2), so the window says "28.80 / 70.00 credits" with bought credits as "+ $5.00 extra" beside it; Max, Ultra and Teams Pro keep the CLI's dollar pool, and Provider, pay as you go, has no month (`cmdPlans`, as the plugin since 0.1.20, plugins #556). Ollama Cloud's `ollama.com/api/balance` (#1888, `readOllamaPlan`) tells the plan's included allowance as one window in USD, *Month* when its period is a month long, renewing at `period.until`, and Aside while credits bought on top are left; those credits are the key's balance card (`readOllamaCredits`), and a reply that names none has no balance card rather than $0. A Mistral key is told its organization's month at `api.mistral.ai/v1/billing/budget`, as Mistral's Vibe CLI reads it (`mistral_plan.go`, dhanyqaz on Discord). The budget is the organization's, so every key of it gets the same `vibe_budget` and `api_budget`; which one a key spends is its kind, asked once a key of `console.mistral.ai/api/vibe/whoami` (`plan_type`). A Vibe key (`chat`) has `vibe_budget` as one *Month* window, a Studio key made in the console (`api`) has `api_budget` as *API · Month*, so the accounts' strip never adds the two; each is in the currency billing names (none when it names none), Aside while pay-as-you-go is on (the budget's own, else the subscription's `vibe_payg_enabled` for Vibe and `payg_enabled` for Studio), with the plan's name from `billing/subscription` (EDU is Student). A key whoami can't place (a failed read, no `plan_type`, Mistral Code's key) or whose budget is 0 has no card, and Le Chat's own message limits are told nowhere. ModelScope's API-Inference token is told its 魔粒 at the OpenAPI's `modelscope.cn/openapi/v1/magicubes/balance` (`readModelScope`, jiabubu on Discord): `available_balance`, which leaves out what running tasks have frozen, as the balance card; the page's daily list (`/magicubes/transactions`) isn't in the OpenAPI, so what is spent a day is the card's own trend. StepFun's Step Plan is read through a platform sign-in, not the key, and isn't one of them: the sign-in is the provider's own, kept by provider id in `stepfun-auth.json` (two StepFun providers on one site can be two accounts, #2384), one card per signed-in provider; a file from before that, kept by site, is given on read to the StepFun providers on that site (`stepfunBySite`), and copies of one sign-in are renewed together. Nor are Volcengine Ark's Coding Plan and Agent Plan (#1427): their 5-hour, weekly and monthly windows are told only to the account's access key (`AccessKeyID`, `SecretAccessKey`), asked of `open.volcengineapi.com` (`GetCodingPlanUsage`, `GetAFPUsage`) and signed as Volcengine's own SDK signs (`volcSign`), so they are cards on the Usage page (`volcPlanQuotas` in `PlanQuotas`), never routing's windows. Nor is Tencent Cloud's Token Plan 企业版 (#1574): what a team plan has used of its cycle's credits (专业套餐) or tokens (轻享套餐) is told only to the account's SecretId and SecretKey (kept as `AccessKeyID`, `SecretAccessKey`), asked of `tokenhub.tencentcloudapi.com` (`DescribeTokenPlanList`, `DescribeTokenPlan`, version 2026-03-22) and signed TC3-HMAC-SHA256 (`tc3Sign`), one card per team plan (`tencentPlanQuotas`). | [`sub2api_usage.go`](../../internal/provider/sub2api_usage.go), [`key_allowance.go`](../../internal/provider/key_allowance.go), [`volcengine_usage.go`](../../internal/provider/volcengine_usage.go), [`tencent_usage.go`](../../internal/provider/tencent_usage.go) | | A relay's balance found | A provider added by hand, or from a relay's preset, with a key and no Balance URL, at no host magpie knows a query for, is asked where relays tell a key its balance: the base's origin's `/v1/usage` (sub2api, `$remaining`), then `/api/usage/token` (new-api, `$data.total_available / 500000`), with the key's own auth and headers (`probesBalance`, `probeBalance`). A 200 whose field reads is the query; it is kept in memory for the origins and key for 24 hours and then looked for again, so a relay that moved to other software is not read at a query that now means something else. When the look finds nothing, the old query stays while it turns the key away (401/403, so the card says so) or the relay is down. Finding none is kept for 6 hours (5 minutes when the relay couldn't be reached). Nothing is written to the provider: the card reads the found URL, `BalanceQuery` names it, and the editor shows it under the Balance URL (`BalanceFound`, `balanceFound` in /api/providers and the check's reply; `balfound.js`), with Use to copy it into the fields so a wrong amount can be put right. None found means no card (`errNoBalance`) and, from the editor's check, *No balance at /v1/usage or /api/usage/token*. Never asked: a model vendor's or local server's preset host, this computer, OpenCode and the Cline API (`noProbeHosts`), a plan's windows (`planQuotaSourceOf`). A hand-added yylx.io relay showed no balance until its operator had the user import it again (11-05). | [`balance_probe.go`](../../internal/provider/balance_probe.go) | diff --git a/internal/catalog/bundled.go b/internal/catalog/bundled.go new file mode 100644 index 000000000..43492696b --- /dev/null +++ b/internal/catalog/bundled.go @@ -0,0 +1,147 @@ +package catalog + +import ( + "bytes" + "compress/gzip" + _ "embed" + "encoding/json" + "io" + "log" + "os" + "path/filepath" + "sync" + "testing" + "time" +) + +// The catalog magpie ships with (creeksuen on X). Where models.dev can't +// be reached (a network in China, a proxy not set yet), a first run had +// no catalog at all: no prices, context windows, reasoning levels or +// names, and a plugin's provider listed no models. The binary carries a +// copy of models.dev's api.json from when it was built. It answers when +// no catalog file can be read, and Seed writes it where Sync keeps the +// catalog, dated when it was taken, so the plugin host reads it too and +// Stale still has the real one fetched as soon as models.dev answers. +// +// To refresh it: +// +//go:generate sh -c "curl -fsS https://models.dev/api.json | gzip -9n > bundled/api.json.gz" +// +// and set bundledAt to the time it was fetched. + +//go:embed bundled/api.json.gz +var bundledGz []byte + +// bundledAt is when bundled/api.json.gz was fetched from models.dev. +var bundledAt = time.Date(2026, 11, 10, 10, 11, 0, 0, time.UTC) + +// bundledOn is whether the shipped copy answers. A test binary has it off, +// so a test's catalog is the one it wrote, or none; the tests of the copy +// turn it on. +var bundledOn = !testing.Testing() + +var bundled = sync.OnceValue(func() []byte { + r, err := gzip.NewReader(bytes.NewReader(bundledGz)) + if err != nil { + return nil + } + b, err := io.ReadAll(r) + if err != nil { + return nil + } + return b +}) + +// bundledCatalog is the shipped copy, or nil when it is off. +func bundledCatalog() []byte { + if !bundledOn { + return nil + } + return bundled() +} + +// Seed writes the shipped copy where Sync keeps the catalog when no +// catalog file is there, or the one there is older than the copy, dated +// when the copy was taken: Stale says so once it is a day old, and the +// fetch that follows replaces it. A sync in progress is left to finish, +// and a copy that can't be written is still read from the binary (load). +// It is cheap when there is nothing to do, a stat or two. +func Seed() { + b := bundledCatalog() + if b == nil || !seedWanted() { + return + } + select { + case syncCh <- struct{}{}: + default: + return // a sync is writing the catalog now + } + defer func() { <-syncCh }() + if !seedWanted() { + return + } + had := Source() != "" + if err := writeWhole(CachePath(), b, bundledAt); err != nil { + log.Println("catalog: shipped copy:", err) + return + } + if had { + // an older catalog was read before: the copy answers now + Reset() + Touched() + } +} + +// seedWanted: no catalog file, or the one read is older than the copy. +func seedWanted() bool { + src := Source() + if src == "" { + return true + } + st, err := os.Stat(src) + return err == nil && st.ModTime().Before(bundledAt) +} + +// writeWhole writes b to p through a file beside it renamed over p, so a +// reader (load, the plugin host's mdev) never reads it half written, and a +// failed write keeps the file as it was. A non-zero mtime dates it. It +// isn't flushed to disk first (a flush on Windows can take a second): a +// copy a power cut leaves empty is passed over by load for the next. +func writeWhole(p string, b []byte, mtime time.Time) error { + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + return err + } + tmp, err := os.CreateTemp(filepath.Dir(p), "."+filepath.Base(p)+"-*") + if err != nil { + return err + } + fail := func(err error) error { + tmp.Close() + os.Remove(tmp.Name()) + return err + } + if _, err := tmp.Write(b); err != nil { + return fail(err) + } + if err := tmp.Close(); err != nil { + return fail(err) + } + if err := os.Chmod(tmp.Name(), 0o644); err != nil { + return fail(err) + } + if !mtime.IsZero() { + if err := os.Chtimes(tmp.Name(), mtime, mtime); err != nil { + return fail(err) + } + } + if err := os.Rename(tmp.Name(), p); err != nil { + return fail(err) + } + return nil +} + +// parses reports whether b reads as a provider catalog. +func parses(b []byte) bool { + var m map[string]json.RawMessage + return json.Unmarshal(b, &m) == nil && len(m) > 0 +} diff --git a/internal/catalog/bundled/api.json.gz b/internal/catalog/bundled/api.json.gz new file mode 100644 index 000000000..b030d77a2 Binary files /dev/null and b/internal/catalog/bundled/api.json.gz differ diff --git a/internal/catalog/bundled_test.go b/internal/catalog/bundled_test.go new file mode 100644 index 000000000..7fa1680c7 --- /dev/null +++ b/internal/catalog/bundled_test.go @@ -0,0 +1,285 @@ +package catalog + +import ( + "bytes" + "context" + "io" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "runtime" + "testing" + "time" +) + +// models.dev unreachable (creeksuen on X: a network in China). Each fake +// models.dev here fails the way such a network does: the connection is +// cut before an answer, the answer never comes, or a page that isn't the +// catalog comes instead (a captive portal, a cut-off body). +func unreachable(t *testing.T) map[string]string { + t.Helper() + hold := make(chan struct{}) + cut := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + c, _, err := w.(http.Hijacker).Hijack() + if err == nil { + c.Close() + } + })) + hang := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + select { + case <-r.Context().Done(): + case <-hold: + } + })) + portal := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "text/html") + io.WriteString(w, "Sign in to the network") + })) + short := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.WriteString(w, `{"anthropic":{"id":"anthropic","models":{"claude-haiku-4-5":{"id":"claude-ha`) + })) + t.Cleanup(func() { + close(hold) + for _, s := range []*httptest.Server{cut, hang, portal, short} { + s.Close() + } + }) + return map[string]string{"cut": cut.URL, "hang": hang.URL, "portal": portal.URL, "short": short.URL} +} + +func pointAt(t *testing.T, url string) { + t.Helper() + was := modelsDevURL + modelsDevURL = url + t.Cleanup(func() { modelsDevURL = was }) +} + +func freshCache(t *testing.T) { + t.Helper() + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + Reset() + t.Cleanup(Reset) +} + +func shipped(t *testing.T, on bool) { + t.Helper() + was := bundledOn + bundledOn = on + Reset() + t.Cleanup(func() { bundledOn = was; Reset() }) +} + +const lastGood = `{"openai":{"id":"openai","models":{"gpt-6.1-sol":{"id":"gpt-6.1-sol","cost":{"input":2,"output":10}}}}}` + +// A fetch that fails, however it fails, keeps the catalog fetched before, +// byte for byte, and what it answers. +func TestFailedSyncKeepsLastGood(t *testing.T) { + for name, url := range unreachable(t) { + t.Run(name, func(t *testing.T) { + freshCache(t) + pointAt(t, url) + p := CachePath() + if err := writeWhole(p, []byte(lastGood), time.Time{}); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + if err := Sync(ctx); err == nil { + t.Fatal("Sync from an unreachable models.dev succeeded") + } + b, err := os.ReadFile(p) + if err != nil || string(b) != lastGood { + t.Fatalf("cache after a failed Sync = %q, %v; want the last good copy", b, err) + } + Reset() + if pr, ok := PriceOf("openai", "gpt-6.1-sol"); !ok || pr.Output != 10 { + t.Fatalf("price after a failed Sync = %+v, %v", pr, ok) + } + }) + } +} + +// A first run with no network answers from the copy magpie ships with: +// prices, context windows, a provider's models. A test binary has it +// off, so it is turned on here, and off it answers nothing. +func TestFirstRunOfflineAnswersFromShippedCopy(t *testing.T) { + urls := unreachable(t) + freshCache(t) + pointAt(t, urls["hang"]) + shipped(t, false) + if _, ok := PriceOf("anthropic", "claude-haiku-4-5"); ok { + t.Fatal("a test binary read the shipped copy with it off") + } + shipped(t, true) + ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond) + defer cancel() + if err := Sync(ctx); err == nil { + t.Fatal("Sync from a models.dev that hangs succeeded") + } + if Source() != "" { + t.Fatalf("a failed Sync left a catalog file: %s", Source()) + } + pr, ok := PriceOf("anthropic", "claude-haiku-4-5") + if !ok || pr.Input <= 0 { + t.Fatalf("claude-haiku-4-5 unpriced on a first run offline: %+v, %v", pr, ok) + } + if n := ContextOf("claude-haiku-4-5"); n <= 0 { + t.Fatalf("claude-haiku-4-5 has no context window offline: %d", n) + } + if len(Provider("anthropic")) == 0 { + t.Fatal("anthropic lists no models offline") + } +} + +// A cache that can't be parsed (cut short on disk) is passed over for the +// shipped copy, not read as no catalog. +func TestUnreadableCacheFallsBackToShippedCopy(t *testing.T) { + freshCache(t) + shipped(t, true) + if err := writeWhole(CachePath(), []byte(`{"anthropic":{"id":"anthr`), time.Time{}); err != nil { + t.Fatal(err) + } + Reset() + if _, ok := PriceOf("anthropic", "claude-haiku-4-5"); !ok { + t.Fatal("a cache cut short left no catalog") + } +} + +// Seed writes the shipped copy where Sync keeps the catalog, dated when it +// was taken, so the plugin host reads it and Stale has the real one +// fetched; it replaces an older catalog and never a newer one. +func TestSeed(t *testing.T) { + freshCache(t) + shipped(t, true) + at := bundledAt + t.Cleanup(func() { bundledAt = at }) + bundledAt = time.Now().Add(-30 * 24 * time.Hour) + + Seed() + p := CachePath() + st, err := os.Stat(p) + if err != nil { + t.Fatalf("Seed wrote nothing: %v", err) + } + if !st.ModTime().Equal(bundledAt) { + t.Fatalf("seeded copy dated %v, want %v", st.ModTime(), bundledAt) + } + if !Stale() { + t.Fatal("a month-old shipped copy isn't stale: it would never be fetched again") + } + if b, _ := os.ReadFile(p); !bytes.Equal(b, bundled()) { + t.Fatal("seeded copy isn't the shipped one") + } + + // a newer catalog (fetched since) is kept + if err := writeWhole(p, []byte(lastGood), time.Time{}); err != nil { + t.Fatal(err) + } + Seed() + if b, _ := os.ReadFile(p); string(b) != lastGood { + t.Fatal("Seed wrote over a newer catalog") + } + + // an older one is replaced, and what is read with it + old := bundledAt.Add(-time.Hour) + os.Chtimes(p, old, old) + Reset() + if _, ok := PriceOf("openai", "gpt-6.1-sol"); !ok { + t.Fatal("the older catalog wasn't read") + } + Seed() + if b, _ := os.ReadFile(p); !bytes.Equal(b, bundled()) { + t.Fatal("Seed kept a catalog older than the shipped copy") + } + if _, ok := PriceOf("anthropic", "claude-haiku-4-5"); !ok { + t.Fatal("the shipped copy isn't read after Seed replaced an older one") + } + + // off (a test binary), Seed writes nothing + freshCache(t) + shipped(t, false) + Seed() + if _, err := os.Stat(CachePath()); err == nil { + t.Fatal("Seed wrote with the shipped copy off") + } +} + +// Sync writes the catalog whole through a rename: one being read while it +// is written is read as it was, never cut short (the plugin host's mdev +// and another magpie read it while a sync writes it). +func TestSyncWritesThroughRename(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("Windows refuses a rename over a file held open; this holds one open to tell the two writes apart") + } + freshCache(t) + next := `{"openai":{"id":"openai","models":{"gpt-6.2":{"id":"gpt-6.2","cost":{"input":3,"output":12}}}}}` + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/api.json" { + io.WriteString(w, next) + return + } + http.NotFound(w, r) + })) + t.Cleanup(srv.Close) + pointAt(t, srv.URL+"/api.json") + p := CachePath() + if err := writeWhole(p, []byte(lastGood), time.Time{}); err != nil { + t.Fatal(err) + } + f, err := os.Open(p) + if err != nil { + t.Fatal(err) + } + defer f.Close() + if err := Sync(context.Background()); err != nil { + t.Fatal(err) + } + held, _ := io.ReadAll(f) + if string(held) != lastGood { + t.Fatalf("the file a reader held open became %q: Sync wrote it in place", held) + } + if b, _ := os.ReadFile(p); string(b) != next { + t.Fatalf("cache after Sync = %q", b) + } + if es, _ := filepath.Glob(filepath.Join(filepath.Dir(p), ".models.json-*")); len(es) > 0 { + t.Fatalf("temp files left beside the cache: %v", es) + } +} + +// A failed fetch is tried again within minutes, not the hour, doubling up +// to it; fetch says it failed. +func TestFailedFetchRetriedSoon(t *testing.T) { + if d := nextRetry(0); d != retryFirst || d >= freshEvery { + t.Fatalf("first retry after %v", d) + } + d, n := time.Duration(0), 0 + for d < freshEvery { + was := d + d = nextRetry(d) + if d <= was || d > freshEvery { + t.Fatalf("retry after %v follows %v", d, was) + } + n++ + } + if n > 8 { + t.Fatalf("%d retries before the hour", n) + } + if nextRetry(freshEvery) != freshEvery { + t.Fatal("retries grow past the hour") + } + + urls := unreachable(t) + freshCache(t) + pointAt(t, urls["hang"]) + b := fetchBound + fetchBound = 200 * time.Millisecond + t.Cleanup(func() { fetchBound = b; lastFetch.Store(0) }) + start := time.Now() + if err := fetch(); err == nil { + t.Fatal("fetch from a models.dev that hangs said it succeeded") + } + if el := time.Since(start); el > 10*time.Second { + t.Fatalf("fetch waited %v past its bound", el) + } +} diff --git a/internal/catalog/catalog.go b/internal/catalog/catalog.go index 0bdf9601a..f15f674f6 100644 --- a/internal/catalog/catalog.go +++ b/internal/catalog/catalog.go @@ -631,9 +631,16 @@ func loadGen() (map[string]mdProvider, int) { if !loaded { loaded = true func() { - for _, p := range []string{CachePath(), opencodeCache()} { - b, err := os.ReadFile(p) - if err != nil { + // magpie's own copy, OpenCode's, then the one magpie ships + // with (bundled.go): a file that can't be read or parsed is + // passed over for the next, never read as no catalog + for _, read := range []func() ([]byte, error){ + func() ([]byte, error) { return os.ReadFile(CachePath()) }, + func() ([]byte, error) { return os.ReadFile(opencodeCache()) }, + func() ([]byte, error) { return bundledCatalog(), nil }, + } { + b, err := read() + if err != nil || b == nil { continue } var m map[string]mdProvider @@ -856,11 +863,9 @@ func syncLock(ctx context.Context, onlyIfMissing bool) error { if err := json.Unmarshal(b, &probe); err != nil || len(probe) == 0 { return fmt.Errorf("models.dev: unexpected payload") } - p := CachePath() - if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { - return err - } - if err := os.WriteFile(p, b, 0o644); err != nil { + // written whole through a rename: a reader never sees it half + // written, and a failed write keeps the last good copy + if err := writeWhole(CachePath(), b, time.Time{}); err != nil { return err } // the lab catalog beside it is best effort: without it the provider diff --git a/internal/catalog/fresh.go b/internal/catalog/fresh.go index a098d2976..31b901859 100644 --- a/internal/catalog/fresh.go +++ b/internal/catalog/fresh.go @@ -34,16 +34,41 @@ var ( // KeepFresh fetches the catalog whenever it is stale, now and every hour // after, for as long as the process runs (the app's backend, `magpie // serve`). It never returns. +// +// A fetch that fails (models.dev unreachable, or hanging past fetch's +// bound) is tried again sooner than the hour, after retryFirst and then +// twice as long each time up to the hour, so a magpie started before the +// network or its proxy was up has the catalog fetched soon after +// (creeksuen on X). Until then the catalog read before answers, or the +// one magpie ships with (bundled.go). func KeepFresh() { keeping.Store(true) + var retry time.Duration for { + wait := freshEvery if Stale() { - fetch() + if err := fetch(); err != nil { + retry = nextRetry(retry) + wait = min(retry, freshEvery) + } else { + retry = 0 + } } - time.Sleep(freshEvery) + time.Sleep(wait) } } +// retryFirst is how soon a failed fetch is tried again the first time. +var retryFirst = 2 * time.Minute + +// nextRetry is the wait after a failed fetch, given the one before it. +func nextRetry(was time.Duration) time.Duration { + if was <= 0 { + return retryFirst + } + return min(2*was, freshEvery) +} + // Missing says a call's model has no price: the catalog is fetched again, // in the background, when it is older than six hours and wasn't tried in // that time. Only in a process that keeps it fresh (KeepFresh), so a CLI @@ -102,16 +127,22 @@ func KeepFreshForTest(url string) (restore func()) { return func() { modelsDevURL = was; keeping.Store(false); lastFetch.Store(0) } } -// fetch is Sync with a bound, one at a time. -func fetch() { +// fetchBound is how long fetch waits for models.dev. +var fetchBound = 30 * time.Second + +// fetch is Sync with a bound, one at a time. Its error is the Sync's, or +// nil when another fetch was running. +func fetch() error { if !fetching.CompareAndSwap(false, true) { - return + return nil } defer fetching.Store(false) lastFetch.Store(time.Now().UnixNano()) - ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + ctx, cancel := context.WithTimeout(context.Background(), fetchBound) defer cancel() - if err := Sync(ctx); err != nil { + err := Sync(ctx) + if err != nil { log.Println("catalog:", err) } + return err } diff --git a/internal/catalog/labs.go b/internal/catalog/labs.go index 13f3bcc60..b2a4d86df 100644 --- a/internal/catalog/labs.go +++ b/internal/catalog/labs.go @@ -21,6 +21,7 @@ import ( "slices" "strings" "sync/atomic" + "time" ) // LabsPath is where Sync keeps models.dev's lab catalog (models.json), @@ -85,32 +86,7 @@ func syncLabs(ctx context.Context) error { if err := json.Unmarshal(b, &probe); err != nil || len(probe) == 0 { return fmt.Errorf("models.dev labs: unexpected payload") } - p := LabsPath() - if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { - return err - } - tmp, err := os.CreateTemp(filepath.Dir(p), ".labs-*.json") - if err != nil { - return err - } - if _, err := tmp.Write(b); err != nil { - tmp.Close() - os.Remove(tmp.Name()) - return err - } - if err := tmp.Close(); err != nil { - os.Remove(tmp.Name()) - return err - } - if err := os.Chmod(tmp.Name(), 0o644); err != nil { - os.Remove(tmp.Name()) - return err - } - if err := os.Rename(tmp.Name(), p); err != nil { - os.Remove(tmp.Name()) - return err - } - return nil + return writeWhole(LabsPath(), b, time.Time{}) } // labsMissing says the provider catalog is magpie's own but no lab catalog diff --git a/internal/cli/providers_cli.go b/internal/cli/providers_cli.go index 23a764b0f..d690ea771 100644 --- a/internal/cli/providers_cli.go +++ b/internal/cli/providers_cli.go @@ -1546,6 +1546,7 @@ func advertisedURL() string { func serve() error { s := gateway.New() go stats.Run(version, "serve") + catalog.Seed() // the shipped copy, when models.dev can't be reached go catalog.KeepFresh() // new models' prices, in a gateway left running // a signed-in account's list exists only at its vendor: asked for here // as the app and the terminal ask (#1789), or a headless gateway offered diff --git a/internal/gui/backend.go b/internal/gui/backend.go index 9b97c9a00..ad7555df4 100644 --- a/internal/gui/backend.go +++ b/internal/gui/backend.go @@ -59,21 +59,30 @@ func startBackend() (gw *gateway.Server) { // comes from the models.dev catalog plus each vendor's own /models answer. // Keep both halves warm without making the user click anything. go func() { - ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) - if catalog.Stale() { + // the copy magpie ships with, on a first run or over an older + // one: models.dev may not be reachable (creeksuen on X) + catalog.Seed() + if catalog.Source() == "" { + // no catalog file at all (the copy couldn't be written): + // fetched before the lists below are made of it + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) if err := catalog.Sync(ctx); err != nil { log.Println("catalog:", err) } + cancel() } - cancel() + // fetched now when stale, beside the lists below rather than + // before them, so a models.dev that hangs holds nothing up; a + // fetch tells the agents (catalog.Changed). Then again each day + // it stays open, for new models' prices, and soon after a fetch + // that failed. + go catalog.KeepFresh() // A signed-in agent's list exists only at the vendor; fill it in the // first time so the picker never shows a stale snapshot. provider.FetchNew(20 * time.Second) // lists an older magpie wrote into agents' files, without what // it has learnt since (context windows, providers added) agent.SyncCatalog() - // and fetched again each day it stays open, for new models' prices - catalog.KeepFresh() }() return gw } diff --git a/internal/plugin/host.go b/internal/plugin/host.go index 05112a91f..221e0551d 100644 --- a/internal/plugin/host.go +++ b/internal/plugin/host.go @@ -1062,6 +1062,7 @@ func startOn(ctx context.Context, bun string) (*host, bool, error) { if err := os.MkdirAll(settings.Dir(), 0o700); err != nil { return nil, false, err } + catalog.Seed() // the shipped copy, read until models.dev answers if catalog.Source() == "" { // a plugin's provider has the models models.dev lists for it, as in // OpenCode; sync in the background so starting the host never stalls diff --git a/internal/plugin/host.js b/internal/plugin/host.js index c05e96c5f..aeae91c22 100644 --- a/internal/plugin/host.js +++ b/internal/plugin/host.js @@ -2059,7 +2059,8 @@ function mdev() { const st = fs.statSync(modelsDevPath, { throwIfNoEntry: false }) const mtime = st ? st.mtimeMs : 0 if (modelsDev === undefined || (mtime > 0 && mtime !== modelsDevMtime) || (Object.keys(modelsDev).length === 0 && mtime > 0)) { - // a file caught half written (catalog.Sync writes it in place) + // a file caught half written (an older magpie's catalog.Sync wrote + // it in place; it goes through a rename now) // reads as unknown: keep what was read before, rather than list the // providers without models.dev, and read it again next time const md = readJSON(modelsDevPath)