gateway: POST /v1/responses/compact is relayed to a provider whose own API is Responses (#7281)

Pi's Responses compaction extension sends OpenAI's unary
POST /v1/responses/compact. Before this change, the generic route
answered it with the 404 for an unknown path and never reached the
upstream.

/v1/responses/compact and /responses/compact (responses_compact.go)
now go through serveAgent and serve, so the key, account and model
holds apply as they do on /responses. The request is marked unary
compact, and the candidates are cut to a key's provider that asks the
model on Responses (compactsUnary: no account, carriesCompaction).
attempt relays it as it came (keep, never translated), and passthrough
sends it to <Responses base>/responses/compact. The unary
response.compaction object goes back untouched, sealed item included.
compactionWatch records who wrote the sealed item, so a later
/responses that carries it goes back to that provider (#1099). The
call is recorded as KindCompact. When no candidate is left, the client
gets a 400 invalid_request_error: "/responses/compact is not supported
for <model>: ... compact on /responses instead". This follows the
CodexPath wording and gives the client a fallback. handle's
codexCompact branch is not on this path, so an earlier compaction item
in the input stays the client's. protoOfPath shapes key-limit errors
on the route as Responses errors.

Not changed: ChatGPT, Copilot and plugin accounts are refused on this
route until a real account is tried (#7285). Codex's own compact still
goes through CodexPath.

Run (mote, at this tree):
- the new TestResponsesCompactRelayed and
  TestResponsesCompactRefusedOffResponses: red on origin/main 7dc85f26e
  (404 not_found_error, both paths), green here.
- go test ./internal/gateway -run
  'TestResponsesCompact|TestCodexCompactionTriggerOnV1|NativeCompaction|KeyLimit':
  ok.
- go vet ./internal/gateway on darwin, linux and windows: ok. gofmt -l:
  clean.
- go test ./internal/gateway -count=1 -timeout 45m: started at this tree
  and not finished at push. The result will go on #7281.
Not tried: a real Pi compaction against a real Responses upstream.
This commit is contained in:
yetone
2026-11-20 11:20:46 +08:00
parent 7dc85f26e6
commit 6e6da86c81
5 changed files with 176 additions and 4 deletions
File diff suppressed because one or more lines are too long
+28 -2
View File
@@ -1158,6 +1158,8 @@ func (s *Server) routes() *routeMux {
mux.HandleFunc("POST /chat/completions", s.handle(provider.Chat))
mux.HandleFunc("POST /v1/responses", s.handle(provider.Responses))
mux.HandleFunc("POST /responses", s.handle(provider.Responses))
mux.HandleFunc("POST /v1/responses/compact", s.responsesCompact)
mux.HandleFunc("POST /responses/compact", s.responsesCompact)
mux.HandleFunc("GET /v1/responses", s.responsesOverHTTP)
mux.HandleFunc("GET /responses", s.responsesOverHTTP)
mux.HandleFunc("POST /v1/messages", keepsSignIn(s.handle(provider.Anthropic)))
@@ -2670,7 +2672,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
// the only place it is counted, and as a plain turn it read as no
// compaction at all (shangyuan0818 on Discord), the OTel export left
// it to that transcript, and its reply ended the agent's turn
if call.Kind == "" && factsOf(from, plain).compact {
if call.Kind == "" && (factsOf(from, plain).compact || unaryCompact(r)) {
call.Kind = KindCompact
}
// Claude Code's auto mode classifier and AgentSummary name themselves
@@ -3341,6 +3343,17 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
return
}
}
// /responses/compact goes only where it is the provider's own
// route (responses_compact.go, #7281)
if unaryCompact(r) {
var left bool
if cands, pl, left = s.unaryCompactCarriers(cands, pl); !left {
call.Status, call.Error = 400, "unary compaction not served"
writeError(w, from, 400, unaryCompactError(call.Model))
turnedAway()
return
}
}
}
var accountHeld bool // every candidate was an account or key the calling key may not use
if keyHeld || accHeld {
@@ -3769,7 +3782,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
// (#1099)
var sealedBy *candidate
wantWhole := wantsWhole(r.Context())
if from == provider.Responses && compactionTriggerIn(body) {
if from == provider.Responses && (compactionTriggerIn(body) || unaryCompact(r)) {
watch := &compactionWatch{w: w}
w = watch
defer func() {
@@ -6118,6 +6131,13 @@ func (s *Server) attempt(w http.ResponseWriter, r *http.Request, from provider.P
// compaction is on, goes as it came: a translation would leave it out
// (#1099)
keep := s.keepsCompaction(from, p, model, body)
// /responses/compact goes as it came, and only to a provider that
// has the route (responses_compact.go)
compact := from == provider.Responses && unaryCompact(r)
if compact {
keep, relayable = true, s.compactsUnary(p, model)
relay = relayable
}
// Codex's custom tools, to a model that turned them away before
// (custom_tool.go, #2656): translated on the client's own API, which
// offers them as functions
@@ -6184,6 +6204,9 @@ func (s *Server) attempt(w http.ResponseWriter, r *http.Request, from provider.P
}
if keep {
msg := fmt.Sprintf("%s doesn't serve %s on the Responses API, so Codex's native compaction can't be asked of it", p.Name, model)
if compact {
msg = unaryCompactError(model)
}
return writeError(w, from, 400, msg), msg
}
to := s.usable(p, model)
@@ -7167,6 +7190,9 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
body = withBodyEffort(proto, body, effort)
}
path := upstreamPath(p, proto, upstream)
if proto == provider.Responses && unaryCompact(r) {
path += "/compact" // responses_compact.go
}
if proto == provider.Gemini && p.IsVertex() && geminiWhole {
path = provider.VertexWholePath(upstream) // answered as one JSON body
}
+1 -1
View File
@@ -157,7 +157,7 @@ func protoOfPath(path string) provider.Protocol {
return provider.Anthropic
case strings.HasPrefix(path, "/v1beta/"):
return provider.Gemini
case strings.HasSuffix(path, "/responses"):
case strings.HasSuffix(path, "/responses"), strings.HasSuffix(path, "/responses/compact"):
return provider.Responses
}
return provider.Chat
+69
View File
@@ -0,0 +1,69 @@
package gateway
import (
"context"
"fmt"
"net/http"
"github.com/yetone/magpie/internal/provider"
)
// POST /v1/responses/compact (and /responses/compact) is OpenAI's unary
// compaction: the conversation in, one response.compaction object back,
// its compaction item sealed (encrypted_content) by the server that wrote
// it. Pi's Responses compaction extension asks it of a provider set to the
// Responses API (#7281); on the generic route it was the 404 of an unknown
// path, and never reached the upstream.
//
// It is relayed as it came, to /responses/compact under the provider's
// Responses base, only where that is the provider's own API: a key's
// provider whose model is asked on Responses (OpenAI, a relay or a local
// server speaking it, another magpie). Nothing else has the route, and a
// translation can't make the sealed item, so anywhere else — a model on
// Chat or Messages only, a subscription or plugin account — is a 400
// saying so, as CodexPath's is for magpie's models, for the client to fall
// back to compacting on /responses. Who sealed the item is remembered
// (wroteCheckpoint), so a later /responses carrying it goes back there
// (#1099). A ChatGPT account isn't asked it here: its backend's compaction
// is reached on CodexPath, as Codex sends it.
type unaryCompactKey struct{}
// responsesCompact serves POST /v1/responses/compact.
func (s *Server) responsesCompact(w http.ResponseWriter, r *http.Request) {
body, ok := s.requestBody(w, r, provider.Responses)
if !ok {
return
}
body, _, err := requestModel(body)
if err != nil {
writeError(w, provider.Responses, 400, err.Error())
return
}
r = r.WithContext(context.WithValue(r.Context(), unaryCompactKey{}, true))
s.serveAgent(w, r, provider.Responses, body)
}
// unaryCompact is whether r is a /responses/compact request.
func unaryCompact(r *http.Request) bool {
v, _ := r.Context().Value(unaryCompactKey{}).(bool)
return v
}
// compactsUnary is whether model at p can be asked /responses/compact: a
// key's provider (no account) whose wire carries Responses and asks model
// on it.
func (s *Server) compactsUnary(p provider.Provider, model string) bool {
return p.Account == nil && s.carriesCompaction(p, model)
}
// unaryCompactCarriers keeps of cands those compactsUnary.
func (s *Server) unaryCompactCarriers(cands []candidate, pl planned) ([]candidate, planned, bool) {
return keepCandidates(cands, pl, func(c candidate) bool { return s.compactsUnary(c.p, c.model) })
}
// unaryCompactError is what a /responses/compact for model is told when
// nothing that serves it has the route.
func unaryCompactError(model string) string {
return fmt.Sprintf("/responses/compact is not supported for %s: it is relayed only to a provider whose own API is Responses (an API key's provider asking the model on Responses), and none of those serves %s; compact on /responses instead", model, model)
}
@@ -0,0 +1,77 @@
package gateway
import (
"encoding/json"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// #7281 (jinpwng): Pi's Responses compaction extension asks POST
// /v1/responses/compact of a provider set to the Responses API. magpie
// answered it the 404 of an unknown path and never asked the upstream.
// From the generic /v1 base URL, and from the bare one, a key's provider
// on Responses is asked once, at /responses/compact under its base, and
// its unary compaction object comes back as it came, the sealed item
// untouched; the next /responses carrying it goes back there (#1099).
func TestResponsesCompactRelayed(t *testing.T) {
const reply = `{"id":"resp_c1","object":"response.compaction","created_at":1,"output":[{"type":"compaction","id":"cmp_1","encrypted_content":"gAAAAopaque=="}],"usage":{"input_tokens":120,"output_tokens":30,"total_tokens":150}}`
for _, path := range []string{"/v1/responses/compact", "/responses/compact"} {
t.Run(path, func(t *testing.T) {
f := &fake{t: t, ctype: "application/json", reply: reply}
setup(t, provider.Responses, f)
// an earlier compaction in the input stays the client's: not
// magpie's summary path (handle's codexCompact)
code, body := post(t, path, `{"model":"fake/m1","instructions":"summarise",
"input":[{"type":"compaction","encrypted_content":"gAAAAearlier=="},{"type":"message","role":"user","content":[{"type":"input_text","text":"fix the bug"}]}]}`)
if code != 200 {
t.Fatalf("%d %s", code, body)
}
if f.calls != 1 || f.path != "/v1/responses/compact" {
t.Fatalf("upstream asked %d times, at %q", f.calls, f.path)
}
var got map[string]any
if err := json.Unmarshal(f.got, &got); err != nil {
t.Fatalf("upstream got %s", f.got)
}
if got["model"] != "m1" || !strings.Contains(string(f.got), "gAAAAearlier==") || strings.Contains(string(f.got), `"stream":true`) {
t.Errorf("upstream got %s", f.got)
}
var out struct {
Object string `json:"object"`
Output []struct {
Type string `json:"type"`
Enc string `json:"encrypted_content"`
} `json:"output"`
}
if err := json.Unmarshal([]byte(body), &out); err != nil || out.Object != "response.compaction" || len(out.Output) != 1 || out.Output[0].Enc != "gAAAAopaque==" {
t.Fatalf("client got %s", body)
}
// who sealed it is remembered, for the next /responses
cp, ok := checkpointOf([]byte(`{"input":[{"type":"compaction","encrypted_content":"gAAAAopaque=="}]}`))
if !ok || cp.Provider != "fake" {
t.Errorf("sealed by %+v, %v", cp, ok)
}
})
}
}
// A model that isn't asked on Responses at its provider has no
// /responses/compact: the client is told so in a 400 it can fall back
// on, not a 404, and the upstream is never asked a translation of it.
func TestResponsesCompactRefusedOffResponses(t *testing.T) {
for _, path := range []string{"/v1/responses/compact", "/responses/compact"} {
t.Run(path, func(t *testing.T) {
f := &fake{t: t, ctype: "application/json", reply: `{}`}
setup(t, provider.Chat, f)
code, body := post(t, path, `{"model":"fake/m1","input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"hi"}]}]}`)
if code != 400 || !strings.Contains(body, "/responses/compact is not supported for fake/m1") || !strings.Contains(body, "invalid_request_error") {
t.Fatalf("%d %s", code, body)
}
if f.calls != 0 {
t.Errorf("upstream asked %d times: %s", f.calls, f.got)
}
})
}
}