plugins: a plugin is told the effort asked, and its usage windows keep their pool and family

What a ported Antigravity needs from the host, kept generic:

- The gateway puts the request's reasoning effort on a plugin's fetch as
  X-Magpie-Effort (provider.EffortHeader), so a plugin that serves one
  model at several levels can pick the level. host.js strips it with the
  other magpie-only headers, so the vendor never sees it.
- A plugin's usage window may name a Pool and a Family; quotaOfPlugin
  passes them through, so PooledWindows names a shared pool
  ("Gemini · 7 days") as it does for the built-in.

Run (WSL magpie-desktop; mote unreachable, kex reset):
- TestPluginToldTheEffort: xhigh, low and none reach the plugin; the
  vendor gets no X-Magpie-Effort. Red with the MAGPIE_ONLY entry removed
  by hand (the vendor saw the header).
- TestPluginWindowsKeepPoolAndFamily, TestPluginToldTheSession: pass.
- Full suite: in the next commit's body (run at the head of both).
This commit is contained in:
yetone
2026-11-10 20:16:44 +08:00
parent 4a9142ccd4
commit f92c0a2bdd
8 changed files with 150 additions and 5 deletions
+8 -1
View File
@@ -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
+70
View File
@@ -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)
}
}
}
}
+3 -2
View File
@@ -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))) {
+5
View File
@@ -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)
+1 -1
View File
@@ -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
+2 -1
View File
@@ -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
@@ -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)
}
}
+16
View File
@@ -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),