gateway: a conversation on a new account leaves out the old one's seals (#3887)

hheei (#3887): a Codex conversation with a web search in it (OpenAI's
own web_search, a web_search_call in its history) failed on every turn
with "HTTP 400: Codex: Encrypted content could not be decrypted or
parsed. (code: invalid_encrypted_content)" once magpie had moved it to
another ChatGPT account of the same routing group: after its affinity
went cold ("why": "cold", over two hours on), or after the account it
was on was used up or rate limited.

What an account's turn wrote comes back sealed for that account
(encrypted_content): its reasoning, a web search, and with Codex's
output token replay on (codex-rs core/src/client.rs: only for a provider
named "OpenAI", which Codex signed in reaches magpie as) each message
and call. Codex hands it all back on every turn, and between ChatGPT
accounts, or a ChatGPT account and an OpenAI API key, magpie sends it as
it came (forVendor, 2a19245c). The account asked next can't read the
first's seals and says so. serve asked again without the reasoning only
(withoutReasoning), was refused again over the web search, had no
compaction to leave out, and passed the 400 on. What it remembered as
refused for the conversation's later turns (refusedSeals) was reasoning
and compactions only, so each later turn went the same way. The relay of
Codex's own sign-in (withoutUnreadable) left only the reasoning out as
well.

