gateway: a provider that refuses auto mode's safeguards is asked again without them and not sent them again, so Copilot's claude-opus-5.5 answers Claude Code (#1756)
Pylogmon's Claude Code on Copilot's claude-opus-5.5 got 400 invalid_request_error "Copilot: safeguards: Extra inputs are not permitted" on every turn, which magpie labels "request format not accepted". Their Sonnet worked. Claude Code's auto mode adds a top-level `safeguards` field for the API's review of its actions. magpie passes it on to any Claude model (automode.go), and Copilot's Messages API checks its fields strictly and turns the field away. The fix uses the existing class for Claude Code's newer fields that a relay refuses (anthropic_shapes.go: thinking.display, a turn's output_config). On a 400 naming `safeguards` with "Extra inputs are not permitted", forward asks again at once without the field and remembers that the provider refuses it (shapeSafeguards), so later requests leave it out the first time. Claude Code, finding no safeguard_results, reviews its actions locally, as it does for every non-Claude model. The fix sits in forward/forwardOnce, so it reaches every route to an Anthropic endpoint: relayed and translated (buildAnthropic), any provider, not only Copilot. What was run: - TestSafeguardsRefusedLeftOut (refusal text as the reporter quoted it): on the old anthropic_shapes.go the agent gets the same "Cop: safeguards: Extra inputs are not permitted" 400; now it gets 200, asked twice the first time and once after that. - TestSafeguardsKeptWhereTaken: a provider that takes the field still gets it. - The shapes, system-message and auto mode tests pass. Not verified: no Copilot account with claude-opus-5.5 was available, so Copilot's raw error body is assumed. The match is on the words the reporter quoted, which magpie shows after "Copilot: ".
This commit is contained in:
@@ -82,7 +82,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md).
|
||||
- Group members are `provider/model[:effort]`. A member with a fixed effort is asked for that effort, bounded by the group's levels (#671).
|
||||
- An agent whose config can't carry an effort has one picked in magpie (`provider.AgentEffort`, settings' `agentEfforts`; Cursor Private Inference's row, #1003). It is asked for on that agent's requests to a model that reasons (`Provider.Thinks`), in place of the level the request sent, fitted to the model's levels and bounded by the group's. Order: a member's fixed effort, then a model's `:effort` suffix, then the turn's pick (a routing rule's), then the agent's pick, then the request's own. A model that doesn't reason is sent as asked; the default (none picked) leaves every request as it came. The pick beats the request's own because Cursor sends its own default as often as a real choice. Picking Default hands the choice back to Cursor.
|
||||
- Gemini's OpenAI-compatible API (AI Studio's, or a proxy in front of Gemini on this computer or the LAN: `geminiCompat`) is asked for the model's thoughts in `extra_body.google.thinking_config`. A 400 or 422 whose error names `extra_body`, `include_thoughts` or thinking at all (`refusesThinkingConfig`) marks the provider unfit for the field (`thinking_config`), and it is asked again with `reasoning_effort` alone. Gemini 3 can't stop thinking, so reasoning turned off goes at `minimal`, its least, or at the model's lowest level where it has no `minimal` (`geminiLevels`: those of the model's levels it hasn't turned away, or of Gemini 3's where its own aren't known or none is left). Gemini 3 turns away a level the model hasn't with a 400 that names the level (`geminiRefusedLevel`): AI Studio's "Thinking level MINIMAL is not supported for this model. Please retry with other thinking level." for gemini-3.8-flash, Vertex AI's "Thinking level is unsupported: THINKING_LEVEL_MINIMAL". It names thinking too, but isn't the field turned away. The level is marked refused for that model (`levelRefused`), and the model is asked again at the nearest level it has left, still for its thoughts, and at that level from then on. A level turned away again, with none left, is the client's 400. Passed through, a Chat client's own `none` or `minimal` that Gemini turns away this way is asked again at the model's lowest level (`onEffort`), and that level goes at the lowest from then on (`turnedAway`); the other still goes as sent, as AI Studio takes `none` from gemini-3.8-flash. A refusal that names the levels the model takes (`effortLevelsNamed`, Command Code's for Qoder's `none`) marks reasoning off as a whole (`offRefused`): both go at the lowest from then on; one that lists the other among the levels taken (`otherOffNamed`, quoted, OpenAI's for gpt-5.1's `minimal`) marks only the level turned away. Both routes read and write the same marks. Vertex AI's OpenAI-compatible API marks each streamed chunk of thoughts in the delta's `extra_content.google.thought`, and such a chunk is read as thinking.
|
||||
- A Claude that thinks only adaptively (`adaptiveOnly` in [`anthropic.go`](../../internal/gateway/anthropic.go): Opus, Sonnet and Haiku from 4.6 on, Fable and Mythos 5 and 5.1, read by `claudeVersion` however a relay spells them) is never sent a thinking budget, which they answer with 400. magpie's own request from a Chat or Responses client (`buildAnthropic`) goes as `thinking: {type: "adaptive", display: "summarized"}` with the effort in `output_config.effort`, so the client sees the reasoning Opus 4.7 and later otherwise leave out (display `omitted` by default), and a relay that refuses `display` is asked again without it (`refuseShapes`); a client's `thinking: {type: "enabled", budget_tokens}` is turned into the same in `forwardOnce` (`adaptiveThinking`), the budget as its nearest effort, above `high` as `max`, and `display: "summarized"` unless the client named its own display, so the thinking that enabled shows stays shown (the refused shapes are taken out after it, and `refuseShapes` reads the display as it is sent); and Pi, dsh and omp are written to ask it adaptively (`AdaptiveThinking`: `forceAdaptiveThinking`, omp's `anthropic-adaptive`; #1470). A client's `xhigh` goes as `xhigh`, except to Opus and Sonnet 4.6, which have no `xhigh` and are asked `max` (`noXhigh`, #1471).
|
||||
- A Claude that thinks only adaptively (`adaptiveOnly` in [`anthropic.go`](../../internal/gateway/anthropic.go): Opus, Sonnet and Haiku from 4.6 on, Fable and Mythos 5 and 5.1, read by `claudeVersion` however a relay spells them) is never sent a thinking budget, which they answer with 400. magpie's own request from a Chat or Responses client (`buildAnthropic`) goes as `thinking: {type: "adaptive", display: "summarized"}` with the effort in `output_config.effort`, so the client sees the reasoning Opus 4.7 and later otherwise leave out (display `omitted` by default), and a relay that refuses `display` is asked again without it (`refuseShapes`), as is one that refuses auto mode's `safeguards` (Copilot's Messages API: 400 "safeguards: Extra inputs are not permitted" on claude-opus-5.5, #1756; `shapeSafeguards`, `TestSafeguardsRefusedLeftOut`), and neither is sent it again while magpie runs; a client's `thinking: {type: "enabled", budget_tokens}` is turned into the same in `forwardOnce` (`adaptiveThinking`), the budget as its nearest effort, above `high` as `max`, and `display: "summarized"` unless the client named its own display, so the thinking that enabled shows stays shown (the refused shapes are taken out after it, and `refuseShapes` reads the display as it is sent); and Pi, dsh and omp are written to ask it adaptively (`AdaptiveThinking`: `forceAdaptiveThinking`, omp's `anthropic-adaptive`; #1470). A client's `xhigh` goes as `xhigh`, except to Opus and Sonnet 4.6, which have no `xhigh` and are asked `max` (`noXhigh`, #1471).
|
||||
- A request to an Anthropic endpoint that turns thinking off is sent as the model takes it (`thinkingOffAsTaken`, in `forwardOnce`, so relayed requests, count_tokens, magpie's own thinking-off and retries all get it; the model is read as the vendor names it, from the body, or from the path for Bedrock and Vertex). Claude Sonnet 5.5 refuses `thinking: {type: "disabled"}` and is sent `{type: "between_tools"}` alone, at effort `high` at most. Opus 5.5, Fable 5 and Mythos 5 refuse it at every effort and are sent no thinking, at effort `low` unless one was asked, with `classifierRoom` added to a reply limit below it, as Claude Code does. Opus 5 and Haiku 5.5 take it only up to `high`, so `xhigh` and `max` are asked as `high`. `between_tools` sent to any other Claude goes as `disabled`, or as none where that is refused too. Other vendors' models, older Claudes and later lines than these go as they came (#1454). A Sonnet 5.5 by a name these rules can't read, answering 400 that asks for `between_tools` (`asksBetweenTools`), is asked again with it, once; a refusal of `disabled` at any effort (`thinkingOffRefused`) is asked again with thinking left to the model, as `alwaysThinks` is.
|
||||
- A Chat or Responses client's reasoning turned off (`none`, `ThinkOff`), translated to an Anthropic endpoint (`buildAnthropic`), goes as `thinking: {type: "disabled"}`; it went as thinking at a 4096-token budget before (#1636). A model that refuses it (`alwaysThinks`, `mandatoryReasoning`, `thinkingOffRefused`) is asked again at its least (`thinkingBackOn`), and `markUnfit(offRefused)` sends it so at once until magpie restarts. A translated request's level can differ from the one asked: `none` and `minimal` go as `low` where the model's levels don't say it stops (`effortOf`). The route keeps the level asked; the try, the usage log and Routing's "went" say the one built (`noteWireEffort`, `wireEffort` in [`wire_effort.go`](../../internal/gateway/wire_effort.go)). Gemini's builders say theirs their own way and are logged as asked.
|
||||
- A request to an Anthropic endpoint with `temperature`, `top_p` or `top_k` reaches a model that refuses them without them (`samplingAsTaken`, beside `thinkingOffAsTaken` in `forwardOnce`): Opus 4.7, 4.8, 5 and 5.5, Fable 5, Mythos 5, Sonnet 5 and 5.5, and Haiku 5.5, whose 400 is "`temperature` is deprecated for this model" (Claude Code's auto mode classifier and magpie's own classifiers ask at temperature 0). Older Claudes, Haiku 4.5 among them, other vendors' models and later lines go as they came (#1454). A Claude by a name these rules can't read, answering that a sampling parameter is deprecated (`samplingDeprecated`), is asked again without them, once — a Chat or Responses client's request translated to Messages (`forwardTranslated`) as much as a relayed one.
|
||||
|
||||
@@ -34,6 +34,11 @@ import (
|
||||
// "Invalid input at messages.1.role" (#1407). A provider that refuses one is
|
||||
// sent its system messages' text at the end of the top-level system, and an
|
||||
// empty one left out.
|
||||
//
|
||||
// Copilot's Messages API turns away auto mode's `safeguards` (automode.go)
|
||||
// on its Claude models: 400 "safeguards: Extra inputs are not permitted"
|
||||
// (#1756, claude-opus-5.5). A provider that refuses it is sent none, and
|
||||
// Claude Code, finding no safeguard_results, reviews its actions locally.
|
||||
|
||||
// The refusals, remembered in unfit under the provider's id as betas are.
|
||||
const (
|
||||
@@ -41,6 +46,7 @@ const (
|
||||
shapeDisplay = "shape:thinking.display" // display at all
|
||||
shapeTurnEffort = "shape:messages[].output_config"
|
||||
shapeTurnSystem = "shape:messages[].role=system"
|
||||
shapeSafeguards = "shape:safeguards"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -48,6 +54,7 @@ var (
|
||||
displayRefused = regexp.MustCompile(`thinking\.(?:adaptive|enabled)\.display:? Extra inputs are not permitted`)
|
||||
turnEffortRefused = regexp.MustCompile(`messages\.\d+\.output_config:? Extra inputs are not permitted`)
|
||||
turnRoleRefused = regexp.MustCompile(`messages\.(\d+)\.role\b`)
|
||||
safeguardsRefused = regexp.MustCompile(`\bsafeguards:? Extra inputs are not permitted`)
|
||||
)
|
||||
|
||||
// knownDisplay is a thinking.display every Anthropic endpoint has taken.
|
||||
@@ -74,6 +81,9 @@ func (s *Server) refuseShapes(p provider.Provider, errBody, body []byte) bool {
|
||||
if turnEffortRefused.Match(errBody) && hasTurnEffort(body) {
|
||||
mark(shapeTurnEffort)
|
||||
}
|
||||
if safeguardsRefused.Match(errBody) && gjson.GetBytes(body, "safeguards").Exists() {
|
||||
mark(shapeSafeguards)
|
||||
}
|
||||
// a role refused at a message that is a system one, counted in the
|
||||
// messages as they were sent; a refusal naming a user or assistant
|
||||
// message is over something else
|
||||
@@ -92,6 +102,9 @@ func (s *Server) withoutRefusedShapes(p provider.Provider, body []byte) []byte {
|
||||
if !s.fits(p.ID, shapeTurnSystem, provider.Anthropic) {
|
||||
body = withSystemOnTop(body)
|
||||
}
|
||||
if !s.fits(p.ID, shapeSafeguards, provider.Anthropic) && gjson.GetBytes(body, "safeguards").Exists() {
|
||||
body = withoutFields(body, "safeguards")
|
||||
}
|
||||
if !bytes.Contains(body, []byte(`"display"`)) && !bytes.Contains(body, []byte(`"output_config"`)) {
|
||||
return body
|
||||
}
|
||||
|
||||
@@ -0,0 +1,118 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// #1756: Claude Code in auto mode through magpie to Copilot's
|
||||
// claude-opus-5.5 got 400 invalid_request_error "safeguards: Extra inputs
|
||||
// are not permitted" on every turn. magpie asks again at once without the
|
||||
// safeguards, and sends that provider none from then on; the rest of the
|
||||
// request goes as it was.
|
||||
func TestSafeguardsRefusedLeftOut(t *testing.T) {
|
||||
fresh(t)
|
||||
var mu sync.Mutex
|
||||
var bodies []map[string]any
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
var m map[string]any
|
||||
json.Unmarshal(b, &m)
|
||||
mu.Lock()
|
||||
bodies = append(bodies, m)
|
||||
mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if _, ok := m["safeguards"]; ok {
|
||||
w.WriteHeader(400)
|
||||
io.WriteString(w, `{"error":{"message":"safeguards: Extra inputs are not permitted","type":"invalid_request_error"}}`)
|
||||
return
|
||||
}
|
||||
io.WriteString(w, `{"id":"msg_1","type":"message","role":"assistant","model":"claude-opus-5.5","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
if err := provider.Save(provider.Provider{ID: "cop", Name: "Cop", Key: "k", Anthropic: srv.URL,
|
||||
Models: []string{"claude-opus-5.5"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body := `{"model":"cop/claude-opus-5.5","max_tokens":64,"safeguards":{"dangerous_tool_use":{"enabled":true}},` +
|
||||
`"messages":[{"role":"user","content":[{"type":"text","text":"say pong"}]}]}`
|
||||
h := New().Handler() // one gateway, which learns
|
||||
post := func() {
|
||||
t.Helper()
|
||||
rec := httptest.NewRecorder()
|
||||
h.ServeHTTP(rec, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)))
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("status %d: %s", rec.Code, rec.Body)
|
||||
}
|
||||
}
|
||||
all := func() []map[string]any {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
return append([]map[string]any(nil), bodies...)
|
||||
}
|
||||
post()
|
||||
sent := all()
|
||||
if len(sent) != 2 {
|
||||
t.Fatalf("asked %d times, want again once after the 400", len(sent))
|
||||
}
|
||||
if _, ok := sent[1]["safeguards"]; ok {
|
||||
t.Fatalf("asked again with the safeguards: %v", sent[1])
|
||||
}
|
||||
if msgs, _ := sent[1]["messages"].([]any); len(msgs) != 1 {
|
||||
t.Fatalf("messages = %v", sent[1]["messages"])
|
||||
}
|
||||
|
||||
// learned: the next request goes without them the first time
|
||||
post()
|
||||
if sent = all(); len(sent) != 3 {
|
||||
t.Fatalf("asked %d times in all, want once more", len(sent))
|
||||
}
|
||||
if _, ok := sent[2]["safeguards"]; ok {
|
||||
t.Fatalf("sent the safeguards again: %v", sent[2])
|
||||
}
|
||||
}
|
||||
|
||||
// A provider that takes the safeguards (Anthropic's own API) keeps getting
|
||||
// them: only a refusal naming them leaves them out.
|
||||
func TestSafeguardsKeptWhereTaken(t *testing.T) {
|
||||
fresh(t)
|
||||
var got []map[string]any
|
||||
var mu sync.Mutex
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
var m map[string]any
|
||||
json.Unmarshal(b, &m)
|
||||
mu.Lock()
|
||||
got = append(got, m)
|
||||
mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
io.WriteString(w, `{"id":"msg_1","type":"message","role":"assistant","model":"claude-opus-5-5","content":[{"type":"text","text":"ok"}],"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}`)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Anthropic: srv.URL,
|
||||
Models: []string{"claude-opus-5-5"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body := `{"model":"relay/claude-opus-5-5","max_tokens":64,"safeguards":{"dangerous_tool_use":{"enabled":true}},` +
|
||||
`"messages":[{"role":"user","content":"hi"}]}`
|
||||
rec := httptest.NewRecorder()
|
||||
New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)))
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("status %d: %s", rec.Code, rec.Body)
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("asked %d times", len(got))
|
||||
}
|
||||
if _, ok := got[0]["safeguards"]; !ok {
|
||||
t.Fatalf("safeguards left out where taken: %v", got[0])
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user