diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index e60fabddf..fd9294e2a 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -8035,7 +8035,14 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to p.Chat = strings.TrimSuffix(p.Chat, "/v1") path = "/beta" + path } - res, err := s.forward(ctx, p, to, path, p.Prepare(body), in) + fctx := ctx + if p.IsPlugin() && req.Effort != "" { + // the effort picked, which a plugin's model with variants is + // told in X-Magpie-Effort: the body says only what Gemini's + // thinkingConfig can, and loses minimal and xhigh + fctx = provider.WithEffort(ctx, req.Effort) + } + res, err := s.forward(fctx, p, to, path, p.Prepare(body), in) if err != nil || res.StatusCode < 400 { if dropped && err == nil { // it was the key: not sent there again diff --git a/internal/gateway/plugin_effort_test.go b/internal/gateway/plugin_effort_test.go new file mode 100644 index 000000000..015644963 --- /dev/null +++ b/internal/gateway/plugin_effort_test.go @@ -0,0 +1,70 @@ +package gateway + +import ( + "io" + "net/http" + "net/http/httptest" + "slices" + "strings" + "sync" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// A plugin's fetch is told the effort a translated request asked +// (EffortHeader): Antigravity's plugin picks a model's level variant by it, +// as the body it gets says only what Gemini's thinkingConfig can and loses +// minimal and xhigh. The header reaches the plugin and never the vendor, +// and a request that asks no effort has none. +func TestPluginToldTheEffort(t *testing.T) { + var mu sync.Mutex + var got []http.Header + pid := besideFake(t, "fakeco", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + io.Copy(io.Discard, r.Body) + mu.Lock() + got = append(got, r.Header.Clone()) + mu.Unlock() + w.Header().Set("Content-Type", "text/event-stream") + for _, e := range []string{ + `{"type":"message_start","message":{"id":"m","type":"message","role":"assistant","model":"fake-claude","content":[],"usage":{"input_tokens":1,"output_tokens":0}}}`, + `{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`, + `{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"hi"}}`, + `{"type":"content_block_stop","index":0}`, + `{"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":1}}`, + `{"type":"message_stop"}`, + } { + io.WriteString(w, "data: "+e+"\n\n") + } + })) + for _, tc := range []struct{ name, field, want string }{ + {"xhigh", `,"reasoning_effort":"xhigh"`, "xhigh"}, + {"low", `,"reasoning_effort":"low"`, "low"}, + {"none asked", "", ""}, + } { + mu.Lock() + got = nil + mu.Unlock() + rec := httptest.NewRecorder() + // Chat Completions to a model on Anthropic Messages: translated + req := httptest.NewRequest("POST", "/v1/chat/completions", strings.NewReader(`{"model":"`+pid+`/fake-claude","stream":false,"messages":[{"role":"user","content":"hi"}]`+tc.field+`}`)) + New().Handler().ServeHTTP(rec, req) + if rec.Code != 200 { + t.Fatalf("%s: %d %s", tc.name, rec.Code, rec.Body) + } + mu.Lock() + sent := slices.Clone(got) + mu.Unlock() + if len(sent) == 0 { + t.Fatalf("%s: the vendor got nothing", tc.name) + } + for _, h := range sent { + if v := h.Values(provider.EffortHeader); len(v) > 0 { + t.Errorf("%s: the vendor got %s: %q", tc.name, provider.EffortHeader, v) + } + if e := h.Get("X-Saw-Effort"); e != tc.want { + t.Errorf("%s: the plugin was told effort %q, want %q", tc.name, e, tc.want) + } + } + } +} diff --git a/internal/plugin/host.js b/internal/plugin/host.js index 652f10786..4902ccfe0 100644 --- a/internal/plugin/host.js +++ b/internal/plugin/host.js @@ -728,10 +728,11 @@ function asked(input, init) { // MAGPIE_ONLY are the headers magpie tells a plugin's fetch where the agent // that asked works (WorkDirHeader and WorkGitHeader in internal/provider), // that a queue needn't be waited out (FallbackHeader), and the session and -// subagent the agent named (SessionToPluginHeader, SubagentToPluginHeader): +// subagent the agent named (SessionToPluginHeader, SubagentToPluginHeader) +// and the effort asked of a model with variants (EffortHeader): // for the plugin to read, never for its vendor, so a plugin that sends on // the headers it was given sends them nowhere. -const MAGPIE_ONLY = ["x-magpie-work-dir", "x-magpie-work-git", "x-magpie-fallback", "x-magpie-session", "x-magpie-subagent"] +const MAGPIE_ONLY = ["x-magpie-work-dir", "x-magpie-work-git", "x-magpie-fallback", "x-magpie-session", "x-magpie-subagent", "x-magpie-effort"] function unsaid(input, init) { if (input instanceof Request && MAGPIE_ONLY.some((k) => input.headers.has(k))) { diff --git a/internal/plugin/providers.go b/internal/plugin/providers.go index 4ea59b1eb..57f80609f 100644 --- a/internal/plugin/providers.go +++ b/internal/plugin/providers.go @@ -1261,6 +1261,11 @@ type UsageWindow struct { Models []string `json:"models"` NotModels []string `json:"notModels"` Aside bool `json:"aside"` + // Pool is the group of models that share one allowance, and Family the + // model family a per-model window belongs to, as Antigravity's quota + // says them (QuotaWindow.Pool, QuotaWindow.Family) + Pool string `json:"pool"` + Family string `json:"family"` // RunsOutAt (RFC 3339) is when the soonest credits left in the window // are lost, and RunsOut how many, when the vendor's credits expire // apart from the window's reset (WorkBuddy's packages) diff --git a/internal/plugin/testdata/fake/index.js b/internal/plugin/testdata/fake/index.js index 25023346c..dd44675f2 100644 --- a/internal/plugin/testdata/fake/index.js +++ b/internal/plugin/testdata/fake/index.js @@ -260,7 +260,7 @@ export const FakePlugin = async ({ client }) => ({ // where magpie said the agent works, as the plugin read it; its own // headers go on too, as a plugin that sends on what it got sends // them, for the host to take off - for (const k of ["x-magpie-work-dir", "x-magpie-work-git", "x-magpie-fallback", "x-magpie-session", "x-magpie-subagent"]) if (h.has(k)) h.set("x-saw-" + k.slice(9), h.get(k)) + for (const k of ["x-magpie-work-dir", "x-magpie-work-git", "x-magpie-fallback", "x-magpie-session", "x-magpie-subagent", "x-magpie-effort"]) if (h.has(k)) h.set("x-saw-" + k.slice(9), h.get(k)) // $FAKE_QUEUE: that model is queued at the vendor, as Qoder's free // models are: waited out (here until magpie gives up) unless magpie // said it needn't be, then said at once with the queue's 503 diff --git a/internal/provider/plugin_usage.go b/internal/provider/plugin_usage.go index 16148bfd6..e3ec5c097 100644 --- a/internal/provider/plugin_usage.go +++ b/internal/provider/plugin_usage.go @@ -158,7 +158,8 @@ func quotaOfPlugin(q SubscriptionQuota, u plugin.Usage) SubscriptionQuota { for _, x := range u.Windows { w := QuotaWindow{Name: x.Name, ResetSecs: x.ResetSecs, Display: x.Display, Amount: x.Amount, Limit: x.Limit, Unit: x.Unit, - Span: time.Duration(x.Span * float64(time.Second)), Model: strings.ToLower(x.Model), Aside: x.Aside} + Span: time.Duration(x.Span * float64(time.Second)), Model: strings.ToLower(x.Model), Aside: x.Aside, + Pool: x.Pool, Family: x.Family} if x.Balance != nil { // a wallet's balance: a reading, though it tells no share (#3950) b := *x.Balance diff --git a/internal/provider/plugin_usage_pool_test.go b/internal/provider/plugin_usage_pool_test.go new file mode 100644 index 000000000..77f29e314 --- /dev/null +++ b/internal/provider/plugin_usage_pool_test.go @@ -0,0 +1,45 @@ +package provider + +import ( + "testing" + "time" + + "github.com/yetone/magpie/internal/plugin" +) + +// A plugin's usage says the pool a window is of and the family a model's +// window belongs to, as Antigravity's plugin says them: the pool's own +// windows are pools (PoolWindow) holding the models put in them, and a page +// of text names them with their pool in place of the models' own, as the +// built-in's quota did. +func TestPluginWindowsKeepPoolAndFamily(t *testing.T) { + week := float64(7 * 24 * 3600) + q := quotaOfPlugin(SubscriptionQuota{Provider: "antigravity", User: "a@gmail.com"}, plugin.Usage{Windows: []plugin.UsageWindow{ + {Name: "Gemini 3.8 Flash", Model: "gemini-3.8-flash", Family: "gemini", Pool: "Gemini", Used: fptr(20), Span: week}, + {Name: "Claude Sonnet 4.6", Model: "claude-sonnet-4-6", Family: "claude", Used: fptr(5)}, + {Name: "7 days", Pool: "Gemini", Used: fptr(20), Span: week, Aside: true}, + }}) + if len(q.Windows) != 3 { + t.Fatalf("windows %+v", q.Windows) + } + m, c, p := q.Windows[0], q.Windows[1], q.Windows[2] + if m.Pool != "Gemini" || m.Family != "gemini" || c.Pool != "" || c.Family != "claude" || p.Pool != "Gemini" || p.Family != "" { + t.Fatalf("pool/family %q/%q %q/%q %q/%q", m.Pool, m.Family, c.Pool, c.Family, p.Pool, p.Family) + } + if !p.PoolWindow() || m.PoolWindow() { + t.Fatalf("PoolWindow: pool %v, model %v", p.PoolWindow(), m.PoolWindow()) + } + if ms := PoolMembers(q.Windows, p); len(ms) != 1 || ms[0].Model != "gemini-3.8-flash" { + t.Fatalf("members %+v", ms) + } + var names []string + for _, w := range PooledWindows(q.Windows) { + names = append(names, w.Name) + } + if len(names) != 2 || names[0] != "Claude Sonnet 4.6" || names[1] != "Gemini ยท 7 days" { + t.Fatalf("pooled %q", names) + } + if p.Span != 7*24*time.Hour { + t.Fatalf("span %v", p.Span) + } +} diff --git a/internal/provider/plugins.go b/internal/provider/plugins.go index f9bc28bf4..c1ee66e74 100644 --- a/internal/provider/plugins.go +++ b/internal/provider/plugins.go @@ -657,6 +657,19 @@ func (p Provider) Origin(ctx context.Context) string { return scheme + "://" + HostOf(rest) } +// EffortHeader is the header a plugin's fetch is told the request's +// effort in: one of the efforts its model's variants named, or another the +// client asked for (minimal, xhigh), for the plugin to pick its variant by. +const EffortHeader = "X-Magpie-Effort" + +type effortKey struct{} + +// WithEffort is ctx carrying the effort a request asks of a plugin's +// model, which pluginFetch tells the plugin in EffortHeader. +func WithEffort(ctx context.Context, effort string) context.Context { + return context.WithValue(ctx, effortKey{}, effort) +} + // pluginFetch sends a request the gateway made for a plugin's provider // through the plugin: to the base URL its loader gave (else the model's, // the provider's, the AI SDK package's), with what the loader adds. @@ -736,6 +749,9 @@ func pluginFetch(pp plugin.Provider, account string, req *http.Request) (*http.R h[strings.ToLower(k)] = vs[0] } } + if e, _ := ctx.Value(effortKey{}).(string); e != "" { + h[strings.ToLower(EffortHeader)] = e + } resp, err := plugin.Fetch(ctx, plugin.FetchRequest{ Provider: pp.ID, Account: account, Model: api, NPM: m.NPM, URL: url, Method: req.Method, Headers: h, Body: body, Session: req.Header.Get(ConversationHeader),