gateway: an input item a Responses upstream has no type for is translated, and a compaction refused so is asked as text (cyberestro on X)
cyberestro on X: a Codex subagent on a local Qwen server's Responses API (qwen, http://127.0.0.1:30010/v1) got "compaction: qwen (qwen, …) answered the summary request 400 Bad Request: qwen: Unsupported input item: agent_message". agent_message is the item Codex's MultiAgentV2 hands a subagent its task in (author, recipient, input_text content, as #5259's and plugins#61's requests carry it). Two gaps, both fixed: - The compaction's fallback for an input kind refused (inputKindRefused, #5181, #5259) read only "unsupported_input_item" and "unknown item type". inputKindWords now reads "unsupported input item" with spaces too, so the summary is asked again with the conversation as text, the agent_message as the user's turn (itemText), then compacted locally. - The normal path relayed every subagent turn to the same server with the agent_message as Codex sent it, and gave the 400 back. passthrough now treats that refusal, on a request carrying an item other than a message, function call, its output or reasoning (hasOtherItem), like a custom tool refused (#2656): the model is marked (inputKindsRefused) and the turn is translated on the same API, where agent_message is the user's turn and a custom tool call a function call; later such turns go translated at once. A native compaction or sealed task still gets the refusal, and magpie's own summary ask (inCompaction) keeps its text fallback. Run (mote, mica): - New tests on the old code (ae0a78368), red: TestUnsupportedInputItemTranslated (400 "qwen: Unsupported input item: agent_message", stream and not), TestInputItemRefusalWordings, TestCodexCompactQwenInputItemAsksAgainAsText (the reporter's compaction error, word for word). - Same tests green on the fix, with TestCodexCompact*, TestCustomTool*, AgentMessage, Sealed, Zed and Grok tests. - A first version also translated the summary ask; it broke TestCodexCompactUnsupportedInputItem* (asked 4 times, not 2), so the summary ask was left to its own fallback. - gofmt; go vet ./internal/gateway on darwin, GOOS=linux (nogui), GOOS=windows; go test -tags nogui -count=1 ./internal/gateway: ok (925s, this change on origin/mainc867a12c5). Not tried: a real Qwen server (the reporter's server and its exact JSON body are unknown; the fixture uses the words magpie showed), Codex end to end, and the full ./... suite (mote was running another session's).
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -4166,7 +4166,9 @@ func itemNotFound(rec *recorder) bool {
|
||||
// outputs and reasoning, and answers anything else 400
|
||||
// "unsupported_input_item" with param "input" (#5181, Edward4226; #5259,
|
||||
// Mmx233, a Codex subagent's history), and Grok's backend an
|
||||
// agent_message 422 "unknown item type". It comes as that status, as
|
||||
// agent_message 422 "unknown item type", and a local Qwen server's
|
||||
// Responses API 400 "Unsupported input item: agent_message" (cyberestro
|
||||
// on X). It comes as that status, as
|
||||
// another magpie's message in front of it ("Remote magpie: Command Code:
|
||||
// {…}", a 400 or its 502), or as an error event in the summary's stream.
|
||||
// The conversation as text is messages alone, which it takes. A refusal
|
||||
@@ -4182,7 +4184,7 @@ func inputKindRefused(rec *recorder, err error) bool {
|
||||
return inputKindWords.Match(rec.body.Bytes())
|
||||
}
|
||||
|
||||
var inputKindWords = lazyre.New(`(?i)unsupported_input_item|unknown item type`)
|
||||
var inputKindWords = lazyre.New(`(?i)unsupported[ _]input[ _]item|unknown item type`)
|
||||
|
||||
// compactFailure names who answered a summary request with a failure — the
|
||||
// provider, the model and the provider's base URL — and what it said.
|
||||
|
||||
@@ -136,6 +136,13 @@ func asksCompaction(ctx context.Context) bool {
|
||||
return v
|
||||
}
|
||||
|
||||
// inCompaction is whether ctx is a summary ask for a compaction, its
|
||||
// roles swapped or as sent (askAsSent).
|
||||
func inCompaction(ctx context.Context) bool {
|
||||
_, ok := ctx.Value(compactionAskKey{}).(bool)
|
||||
return ok
|
||||
}
|
||||
|
||||
func askCompaction(r *http.Request) *http.Request {
|
||||
return r.WithContext(context.WithValue(r.Context(), compactionAskKey{}, true))
|
||||
}
|
||||
|
||||
@@ -5903,6 +5903,15 @@ func (s *Server) attempt(w http.ResponseWriter, r *http.Request, from provider.P
|
||||
if relay && !keep && customOff() {
|
||||
relay, ownAPI = false, true
|
||||
}
|
||||
// and input items a model turned away before (input_kinds.go: a
|
||||
// subagent's agent_message to a server that knows OpenAI's first
|
||||
// items alone)
|
||||
itemsOff := func() bool {
|
||||
return from == provider.Responses && !inCompaction(r.Context()) && !s.fits(p.ID, inputKindsRefused(model), from) && hasOtherItem(body)
|
||||
}
|
||||
if relay && !keep && itemsOff() {
|
||||
relay, ownAPI = false, true
|
||||
}
|
||||
// and a backend that turned a request for one body away because it
|
||||
// only streams (stream_only.go) is asked streamed, translated
|
||||
streamOnly := (from == provider.Chat || from == provider.Responses) && !streamOf(body) && !s.fits(p.ID, streamOnlyRefused(model), from)
|
||||
@@ -5930,7 +5939,7 @@ func (s *Server) attempt(w http.ResponseWriter, r *http.Request, from provider.P
|
||||
// or it turned the custom tools away just now: speak it translated,
|
||||
// except a compaction or a sealed subagent task, which a
|
||||
// translation would leave out
|
||||
if customOff() || !s.fits(p.ID, streamOnlyRefused(model), from) && !streamOf(body) {
|
||||
if customOff() || itemsOff() || !s.fits(p.ID, streamOnlyRefused(model), from) && !streamOf(body) {
|
||||
if keep || sealed {
|
||||
return writeError(w, from, status, msg), msg
|
||||
}
|
||||
@@ -7109,6 +7118,16 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
|
||||
s.markUnfit(p.ID, customToolRefused(model), proto)
|
||||
return res.StatusCode, p.Name + ": " + provider.APIError(b, res.Status), false
|
||||
}
|
||||
if proto == provider.Responses && !inCompaction(r.Context()) && inputKindWords.Match(b) && hasOtherItem(body) {
|
||||
// an input item it has no type for turned away (a local
|
||||
// Qwen server's "Unsupported input item: agent_message",
|
||||
// input_kinds.go): translated on the same API, and so from
|
||||
// then on. A compaction's summary ask has its own way on, the
|
||||
// conversation as text (inputKindRefused)
|
||||
res.Body.Close()
|
||||
s.markUnfit(p.ID, inputKindsRefused(model), proto)
|
||||
return res.StatusCode, p.Name + ": " + provider.APIError(b, res.Status), false
|
||||
}
|
||||
if gather == nil && refusesWhole(proto, body, b) {
|
||||
// a backend that only streams (stream_only.go): the request
|
||||
// is translated on the same API, which asks it streamed and
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// qwenInputRefusal is a local Qwen server's Responses API turning away an
|
||||
// input item it has no type for, as cyberestro on X got it from
|
||||
// http://127.0.0.1:30010/v1 for a Codex subagent's agent_message:
|
||||
// "qwen: Unsupported input item: agent_message".
|
||||
func qwenInputRefusal(kind string) string {
|
||||
return `{"error":{"message":"Unsupported input item: ` + kind + `","type":"invalid_request_error","code":400}}`
|
||||
}
|
||||
|
||||
// basicItem is whether a Responses server that knows OpenAI's first
|
||||
// input items alone takes it: messages, function calls, their outputs and
|
||||
// reasoning.
|
||||
func basicItem(kind string) bool {
|
||||
switch kind {
|
||||
case "", "message", "function_call", "function_call_output", "reasoning":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// strictInputUpstream is such a server: an item of another kind is
|
||||
// refused, in qwen's words; anything else is answered "ok".
|
||||
type strictInputUpstream struct {
|
||||
mu sync.Mutex
|
||||
asked []map[string]any
|
||||
}
|
||||
|
||||
func (u *strictInputUpstream) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
var q map[string]any
|
||||
json.Unmarshal(b, &q)
|
||||
u.mu.Lock()
|
||||
u.asked = append(u.asked, q)
|
||||
u.mu.Unlock()
|
||||
items, _ := q["input"].([]any)
|
||||
for _, it := range items {
|
||||
if m, _ := it.(map[string]any); m != nil {
|
||||
if k, _ := m["type"].(string); !basicItem(k) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(400)
|
||||
io.WriteString(w, qwenInputRefusal(k))
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
answerOK(w, r, q["stream"] == true)
|
||||
}
|
||||
|
||||
// answerOK answers "ok", streamed or whole.
|
||||
func answerOK(w http.ResponseWriter, r *http.Request, stream bool) {
|
||||
if stream {
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
msg := `{"type":"message","id":"m1","role":"assistant","content":[{"type":"output_text","text":"ok"}]}`
|
||||
io.WriteString(w, sse(
|
||||
`data: {"type":"response.created","response":{"id":"r1","status":"in_progress","output":[]}}`,
|
||||
`data: {"type":"response.output_item.added","output_index":0,"item":{"type":"message","id":"m1","role":"assistant","content":[]}}`,
|
||||
`data: {"type":"response.output_text.delta","output_index":0,"item_id":"m1","content_index":0,"delta":"ok"}`,
|
||||
`data: {"type":"response.output_item.done","output_index":0,"item":`+msg+`}`,
|
||||
`data: {"type":"response.completed","response":{"id":"r1","status":"completed","output":[`+msg+`],"usage":{"input_tokens":9,"output_tokens":1}}}`))
|
||||
return
|
||||
}
|
||||
answer(w, r)
|
||||
}
|
||||
|
||||
// subagentTurn is a Codex subagent's turn under MultiAgentV2: its task
|
||||
// came as an agent_message (the item codex-rs hands a subagent its
|
||||
// NEW_TASK in, as #5259's and plugins#61's requests carry it), and it has
|
||||
// called a tool since.
|
||||
const subagentTurn = `{"model":%q,"stream":%t,"store":false,"input":[
|
||||
{"type":"message","role":"developer","content":[{"type":"input_text","text":"be brief"}]},
|
||||
{"type":"agent_message","author":"/root","recipient":"/root/research","content":[{"type":"input_text","text":"Message Type: NEW_TASK\nPayload:\nCompare Vault secret rotation with rollout restart timing."}]},
|
||||
{"type":"function_call","call_id":"call_1","name":"exec_command","arguments":"{\"cmd\":\"ls\"}"},
|
||||
{"type":"function_call_output","call_id":"call_1","output":"notes.md"},
|
||||
{"type":"agent_message","author":"/root","recipient":"/root/research","content":[{"type":"input_text","text":"Message Type: MESSAGE\nPayload:\nKeep the observed event order."}]}],
|
||||
"tools":[{"type":"function","name":"exec_command","parameters":{"type":"object","properties":{"cmd":{"type":"string"}}}}]}`
|
||||
|
||||
// cyberestro on X: a Codex subagent on a local Qwen server's Responses
|
||||
// API was refused 400 "Unsupported input item: agent_message", the item
|
||||
// its task comes in, and magpie gave the 400 back, every turn. The turn
|
||||
// is now asked again translated on the same API, the agent_message as the
|
||||
// user's turn it is, and the next turn goes translated at once; a server
|
||||
// that takes the item still gets it as sent.
|
||||
func TestUnsupportedInputItemTranslated(t *testing.T) {
|
||||
for _, stream := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("stream %t", stream), func(t *testing.T) {
|
||||
fresh(t)
|
||||
strict := &strictInputUpstream{}
|
||||
qs := httptest.NewServer(strict)
|
||||
t.Cleanup(qs.Close)
|
||||
var taking []map[string]any
|
||||
var mu sync.Mutex
|
||||
lax := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
var q map[string]any
|
||||
json.Unmarshal(b, &q)
|
||||
mu.Lock()
|
||||
taking = append(taking, q)
|
||||
mu.Unlock()
|
||||
answerOK(w, r, q["stream"] == true)
|
||||
}))
|
||||
t.Cleanup(lax.Close)
|
||||
for _, p := range []provider.Provider{
|
||||
{ID: "qwen", Name: "qwen", Key: "k", Models: []string{"qwen"}, Responses: qs.URL + "/v1"},
|
||||
{ID: "lax", Name: "Lax", Key: "k", Models: []string{"m1"}, Responses: lax.URL + "/v1"},
|
||||
} {
|
||||
if err := provider.Save(p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
s := New()
|
||||
ask := func(model string) *httptest.ResponseRecorder {
|
||||
rec := httptest.NewRecorder()
|
||||
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(fmt.Sprintf(subagentTurn, model, stream))))
|
||||
return rec
|
||||
}
|
||||
rec := ask("qwen/qwen")
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("qwen: %d %s", rec.Code, rec.Body)
|
||||
}
|
||||
if len(strict.asked) != 2 {
|
||||
t.Fatalf("qwen asked %d times", len(strict.asked))
|
||||
}
|
||||
again, _ := json.Marshal(strict.asked[1]["input"])
|
||||
for _, want := range []string{"Compare Vault secret rotation", "Keep the observed event order", "exec_command", "notes.md"} {
|
||||
if !strings.Contains(string(again), want) {
|
||||
t.Errorf("asked again without %q: %s", want, again)
|
||||
}
|
||||
}
|
||||
if !strings.Contains(rec.Body.String(), "ok") {
|
||||
t.Errorf("Codex got %s", rec.Body)
|
||||
}
|
||||
|
||||
// the next turn goes translated at once
|
||||
if rec = ask("qwen/qwen"); rec.Code != 200 || len(strict.asked) != 3 {
|
||||
t.Fatalf("next turn: %d, asked %d times: %s", rec.Code, len(strict.asked), rec.Body)
|
||||
}
|
||||
|
||||
// a server that takes the item gets it as sent
|
||||
if rec = ask("lax/m1"); rec.Code != 200 || len(taking) != 1 {
|
||||
t.Fatalf("lax: %d, asked %d times: %s", rec.Code, len(taking), rec.Body)
|
||||
}
|
||||
if b, _ := json.Marshal(taking[0]["input"]); !strings.Contains(string(b), `"agent_message"`) {
|
||||
t.Errorf("lax got %s", b)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The refusal's wordings that name an input item the server has no type
|
||||
// for are read as one; a refusal of anything else is not.
|
||||
func TestInputItemRefusalWordings(t *testing.T) {
|
||||
for _, b := range []string{
|
||||
qwenInputRefusal("agent_message"),
|
||||
"Unsupported input item: custom_tool_call",
|
||||
commandCodeInputRefusal,
|
||||
`{"error":{"message":"unknown item type"}}`,
|
||||
} {
|
||||
if !inputKindWords.MatchString(b) {
|
||||
t.Errorf("not read as an input item refusal: %s", b)
|
||||
}
|
||||
}
|
||||
for _, b := range []string{
|
||||
`{"error":{"message":"Unsupported parameter: temperature"}}`,
|
||||
`{"error":{"message":"Invalid API key"}}`,
|
||||
deepSeekCustomRefusal,
|
||||
} {
|
||||
if inputKindWords.MatchString(b) {
|
||||
t.Errorf("read as an input item refusal: %s", b)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// cyberestro's compaction: the summary request of a subagent's
|
||||
// conversation, refused for its agent_message in qwen's words, is asked
|
||||
// again with the conversation as text, which the server takes, and the
|
||||
// subagent's task is in it.
|
||||
func TestCodexCompactQwenInputItemAsksAgainAsText(t *testing.T) {
|
||||
f := &fake{t: t}
|
||||
f.refuse = func(b []byte) (int, string) {
|
||||
f.reply = wholeSummary(provider.Responses)
|
||||
var q struct {
|
||||
Input []struct {
|
||||
Type string `json:"type"`
|
||||
} `json:"input"`
|
||||
}
|
||||
json.Unmarshal(b, &q)
|
||||
for _, it := range q.Input {
|
||||
if !basicItem(it.Type) {
|
||||
return 400, qwenInputRefusal(it.Type)
|
||||
}
|
||||
}
|
||||
return 0, ""
|
||||
}
|
||||
setup(t, provider.Responses, f)
|
||||
code, body := codexPost(t, compactSubagentRequest)
|
||||
if code != 200 {
|
||||
t.Fatalf("%d %s", code, body)
|
||||
}
|
||||
if got := compactedText(t, body); got != "SUMMARY" {
|
||||
t.Fatalf("summary %q, want the model's", got)
|
||||
}
|
||||
if !strings.Contains(string(f.got), "Compare Vault secret rotation") {
|
||||
t.Errorf("the summary was asked without the task: %s", f.got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
)
|
||||
|
||||
// A Responses API that knows OpenAI's first input items alone — messages,
|
||||
// function calls, their outputs and reasoning — turns away a request
|
||||
// carrying any other: a local Qwen server answers a Codex subagent's turn
|
||||
// 400 "Unsupported input item: agent_message" (cyberestro on X), the item
|
||||
// MultiAgentV2 hands a subagent its task in, and Command Code's answers
|
||||
// "unsupported_input_item" (#5181, #5259). A relay sends Codex's items as
|
||||
// they came, so every such turn failed. The request is then translated
|
||||
// on the same API, which reads an agent_message as the user's turn, a
|
||||
// custom tool call as a function call, and leaves out what has no
|
||||
// counterpart; and so from then on for that model, as a custom tool
|
||||
// turned away is (custom_tool.go). The words are inputKindWords, which
|
||||
// the compaction's summary ask reads too (inputKindRefused): that ask is
|
||||
// left to its own way on, the conversation as text (inCompaction).
|
||||
|
||||
// inputKindsRefused is how unfit remembers model turning away input
|
||||
// items other than the first ones.
|
||||
func inputKindsRefused(model string) string { return "input kinds\x00" + model }
|
||||
|
||||
// hasOtherItem reports whether a Responses body's input carries an item
|
||||
// other than a message, a function call, its output or reasoning.
|
||||
func hasOtherItem(body []byte) bool {
|
||||
if !bodyHas(body, `"input"`) {
|
||||
return false
|
||||
}
|
||||
var q struct {
|
||||
Input json.RawMessage `json:"input"`
|
||||
}
|
||||
if json.Unmarshal(body, &q) != nil {
|
||||
return false
|
||||
}
|
||||
var items []struct {
|
||||
Type string `json:"type"`
|
||||
}
|
||||
if json.Unmarshal(q.Input, &items) != nil {
|
||||
return false
|
||||
}
|
||||
for _, it := range items {
|
||||
switch it.Type {
|
||||
case "", "message", "function_call", "function_call_output", "reasoning":
|
||||
default:
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
Reference in New Issue
Block a user