Files
magpie/internal/gateway/reasoning_carry.go
T
JoeyWu-tech b59e4b747f 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).
2026-11-03 20:38:11 +08:00

269 lines
8.9 KiB
Go

package gateway
import (
"bytes"
"context"
"crypto/sha256"
"encoding/json"
"slices"
"strconv"
"time"
"github.com/yetone/magpie/internal/provider"
)
// A Responses upstream's sealed reasoning across a client of another API
// (jenryai on X: Grok through Claude Desktop repeats itself and writes
// broken calls, where Grok Build doesn't). A model that reasons between
// tool calls reads the step's reasoning back on the next request: Grok
// Build sends every reasoning item it was given, encrypted_content and
// all, before the calls it led to. A Messages, Chat or Gemini client
// keeps no such item, so each step of its tool loop reached Grok with
// none of the reasoning that made the calls before it.
//
// So the reasoning items that come before a step's first call ride in
// that call's id, as Gemini's signatures do (gemini_signature.go): they
// are kept in magpie's folder (keepSignature, by their hash) and the id
// carries the key, <id>__rk16__<key>. Every client sends a call's id back
// as it was given, and on the way back the items go in front of the
// assistant turn that made the call, and the id is the call's own again.
// A key magpie no longer has (or an id a client shortened) is no
// reasoning: the step goes as before.
const (
reasonMark = "__rk"
reasonEnd = "__"
)
// reasonKeyLen is a kept item's key's length in an id.
var reasonKeyLen = len(sigKey(""))
// reasonTail is what an id carrying reasoning ends with before its key.
var reasonTail = reasonMark + strconv.Itoa(reasonKeyLen) + reasonEnd
// asksSealedReasoning says whether a request from a client of from is
// made to ask p for its sealed reasoning, to carry it in the calls' ids:
// a Grok subscription's plugin, asked as Grok Build asks it. A Responses
// client asks for itself, and keeps the items it is given.
func asksSealedReasoning(p provider.Provider, from provider.Protocol) bool {
return from != provider.Responses && p.PluginProvider() == "grok"
}
// askSealedReasoning adds reasoning.encrypted_content to r's include when
// asksSealedReasoning says so (buildResponses sends it only with reasoning).
func askSealedReasoning(p provider.Provider, from provider.Protocol, r *Request) {
const v = "reasoning.encrypted_content"
if asksSealedReasoning(p, from) && !slices.Contains(r.Include, v) {
r.Include = append(slices.Clip(r.Include), v)
}
}
// reasonedID is a call's id carrying the reasoning items before it, or the
// id as it was when they couldn't be kept.
func reasonedID(id string, items []json.RawMessage) string {
if len(items) == 0 {
return id
}
b, err := json.Marshal(items)
if err != nil {
return id
}
key := keepSignature(string(b))
if key == "" {
return id
}
if id == "" {
id = "call_" + newID()
}
return id + reasonTail + key
}
// unreasonedID splits an id reasonedID made into the call's own id and
// the reasoning items it refers to (none when magpie no longer has them).
// Any other id comes back as it is.
func unreasonedID(id string) (string, []json.RawMessage) {
at := len(id) - reasonKeyLen - len(reasonTail)
if at < 1 || id[at:at+len(reasonTail)] != reasonTail {
return id, nil
}
own, key := id[:at], id[at+len(reasonTail):]
var items []json.RawMessage
if kept := keptSignature(key); kept != "" {
if json.Unmarshal([]byte(kept), &items) != nil {
items = nil
}
}
return own, items
}
// carryReasoning is dec for a client of from, with the sealed reasoning a
// Responses upstream gives before a call carried in that call's id, when
// the client is of another API.
func carryReasoning(dec func(string, func(Event)) error, from, actual provider.Protocol) func(string, func(Event)) error {
if from == provider.Responses || actual != provider.Responses {
return dec
}
var held []json.RawMessage
return func(data string, emit func(Event)) error {
return dec(data, func(ev Event) {
switch {
case ev.Kind == KSealed && ev.Name == sealResponses && ev.Text != "":
held = append(held, json.RawMessage(ev.Text))
case ev.Kind == KToolStart && len(held) > 0:
ev.ID = reasonedID(ev.ID, held)
held = nil
}
emit(ev)
})
}
}
// unreasonCalls takes the reasoning off a parsed request's call ids: each
// assistant turn leads with the items its calls carried, sealed as the
// Responses upstream gave them (buildResponses sends them back; another
// API's build leaves them out), and a call and its result have the call's
// own id. Messages are copied before they change.
func unreasonCalls(r *Request) {
for i, m := range r.Messages {
var parts, lead []Part
for j, p := range m.Parts {
var items []json.RawMessage
switch p.Kind {
case ToolCall:
id, its := unreasonedID(p.ID)
if id == p.ID {
continue
}
p.ID, items = id, its
case ToolResult:
id, _ := unreasonedID(p.CallID)
if id == p.CallID {
continue
}
p.CallID = id
default:
continue
}
if parts == nil {
parts = slices.Clone(m.Parts)
}
parts[j] = p
for _, it := range items {
lead = append(lead, Part{Kind: Thinking, Sealed: it, SealedBy: sealResponses})
}
}
if parts != nil {
r.Messages[i].Parts = append(lead, parts...)
}
}
}
// A carried item reaches whichever Responses upstream a conversation goes
// to next, not only the one that sealed it: after a fallback, a switch of
// account or a group's next turn, Codex refuses Grok's ("The encrypted
// content … could not be verified") and Grok Codex's ("Could not decrypt
// the provided encrypted_content"), and the call's id stays in the
// 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 (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
// (refuseCarried), the request is asked again, and the translation leaves
// them out of this and every later request to it (withoutRefusedCarry).
// The calls, their results and the text stay as they were; the call's id
// is its own either way. Another key or account, the one that sealed it
// among them, is still given them.
// sealScopeKey holds a try's sealScope in its context.
type sealScopeKey struct{}
// sealScope is whose refusals of carried reasoning a try's translation
// reads: the conversation (stickKey), and the key or account
// (candidate.vendor) of the provider it goes to.
type sealScope struct {
id, key, who string
}
// withSealScope is ctx for a try to provider id, as who, in the
// conversation key.
func withSealScope(ctx context.Context, id, key, who string) context.Context {
return context.WithValue(ctx, sealScopeKey{}, sealScope{id: id, key: key, who: who})
}
// carriedSeal is the hash refusedSeals knows a carried reasoning part by:
// its item's encrypted_content, as seals hashes a Responses client's.
func carriedSeal(p Part) ([sha256.Size]byte, bool) {
if !p.sealedBy(sealResponses) {
return [sha256.Size]byte{}, false
}
var it sealedItem
if decodeJSON(p.Sealed, &it) != nil || !sealedKinds[it.Type] || it.Enc == "" {
return [sha256.Size]byte{}, false
}
return sha256.Sum256([]byte(it.Enc)), true
}
// withoutRefusedCarry leaves out of req the carried reasoning the key or
// account of ctx's try to p refused earlier in the conversation. Nothing
// else changes; a request with none goes as it is.
func withoutRefusedCarry(ctx context.Context, p provider.Provider, req *Request) {
sc, ok := ctx.Value(sealScopeKey{}).(sealScope)
if !ok || sc.id != p.ID {
return
}
refusedSeals.Lock()
r, ok := refusedSeals.m[sc.key+"|"+sc.who]
refusedSeals.Unlock()
if !ok || time.Since(r.at) > stickKeep {
return
}
for i, m := range req.Messages {
gone := func(p Part) bool {
h, ok := carriedSeal(p)
return ok && r.seals[h]
}
if slices.ContainsFunc(m.Parts, gone) {
req.Messages[i].Parts = slices.DeleteFunc(slices.Clone(m.Parts), gone)
}
}
}
// refuseCarried remembers the reasoning body's calls carry, in a request
// from a client of from, as refused by who in the conversation key; true
// when any of it wasn't already, so that asking again leaves something
// out.
func refuseCarried(key, who string, from provider.Protocol, body []byte) bool {
if from == provider.Responses || !bytes.Contains(body, []byte(reasonTail)) {
return false
}
req, err := parseRequest(from, body, false, true)
if err != nil {
return false
}
var ss [][sha256.Size]byte
for _, m := range req.Messages {
for _, p := range m.Parts {
if h, ok := carriedSeal(p); ok {
ss = append(ss, h)
}
}
}
k := key + "|" + who
refusedSeals.Lock()
r := refusedSeals.m[k]
fresh := false
for _, h := range ss {
if !r.seals[h] || time.Since(r.at) > stickKeep {
fresh = true
}
}
refusedSeals.Unlock()
if !fresh {
return false
}
noteRefused(key, who, ss)
return true
}