gateway: a Codex conversation moved from Muse Spark to GPT on Copilot is answered, not refused over Muse's "rs_…:rs_…" item ids (echo_ts)
echo_ts (Discord) switched a Codex conversation from Muse Spark (OpenCode)
to gpt-6.1 on GitHub Copilot and every turn failed:
Copilot: Invalid 'input[1].id': 'rs_6aca2fc7533c979d5f0e4f7a:rs_01a125caa544754e9a3c70080100b009'.
Expected an ID that contains letters, numbers, underscores, or dashes,
but this value contained additional characters.
Cause: magpie does not build that id. Muse's upstream hands Codex reasoning
items whose id is two ids joined with a colon; Codex sends every earlier
item back on each turn, and magpie relayed them to the new upstream as they
were. OpenAI checks every input item id against [A-Za-z0-9_-], and Copilot
(and the ChatGPT backend, Azure, relays in front of OpenAI) pass that 400 on.
The existing foreign-seal retry did not fire, because the refusal is about
the id, not the encrypted_content.
Fix (plainItemIDs, codex_backend.go):
- reasoning whose id has another character is dropped: an upstream that
checks ids never minted it, so its encrypted_content is another vendor's,
which it couldn't read either;
- any other item (message, function_call, custom/tool_search call) keeps
its content, its id with each other character as "_"; call_id is not
touched, so outputs stay paired.
Applied up front to OpenAI's API, Azure, the ChatGPT backend (Codex
sign-in path and Codex's own models' passthrough) and Copilot; any other
Responses upstream that refuses with OpenAI's id message is asked once more
with plain ids and remembered (itemIDsRefused, per model). OpenCode itself
still gets Muse's items byte for byte, so Muse can read its own reasoning.
Siblings checked: translated Chat and Messages upstreams never get item ids
(probe: only call_id goes, as tool_call_id / tool_use id), so they are not
affected by this; tool_use ids on Messages are a separate commit.
Tests (internal/gateway/item_ids_test.go), fixtures built from echo_ts's
literal id and error text:
- TestCopilotTakesAnotherVendorsItemIDs (copilot/gpt-6.1 via /responses)
- TestRelayRefusingItemIDsAskedAgain (unknown relay: 2 asks, then 1)
- TestMuseKeepsItsOwnItemIDs (OpenCode gets them as sent)
- TestCodexOwnModelTakesAnotherVendorsItemIDs (ChatGPT backend passthrough)
Broken by hand: old code -> Copilot/relay/native red with the reporter's
400; no up-front pass -> "asked Copilot 2 times"; no retry -> relay red;
no native pass -> native red; reasoning kept with a rewritten id -> all
three red ("Muse's reasoning sent").
Run: go test -tags nogui ./... (sandbox HOME, pinned caches), gofmt -l,
go vet + GOOS=linux / GOOS=windows go vet -tags nogui ./internal/gateway/.
Not run: a real Muse Spark reply (OpenCode Go refuses this account: the
model trains on request data and the workspace hasn't allowed it), nor a
real Copilot request.
This commit is contained in:
@@ -121,7 +121,8 @@ func (s *Server) codexBackend(w http.ResponseWriter, r *http.Request) {
|
||||
s.serveAgent(w, r, provider.Responses, body)
|
||||
return
|
||||
}
|
||||
body = boundCallIDs(callItemIDs(body))
|
||||
// the ChatGPT backend checks every item id as OpenAI does
|
||||
body = plainItemIDs(boundCallIDs(callItemIDs(body)))
|
||||
if rest == "/responses/compact" {
|
||||
// a key held to some accounts (#905) may not spend the sign-in
|
||||
// compaction still relays on: refused as its turns are (#967),
|
||||
@@ -1407,6 +1408,81 @@ func callItemIDs(body []byte) []byte {
|
||||
return nb
|
||||
}
|
||||
|
||||
// itemIDRefusal is OpenAI's refusal of an input item whose id has a
|
||||
// character other than [A-Za-z0-9_-], which Copilot passes on as it is
|
||||
// (echo_ts, Codex moved from Muse Spark on OpenCode to GPT on Copilot):
|
||||
// "Invalid 'input[1].id': 'rs_6aca2fc7533c979d5f0e4f7a:rs_01a125caa544754e9a3c70080100b009'.
|
||||
// Expected an ID that contains letters, numbers, underscores, or dashes,
|
||||
// but this value contained additional characters."
|
||||
var itemIDRefusal = regexp.MustCompile(`(?s)Invalid 'input\[\d+\]\.id'.{0,1000}?Expected an ID that contains letters, numbers, underscores, or dashes`)
|
||||
|
||||
// itemIDsRefused is how unfit remembers a provider turning away, for
|
||||
// model, an input item id with another character in it (plainItemIDs).
|
||||
func itemIDsRefused(model string) string { return "item ids\x00" + model }
|
||||
|
||||
// validatesItemIDs reports whether p checks a Responses input item's id
|
||||
// as OpenAI does, without having to be told by a refusal: OpenAI's API,
|
||||
// Azure OpenAI's, the ChatGPT backend behind a Codex sign-in, and Copilot's
|
||||
// /responses in front of them.
|
||||
func validatesItemIDs(p provider.Provider) bool {
|
||||
return strings.HasSuffix(p.Host(), "openai.com") || p.IsAzure() ||
|
||||
p.Account != nil && (p.Account.Agent == "codex" || p.Account.Agent == "copilot")
|
||||
}
|
||||
|
||||
// plainItemIDs is a Responses request whose input items' ids are of
|
||||
// [A-Za-z0-9_-] only, as OpenAI takes them, and the rest of the request
|
||||
// byte for byte. Another vendor's reply can hand the agent an item whose
|
||||
// id has more in it — Muse Spark on OpenCode's reasoning id is two joined
|
||||
// with a colon ("rs_6aca…:rs_01a1…") — and the agent sends it back on
|
||||
// every later turn, after a switch too, where OpenAI and Copilot turn the
|
||||
// whole request away over it (echo_ts). Such reasoning goes: an upstream
|
||||
// that checks ids never made it, so its encrypted_content is another
|
||||
// vendor's, which it couldn't read either. Any other item (a message, a
|
||||
// call) keeps what it says, its id with each other character as "_"; a
|
||||
// call's call_id, which its output names it by, stays as it was.
|
||||
func plainItemIDs(body []byte) []byte {
|
||||
if !bytes.Contains(body, []byte(`"id"`)) {
|
||||
return body
|
||||
}
|
||||
var q map[string]json.RawMessage
|
||||
if json.Unmarshal(body, &q) != nil {
|
||||
return body
|
||||
}
|
||||
var items []json.RawMessage
|
||||
if json.Unmarshal(q["input"], &items) != nil {
|
||||
return body
|
||||
}
|
||||
changed := false
|
||||
kept := items[:0:0]
|
||||
for _, raw := range items {
|
||||
var it map[string]json.RawMessage
|
||||
var typ, id string
|
||||
if json.Unmarshal(raw, &it) != nil || json.Unmarshal(it["id"], &id) != nil || id == "" || safeIDChars.MatchString(id) {
|
||||
kept = append(kept, raw)
|
||||
continue
|
||||
}
|
||||
changed = true
|
||||
if json.Unmarshal(it["type"], &typ) == nil && typ == "reasoning" {
|
||||
continue
|
||||
}
|
||||
it["id"], _ = json.Marshal(unsafeToolID.ReplaceAllString(id, "_"))
|
||||
b, err := marshalPlain(it)
|
||||
if err != nil {
|
||||
return body
|
||||
}
|
||||
kept = append(kept, b)
|
||||
}
|
||||
if !changed {
|
||||
return body
|
||||
}
|
||||
q["input"], _ = marshalPlain(kept)
|
||||
nb, err := marshalPlain(q)
|
||||
if err != nil {
|
||||
return body
|
||||
}
|
||||
return nb
|
||||
}
|
||||
|
||||
// longCallID finds a call_id longer than the ChatGPT backend takes.
|
||||
var longCallID = regexp.MustCompile(`"call_id"\s*:\s*"[^"]{65,}"`)
|
||||
|
||||
|
||||
@@ -3192,6 +3192,12 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
|
||||
// Relays enforce OpenAI's item ID prefixes too, including during
|
||||
// compaction. call_id stays unchanged so tool outputs remain paired.
|
||||
body = callItemIDs(body)
|
||||
// and an item id with a character OpenAI's don't have, another
|
||||
// vendor's (Muse Spark's "rs_…:rs_…"), to an upstream that checks
|
||||
// them (echo_ts)
|
||||
if validatesItemIDs(p) || !s.fits(p.ID, itemIDsRefused(model), proto) {
|
||||
body = plainItemIDs(body)
|
||||
}
|
||||
// xAI's API turns away a tool_choice with no tools beside it ("A
|
||||
// tool_choice was set on the request but no tools were specified"),
|
||||
// and Copilot's /responses, in front of it for Grok, with a bare
|
||||
@@ -3376,6 +3382,20 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
|
||||
continue
|
||||
}
|
||||
}
|
||||
if len(fs) == 0 && len(ms) == 0 && proto == provider.Responses && itemIDRefusal.Match(b) {
|
||||
// and an input item's id with a character OpenAI's don't
|
||||
// have, which a relay in front of OpenAI turns away as it
|
||||
// does (echo_ts): asked once more with ids it takes, and so
|
||||
// from then on
|
||||
if nb := plainItemIDs(body); !bytes.Equal(nb, body) {
|
||||
refused = append(refused, itemIDsRefused(model))
|
||||
body = nb
|
||||
if res, err = s.forward(r.Context(), p, proto, path, p.Prepare(body), r.Header); err != nil {
|
||||
return writeError(w, proto, 502, p.Name+": "+err.Error()), err.Error(), true
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
if len(fs) == 0 && len(ms) == 0 {
|
||||
// and a bare 400 over Codex's image tool, which a vendor
|
||||
// that knows no namespaces gives (#949): asked once more
|
||||
|
||||
@@ -0,0 +1,219 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// museReasoningID is the reasoning item id Muse Spark on OpenCode handed
|
||||
// Codex, as echo_ts's error quotes it: two ids joined with a colon.
|
||||
const museReasoningID = "rs_6aca2fc7533c979d5f0e4f7a:rs_01a125caa544754e9a3c70080100b009"
|
||||
|
||||
// museConversation is echo_ts's conversation after the switch: a user
|
||||
// turn, Muse's reasoning at input[1] with its id and its sealed content,
|
||||
// a call Muse made (its item id joined the same way) and its output, and
|
||||
// Muse's answer.
|
||||
const museConversation = `{"type":"message","role":"user","content":[{"type":"input_text","text":"fix the login bug"}]},
|
||||
{"type":"reasoning","id":"` + museReasoningID + `","summary":[],"encrypted_content":"muse-sealed"},
|
||||
{"type":"function_call","id":"fc_6aca2fc7533c979d5f0e4f7b:fc_01a125caa544754e9a3c70080100b00a","call_id":"call_muse_1","name":"shell","arguments":"{\"cmd\":\"ls\"}"},
|
||||
{"type":"function_call_output","call_id":"call_muse_1","output":"main.go"},
|
||||
{"type":"message","id":"msg_6aca2fc7533c979d5f0e4f7c:msg_01a125caa544754e9a3c70080100b00b","role":"assistant","content":[{"type":"output_text","text":"I fixed main.go"}]}`
|
||||
|
||||
// openaiItemID is the id OpenAI takes on an input item.
|
||||
var openaiItemID = regexp.MustCompile(`^[A-Za-z0-9_-]+$`)
|
||||
|
||||
// idChecker plays OpenAI's /responses as Copilot passes it on: an input
|
||||
// item whose id has another character is refused with OpenAI's 400, word
|
||||
// for word as echo_ts got it (Copilot's name is magpie's, before it).
|
||||
// With check off it takes any id, as OpenCode does its own.
|
||||
type idChecker struct {
|
||||
mu sync.Mutex
|
||||
check bool
|
||||
inputs [][]map[string]any
|
||||
}
|
||||
|
||||
func (u *idChecker) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
var q struct {
|
||||
Input []map[string]any `json:"input"`
|
||||
}
|
||||
json.Unmarshal(body, &q)
|
||||
u.mu.Lock()
|
||||
u.inputs = append(u.inputs, q.Input)
|
||||
u.mu.Unlock()
|
||||
for i, it := range q.Input {
|
||||
id, ok := it["id"].(string)
|
||||
if u.check && ok && !openaiItemID.MatchString(id) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
io.WriteString(w, `{"error":{"message":"Invalid 'input[`+mustString(int64(i))+`].id': '`+id+`'. Expected an ID that contains letters, numbers, underscores, or dashes, but this value contained additional characters.","type":"invalid_request_error","param":"input[`+mustString(int64(i))+`].id","code":"invalid_value"}}`)
|
||||
return
|
||||
}
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
io.WriteString(w, sse(
|
||||
`data: {"type":"response.created","response":{"id":"resp_1","status":"in_progress"}}`,
|
||||
`data: {"type":"response.output_item.done","output_index":0,"item":{"type":"message","id":"msg_1","role":"assistant","content":[{"type":"output_text","text":"DONE"}]}}`,
|
||||
`data: {"type":"response.completed","response":{"id":"resp_1","status":"completed","output":[],"usage":{"input_tokens":5,"output_tokens":1}}}`))
|
||||
}
|
||||
|
||||
func (u *idChecker) asked() [][]map[string]any {
|
||||
u.mu.Lock()
|
||||
defer u.mu.Unlock()
|
||||
return append([][]map[string]any(nil), u.inputs...)
|
||||
}
|
||||
|
||||
// checkSent fails unless input is museConversation as an id checker takes
|
||||
// it: Muse's reasoning gone, every other item there with an id of
|
||||
// [A-Za-z0-9_-], and the call still paired with its output.
|
||||
func checkSent(t *testing.T, input []map[string]any) {
|
||||
t.Helper()
|
||||
var types []string
|
||||
for _, it := range input {
|
||||
types = append(types, it["type"].(string))
|
||||
if id, ok := it["id"].(string); ok && !openaiItemID.MatchString(id) {
|
||||
t.Errorf("item id %q sent", id)
|
||||
}
|
||||
if it["type"] == "reasoning" {
|
||||
t.Errorf("Muse's reasoning sent: %v", it)
|
||||
}
|
||||
}
|
||||
if got := strings.Join(types, ","); !strings.HasPrefix(got, "message,function_call,function_call_output,message") {
|
||||
t.Errorf("items sent: %s", got)
|
||||
}
|
||||
b, _ := json.Marshal(input)
|
||||
for _, want := range []string{`"fc_6aca2fc7533c979d5f0e4f7b_fc_01a125caa544754e9a3c70080100b00a"`, `"call_muse_1"`, "I fixed main.go", "fix the login bug"} {
|
||||
if !strings.Contains(string(b), want) {
|
||||
t.Errorf("input lacks %s: %s", want, b)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// echo_ts, in Codex: a conversation on Muse Spark (OpenCode), switched to
|
||||
// GPT on GitHub Copilot. Muse's items, ids joined with a colon, went to
|
||||
// Copilot as Codex sent them, and every turn was turned away "Invalid
|
||||
// 'input[1].id'". Copilot checks ids as OpenAI does, so they go as it
|
||||
// takes them from the first ask.
|
||||
func TestCopilotTakesAnotherVendorsItemIDs(t *testing.T) {
|
||||
fresh(t)
|
||||
cfg := os.Getenv("XDG_CONFIG_HOME")
|
||||
os.MkdirAll(filepath.Join(cfg, "github-copilot"), 0o755)
|
||||
os.WriteFile(filepath.Join(cfg, "github-copilot", "apps.json"), mustJSON(map[string]any{
|
||||
"github.com:Iv1.x": map[string]any{"user": "echo", "oauth_token": "gho_echo"},
|
||||
}), 0o600)
|
||||
up := &idChecker{check: true}
|
||||
api := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/models":
|
||||
io.WriteString(w, `{"data":[{"id":"gpt-6.1","name":"GPT-6.1","model_picker_enabled":true,"policy":{"state":"enabled"},"supported_endpoints":["/responses"],"capabilities":{"type":"chat","supports":{"reasoning_effort":["low","medium","high"]}}}]}`)
|
||||
case "/responses":
|
||||
up.ServeHTTP(w, r)
|
||||
default:
|
||||
w.WriteHeader(404)
|
||||
}
|
||||
}))
|
||||
defer api.Close()
|
||||
gh := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.HasSuffix(r.URL.Path, "/token") {
|
||||
json.NewEncoder(w).Encode(map[string]any{"token": "sess", "expires_at": time.Now().Add(time.Hour).Unix(), "endpoints": map[string]string{"api": api.URL}})
|
||||
return
|
||||
}
|
||||
io.WriteString(w, `{"copilot_plan":"individual"}`)
|
||||
}))
|
||||
defer gh.Close()
|
||||
oldTok, oldUser := provider.CopilotTokenURL, provider.CopilotUserURL
|
||||
provider.CopilotTokenURL, provider.CopilotUserURL = gh.URL+"/token", gh.URL+"/user"
|
||||
defer func() { provider.CopilotTokenURL, provider.CopilotUserURL = oldTok, oldUser }()
|
||||
|
||||
s := New()
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest("POST", "/v1/responses", strings.NewReader(`{"model":"copilot/gpt-6.1","stream":true,"store":false,"include":["reasoning.encrypted_content"],
|
||||
"input":[`+museConversation+`,{"type":"message","role":"user","content":[{"type":"input_text","text":"now add a test"}]}]}`))
|
||||
s.Handler().ServeHTTP(rec, req)
|
||||
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "DONE") {
|
||||
t.Fatalf("%d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
asked := up.asked()
|
||||
if len(asked) != 1 {
|
||||
t.Fatalf("asked Copilot %d times", len(asked))
|
||||
}
|
||||
checkSent(t, asked[0])
|
||||
}
|
||||
|
||||
// A relay in front of OpenAI, which magpie can't tell from any other
|
||||
// upstream, refuses the ids as OpenAI does: asked once more with ids it
|
||||
// takes, and from then on asked that way at once.
|
||||
func TestRelayRefusingItemIDsAskedAgain(t *testing.T) {
|
||||
fresh(t)
|
||||
up := &idChecker{check: true}
|
||||
srv := httptest.NewServer(up)
|
||||
t.Cleanup(srv.Close)
|
||||
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Key: "k", Models: []string{"gpt-6.1"}, Responses: srv.URL + "/v1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
s := New()
|
||||
for turn := range 2 {
|
||||
rec := codexPostTo(s, `{"model":"relay/gpt-6.1","stream":true,"store":false,"input":[`+museConversation+`]}`)
|
||||
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "DONE") {
|
||||
t.Fatalf("turn %d: %d %s", turn, rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
asked := up.asked()
|
||||
if len(asked) != 3 {
|
||||
t.Fatalf("asked the relay %d times, want 2 for the first turn and 1 for the second", len(asked))
|
||||
}
|
||||
checkSent(t, asked[1])
|
||||
checkSent(t, asked[2])
|
||||
}
|
||||
|
||||
// OpenCode, where Muse made them, gets Muse's items as Codex sent them:
|
||||
// its reasoning, id and seal, is its own to read back.
|
||||
func TestMuseKeepsItsOwnItemIDs(t *testing.T) {
|
||||
fresh(t)
|
||||
up := &idChecker{}
|
||||
srv := httptest.NewServer(up)
|
||||
t.Cleanup(srv.Close)
|
||||
if err := provider.Save(provider.Provider{ID: "zen", Name: "OpenCode", Key: "k", Models: []string{"muse-spark-1.3-contributor"}, Responses: srv.URL + "/v1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := codexPostTo(New(), `{"model":"zen/muse-spark-1.3-contributor","stream":true,"store":false,"input":[`+museConversation+`]}`)
|
||||
if rec.Code != 200 {
|
||||
t.Fatalf("%d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
asked := up.asked()
|
||||
if len(asked) != 1 {
|
||||
t.Fatalf("asked %d times", len(asked))
|
||||
}
|
||||
b, _ := json.Marshal(asked[0])
|
||||
if !strings.Contains(string(b), `"`+museReasoningID+`"`) || !strings.Contains(string(b), "muse-sealed") {
|
||||
t.Errorf("Muse's reasoning not sent as it was: %s", b)
|
||||
}
|
||||
}
|
||||
|
||||
// Back on one of Codex's own models, on the ChatGPT backend, which checks
|
||||
// ids as OpenAI does.
|
||||
func TestCodexOwnModelTakesAnotherVendorsItemIDs(t *testing.T) {
|
||||
setup(t, provider.Chat, &fake{t: t})
|
||||
up := &idChecker{check: true}
|
||||
chatgpt(t, up.ServeHTTP)
|
||||
code, body := codexPost(t, `{"model":"gpt-6-luna","stream":true,"store":false,"input":[`+museConversation+`]}`)
|
||||
if code != 200 || !strings.Contains(body, "DONE") {
|
||||
t.Fatalf("%d %s", code, body)
|
||||
}
|
||||
asked := up.asked()
|
||||
if len(asked) != 1 {
|
||||
t.Fatalf("asked the backend %d times", len(asked))
|
||||
}
|
||||
checkSent(t, asked[0])
|
||||
}
|
||||
Reference in New Issue
Block a user