Now such a refusal is asked again without every seal but a compaction's
(withoutSeals): reasoning goes whole, as before, and any other item
keeps all but its encrypted_content (withoutItemSeal, the rest of it
byte for byte). refused records what was taken out for the key or
account that refused, and withoutRefused leaves it out of the
conversation's later requests there up front, reasoning whole and the
rest by its seal alone. What that one sealed itself still goes along,
and a request on the account that sealed what it carries goes as it
came, so a turn that doesn't move keeps OpenAI's cache and replay as
before. A compaction keeps its own step (withoutCompaction after a
second refusal, unless native compaction is on). The relay asks again
the same way after its 400. The retry is serve's, so it holds whatever
moved the conversation: an account used up, rate limited or resting, the
next member of a group, routing's own pick once the affinity went cold;
on the backend path (one of Codex's own models, signed in) and on
/v1/responses (the codex provider's model, a group of it) alike.
gateway-routing.md says so.

A refusal doesn't say whose seal it couldn't read, so the account asked
loses its own seals from an earlier stay in the conversation too, and
they are remembered as refused, as its reasoning already was.

Not changed, each as on main (#3934): a context_compaction
another account sealed stays in through both steps (keepsSeal has it,
compactionKinds doesn't); the relay keeps no record of what was refused,
so each later turn there is refused once and asked again, and a refusal
in its stream reaches Codex as it came; the relay's /responses/compact
isn't asked again; the Routing view still calls such a try "another
account's reasoning" (client.js and its translations).

What was run (tree 326b178e, on origin/main f8cd964a, go1.26.8,
linux/amd64, Linux 5.15), outside graftcp, umask 077:
- TestForeignSealedItemsMoveToAnotherAccount, new: a conversation
  holding acct-1's sealed reasoning, web search, call and answer moves
  to acct-2 as acct-1 answers 429 or response.failed
  rate_limit_exceeded, signed in, as codex/gpt-5.5 and as group/g,
  acct-2 refusing with a 400 or in its stream (12 cases). acct-2 is
  asked with every seal, refuses, is asked again bare and answers, and
  the next turn asks it bare with its own seals on: ok
- TestForeignSealedItemsAfterAColdSwitch, new: the same conversation
  moved back to acct-1 by its affinity gone cold (Why "cold"), 6 cases:
  ok
- TestForeignSealedItemsRelayedToAnotherSignIn, new: Codex's own sign-in
  relayed as acct-2, the history sealed by acct-1: ok
- TestSealsTakenOutLeaveTheRest, new: the exact bytes withoutSeals and
  withoutRefused leave (a seal first, in the middle and last in its
  item; compactions keeping theirs; reasoning alone taken as
  withoutKinds took it), and nothing taken out for another account or
  conversation: ok
- the three new end-to-end tests with affinity.go, gateway.go,
  codex_backend.go and routing.go as on main (swapped in through go test
  -overlay, the checkout left as committed; the unit test left out, as
  it calls withoutSeals): 21 of 21 red. The 400 cases: "moved on: 400
  {"error":{"code":"invalid_encrypted_content","message":"Codex:
  Encrypted content could not be decrypted or
  parsed.","param":null,"type":"invalid_request_error"}}", and "gone
  cold: 400" with the same; in the stream: "moved on: 200" and "gone
  cold: 200", the response.failed invalid_encrypted_content passed on to
  Codex; the relay: "400 {"error":{"message":"Encrypted content could
  not be decrypted or parsed.", ...
  "code":"invalid_encrypted_content"}}"
- broken by hand, one at a time, each swapped in the same way, beside
  the tests already there for foreign seals, compactions, reasoning and
  output replay (TestForeignSeal*, TestForeignCompaction*,
  TestForeignReasoning*, TestCodexOwnModelAfterAnotherVendor,
  TestCodexSpentMovesToGrokWithSealedReasoning, TestCodexOutputReplay*),
  all green under each but where named:
  - serve's retry taking the reasoning only (withoutKinds(body,
    "reasoning")): TestForeignSealedItemsMoveToAnotherAccount (12 of 12)
    and TestForeignSealedItemsAfterAColdSwitch (6 of 6) red, "moved on:
    400" and "gone cold: 400" with the error as on main
  - the relay's taking the reasoning only:
    TestForeignSealedItemsRelayedToAnotherSignIn red, "400
    {"error":{"message":"Encrypted content could not be decrypted or
    parsed.",...}}"
  - refused recording reasoning and compactions only (seals as on main):
    the same 18 cases and TestSealsTakenOutLeaveTheRest red, the next
    turn refused once more, "then asked [{"acct-2" "message user,
    web_search_call 上海天气 gAAAA-acct-1-w1, function_call c1
    gAAAA-acct-1-f1, ..."} {"acct-2" ...}]", and "next turn:" with the
    seals left on
  - withoutRefused taking out reasoning and compactions only: the same
    19 red, with the same lines
  - withoutRefused dropping each refused item whole: the same 19 red,
    "then asked [{"acct-2" "message user, message assistant, message
    user, message assistant, message user, reasoning gAAAA-acct-2-r3,
    ..."}]", the searches and calls gone
  - withoutItemSeal writing the item out again (marshalPlain):
    TestSealsTakenOutLeaveTheRest red, "got {...}" with the web search's
    keys sorted,
    {"action":{...},"id":"ws_1",...,"type":"web_search_call"}
  - withoutItemSeal without its keepsSeal check:
    TestSealsTakenOutLeaveTheRest and TestForeignCompactionToGrok red,
    "grok was sent [["compaction:sealed-by-openai-compaction"
    "reasoning:sealed-by-openai"] []]": the compaction lost its seal in
    the first step instead of going in its own
- the related tests (TestForeign*, TestCodexOwnModel*, TestCodexSpent*,
  output replay, the rewrite equivalence tests, TestAffinity*,
  TestNativeCompaction*, TestRemoteMagpie*, TestGatewayKey*, groups and
  Codex accounts): 257 passed with their subtests, none skipped (Bun
  1.4.2)
- go test -tags nogui -count=1 -timeout 45m ./internal/gateway (log
  kept), Bun 1.4.2: 5418 passed with their subtests, 3 skipped, and one
  red, TestPluginToldWhereTheAgentWorks (#3675): "not in one: the plugin
  was told "/tmp/TestPluginToldWhereTheAgentWorks191044475/005", git
  "yes"; want "/tmp/TestPluginToldWhereTheAgentWorks191044475/005",
  "no"". It is red the same alone, and with the four code files as on
  f8cd964a: this box has an empty /tmp/.git, and GitOnDisk counts a .git
  in any folder above.
- read against main's 7f0f71a0 (#2481) and fff05e55 (#2725), which
  change code beside this: 7f0f71a0 puts the route on two of the relay's
  record exits, which come after withoutUnreadable has chosen the body
  asked again; fff05e55 changes only whether Codex's compaction trigger
  is kept native (plannedCarrier), not serve's retry or the step it
  skips for a provider compacting natively (compactsNatively), so a
  trigger it now has magpie summarise goes through serve and the same
  retry. Neither changes what withoutSeals or withoutUnreadable do.
- go test -tags nogui -count=1 -timeout 45m ./... (log kept), Bun
  1.4.2: 69 packages ok and 7 red, none in what this changes; gateway's
  only red is TestPluginToldWhereTheAgentWorks (#3675), the new tests
  pass in it. The reds: agent TestInstalledVersion,
  TestCopilotFolderFromAnIDEPluginIsNotTheCLI,
  TestQoderSettingsFromAnIDEPluginIsNotTheCLI and
  TestOmpDetectedWithPiDir (#3141), the two Reasonix tests (#3641) and
  TestWSLColdPlaceOpensNothing (#3924); edit
  TestWriteAtomicReadOnlyHardLink and testenv TestProgram (umask 077,
  #3640); gui TestGatewayHeldByAContainer and
  TestGatewayFixQuitsOnlyAMagpie (#3649); provider
  TestCodexAppServersOnHome (#3906), then "close of synctest channel
  from outside bubble" (#3632); tui
  TestTUIFetchesSubscriptionModels/agent (#3919).
- gofmt -l clean. go vet -tags nogui for linux, windows and darwin, go
  build -tags nogui for linux and darwin, and go vet and go build for
  windows without the tag: exit 0 each. go vet and go build without the
  tag on linux: exit 1 (this box has no GTK or WebKitGTK dev packages).

Not tried: real ChatGPT or OpenAI accounts. Whether the ChatGPT backend
takes a web_search_call with neither its id (magpie's Codex account
route sends none, as on main) nor its seal; hheei's 200 was OpenAI's
Responses API with the id kept. Whether one account refuses another's
replayed message and call seals at all (the fake does; if it reads them,
they are still taken out on a hop, where the conversation's cache is
gone anyway). OpenAI refusing in the stream: the fake does, as xAI may;
hheei's refusal came as a 400. An OpenAI API key as the next member of a
group: forVendor keeps the seals for *openai.com only, so a fake on
127.0.0.1 can't stand in for it; it reaches the same retry in serve. Nor
magpie's summary of a Codex compaction after a move: codexCompact asks
through serve, so the same retry should apply, but no test drives it.

Ported onto origin/main 5ee5274bd from yinwu01/magpie 2d764b1c (posted
on #3887, sha256 d9185e84...). Conflicts resolved by hand: main had
since grown noteRefused (also used by reasoning_carry.go's
refuseCarried), so refused(key, who, sent, left) now hands it the seals
sent minus those left; foreignReasoning keeps main's broader pattern;
foreign_seal_test.go keeps main's TestForeignSealAzureSummary and
TestForeignSealGrokRelayCompactionBlob beside the four new tests; the
Affinity row and the new bullet in gateway-routing.md were merged into
main's text.

What was run for the port (mote, macOS, go1.26.8):
- go vet -tags nogui ./internal/gateway, and go test -tags nogui
  -count=1 -run 'TestForeign|TestSeals|TestCodexOutputReplay|
  TestCodexOwnModel|TestCodexSpent|TestRefused|TestReasoningCarr|
  TestWithout|TestNativeCompaction' ./internal/gateway: ok
- the three new end-to-end tests on 5ee5274bd (old code, the unit test
  left out as it calls withoutSeals): all red,
  TestForeignSealedItemsMoveToAnotherAccount and ...AfterAColdSwitch
  "moved on: 400 {...invalid_encrypted_content... Codex: Encrypted
  content could not be decrypted or parsed.}" and "gone cold: 400",
  ...RelayedToAnotherSignIn "400 {...Encrypted content could not be
  decrypted or parsed...}"

Batch run, at tree 104d75f0a (the twelve coffemon ports together, on
origin/main 7d022bdb6), mote, macOS, go1.26.8:
- go test -tags nogui -count=1 -timeout 45m on the packages the batch
  changes (agent, autostart, daemon, gateway, library, proc, provider,
  sessions, testenv, tui, gui): ok each.
- GUI, node --test with Playwright 1.62.0, Chromium and WebKit:
  library-*.test.cjs and i18n-keys.test.cjs, 1044 of 1044 pass.
- gofmt -l: nothing. go vet ./..., GOOS=linux go vet -tags nogui ./...,
  GOOS=windows go vet ./... and go build ./...: ok at cdd7c8e46, the same
  batch on origin/main 00098f12b one rebase before.
- The whole go test ./... at cdd7c8e46: 86 packages ok, one red,
  internal/cli TestEveryRouteHasACommandOrIsNamed (GET
  /api/context/reply has no command), red on main too (#5026).
- Linux (wsl-run, Ubuntu 24.04, at 339055896, the batch on f4c664a09):
  proc, autostart, testenv, tui ok; agent: only TestGrokInstalled red
  (#3548); #4033's proc.Look reds (Zed, Copilot, Qoder, Cursor, Omp)
  pass.
- Windows (win-run, Windows 11, at 339055896): proc, autostart, testenv,
  tui ok; library and agent red in the same tests as on origin/main
  f4c664a09 (#4115, #1827, #4786; #5068, #5069, #5070 filed now).
- Rebased onto origin/main fb1f4856a (three commits, no file in
  common with the batch) and run again at the pushed tree: gofmt -l
  nothing, go build ./... and go vet ./... ok; go test -tags nogui
  sessions, agent, autostart, tui, proc, testenv ok; i18n-keys and
  library-* 1044 of 1044 pass.
- Not run before the push: the whole GUI suite (a run at cdd7c8e46 was
  cut off at 1170 of ~1174 tests when mote rebooted; it runs again after
  the tag and any red is filed).
This commit is contained in:
JoeyWu-tech
2026-11-03 20:38:11 +08:00
committed by yetone
parent 62f612fd44
commit b59e4b747f
7 changed files with 492 additions and 47 deletions
File diff suppressed because one or more lines are too long
+89 -29
View File
@@ -1022,7 +1022,9 @@ func unanswered(key string, c candidate) {
// foreignReasoning is how a vendor refuses reasoning another account (or
// organization, or vendor) sealed: OpenAI's "The encrypted content for
// item rs_… could not be verified", invalid_encrypted_content; xAI's
// item rs_… could not be verified", invalid_encrypted_content, and for a
// web search another ChatGPT account ran "Encrypted content could not be
// decrypted or parsed." (#3887); xAI's
// (Grok's API and a SuperGrok account alike) "Could not decrypt the
// provided encrypted_content. Ensure the value is the unmodified
// encrypted_content from a previous response."; Azure's (through a relay
@@ -1037,12 +1039,13 @@ func unanswered(key string, c candidate) {
var foreignReasoning = regexp.MustCompile(`(?i)invalid_encrypted_content|invalid[ _]encrypted[ _](summary|content)|encrypted[ _]content.{0,80}could not be (verified|decrypted)|could not (decrypt|verify).{0,40}encrypted[ _]content|could not (decode|decrypt).{0,20}compaction[ _]blob`)
// refusedSeals remembers, per conversation and the key or account that
// refused it, the sealed reasoning another one wrote. Codex hands every
// earlier turn's reasoning back on each request, so once a conversation
// has moved, what was sealed before it moved is left out of its later
// requests there up front, rather than refused and asked again each turn.
// Reasoning the one it moved to sealed itself still goes along, for its
// cache and its train of thought.
// refused it, what another one sealed: its reasoning, and the sealed copy
// output token replay keeps of each message, call and web search (#3887).
// Codex hands every earlier turn's items back on each request, so once a
// conversation has moved, what was sealed before it moved is left out of
// its later requests there up front, rather than refused and asked again
// each turn. What the one it moved to sealed itself still goes along, for
// its cache and its train of thought.
var refusedSeals = struct {
sync.Mutex
m map[string]sealsRefused // scope|conversation|who → what it refused
@@ -1053,7 +1056,7 @@ type sealsRefused struct {
seals map[[sha256.Size]byte]bool
}
// sealedItem is what's read of an input item to tell sealed reasoning.
// sealedItem is what's read of an input item to tell what it has sealed.
type sealedItem struct {
Type string `json:"type"`
Enc string `json:"encrypted_content"`
@@ -1062,14 +1065,15 @@ type sealedItem struct {
// sealedKinds are the input items a vendor seals for itself: its
// reasoning, and the compaction a conversation's earlier turns were
// folded into (OpenAI's, when Codex compacts on its own models; magpie's
// own is text by the time a request is sent).
// own is text by the time a request is sent). Refused, they go whole;
// any other item loses its sealed copy alone (withoutItemSeal).
var sealedKinds = map[string]bool{"reasoning": true, "compaction": true, "compaction_summary": true}
var compactionKinds = []string{"compaction", "compaction_summary"}
// seals are the sealed reasoning and compactions (encrypted_content) in a
// Responses request's input, of these types.
func seals(body []byte, kinds ...string) [][sha256.Size]byte {
// seals are what is sealed (encrypted_content) in a Responses request's
// input, item by item.
func seals(body []byte) [][sha256.Size]byte {
var q struct {
Input []sealedItem `json:"input"`
}
@@ -1078,17 +1082,22 @@ func seals(body []byte, kinds ...string) [][sha256.Size]byte {
}
var out [][sha256.Size]byte
for _, it := range q.Input {
if slices.Contains(kinds, it.Type) && it.Enc != "" {
if it.Enc != "" {
out = append(out, sha256.Sum256([]byte(it.Enc)))
}
}
return out
}
// refused notes that who turned away the sealed items of these types in
// body, in the conversation key names.
func refused(key, who string, body []byte, kinds ...string) {
noteRefused(key, who, seals(body, kinds...))
// refused notes, in the conversation key names, that who turned away the
// seals taken out of sent, the request it refused, to make left, the one
// asked in its place.
func refused(key, who string, sent, left []byte) {
kept := map[[sha256.Size]byte]bool{}
for _, s := range seals(left) {
kept[s] = true
}
noteRefused(key, who, slices.DeleteFunc(seals(sent), func(s [sha256.Size]byte) bool { return kept[s] }))
}
// noteRefused notes that who turned away the sealed items of these hashes
@@ -1119,9 +1128,9 @@ func noteRefused(key, who string, ss [][sha256.Size]byte) {
}
}
// withoutRefused takes out of a Responses request the sealed reasoning
// and compactions who already refused in this conversation; the rest
// stays as it is.
// withoutRefused takes out of a Responses request what who already
// refused in this conversation: sealed reasoning and compactions whole,
// any other item's sealed copy alone; the rest stays as it is.
func withoutRefused(key, who string, body []byte) ([]byte, bool) {
k := key + "|" + who
refusedSeals.Lock()
@@ -1142,15 +1151,21 @@ func withoutRefused(key, who string, body []byte) ([]byte, bool) {
if !isList {
return nil, false
}
kept := items[:0:0]
kept, changed := items[:0:0], false
for _, it := range items {
var t sealedItem
if decodeJSONView(it, &t) == nil && sealedKinds[t.Type] && t.Enc != "" && r.seals[sha256.Sum256([]byte(t.Enc))] {
continue
if decodeJSONView(it, &t) == nil && t.Enc != "" && r.seals[sha256.Sum256([]byte(t.Enc))] {
if sealedKinds[t.Type] {
changed = true
continue
}
if b, ok := withoutItemSeal(it); ok {
it, changed = b, true
}
}
kept = append(kept, it)
}
if len(kept) == len(items) {
if !changed {
return nil, false
}
q["input"], _ = json.Marshal(kept)
@@ -1158,11 +1173,56 @@ func withoutRefused(key, who string, body []byte) ([]byte, bool) {
return b, err == nil
}
// withoutReasoning takes the sealed reasoning out of a Responses request's
// input — what another account wrote and this one can't read. What was
// said and done stays; only the model's private notes to itself go.
func withoutReasoning(body []byte) ([]byte, bool) {
return withoutKinds(body, "reasoning")
// withoutSeals takes out of a Responses request's input what is sealed,
// but a compaction, for one that can't read what another account sealed:
// the sealed reasoning, the model's private notes to itself, and the
// sealed copy output token replay keeps of each item answered, a message,
// a call or a web search (#3887, hheei: the reasoning alone went, and the
// web search another ChatGPT account ran was refused again). What was
// said and done stays.
func withoutSeals(body []byte) ([]byte, bool) {
var q map[string]json.RawMessage
if decodeJSONView(body, &q) != nil {
return nil, false
}
items, isList := inputList(q["input"])
if !isList {
return nil, false
}
kept, changed := items[:0:0], false
for _, it := range items {
var t struct {
Type string `json:"type"`
}
if decodeJSONView(it, &t) == nil && t.Type == "reasoning" {
changed = true
continue
}
if b, ok := withoutItemSeal(it); ok {
it, changed = b, true
}
kept = append(kept, it)
}
if !changed {
return nil, false
}
q["input"], _ = json.Marshal(kept)
b, err := marshalJSON(q)
return b, err == nil
}
// withoutItemSeal is an input item without its sealed copy
// (encrypted_content), every other byte as it came; false for one with
// nothing sealed, and for reasoning and a compaction (keepsSeal), whose
// seal is all there is of them.
func withoutItemSeal(it []byte) ([]byte, bool) {
if keepsSeal[string(memberOrNil(it, "type"))] {
return nil, false
}
if s, ok := stringBytes(memberOrNil(it, "encrypted_content")); !ok || len(s) == 0 {
return nil, false
}
return withoutTopMember(it, "encrypted_content"), true
}
// withoutCompaction takes out of a Responses request's input the sealed
+4 -3
View File
@@ -1754,8 +1754,9 @@ func codexRelayedAccount(base string, h http.Header, on *provider.Provider) (pro
var unreadableItem = regexp.MustCompile(`(?i)(?:encrypted content for item|item with id|referenced reasoning item) '?([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, the reasoning another account sealed, or
// a member of Codex's passthrough it doesn't know.
// can't read: the item it names, what another account sealed
// (withoutSeals: a web search's too, #3887), or a member of Codex's
// passthrough it doesn't know.
func withoutUnreadable(body, msg []byte) ([]byte, bool) {
if f, ok := refusedPassthrough(msg); ok {
// a member of Codex's passthrough the backend doesn't know yet
@@ -1771,7 +1772,7 @@ func withoutUnreadable(body, msg []byte) ([]byte, bool) {
}
}
if foreignReasoning.Match(msg) {
return withoutReasoning(body)
return withoutSeals(body)
}
return nil, false
}
+381
View File
@@ -503,3 +503,384 @@ func TestForeignSealGrokRelayCompactionBlob(t *testing.T) {
t.Fatalf("next turn sent %q, want one request without the seal", got)
}
}
// openaiUndecryptable is what OpenAI told hheei (#3887) of a web search
// another ChatGPT account ran, with code invalid_encrypted_content, and
// magpie passed on as "Codex: Encrypted content could not be decrypted or
// parsed.". It names no item.
const openaiUndecryptable = "Encrypted content could not be decrypted or parsed."
// accountSealer is the ChatGPT backend behind several of Codex's
// accounts, told apart by chatgpt-account-id. Each seals what it writes
// as "gAAAA-<account>-…" and reads no other account's seal: neither its
// sealed reasoning nor, with output token replay, the sealed copy of a
// message, a call or a web search. It refuses one sealed elsewhere as a
// 400, or in the stream after the backend's first events: reasoning as
// openaiUnverifiable, anything else as hheei was told. An account in out
// answers as that says instead.
type accountSealer struct {
stream bool
mu sync.Mutex
out map[string]func(w http.ResponseWriter)
asked []sealedAsk
}
// sealedAsk is a request accountSealer was sent: the account, and its
// input as heldItems reads it.
type sealedAsk struct{ acct, input string }
func (c *accountSealer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
acct := r.Header.Get("chatgpt-account-id")
var q struct {
Input []sealedItem `json:"input"`
}
json.Unmarshal(b, &q)
why := ""
for _, it := range q.Input {
if it.Enc != "" && !strings.HasPrefix(it.Enc, "gAAAA-"+acct+"-") && why != openaiUnverifiable {
why = openaiUndecryptable
if it.Type == "reasoning" {
why = openaiUnverifiable
}
}
}
c.mu.Lock()
c.asked = append(c.asked, sealedAsk{acct, heldItems(b)})
out := c.out[acct]
c.mu.Unlock()
if out != nil {
out(w)
return
}
if why != "" && !c.stream {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(400)
io.WriteString(w, `{"error":{"message":"`+why+`","type":"invalid_request_error","param":null,"code":"invalid_encrypted_content"}}`)
return
}
lead := []string{
`event: codex.rate_limits` + "\n" + `data: {"type":"codex.rate_limits","plan_type":"plus","rate_limits":{"allowed":true,"limit_reached":false,"primary":{"used_percent":3,"window_minutes":300,"reset_after_seconds":100}}}`,
`event: response.created` + "\n" + `data: {"type":"response.created","response":{"id":"r0","model":"gpt-5.5"}}`,
`event: response.in_progress` + "\n" + `data: {"type":"response.in_progress","response":{"id":"r0","model":"gpt-5.5"}}`,
}
if why != "" {
io.WriteString(w, sse(append(lead,
`event: response.failed`+"\n"+`data: {"type":"response.failed","response":{"id":"r0","status":"failed","error":{"code":"invalid_encrypted_content","message":"`+why+`"}}}`)...))
return
}
// most of it read from the account's cache, which keeps the
// conversation there while it is warm
io.WriteString(w, sse(append(lead,
`event: response.output_text.delta`+"\n"+`data: {"type":"response.output_text.delta","delta":"from `+acct+`"}`,
`event: response.completed`+"\n"+`data: {"type":"response.completed","response":{"id":"r1","usage":{"input_tokens":24000,"input_tokens_details":{"cached_tokens":20000},"output_tokens":5}}}`)...))
}
func (c *accountSealer) setOut(acct string, answer func(w http.ResponseWriter)) {
c.mu.Lock()
defer c.mu.Unlock()
if c.out == nil {
c.out = map[string]func(w http.ResponseWriter){}
}
c.out[acct] = answer
}
// took is what was asked since the last call.
func (c *accountSealer) took() []sealedAsk {
c.mu.Lock()
defer c.mu.Unlock()
out := c.asked
c.asked = nil
return out
}
// on puts c behind Codex's sign-in, for the test.
func (c *accountSealer) on(t *testing.T) {
t.Helper()
up := httptest.NewServer(c)
t.Cleanup(up.Close)
was := provider.CodexBase
provider.CodexBase = up.URL + "/backend-api/codex"
t.Cleanup(func() { provider.CodexBase = was })
}
// heldItems is a Responses request's input as these tests check it: each
// item's type, a message's role, a call's call_id, a web search's query,
// and its seal.
func heldItems(body []byte) string {
var q struct {
Input []struct {
Type string `json:"type"`
Role string `json:"role"`
CallID string `json:"call_id"`
Action struct {
Query string `json:"query"`
} `json:"action"`
Enc string `json:"encrypted_content"`
} `json:"input"`
}
if json.Unmarshal(body, &q) != nil {
return "unreadable"
}
var out []string
for _, it := range q.Input {
out = append(out, strings.Join(strings.Fields(strings.Join([]string{it.Type, it.Role, it.CallID, it.Action.Query, it.Enc}, " ")), " "))
}
return strings.Join(out, ", ")
}
// codexUser is the user's message in a Codex conversation.
func codexUser(text string) string {
return `{"type":"message","role":"user","content":[{"type":"input_text","text":"` + text + `"}]}`
}
// replayedTurn is what turn n on acct leaves in a Codex conversation with
// output token replay on: its sealed reasoning, a web search it ran
// (hheei's), a call with its output, and its answer, the search, the call
// and the answer each with its sealed copy.
func replayedTurn(acct, n string) string {
seal := func(what string) string { return `"encrypted_content":"gAAAA-` + acct + `-` + what + n + `"` }
return `{"type":"reasoning","id":"rs_` + n + `","summary":[],"content":null,` + seal("r") + `},` +
`{"type":"web_search_call","id":"ws_` + n + `","status":"completed","action":{"type":"search","query":"上海天气","sources":[{"type":"url","url":"https://www.weather.com.cn/weather/101020100.shtml"}]},` + seal("w") + `},` +
`{"type":"function_call","name":"shell","arguments":"{\"cmd\":\"ls\"}","call_id":"c` + n + `",` + seal("f") + `},` +
`{"type":"function_call_output","call_id":"c` + n + `","output":"a.go"},` +
`{"type":"message","role":"assistant","content":[{"type":"output_text","text":"晴,22 度"}],` + seal("m") + `}`
}
// replayedHeld is replayedTurn as heldItems reads it: as acct sealed it,
// or with its reasoning gone and no seal left on the rest.
func replayedHeld(acct, n string, sealed bool) string {
if !sealed {
return "web_search_call 上海天气, function_call c" + n + ", function_call_output c" + n + ", message assistant"
}
s := " gAAAA-" + acct + "-"
return "reasoning" + s + "r" + n + ", web_search_call 上海天气" + s + "w" + n + ", function_call c" + n + s + "f" + n +
", function_call_output c" + n + ", message assistant" + s + "m" + n
}
// askThread is Codex signed in to ChatGPT as signedIn asking s at path for
// model, in its thread 3887, with the conversation's items.
func askThread(s *Server, path, model, signedIn string, items ...string) (int, string) {
body := `{"model":"` + model + `","stream":true,"store":false,` +
`"include":["reasoning.encrypted_content","output.encrypted_content"],"prompt_cache_key":"thread-3887",` +
`"tools":[{"type":"web_search"},{"type":"function","name":"shell","parameters":{"type":"object"}}],` +
`"input":[` + strings.Join(items, ",") + `]}`
rec := httptest.NewRecorder()
req := httptest.NewRequest("POST", path, strings.NewReader(body))
req.Header.Set("Authorization", "Bearer chatgpt-token")
req.Header.Set("chatgpt-account-id", signedIn)
req.Header.Set("session_id", "thread-3887")
s.Handler().ServeHTTP(rec, req)
return rec.Code, rec.Body.String()
}
// Where a Codex conversation is asked through magpie's Codex accounts: one
// of Codex's own models signed in, the codex provider's model, and a
// routing group of it.
var codexAccountRoutes = []struct{ name, path, model string }{
{"signed in", CodexPath + "/responses", "gpt-5.5"},
{"magpie model", "/v1/responses", "codex/gpt-5.5"},
{"group", "/v1/responses", "group/g"},
}
var sealRefusals = []struct {
name string
stream bool
}{{"400", false}, {"in the stream", true}}
// A Codex conversation with a web search in it (hheei, #3887), and with
// output token replay on a sealed copy on each message and call, moves
// from one ChatGPT account to another as the first is used up or rate
// limited. The second can't read what the first sealed and says so; it is
// asked again with the reasoning left out and the seal taken off the
// rest, and the next turn goes to it so up front, its own seals on.
// Before, only the reasoning went, the search was refused again, and
// Codex got "Encrypted content could not be decrypted or parsed.".
func TestForeignSealedItemsMoveToAnotherAccount(t *testing.T) {
for _, x := range codexSpent {
if x.name != "429 json" && x.name != "response.failed rate_limit_exceeded" {
continue
}
for _, on := range codexAccountRoutes {
for _, refusal := range sealRefusals {
t.Run(x.name+", "+on.name+", refused "+refusal.name, func(t *testing.T) {
codexSignedIn(t, "spare@example.com")
if err := provider.SetRouting("codex", provider.Ordered); err != nil {
t.Fatal(err)
}
up := &accountSealer{stream: refusal.stream}
up.on(t)
if on.model == "group/g" {
refusalGroup(t, "codex/gpt-5.5")
}
s := New()
// the account that sealed it all reads it back as it came
turn := []string{codexUser("上海天气怎么样"), replayedTurn("acct-1", "1"), codexUser("明天呢")}
if code, body := askThread(s, on.path, on.model, "acct-1", turn...); code != 200 || !strings.Contains(body, "from acct-1") {
t.Fatalf("first: %d %s", code, body)
}
if got := up.took(); len(got) != 1 || got[0] != (sealedAsk{"acct-1", "message user, " + replayedHeld("acct-1", "1", true) + ", message user"}) {
t.Fatalf("acct-1 was sent %q", got)
}
up.setOut("acct-1", x.refuse)
turn = append(turn, replayedTurn("acct-1", "2"), codexUser("后天呢"))
code, body := askThread(s, on.path, on.model, "acct-1", turn...)
if code != 200 || !strings.Contains(body, "from acct-2") {
t.Fatalf("moved on: %d %s", code, body)
}
sealed := "message user, " + replayedHeld("acct-1", "1", true) + ", message user, " + replayedHeld("acct-1", "2", true) + ", message user"
bare := "message user, " + replayedHeld("acct-1", "1", false) + ", message user, " + replayedHeld("acct-1", "2", false) + ", message user"
if got := up.took(); len(got) != 3 || got[0].acct != "acct-1" || got[1] != (sealedAsk{"acct-2", sealed}) || got[2] != (sealedAsk{"acct-2", bare}) {
t.Fatalf("asked %q", got)
}
if r := lastRoute(s); len(r.Tries) != 3 || r.Tries[1].Fail != failForeign || r.Tries[2].Status != 200 {
t.Fatalf("tries: %+v", r.Tries)
}
// what acct-2 refused stays out of the next turn up front,
// and what it sealed itself goes along
turn = append(turn, replayedTurn("acct-2", "3"), codexUser("谢谢"))
if code, body := askThread(s, on.path, on.model, "acct-1", turn...); code != 200 || !strings.Contains(body, "from acct-2") {
t.Fatalf("next turn: %d %s", code, body)
}
if got := up.took(); len(got) != 1 || got[0] != (sealedAsk{"acct-2", bare + ", " + replayedHeld("acct-2", "3", true) + ", message user"}) {
t.Fatalf("then asked %q", got)
}
})
}
}
}
}
// The same conversation moved by its affinity going cold, as hheei's did
// ("why": "cold", two hours on): the account that answered it last did so
// over an hour ago, so routing's first is asked, and it reads none of the
// other's seals.
func TestForeignSealedItemsAfterAColdSwitch(t *testing.T) {
for _, on := range codexAccountRoutes {
for _, refusal := range sealRefusals {
t.Run(on.name+", refused "+refusal.name, func(t *testing.T) {
codexSignedIn(t, "spare@example.com")
if err := provider.SetRouting("codex", provider.Ordered); err != nil {
t.Fatal(err)
}
up := &accountSealer{stream: refusal.stream}
up.on(t)
if on.model == "group/g" {
refusalGroup(t, "codex/gpt-5.5")
}
s := New()
// acct-1's safety filter refuses the first turn, so acct-2
// answers it, and the conversation stays there (#248)
up.setOut("acct-1", refusing400)
turn := []string{codexUser("上海天气怎么样")}
if code, body := askThread(s, on.path, on.model, "acct-1", turn...); code != 200 || !strings.Contains(body, "from acct-2") {
t.Fatalf("first: %d %s", code, body)
}
up.setOut("acct-1", nil)
up.took()
sticks.Lock()
for k, st := range sticks.m {
st.at = st.at.Add(-2 * time.Hour)
sticks.m[k] = st
}
sticks.Unlock()
turn = append(turn, replayedTurn("acct-2", "1"), codexUser("明天呢"))
code, body := askThread(s, on.path, on.model, "acct-1", turn...)
if code != 200 || !strings.Contains(body, "from acct-1") {
t.Fatalf("gone cold: %d %s", code, body)
}
if r := lastRoute(s); r.Affinity == nil || r.Affinity.Why != "cold" {
t.Fatalf("affinity %+v", r.Affinity)
}
bare := "message user, " + replayedHeld("acct-2", "1", false) + ", message user"
if got := up.took(); len(got) != 2 || got[0] != (sealedAsk{"acct-1", "message user, " + replayedHeld("acct-2", "1", true) + ", message user"}) || got[1] != (sealedAsk{"acct-1", bare}) {
t.Fatalf("asked %q", got)
}
turn = append(turn, replayedTurn("acct-1", "2"), codexUser("后天呢"))
if code, body := askThread(s, on.path, on.model, "acct-1", turn...); code != 200 || !strings.Contains(body, "from acct-1") {
t.Fatalf("next turn: %d %s", code, body)
}
if got := up.took(); len(got) != 1 || got[0] != (sealedAsk{"acct-1", bare + ", " + replayedHeld("acct-1", "2", true) + ", message user"}) {
t.Fatalf("then asked %q", got)
}
})
}
}
}
// Codex's own sign-in alone, relayed as it came, now on another account
// (signed in again, or moved on once the first was spent,
// provider.SwitchWhenSpent): the backend's 400 for the first account's
// seals is answered by asking again without them, the web search's and
// the replayed copies too.
func TestForeignSealedItemsRelayedToAnotherSignIn(t *testing.T) {
codexSignedIn(t)
up := &accountSealer{}
up.on(t)
turn := []string{codexUser("上海天气怎么样"), replayedTurn("acct-1", "1"), codexUser("明天呢")}
code, body := askThread(New(), CodexPath+"/responses", "gpt-5.5", "acct-2", turn...)
if code != 200 || !strings.Contains(body, "from acct-2") {
t.Fatalf("%d %s", code, body)
}
if got := up.took(); len(got) != 2 || got[0] != (sealedAsk{"acct-2", "message user, " + replayedHeld("acct-1", "1", true) + ", message user"}) ||
got[1] != (sealedAsk{"acct-2", "message user, " + replayedHeld("acct-1", "1", false) + ", message user"}) {
t.Fatalf("asked %q", got)
}
}
// What another account sealed is taken out with every other byte as it
// came: reasoning whole, and of a web search, a message and a call only
// their sealed copy, wherever it sits in the item. A compaction's seal
// stays for withoutCompaction. What was refused is left out of the
// conversation's later requests to who refused it, and only that.
func TestSealsTakenOutLeaveTheRest(t *testing.T) {
fresh(t)
in := `{"input":[` + codexUser("上海天气怎么样") + `,` +
`{"type":"reasoning","id":"rs_1","summary":[],"encrypted_content":"gAAAA-r1"},` +
`{"encrypted_content":"gAAAA-w1","type":"web_search_call","id":"ws_1","status":"completed","action":{"type":"search","query":"上海天气"}},` +
`{"type":"function_call","name":"shell","encrypted_content":"gAAAA-f1","arguments":"{\"cmd\":\"ls\"}","call_id":"c1"},` +
`{"type":"function_call_output","call_id":"c1","output":"a.go"},` +
`{"type":"message","role":"assistant","content":[{"type":"output_text","text":"晴"}],"encrypted_content":"gAAAA-m1"},` +
`{"type":"compaction","encrypted_content":"gAAAA-c1"},{"type":"context_compaction","encrypted_content":"gAAAA-x1"}],"model":"gpt-5.5","stream":true}`
want := `{"input":[` + codexUser("上海天气怎么样") + `,` +
`{"type":"web_search_call","id":"ws_1","status":"completed","action":{"type":"search","query":"上海天气"}},` +
`{"type":"function_call","name":"shell","arguments":"{\"cmd\":\"ls\"}","call_id":"c1"},` +
`{"type":"function_call_output","call_id":"c1","output":"a.go"},` +
`{"type":"message","role":"assistant","content":[{"type":"output_text","text":"晴"}]},` +
`{"type":"compaction","encrypted_content":"gAAAA-c1"},{"type":"context_compaction","encrypted_content":"gAAAA-x1"}],"model":"gpt-5.5","stream":true}`
left, ok := withoutSeals([]byte(in))
if !ok || string(left) != want {
t.Fatalf("got %s", left)
}
// reasoning alone is taken out as it was before
alone := `{"input":[` + codexUser("hi") + `,{"type":"reasoning","id":"rs_1","summary":[],"encrypted_content":"gAAAA-r1"},` +
`{"type":"function_call","name":"shell","arguments":"{}","call_id":"c1"}],"model":"gpt-5.5"}`
was, _ := withoutKinds([]byte(alone), "reasoning")
if got, ok := withoutSeals([]byte(alone)); !ok || string(got) != string(was) {
t.Fatalf("reasoning alone: %s, was %s", got, was)
}
// nothing but a compaction sealed: nothing to take out here
if got, ok := withoutSeals([]byte(`{"input":[{"type":"compaction","encrypted_content":"gAAAA-c1"},{"type":"message","role":"user","content":"hi"}]}`)); ok {
t.Fatalf("compaction: %s", got)
}
// the next turn, with what the one that refused sealed itself
refused("thread", "codex@b", []byte(in), left)
own := `,{"type":"message","role":"assistant","content":[{"type":"output_text","text":"多云"}],"encrypted_content":"gAAAA-b2"}`
next := strings.Replace(in, `],"model"`, own+`],"model"`, 1)
if got, ok := withoutRefused("thread", "codex@b", []byte(next)); !ok || string(got) != strings.Replace(want, `],"model"`, own+`],"model"`, 1) {
t.Fatalf("next turn: %s", got)
}
for _, other := range [][2]string{{"thread", "codex@a"}, {"another", "codex@b"}} {
if got, ok := withoutRefused(other[0], other[1], []byte(next)); ok {
t.Fatalf("%v: %s", other, got)
}
}
}
+13 -11
View File
@@ -3235,8 +3235,8 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
var nt netTrace // where the try's time went (TryNet)
attemptBody := body
if from == provider.Responses {
// reasoning another sealed, which this one refused earlier in
// the conversation, isn't sent to be refused again; its own is
// what another sealed, which this one refused earlier in the
// conversation, isn't sent to be refused again; its own is
if b, ok := withoutRefused(stuck, c.vendor(), attemptBody); ok {
attemptBody = b
}
@@ -3832,17 +3832,19 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
}
if resealed < 2 && from == provider.Responses && !hw.passing && hw.code() >= 400 && foreignReasoning.Match(hw.errBody()) {
// the conversation moved here from another account or vendor,
// whose sealed reasoning this one can't read: asked again
// without it, and what it refused isn't sent here again. xAI
// says so as a 400, or as the stream's error, which may be
// read as another status. Refused again, or with no reasoning
// to leave out, it's the compaction OpenAI sealed that goes
// (waroy: Codex compacted on GPT, then switched to Grok)
// whose seals this one can't read: asked again without them
// (its reasoning, and each message's, call's and web search's
// sealed copy, #3887), and what it refused isn't sent here
// again. xAI says so as a 400, or as the stream's error, which
// may be read as another status. Refused again, or with
// nothing else sealed to leave out, it's the compaction OpenAI
// sealed that goes (waroy: Codex compacted on GPT, then
// switched to Grok)
b, ok := []byte(nil), false
if resealed == 0 {
resealed = 1
if b, ok = withoutReasoning(body); ok {
refused(stuck, c.vendor(), attemptBody, "reasoning")
if b, ok = withoutSeals(body); ok {
refused(stuck, c.vendor(), attemptBody, b)
}
}
// a compaction sealed where native compaction is on is never
@@ -3850,7 +3852,7 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
if !ok && checkpoint == nil && !s.compactsNatively(c.p, c.model) {
resealed = 2
if b, ok = withoutCompaction(body); ok {
refused(stuck, c.vendor(), attemptBody, compactionKinds...)
refused(stuck, c.vendor(), attemptBody, b)
}
}
if ok {
+1 -1
View File
@@ -166,7 +166,7 @@ func unreasonCalls(r *Request) {
// client's history, so every later turn carried the same item and was
// refused the same way (#4798, zane668: Pi's Chat to Grok, then Codex;
// ZanderH-code: Claude Desktop's Messages to Codex). A Responses client's
// own items are asked again without them (withoutReasoning) and left out
// own items are asked again without them (withoutSeals) and left out
// of the conversation's later requests there (withoutRefused); a carried
// item goes the same way: refused, the items the request carried are
// remembered as refused by that key or account in the conversation
+2 -2
View File
@@ -380,8 +380,8 @@ const (
failAuth = "auth"
// failCanceled: the agent went away before the answer came
failCanceled = "canceled"
// failForeign: the conversation's reasoning was sealed by another
// account, and is sent again without it
// failForeign: the conversation's reasoning, or another item's sealed
// copy, was sealed by another account, and is sent again without it
failForeign = "foreign"
// failFloor: the request asked for a shorter reply than the provider
// gives, and is sent again asking for the least it takes