Files
magpie/internal/gateway/middleware.go
T
yetone e44b9aef33 middleware: onProvider changes what one provider a request is tried on is sent
A JS gateway middleware can export onProvider(body, ctx). The gateway
calls it on each try, just before the body goes to that provider, with
ctx.provider = {id, name, account, model}: account is the subscription's
kind (claude, antigravity, …), absent for a key. Every try starts again
from the body onRequest left, so a change for one provider never reaches
another in a routing group. null and ctx.reject turn nothing away there.
A hook that throws or runs past 250ms leaves the try's body as it was.

A plugin could act only before routing until now, by the model name the
agent asked for. Claude Desktop asks for opaque aliases, so a plugin
couldn't tell which vendor a request was going to. The first user is
@magpie-community/middleware-antigravity-cloak: it changes only what an
Antigravity account is sent, so that Antigravity stops refusing Claude
Code's system prompt (xzplzpl on X). magpie itself still sends every
prompt as the agent wrote it.

- gwmw.To and gwmw.Tried; middleware.Run.Tried runs the hooks.
- serveAgent puts the runs on the request's context, and serve's
  candidate loop calls triedOn before the Antigravity foresight, so it
  judges the body that will be sent.
- Docs: gateway-middleware.md, reference.md, integrating.md, and the
  hooks table and community list in site docs plugins.html (en, zh, ja).

Run:
- go test ./... -timeout 45m in a sandbox HOME (macOS, at de671719a):
  every package ok but two. internal/middleware's TestPointsLoadErrors
  pinned the old list of exports; it now says onProvider too, and the
  package is green. internal/gateway's
  TestTranslatedStreamKeepsClientAlive/chat_to_responses went red under
  the full run's load (#2737, numbers added there); -count=10 alone is
  10/10 green, and with no middleware triedOn returns the body as is.
- TestMiddlewareOnProviderPerTry (gateway): a group a/m1 (500) then b/m1;
  a got "asked for a/A/m1/key", b got "asked". With the triedOn call
  replaced by `_ = triedOn` it is red (sent a:"asked" b:"asked").
- TestOnProvider (middleware): per-try bodies, throw and null fail open
  and are counted, a reject is a no-op, a nil Run passes through.
- gofmt -l clean; go vet darwin, GOOS=linux -tags nogui, GOOS=windows
  on the changed packages.
- node --test internal/gui/tests/plugin-middleware.test.cjs: 24 pass.
- Real use: a sandbox magpie built from this tree, a real Antigravity
  account, the plugin installed from its folder. Real Claude Code 2.1.302
  (`claude -p` with a sandbox CLAUDE_CONFIG_DIR, model
  antigravity/gemini-3-flash) got its answer. With the plugin's
  {"off": true} the same run got the 400 "Resource has been exhausted".
  Direct /v1/messages with the billing line, the Agent SDK line, and
  Claude Code's three blocks: 200 each with the plugin on, 400 each with
  it off.
2026-10-18 00:50:14 +08:00

131 lines
4.4 KiB
Go

package gateway
import (
"context"
"net/http"
"slices"
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/gwmw"
"github.com/yetone/magpie/internal/middleware"
"github.com/yetone/magpie/internal/plugin"
"github.com/yetone/magpie/internal/provider"
)
// serveAgent is serve for a request an agent sent: the agent middleware
// of the gateway's middleware point (gwmw.Agents: the JS gateway middleware
// plugins, internal/middleware, while plugins/middleware is on) see its
// body first, and its reply on the way back, in the agent's own API.
// magpie's own requests through serve (titles, the router's classifier,
// search and vision stand-ins) go without them, as their replies are
// magpie's to read.
func (s *Server) serveAgent(w http.ResponseWriter, r *http.Request, from provider.Protocol, body []byte) {
withGatewaySession(w, r)
w, recorded := recordConversation(w, r, from, body)
defer recorded()
w, body, hooked := gatewayHooks(w, r, from, body)
defer hooked()
agents := gwmw.AgentsWanted(middlewareWanted)
if len(agents) == 0 {
s.serve(w, r, from, body)
return
}
info := gwmw.Info{Protocol: string(from), Model: modelOf(body), Stream: streamOf(body), Path: r.URL.Path, Agent: agentOf(r)}
var tried []gwmw.Tried
for _, a := range agents {
run := a.Begin(info)
if run == nil {
continue
}
defer run.End()
if t, ok := run.(gwmw.Tried); ok {
tried = append(tried, t)
}
var turned *gwmw.Reject
body, turned = run.Request(body)
if turned != nil {
writeError(w, from, turned.Status, turned.Message)
return
}
var done func()
w, done = run.Wrap(w)
defer done()
}
if len(tried) > 0 {
r = r.WithContext(context.WithValue(r.Context(), triedKey{}, tried))
}
s.serve(w, r, from, body)
}
type triedKey struct{}
// triedOn is body as it goes to model on p, in the agent's API: what each
// middleware of the request that is also gwmw.Tried (the JS chain's
// onProvider) made of it for that provider. Each try starts from the body
// it is given, so a change for one provider never reaches another's.
func triedOn(ctx context.Context, p provider.Provider, model string, body []byte) []byte {
tried, _ := ctx.Value(triedKey{}).([]gwmw.Tried)
if len(tried) == 0 {
return body
}
to := gwmw.To{ID: p.ID, Name: p.Name, Account: accountAgent(p), Model: model}
for _, t := range tried {
body = t.Tried(body, to)
}
return body
}
// middlewareWanted: plugins.json has a JS middleware on, so plugins/middleware
// is in use.
func middlewareWanted() bool { return middleware.On() > 0 }
// gatewayHooks runs the asynchronous request hooks (OpenCode plugins'
// gateway entries, in the plugin host) on an agent's request: the body they
// leave is the one served, and they see the reply the agent got once it is
// whole. Its writer wraps the middleware's, so what they see is what the
// agent was given. With no hook it is the request as it came.
func gatewayHooks(w http.ResponseWriter, r *http.Request, from provider.Protocol, body []byte) (http.ResponseWriter, []byte, func()) {
if !plugin.HasGateway() {
return w, body, func() {}
}
info := plugin.GatewayContext{Origin: gatewayOrigin(r), Protocol: string(from), Model: modelOf(body), Stream: streamOf(body), Path: r.URL.Path, Agent: agentOf(r), Session: sessionOf(r.Header)}
if req, err := parse(from, body); err == nil {
info.Cwd = workDir(req)
info.Query = gatewayQuery(req)
}
run := plugin.GatewayBegin(r.Context(), body, info)
if run == nil {
return w, body, func() {}
}
w, done := gatewayResponse(w, r, from, run.Body, run)
return w, run.Body, func() { done(); run.Close() }
}
// gatewayQuery uses the same user-authored words as routing, excluding
// agent context, tool results and images. Tool-only increments have none.
func gatewayQuery(req *Request) string {
for i := len(req.Messages) - 1; i >= 0; i-- {
m := req.Messages[i]
if m.Role != "user" {
continue
}
if query := userSaid(m); query != "" {
return query
}
}
return ""
}
// gatewayOrigin exposes provenance, never credentials or peer addresses.
// Forwarded traffic remains remote even when the administrator trusts its
// proxy for authentication: that trust does not establish conversation ownership.
func gatewayOrigin(r *http.Request) string {
if access.Caller(r.Context()).KeyID != "" || managedKey(r) {
return "gateway-key"
}
if local(r) && !slices.ContainsFunc(forwardHeaders, func(h string) bool { return r.Header.Get(h) != "" }) {
return "local"
}
return "remote"
}