From 67056512e0d47cfddc79b605a271e448de7a893a Mon Sep 17 00:00:00 2001 From: yetone Date: Sat, 26 Sep 2026 13:59:01 +0800 Subject: [PATCH] =?UTF-8?q?codex:=20back=20on=20one=20of=20Codex's=20own?= =?UTF-8?q?=20models=20after=20another=20vendor's,=20the=20conversation=20?= =?UTF-8?q?goes=20on=20=E2=80=94=20another=20vendor's=20reasoning=20(an=20?= =?UTF-8?q?rs=5F=E2=80=A6=20id=20with=20nothing=20sealed=20in=20it,=20as?= =?UTF-8?q?=20Volcengine=20writes=20it)=20went=20on=20to=20OpenAI,=20which?= =?UTF-8?q?=20keeps=20nothing=20(store=20is=20false),=20looked=20the=20id?= =?UTF-8?q?=20up=20and=20answered=20404=20"Item=20with=20id=20'rs=5F?= =?UTF-8?q?=E2=80=A6'=20not=20found"=20on=20every=20turn=20and=20compactio?= =?UTF-8?q?n;=20it=20now=20stays=20out,=20and=20an=20item=20OpenAI=20still?= =?UTF-8?q?=20refuses=20(sealed=20content=20it=20can't=20verify,=20an=20id?= =?UTF-8?q?=20it=20doesn't=20have)=20is=20taken=20out=20and=20the=20rest?= =?UTF-8?q?=20asked=20again=20instead=20of=20the=20session=20stuck=20on=20?= =?UTF-8?q?it?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/gateway/codex_backend.go | 98 ++++++++++++++++++++++---- internal/gateway/codex_backend_test.go | 56 +++++++++++++++ 2 files changed, 142 insertions(+), 12 deletions(-) diff --git a/internal/gateway/codex_backend.go b/internal/gateway/codex_backend.go index 2cec13a46..095f39365 100644 --- a/internal/gateway/codex_backend.go +++ b/internal/gateway/codex_backend.go @@ -8,6 +8,7 @@ import ( "fmt" "io" "net/http" + "regexp" "strings" "time" @@ -132,18 +133,35 @@ func (s *Server) codexUpstream(w http.ResponseWriter, r *http.Request, rest stri if r.URL.RawQuery != "" { u += "?" + r.URL.RawQuery } - req, err := http.NewRequestWithContext(r.Context(), r.Method, u, bytes.NewReader(body)) - if err != nil { - writeError(w, provider.Responses, 502, err.Error()) - return - } - copyHeaders(req.Header, r.Header) - // left to the transport, the reply comes back plain for the usage in it - req.Header.Del("Accept-Encoding") - res, err := s.client.Do(req) - if err != nil { - writeError(w, provider.Responses, 502, "OpenAI: "+err.Error()) - return + var res *http.Response + for tries := 0; ; tries++ { + req, err := http.NewRequestWithContext(r.Context(), r.Method, u, bytes.NewReader(body)) + if err != nil { + writeError(w, provider.Responses, 502, err.Error()) + return + } + copyHeaders(req.Header, r.Header) + // left to the transport, the reply comes back plain for the usage in it + req.Header.Del("Accept-Encoding") + if res, err = s.client.Do(req); err != nil { + writeError(w, provider.Responses, 502, "OpenAI: "+err.Error()) + return + } + if rest != "/responses" || tries >= 3 || (res.StatusCode != 400 && res.StatusCode != 404) { + break + } + // an item OpenAI can't take — sealed by another account, or + // another vendor's that it looks up and doesn't have — is taken + // out and the rest asked again, rather than the conversation + // stuck on it for good + msg, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) + res.Body.Close() + res.Body = io.NopCloser(bytes.NewReader(msg)) + b, ok := withoutUnreadable(body, msg) + if !ok { + break + } + body = b } defer res.Body.Close() for k, vs := range res.Header { @@ -198,6 +216,55 @@ func (s *Server) codexUpstream(w http.ResponseWriter, r *http.Request, rest stri Reasoning: uu.Reasoning, Millis: call.Millis, Status: call.Status}) } +// unreadableItem is the item OpenAI's refusal names: sealed content it +// can't verify, or an id it doesn't have ("Item with id 'rs_…' not found"). +var unreadableItem = regexp.MustCompile(`(?i)(?:encrypted content for item|item with id) '?([A-Za-z]+_[A-Za-z0-9_-]+)'?`) + +// withoutUnreadable is body without what OpenAI's refusal msg says it +// can't read: the item it names, or the reasoning another account sealed. +func withoutUnreadable(body, msg []byte) ([]byte, bool) { + if !foreignReasoning.Match(msg) && !bytes.Contains(bytes.ToLower(msg), []byte("not found")) { + return nil, false + } + if m := unreadableItem.FindSubmatch(msg); m != nil { + if b, ok := withoutItem(body, string(m[1])); ok { + return b, true + } + } + if foreignReasoning.Match(msg) { + return withoutReasoning(body) + } + return nil, false +} + +// withoutItem is a Responses request without the input item of this id. +func withoutItem(body []byte, id string) ([]byte, bool) { + var q map[string]json.RawMessage + if json.Unmarshal(body, &q) != nil { + return nil, false + } + var items []json.RawMessage + if json.Unmarshal(q["input"], &items) != nil { + return nil, false + } + kept := items[:0:0] + for _, it := range items { + var t struct { + ID string `json:"id"` + } + if json.Unmarshal(it, &t) == nil && t.ID == id { + continue + } + kept = append(kept, it) + } + if len(kept) == len(items) { + return nil, false + } + q["input"], _ = json.Marshal(kept) + b, err := json.Marshal(q) + return b, err == nil +} + // apiKey reports whether Codex signed in with an API key rather than a // ChatGPT account. func apiKey(h http.Header) bool { @@ -315,6 +382,13 @@ func codexInput(body []byte, magpieModel bool) (_ []byte, compact bool) { continue } } + // Nor reasoning with nothing sealed in it — another vendor's, + // only an id (rs_…): OpenAI, which keeps nothing (store is + // false), looks the id up and answers 404 "Item … not found". + if enc, _ := it["encrypted_content"].(string); enc == "" { + changed = true + continue + } } out = append(out, it) default: diff --git a/internal/gateway/codex_backend_test.go b/internal/gateway/codex_backend_test.go index 51341e17e..7a2509dfa 100644 --- a/internal/gateway/codex_backend_test.go +++ b/internal/gateway/codex_backend_test.go @@ -108,6 +108,62 @@ func TestCodexOwnModelOmitsNonemptyReasoning(t *testing.T) { } } +// Back on one of Codex's own models after another vendor's: its reasoning, +// an id with nothing sealed in it, would be looked up by OpenAI and not +// found, so it doesn't go. An item OpenAI still refuses is taken out and +// the rest asked again. +func TestCodexOwnModelAfterAnotherVendor(t *testing.T) { + setup(t, provider.Chat, &fake{t: t}) + var got [][]byte + chatgpt(t, func(w http.ResponseWriter, r *http.Request) { + b, _ := io.ReadAll(r.Body) + got = append(got, b) + if bytes.Contains(b, []byte(`cmp_0217`)) { + w.WriteHeader(400) + io.WriteString(w, `{"error":{"message":"The encrypted content for item cmp_0217abc could not be verified. Reason: Encrypted content could not be decrypted or parsed.","code":"invalid_encrypted_content"}}`) + return + } + if bytes.Contains(b, []byte(`rs_other`)) { + w.WriteHeader(404) + io.WriteString(w, `{"error":{"message":"Item with id 'rs_other' not found. Items are not persisted when `+"`store`"+` is set to false."}}`) + return + } + io.WriteString(w, sse(`data: {"type":"response.completed","response":{"id":"r1"}}`)) + }) + code, body := codexPost(t, `{"model":"gpt-6-luna","stream":true,"store":false,"input":[ + {"type":"reasoning","id":"rs_0217903544582750000","summary":[{"type":"summary_text","text":"volc thought"}],"encrypted_content":null}, + {"type":"reasoning","id":"rs_other","summary":[],"encrypted_content":"sealed-elsewhere"}, + {"type":"compaction","id":"cmp_0217abc","encrypted_content":"not-openai"}, + {"type":"reasoning","id":"rs_own","summary":[],"encrypted_content":"openai-own"}, + {"type":"message","role":"user","content":[{"type":"input_text","text":"go on"}]}]}`) + if code != 200 || !strings.Contains(body, `response.completed`) { + t.Fatalf("%d %s", code, body) + } + if len(got) != 3 || bytes.Contains(got[0], []byte("volc thought")) { + t.Fatalf("%d asks, first: %s", len(got), got[0]) + } + last := string(got[2]) + if strings.Contains(last, "cmp_0217abc") || strings.Contains(last, "rs_other") || + !strings.Contains(last, "openai-own") || !strings.Contains(last, "go on") { + t.Errorf("last ask: %s", last) + } +} + +// A refusal that names nothing magpie can take out goes to Codex as it came. +func TestCodexOwnModelRefusalPassesThrough(t *testing.T) { + setup(t, provider.Chat, &fake{t: t}) + asks := 0 + chatgpt(t, func(w http.ResponseWriter, r *http.Request) { + asks++ + w.WriteHeader(404) + io.WriteString(w, `{"error":{"message":"The model 'gpt-x' does not exist"}}`) + }) + code, body := codexPost(t, `{"model":"gpt-x","input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"hi"}]}]}`) + if code != 404 || asks != 1 || !strings.Contains(body, "does not exist") { + t.Errorf("%d asks=%d %s", code, asks, body) + } +} + func TestCodexMagpieModelKeepsReasoningInput(t *testing.T) { body := `{"model":"fake/m1","input":[{"type":"reasoning","content":[{"type":"reasoning_text","text":"thought"}],"encrypted_content":"foreign-token"}]}` got, compact := codexInput([]byte(body), true)