gateway: a Codex lead on a chat provider goes on when its subagent on one of Codex's own models sends it a message, the sealed message left out with a note (#1613, laacmilan)

laacmilan's lead was on token/gpt-6.1-sol, an API key on Chat
Completions. Codex put a subagent on one of its own models, which magpie
serves from the ChatGPT account. The ChatGPT backend seals that
subagent's send_message, and Codex hands it to the lead as an
agent_message: a plain "Message Type: MESSAGE" header plus
encrypted_content (codex-rs protocol.rs to_model_input_item). serve's
sealed gate (#619, #1237) took any sealed agent_message as a task. Only
the ChatGPT backend can read it, so the lead's next turn was refused. The
refusal said the lead "has since been on one of Codex's own models",
which it never was. This had been so since the gate was added, not only
since yesterday's release.

- A sealed message (not a task) that no candidate can open is left out
  now (withoutSealedMessages). An input_text note naming its sender goes
  in its place, and the request goes on where it was. The subagent's
  final result still reaches the lead as text. A sealed task (NEW_TASK,
  or an item with no header) is still refused, as in #619: without it
  the subagent has nothing to do.
- The refusal for a sealed task, where the provider that answered the
  lead can't seal, no longer says the lead switched models. It says the
  task came from an agent of this thread on one of Codex's own models,
  and points to Codex's subagent model on the Agents page.
- docs/subsystems/gateway-routing.md says so.

Run:
- The new tests in sealed_message_left_out_test.go. The lead and
  subagent cases fail on the old code with the reporter's exact message,
  and also fail with the strip turned off by hand.
- go test -tags nogui -run 'TestSealed|Codex|Sealed' ./internal/gateway.
- go test -tags nogui -timeout 40m ./internal/gateway.
- gofmt -l.
- GOOS=linux and GOOS=windows go vet -tags nogui ./internal/gateway.

Not tried: real Codex desktop with a real ChatGPT account and a chat
provider. The requests are Codex-shaped fixtures built from codex-rs's
item format.
This commit is contained in:
yetone
2026-10-11 21:17:02 +08:00
parent 398f8469be
commit 149ab950e7
5 changed files with 221 additions and 3 deletions
+1 -1
View File
@@ -36,7 +36,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md).
- With *Mask secrets* on, the user's own masking rules (`redactRules`, `redact.Rule`: a placeholder name and a prefix or an RE2 pattern, [`internal/redact/rules.go`](../../internal/redact/rules.go)) run before magpie's. Settings → Privacy adds them, removes them, and edits one in place (`POST /api/settings/redact-rule` with the rule's index and its current value, `editRedactRule` in [`internal/gui/api.go`](../../internal/gui/api.go)). Every rule is checked by `redact.CheckRules` when settings are saved; an edit that doesn't compile, matches the empty string, repeats another rule or names a rule no longer at that index is refused with the rules left as they were. The gateway reads the rules from settings on each request (`redactionOptions`), so a change applies to the next request.
- `DecidesModel` gives a 400.
- A gateway key held to some models (`keyHolds`, #882) gets a 403 for any other model.
- Sealed tasks (#619) are checked here. A Codex subagent's task its lead's `spawn_agent` sealed goes only to a ChatGPT account, or back to the Responses provider that answered the lead (`leadProvider`, a relay of the ChatGPT backend such as Sub2API, #1109), relayed as it came even when web search is offered. A lead's turn carrying its subagent's sealed reply (`send_message`) goes back to the Responses provider that answered the lead's own conversation (`leadProvider` of the request's `conversationID`, #1237); otherwise it is refused before anyone is asked (`sealedReader`, `sealedTaskError`). Who answered is first what affinity remembers; when affinity has let it go (a day since, a restart past the 512 conversations `affinity.json` keeps, or the lead's last reply broken off, `unanswered`), the usage log's answers to the lead's thread and the request's own conversation in the last 30 days count too (`loggedAnswers`, #1367), and `leadFirst` reads the lead's key or account from them. A refused or failed call and a title answer nothing, and Codex's own sign-in is told of as the ChatGPT backend. The refusal names who sealed the task when it is known, and says how to go on with it.
- Sealed tasks (#619) are checked here. A Codex subagent's task its lead's `spawn_agent` sealed goes only to a ChatGPT account, or back to the Responses provider that answered the lead (`leadProvider`, a relay of the ChatGPT backend such as Sub2API, #1109), relayed as it came even when web search is offered. A lead's turn carrying its subagent's sealed reply (`send_message`) goes back to the Responses provider that answered the lead's own conversation (`leadProvider` of the request's `conversationID`, #1237); otherwise it is refused before anyone is asked (`sealedReader`, `sealedTaskError`). A sealed message (`Message Type: MESSAGE`, not a task) that nobody asked can open is left out instead, an `input_text` note naming its sender in its place (`withoutSealedMessages`, #1613): a lead on a chat provider whose subagent is on one of Codex's own models goes on, as the subagent's final result still reaches it as text. Only a sealed task (`NEW_TASK`, or an item with neither header) is refused. Who answered is first what affinity remembers; when affinity has let it go (a day since, a restart past the 512 conversations `affinity.json` keeps, or the lead's last reply broken off, `unanswered`), the usage log's answers to the lead's thread and the request's own conversation in the last 30 days count too (`loggedAnswers`, #1367), and `leadFirst` reads the lead's key or account from them. A refused or failed call and a title answer nothing, and Codex's own sign-in is told of as the ChatGPT backend. The refusal names who sealed the task when it is known, and says how to go on with it.
- A model set for Codex's subagents (`settings.CodexSubagentModel`, the Agents page's Codex "subagent model", willz on Discord) is put on a Codex subagent's request (`x-openai-subagent` read as `kind:collab_spawn`) before this check, whatever model its lead's `spawn_agent` asked for (`codexSubagentPick` in [`codex_subagent.go`](../../internal/gateway/codex_subagent.go)): in `codexBackend` for one of Codex's own bare models, which then goes through `serveAgent`, and in `serve` for any other. Only a ChatGPT account's model can be set (`provider.SetCodexSubagentModel`), as nothing else reads the sealed task. When no ChatGPT account on in magpie serves it now, or a gateway key held to some models may not use it, the subagent goes on the model asked for. The route trace keeps both models and the reason it stayed (`Route.Subagent`), and the Routing page's `kindWhy` says it. The lead's turns, titles and every other kind are never moved.
- Rules and image inputs are handled here too.
- A rule by folder (`Rule.Folders`, `folders=~/work/acme,~/oss`; Cario0x on X: routing by the project being worked on) matches when the folder the agent works in is one of them or inside one (`provider.FolderUnder`, [`rulefolder.go`](../../internal/provider/rulefolder.go)): at a path's boundary, so `/a/b` is not under `/a/bc`; `~` is the home folder; a Windows drive is one with its WSL mount (`C:\work` is `/mnt/c/work`) and a `\\wsl$\<distro>` or `\\wsl.localhost\<distro>` share is the distro's own path; case doesn't count on macOS and Windows, nor ever for a drive. The folder is read from the request only when a rule of the group has folders (`workDir` in [`workdir.go`](../../internal/gateway/workdir.go)), in each agent's own words, taken from captured requests: Claude Code's ` - Primary working directory: <path>` (its `<`/`>` as entities; ` (was <old>)` after a change dropped), Codex's `<environment_context>` `<cwd>`, Pi's `<cwd>` in the system prompt, and OpenCode's `Working directory:` inside its `<env>` block. Only the system prompt and the user's and system messages' text count, never the model's words or a tool's result, and the last said wins. An agent that says none has no folder, and no rule by folder matches it (unknown, never empty). A pause rule can't have folders. The trace's `RuleHit.Folder` is the folder read, and the Routing page tells it beside the rule's `folder …` condition. `TestFolderUnder`, `TestRuleMatchesByFolder`, `TestParseRuleFolders`, `TestWorkDirOfEachAgent`, `TestRuleByFolder`, `routing-folder.test.cjs`.
+80 -1
View File
@@ -170,7 +170,7 @@ func (s *Server) codexBackend(w http.ResponseWriter, r *http.Request) {
// task was sealed there (plugins#70).
func sealedTaskError(model, lead, earlier string) string {
if earlier != "" {
return fmt.Sprintf("This subagent's task was sealed by the ChatGPT backend that answered its lead, and only that backend can open it: a ChatGPT account, or the Responses API provider that answered the lead. %s can't. %s answered the lead's earlier turns, but it neither seals a task nor opens one: the lead has since been on one of Codex's own models. Give the subagent the lead's model, or a lead model that isn't served by the ChatGPT backend, so its subagents get a task they can read. To go on with this task, use the lead's model, or have the lead spawn the subagent again.", model, earlier)
return fmt.Sprintf("This subagent's task was sealed by the ChatGPT backend, which answered the agent that sent it on one of Codex's own models (a subagent of this thread put there, or the lead after a switch), and only a ChatGPT account can open it. %s can't. %s answered the lead's earlier turns, but it neither seals a task nor opens one. Set Codex's subagent model on magpie's Agents page to a model of a ChatGPT account added in magpie, or to one that isn't served by the ChatGPT backend, so subagents get tasks they can read. To go on with this task, have it spawned again from an agent that isn't on Codex's own models.", model, earlier)
}
if lead != "" {
return fmt.Sprintf("This subagent's task was sealed by the server that answered its lead (%s), and only that server can open it; %s can't. Give the subagent the lead's model, or a lead model that isn't served by the ChatGPT backend, so its subagents get a task they can read. To go on with this task, use a model on %s for the lead and the subagent, or have the lead spawn the subagent again.", lead, model, lead)
@@ -400,6 +400,85 @@ func hasSealedAgentMessage(body []byte) bool {
return false
}
// withoutSealedMessages is a request's input with each sealed agent message
// that is not a task left out, a note in its place; ok says one was. In
// MultiAgentV2 an agent on one of Codex's own models has its send_message
// sealed by the ChatGPT backend, and Codex hands it on as encrypted_content
// under a plain header (codex-rs protocol.rs to_model_input_item: "Message
// Type: MESSAGE" for a message, NEW_TASK for a task, spawn_agent's or
// followup_task's). A lead or subagent served by a model that can't open
// it was turned away whole, though all it lost was that message: the
// sender's final result reaches its lead as text all the same (#1613). A
// task is kept, and still turned away (serve): the subagent would have
// nothing to do. An item whose header says neither is taken as a task.
func withoutSealedMessages(body []byte) ([]byte, bool) {
var q map[string]json.RawMessage
if json.Unmarshal(body, &q) != nil {
return body, false
}
var items []json.RawMessage
if json.Unmarshal(q["input"], &items) != nil {
return body, false
}
changed := false
for i, raw := range items {
var item map[string]json.RawMessage
if json.Unmarshal(raw, &item) != nil || string(item["type"]) != `"agent_message"` {
continue
}
var parts []map[string]any
if json.Unmarshal(item["content"], &parts) != nil {
continue
}
message, sealed := false, false
for _, p := range parts {
switch p["type"] {
case "input_text":
t, _ := p["text"].(string)
message = message || strings.HasPrefix(t, "Message Type: MESSAGE\n")
case "encrypted_content":
c, _ := p["encrypted_content"].(string)
sealed = sealed || nativeSealedAgentPayload.MatchString(c)
}
}
if !message || !sealed {
continue
}
var from string
json.Unmarshal(item["author"], &from)
if from == "" {
from = "another agent"
}
note := "[magpie: this message from " + from + " was sealed by the ChatGPT backend, which answered that agent on one of Codex's own models, and only it can open it; this model can't, so it was left out. An agent's final result still reaches the agent that spawned it as text.]"
for j, p := range parts {
if c, _ := p["encrypted_content"].(string); p["type"] == "encrypted_content" && nativeSealedAgentPayload.MatchString(c) {
parts[j] = map[string]any{"type": "input_text", "text": note}
}
}
b, err := marshalPlain(parts)
if err != nil {
continue
}
item["content"] = b
if b, err = marshalPlain(item); err != nil {
continue
}
items[i], changed = b, true
}
if !changed {
return body, false
}
var err error
if q["input"], err = marshalPlain(items); err != nil {
return body, false
}
nb, err := marshalPlain(q)
if err != nil {
return body, false
}
return nb, true
}
// compactSigninHeld is the calling key when its accounts (#905) hold a
// native compaction off the account Codex is signed in to. Compaction
// relays as it came (#876, the encrypted history in it readable only by
+13
View File
@@ -1499,6 +1499,19 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro
sealedLead = sealers[1] // a lead's own turn: who answered it
}
if !readable() {
// a sealed message, not a task, is left out with a note in its
// place: the lead or subagent it was sent to goes on where it
// is, and the sender's final result still reaches its lead as
// text (#1613)
if b, ok := withoutSealedMessages(body); ok {
body = b
if masked != nil {
masked, _ = withoutSealedMessages(masked)
}
sealedTask = hasSealedAgentMessage(body)
}
}
if sealedTask && !readable() {
call.Status, call.Error = 400, "sealed subagent task"
// a lead answered by a chat provider, then on one of Codex's
// own models, is remembered as answered by the chat provider,
+1 -1
View File
@@ -57,7 +57,7 @@ func TestSealedTaskNotPinnedOnALeadsEarlierChatProvider(t *testing.T) {
t.Fatalf("subagent: %d %s (qdr asked %d times)", rec.Code, body, *asked)
}
if strings.Contains(body, "(qdr)") || strings.Contains(body, "use a model on qdr") ||
!strings.Contains(body, "sealed by the ChatGPT backend that answered its lead") ||
!strings.Contains(body, "sealed by the ChatGPT backend, which answered the agent that sent it") ||
!strings.Contains(body, "qdr/dfmodel can't. qdr answered the lead's earlier turns") {
t.Fatalf("the refusal names qdr as the lead's sealer: %s", body)
}
@@ -0,0 +1,126 @@
package gateway
import (
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/yetone/magpie/internal/provider"
)
// sealedWorkerMessage is what Codex (codex-rs protocol.rs,
// InterAgentCommunication::to_model_input_item) puts in its lead's input
// when a subagent on one of Codex's own models sends it a message with
// send_message: the ChatGPT backend sealed the call's arguments, so the
// message goes as encrypted_content, under a plain header.
const sealedWorkerMessage = `{"type":"agent_message","author":"/root/worker","recipient":"/root","content":[{"type":"input_text","text":"Message Type: MESSAGE\nTask name: /root\nSender: /root/worker\nPayload:\n"},{"type":"encrypted_content","encrypted_content":"gAAAAATest_worker_message=="}]}`
// plainTask is a lead's spawn_agent message as Codex hands it to a subagent
// when magpie served the lead: plain text, encrypted_function_args [].
const plainTask = `{"type":"agent_message","author":"/root","recipient":"/root/helper","content":[{"type":"input_text","text":"read the README"}]}`
// chatRecorded is a Chat Completions provider (an API key on an
// OpenAI-compatible endpoint, laacmilan's "token"), keeping every request.
type chatRecorded struct {
mu sync.Mutex
got []string
}
func (f *chatRecorded) requests() []string {
f.mu.Lock()
defer f.mu.Unlock()
return append([]string(nil), f.got...)
}
func chatRecordedOn(t *testing.T, id, model string) *chatRecorded {
t.Helper()
f := &chatRecorded{}
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
f.mu.Lock()
f.got = append(f.got, string(b))
f.mu.Unlock()
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, "data: {\"id\":\"c1\",\"choices\":[{\"index\":0,\"delta\":{\"content\":\"ok\"}}]}\n\n"+
"data: {\"id\":\"c1\",\"choices\":[{\"index\":0,\"delta\":{},\"finish_reason\":\"stop\"}]}\n\ndata: [DONE]\n\n")
}))
t.Cleanup(up.Close)
if err := provider.Save(provider.Provider{ID: id, Name: id, Key: "k", Chat: up.URL + "/v1", Models: []string{model}}); err != nil {
t.Fatal(err)
}
return f
}
// #1613 (laacmilan): Codex's lead on token/gpt-6.1-sol, a provider on Chat
// Completions, and a subagent on one of Codex's own models, answered by
// the ChatGPT account. The subagent's send_message to the lead is sealed
// by the ChatGPT backend. The lead's next turn went nowhere: magpie turned
// it away as a "subagent's task" sealed for a lead that "has since been on
// one of Codex's own models", which it never was. A sealed message (not a
// task) the model can't open is left out, said so in its place, and the
// lead goes on on token.
func TestSealedMessageToALeadOnAChatProviderIsLeftOut(t *testing.T) {
fresh(t)
var native int
chatgpt(t, func(w http.ResponseWriter, r *http.Request) { io.ReadAll(r.Body); native++ })
token := chatRecordedOn(t, "token", "gpt-6.1-sol")
s := New()
if rec := codexSubTurn(s, "token/gpt-6.1-sol", "lead-1", "", leadAsk); rec.Code != 200 {
t.Fatalf("lead's first turn: %d %s", rec.Code, rec.Body.String())
}
rec := codexSubTurn(s, "token/gpt-6.1-sol", "lead-1", "", leadAsk+`,`+sealedWorkerMessage)
if rec.Code != 200 {
t.Fatalf("lead's turn with its subagent's sealed message: %d %s", rec.Code, rec.Body.String())
}
got := token.requests()
if len(got) != 2 || native != 0 {
t.Fatalf("token was asked %d times, the ChatGPT backend %d", len(got), native)
}
if strings.Contains(got[1], "gAAAAA") || !strings.Contains(got[1], "/root/worker") || !strings.Contains(got[1], "left out") {
t.Fatalf("the lead's request to token: %s", got[1])
}
}
// The same for a subagent on token whose task is plain (its lead on
// token) and that is sent a sealed message by an agent on one of Codex's
// own models: the message is left out, the task kept.
func TestSealedMessageToASubagentOnAChatProviderIsLeftOut(t *testing.T) {
fresh(t)
chatgpt(t, func(w http.ResponseWriter, r *http.Request) { io.ReadAll(r.Body) })
token := chatRecordedOn(t, "token", "gpt-6.1-sol")
s := New()
if rec := codexSubTurn(s, "token/gpt-6.1-sol", "lead-1", "", leadAsk); rec.Code != 200 {
t.Fatalf("lead: %d %s", rec.Code, rec.Body.String())
}
msg := strings.NewReplacer(`"recipient":"/root"`, `"recipient":"/root/helper"`, `Task name: /root\n`, `Task name: /root/helper\n`).Replace(sealedWorkerMessage)
rec := codexSubTurn(s, "token/gpt-6.1-sol", "helper-1", "lead-1", plainTask+`,`+msg)
if rec.Code != 200 {
t.Fatalf("subagent: %d %s", rec.Code, rec.Body.String())
}
got := token.requests()
if len(got) != 2 || strings.Contains(got[1], "gAAAAA") || !strings.Contains(got[1], "read the README") || !strings.Contains(got[1], "left out") {
t.Fatalf("token was sent %d requests; the subagent's: %v", len(got), got[len(got)-1:])
}
}
// A sealed task is still turned away: without it the subagent has
// nothing to do. Only a message is left out.
func TestSealedTaskOnAChatProviderStillTurnedAway(t *testing.T) {
fresh(t)
chatgpt(t, func(w http.ResponseWriter, r *http.Request) { io.ReadAll(r.Body) })
token := chatRecordedOn(t, "token", "gpt-6.1-sol")
s := New()
if rec := codexSubTurn(s, "token/gpt-6.1-sol", "lead-1", "", leadAsk); rec.Code != 200 {
t.Fatalf("lead: %d %s", rec.Code, rec.Body.String())
}
rec := codexSubTurn(s, "token/gpt-6.1-sol", "worker-1", "lead-1", sealedHandoff)
if rec.Code != 400 || len(token.requests()) != 1 {
t.Fatalf("subagent: %d %s (token asked %d times)", rec.Code, rec.Body.String(), len(token.requests()))
}
if body := rec.Body.String(); strings.Contains(body, "the lead has since been on") || !strings.Contains(body, "token/gpt-6.1-sol can't") {
t.Fatalf("the refusal: %s", body)
}
}