diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index a7ae54968..8c91180d5 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -17,7 +17,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | Part | Responsibility | Source | | --- | --- | --- | -| Provider | `Provider` holds the endpoint bases for each `Protocol` (Chat, Responses, Anthropic, Gemini), the keys, `Fallback`, `Routing`, `Sink`, `UseFirst` (Smart puts it ahead of the other providers it weighs it with, [gateway routing](gateway-routing.md)), `NoStandIn` (never a fallback for another model, [gateway routing](gateway-routing.md)), `Affinity`, concurrency and queue limits, `Headers`, `Proxy`, models, and balance settings. `BaseAPI` is the API a custom provider's editor shows its Base URL as: the one the user picked and saved, while it has a URL, so a provider with a chat URL beside its Responses one isn't shown as OpenAI compatible after Responses was picked. Requests go by which URLs are set; `Native`, the API agents' model files ask a model on, takes `BaseAPI` where it serves the model, after the OpenAI-model and Claude-on-Messages rules (nb5p on Discord: dsh asked a Responses relay's GPTs on Chat). A custom provider's `Gemini` URL is the base of Google's Gemini API, or of one that answers as it does (#1346): `GeminiBase` keeps it as the base, as typed (a pasted endpoint or model list cut back; only Google's own bare host is given /v1beta, JNDliuliuM on X), and `Base(Gemini)` asks it at `GeminiAsked`'s base: a bare host at its /v1beta, as Google's SDKs ask one, any base with a path as typed (equinox0253 on X, `TestGeminiAsked`, `TestGeminiBareHostAskedAtV1beta`). Requests, a model's test and the model list go there: requests to `models/{model}:streamGenerateContent?alt=sse` under it (`GeminiPath`) signed with `x-goog-api-key` (`AuthHeaders`), and its models are listed by `catalog.FetchGemini` (paged, only those serving generateContent). Factory's sign-in alone keeps its own `/generate` route and token (`FactoryGemini`). `Account` is set only for a subscription and is never saved (`json:"-"`). | [`provider.go`](../../internal/provider/provider.go) | +| Provider | `Provider` holds the endpoint bases for each `Protocol` (Chat, Responses, Anthropic, Gemini), the keys, `Fallback`, `Routing`, `Sink`, `UseFirst` (Smart puts it ahead of the other providers it weighs it with, [gateway routing](gateway-routing.md)), `NoStandIn` (never a fallback for another model, [gateway routing](gateway-routing.md)), `Affinity`, concurrency and queue limits, `Headers`, `Proxy`, models, and balance settings. `BaseAPI` is the API a custom provider's editor shows its Base URL as: the one the user picked and saved, while it has a URL, so a provider with a chat URL beside its Responses one isn't shown as OpenAI compatible after Responses was picked. Requests go by which URLs are set; `Native`, the API agents' model files ask a model on, takes `BaseAPI` where it serves the model, after the OpenAI-model and Claude-on-Messages rules (nb5p on Discord: dsh asked a Responses relay's GPTs on Chat). A custom provider's `Gemini` URL is the base of Google's Gemini API, or of one that answers as it does (#1346): `GeminiBase` keeps it as the base, as typed (a pasted endpoint or model list cut back; only Google's own bare host is given /v1beta, JNDliuliuM on X), and `Base(Gemini)` asks it at `GeminiAsked`'s base: a bare host at its /v1beta, as Google's SDKs ask one, any base with a path as typed (equinox0253 on X, `TestGeminiAsked`, `TestGeminiBareHostAskedAtV1beta`). Requests, a model's test and the model list go there: requests to `models/{model}:streamGenerateContent?alt=sse` under it (`GeminiPath`), a namespaced id's slashes kept and each segment escaped (`GeminiModelPath`, which Vertex AI's, a plugin's Code Assist and Gemini image generation (`draw.go`) share; an id with an empty, `.` or `..` segment goes as one escaped segment, #6695) signed with `x-goog-api-key` (`AuthHeaders`), and its models are listed by `catalog.FetchGemini` (paged, only those serving generateContent). Factory's sign-in alone keeps its own `/generate` route and token (`FactoryGemini`). `Account` is set only for a subscription and is never saved (`json:"-"`). | [`provider.go`](../../internal/provider/provider.go) | | Rate windows | A provider bills the hours it says at its own rate (#2463): `RateWindows`, each a span `HH:MM`–`HH:MM` on this computer's clock whose end may pass its start over midnight, the days it is on (`Days`, `time.Weekday`'s numbers, none for every day), and a rate from just over 0 to 1000 at three decimals. The first window that holds a call's time multiplies the price again, on top of `PriceRate` — a price the user set for a model included, which the price rate alone leaves as set — and outside every window the price rate alone counts. A call is priced at its own time wherever a cost is counted call by call — the Usage page and its CSV, a gateway key's cost limit, the gateway's sessions in Usage — by `EffectivePriceAt`, which `EffectivePriceIn` is at `time.Now()`, and its record's time is read on this computer's clock whatever zone it was written in (a call reported as `…Z`); the Sessions page sums a session's calls by model, not by time, so it prices them without any window (`BasePriceIn` in `sessions.priceOf`), the same at every hour it is read; the ledger's `Pricer` holds each provider's base price and windows once and reads each record's rate at the record's own time, so a window that opens mid-page prices only the calls inside it; a gateway block's rows (`blockPricer`, the Requests tab) take their price from a memo asked with no time, which `RateAt` reads as no window, and each row is put at its own window's rate there (`atWindow` before `Price.In`). A list price billed double at peak (`Peak`, DeepSeek's, Ollama Cloud's two DeepSeek models' and the relays `PeakOf` names) is part of the base: the final price is that base, peak included, times the window's rate, so a provider with a `Peak` needs no window for the same hours: the order is the spec (the author, YangHonghang), so a 0.8 window on a shared DeepSeek key takes 0.8 off the peak price at peak, and a window set over the official peak hours would double them twice, which the editor's hint says under the windows. `/v1/models` prices its list at now (`EntryPricer`); the model list magpie writes into an agent's own config (`AgentPricer`, Pi's and omp's cost) leaves every window out, since nothing rewrites that file as a window opens or closes. `CheckRateWindows` says what is wrong with a set; the editor keeps the windows under Advanced, drawn by `ratewindows.js`, which app.js imports when an editor draws the field (`rateWindowsField`) so it adds nothing to the core's scripts — until it has loaded, a save leaves `rateWindows` out, which keeps them. A provider with windows shows what it bills at now on its row (`rateNow` in `/api/providers`, `rateNowOf` in the GUI's `providers.go`: `RateAt` on the server's clock, which calls are counted on, never the browser's); one with a price rate alone shows nothing new. Windows are kept with the provider: a save that leaves them out keeps them, null or an empty list clears them, and a signed-in account's survive its `Save` — the account branch and `withPicks` both go through one list, `accountSettings`, beside its `PriceRate`, or the editor's Save would quietly drop what it shows (#4738: two lists drifted, and `additionalTools`, extraBody, reply headers, its rests, `limitRestOff` and patience were each lost one way; `TestAccountSettingsKept`). | [`ratewindow.go`](../../internal/provider/ratewindow.go), [`models.go`](../../internal/provider/models.go), [`ledger.go`](../../internal/usage/ledger.go) (`Pricer`), [`app.js`](../../internal/gui/assets/app.js) (`rateWindowsField`), [`ratewindows.js`](../../internal/gui/assets/ratewindows.js), [`gui/providers.go`](../../internal/gui/providers.go) (`rateNowOf`) | | Key price rates | A provider of API keys can bill each key at a price rate of its own (`KeyPriceRates`, by the key's fingerprint in lower case, above 0 up to 1000 at three decimals; @tnt12231 on X: a relay sells keys in groups at 0.5× and 1.2× under one endpoint). A key without one bills at the provider's `PriceRate` (`KeyPriceRate`). The ledger's `Pricer` memoizes by the record's `ProviderKeyID` too and prices through `BaseKeyPriceIn`, so the Usage page, its CSV, a key's spend cap and a typed balance (`usage.KeySpent`) count each key's calls at its rate; `PriceAt` prices a routing candidate at the rate of the key it holds (By price). A call with no key recorded, the Sessions page and the budget's estimate before a key is picked use the provider's rate. A price the user set for a model stands as set, as under the provider's rate, and rate windows multiply on top. `SetKeyPriceRate` refuses a subscription, a rate of 0 or out of range and a key the provider hasn't; nil takes it off. `ReplaceKey` carries it to the new value. Set under the editor's Advanced, a line per key under Price rate once there are two keys or more (folded past eight as the per-key proxies are; an empty line shows the provider's rate as its placeholder), saved as `keyPriceRates` on `provider/save` (`{}` takes them off, left out keeps them), or `magpie provider key-rate [key [rate|default]]`, which also lists each key's rate. | [`key_rate.go`](../../internal/provider/key_rate.go), `TestKeyPriceRateSet`, `TestKeyPriceRatePrices`, `TestPricerKeyPriceRates`, `TestKeyRateCmd`, `TestProviderSaveKeyPriceRates`, [`key-price-rate.test.cjs`](../../internal/gui/tests/key-price-rate.test.cjs) | | Billing | Whether a provider is on a plan or paid as used, marked by a grey badge on its Providers row and summed up as a tag on a routing group's card (EV_John_Liu on X). `BillingKind` ([`billing.go`](../../internal/provider/billing.go)) is the user's word (`Billing`: the editor's *Billing* under Advanced, Auto/Plan/Pay as you go; `magpie provider set billing=plan\|payg\|auto`), else a signed-in account (a plan), a plan's own preset (`planPresets`: Kimi Code, the Token Plans, OpenCode Go, ClinePass), else the name of the preset region it sits at (`regionOf`: "Pay as you go…" or "…Plan…"; one named by place, or a preset with no regions, is the vendor's API, pay as you go), and `mixed` when a key of it is on a plan of the other kind (`KeyAccount.Plan`). It is "", and nothing is shown, for a provider added by its address, a local server, another magpie, a decision model, or a preset whose one endpoint takes both (`unsaidPresets`: MiniMax, ModelScope and the like). `/api/providers` gives `billing` and `billingKind`, a group's `memberInfo[].billing`; the card's tag is shown only when every member's is known. It marks only: routing and prices don't read it. `TestBillingKind`, `TestBillingEveryRegion`, `TestProviderBilling`, `TestProviderSetBilling`, `provider-billing.test.cjs`. | [`billing.go`](../../internal/provider/billing.go), [`providers.go`](../../internal/gui/providers.go) | diff --git a/internal/gateway/draw.go b/internal/gateway/draw.go index a5f9131d1..713234901 100644 --- a/internal/gateway/draw.go +++ b/internal/gateway/draw.go @@ -2145,7 +2145,7 @@ func (s *Server) drawGemini(ctx context.Context, p provider.Provider, model stri } body, _ := json.Marshal(map[string]any{"contents": []map[string]any{{"role": "user", "parts": parts}}, "generationConfig": cfg}) base := strings.TrimSuffix(strings.TrimRight(p.Base(provider.Chat), "/"), "/openai") - url := base + "/models/" + model + ":generateContent" + url := base + "/models/" + provider.GeminiModelPath(model) + ":generateContent" return s.eachDrawing(d.N, func() (drawn, int, error) { b, code, err := s.send(ctx, p, url, "application/json", body, false) if err != nil { diff --git a/internal/gateway/gemini_slash_model_test.go b/internal/gateway/gemini_slash_model_test.go new file mode 100644 index 000000000..e5a20cec7 --- /dev/null +++ b/internal/gateway/gemini_slash_model_test.go @@ -0,0 +1,47 @@ +package gateway + +import ( + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// A custom Gemini compatible provider's namespaced model id +// (example/model-demo) is asked at /models/example/model-demo, its slash +// kept, as a relay that routes by path segments takes it: escaped whole +// (example%2Fmodel-demo) such a relay answered 403 Invalid URL (#6695, +// LuoRuiyao on X). The raw RequestURI is checked, since the decoded path +// is the same either way. +func TestGeminiNamespacedModelKeepsItsSlash(t *testing.T) { + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + const want = "/v1beta/models/example/model-demo:streamGenerateContent?alt=sse" + var asked []string + up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + asked = append(asked, r.RequestURI) + if r.RequestURI != want { + http.Error(w, `{"error":{"code":403,"message":"Invalid URL"}}`, http.StatusForbidden) + return + } + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse( + `data: {"candidates":[{"content":{"role":"model","parts":[{"text":"demo ok"}]},"finishReason":"STOP"}],"usageMetadata":{"promptTokenCount":3,"candidatesTokenCount":2,"totalTokenCount":5}}`, + )) + })) + t.Cleanup(up.Close) + if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Gemini: up.URL + "/v1beta", Models: []string{"example/model-demo"}}); err != nil { + t.Fatal(err) + } + code, body := post(t, "/v1/messages", `{"model":"relay/example/model-demo","max_tokens":64,"stream":true,"messages":[{"role":"user","content":"hi"}]}`) + if code != 200 || !strings.Contains(body, "demo ok") { + t.Fatalf("status %d, asked %v: %s", code, asked, body) + } + if len(asked) != 1 || asked[0] != want { + t.Errorf("asked %v, want %s", asked, want) + } +} diff --git a/internal/provider/gemini_api.go b/internal/provider/gemini_api.go index ac82ccc8e..328ffe36d 100644 --- a/internal/provider/gemini_api.go +++ b/internal/provider/gemini_api.go @@ -76,10 +76,28 @@ func geminiKept(u string) bool { return j > 0 } +// GeminiModelPath is model as every Gemini and Vertex AI path names it +// after models/: each slash-separated segment escaped and the slashes +// kept, so a relay's namespaced id (example/model-demo) is asked at +// /models/example/model-demo, the path the relay routes by, not +// /models/example%2Fmodel-demo (#6695, LuoRuiyao on X). An id with an +// empty, . or .. segment, which a server or proxy could clean into a +// path outside models/, goes as one escaped segment instead. +func GeminiModelPath(model string) string { + segs := strings.Split(model, "/") + for i, s := range segs { + if s == "" || s == "." || s == ".." { + return url.PathEscape(model) + } + segs[i] = url.PathEscape(s) + } + return strings.Join(segs, "/") +} + // GeminiPath is the path under a Gemini base model is asked at: streamed as // server-sent events (alt=sse) when stream, else one JSON reply. func GeminiPath(model string, stream bool) string { - m := url.PathEscape(strings.TrimPrefix(model, "models/")) + m := GeminiModelPath(strings.TrimPrefix(model, "models/")) if stream { return "/models/" + m + ":streamGenerateContent?alt=sse" } diff --git a/internal/provider/gemini_api_test.go b/internal/provider/gemini_api_test.go index adc495763..497073c7c 100644 --- a/internal/provider/gemini_api_test.go +++ b/internal/provider/gemini_api_test.go @@ -5,7 +5,9 @@ import ( "encoding/json" "net/http" "net/http/httptest" + "path" "slices" + "strings" "testing" ) @@ -33,6 +35,54 @@ func TestGeminiBase(t *testing.T) { } } +// A namespaced model id keeps its slashes in every Gemini and Vertex AI +// path, each segment escaped on its own (#6695); Google's own ids are +// unchanged, and an id whose segments a server could clean into another +// path (empty, . or ..) stays one escaped segment under models/. +func TestGeminiModelPathKeepsSlashes(t *testing.T) { + for in, want := range map[string]string{ + "gemini-2.5-pro": "gemini-2.5-pro", + "gemini-3.8-flash-preview": "gemini-3.8-flash-preview", + "claude-sonnet-4-5@20250929": "claude-sonnet-4-5@20250929", + "qwen3:8b": "qwen3:8b", + "example/model-demo": "example/model-demo", + "a/b/c": "a/b/c", + "ex ample/model?x#y": "ex%20ample/model%3Fx%23y", + "ns/100%": "ns/100%25", + "../secret": "..%2Fsecret", + "a/../b": "a%2F..%2Fb", + "a/./b": "a%2F.%2Fb", + "a//b": "a%2F%2Fb", + "/abs": "%2Fabs", + "trail/": "trail%2F", + } { + if got := GeminiModelPath(in); got != want { + t.Errorf("GeminiModelPath(%q) = %q, want %q", in, got, want) + } + } + for got, want := range map[string]string{ + GeminiPath("example/model-demo", true): "/models/example/model-demo:streamGenerateContent?alt=sse", + GeminiPath("models/example/model-demo", false): "/models/example/model-demo:generateContent", + GeminiPath("gemini-2.5-pro", true): "/models/gemini-2.5-pro:streamGenerateContent?alt=sse", + VertexPath("example/model-demo"): "/publishers/google/models/example/model-demo:streamGenerateContent?alt=sse", + VertexWholePath("example/model-demo"): "/publishers/google/models/example/model-demo:generateContent", + VertexWholePath("gemini-2.5-pro"): "/publishers/google/models/gemini-2.5-pro:generateContent", + } { + if got != want { + t.Errorf("path %q, want %q", got, want) + } + } + // whatever the id, the path stays under models/: cleaning it as a + // server or proxy may never leaves the models/ folder + for _, id := range []string{"..", "../..", "a/../../b", "./x", "x/.", "..%2F..", "%2e%2e/x"} { + p := GeminiPath(id, false) + clean := path.Clean(p) + if !strings.HasPrefix(clean, "/models/") || !strings.HasSuffix(clean, ":generateContent") { + t.Errorf("GeminiPath(%q) = %q cleans to %q, outside /models/", id, p, clean) + } + } +} + // A custom provider with a Gemini URL alone speaks Gemini upstream, is // signed with x-goog-api-key, and lists the models its API serves for // generateContent, a page at a time, under a base with a path prefix diff --git a/internal/provider/plugins.go b/internal/provider/plugins.go index 0deafa8e7..d73f2b6b1 100644 --- a/internal/provider/plugins.go +++ b/internal/provider/plugins.go @@ -766,7 +766,7 @@ func pluginFetch(pp plugin.Provider, account string, req *http.Request) (*http.R var url string switch { case codeAssist: - url = base + "/models/" + api + ":streamGenerateContent?alt=sse" + url = base + "/models/" + GeminiModelPath(api) + ":streamGenerateContent?alt=sse" case strings.HasPrefix(rest, "/v1/"): // chat, responses and Anthropic's messages: the AI SDK's base // ends where magpie's /v1 does diff --git a/internal/provider/vertex.go b/internal/provider/vertex.go index 13bec6a05..3d9535a19 100644 --- a/internal/provider/vertex.go +++ b/internal/provider/vertex.go @@ -236,7 +236,7 @@ func (p Provider) VertexExpress() bool { // model goes: streamed, as the gateway asks every one there but a Gemini // client's own asked whole (VertexWholePath). func VertexPath(model string) string { - return "/publishers/google/models/" + url.PathEscape(model) + ":streamGenerateContent?alt=sse" + return "/publishers/google/models/" + GeminiModelPath(model) + ":streamGenerateContent?alt=sse" } // VertexPartner is whether model is one of Vertex AI's partner or open @@ -297,7 +297,7 @@ func VertexClaudeRequest(path string, body []byte) (string, []byte, bool) { if stream { verb = ":streamRawPredict" } - at += url.PathEscape(model) + verb + at += GeminiModelPath(model) + verb delete(m, "model") } out, err := marshalRaw(m) @@ -322,7 +322,7 @@ func marshalRaw(m map[string]json.RawMessage) ([]byte, error) { // VertexWholePath is where a request for model answered as one JSON body // goes. func VertexWholePath(model string) string { - return "/publishers/google/models/" + url.PathEscape(model) + ":generateContent" + return "/publishers/google/models/" + GeminiModelPath(model) + ":generateContent" } // vertexTest is the smallest request for model at a Vertex AI provider: @@ -341,7 +341,7 @@ func vertexTest(q Provider, model string) (string, string) { case vertexGeneration(m) < 3: think = "" } - return q.Base(Gemini) + "/publishers/google/models/" + url.PathEscape(model) + ":generateContent", + return q.Base(Gemini) + "/publishers/google/models/" + GeminiModelPath(model) + ":generateContent", `{"contents":[{"role":"user","parts":[{"text":"hi"}]}],"generationConfig":{` + think + `"maxOutputTokens":16}}` } diff --git a/internal/provider/vertex_test.go b/internal/provider/vertex_test.go index ed145ddd9..abddfa005 100644 --- a/internal/provider/vertex_test.go +++ b/internal/provider/vertex_test.go @@ -343,7 +343,8 @@ func TestVertexAddress(t *testing.T) { if got := VertexPath("gemini-3.1-pro-preview-customtools"); got != "/publishers/google/models/gemini-3.1-pro-preview-customtools:streamGenerateContent?alt=sse" { t.Errorf("a model's path: %s", got) } - if got := VertexPath("tuned/gemini 1?x#y"); got != "/publishers/google/models/tuned%2Fgemini%201%3Fx%23y:streamGenerateContent?alt=sse" { + // each segment escaped, the slash kept, as at a Gemini URL (#6695) + if got := VertexPath("tuned/gemini 1?x#y"); got != "/publishers/google/models/tuned/gemini%201%3Fx%23y:streamGenerateContent?alt=sse" { t.Errorf("a model with a slash, a space, ? and # in it: %s", got) } }