codex: guide sealed subagent handoffs to supported models (#188)
This commit is contained in:
@@ -35,6 +35,8 @@ var codexAPIBase = "https://api.openai.com/v1"
|
||||
// only magpie reads back.
|
||||
const magpieCompaction = "magpie1:"
|
||||
|
||||
var nativeSealedAgentPayload = regexp.MustCompile(`^gAAAAA[A-Za-z0-9_-]+={0,2}$`)
|
||||
|
||||
// codexCompactPrompt and codexSummaryPrefix are Codex's own (Apache-2.0,
|
||||
// openai/codex, prompts/templates/compact).
|
||||
const codexCompactPrompt = `You are performing a CONTEXT CHECKPOINT COMPACTION. Create a handoff summary for another LLM that will resume the task.
|
||||
@@ -79,6 +81,10 @@ func (s *Server) codexBackend(w http.ResponseWriter, r *http.Request) {
|
||||
writeError(w, provider.Responses, 400, "/responses/compact is not supported for Magpie models; use a compaction_trigger on /responses")
|
||||
return
|
||||
}
|
||||
if hasSealedAgentMessage(body) {
|
||||
writeError(w, provider.Responses, 400, "An OpenAI lead sent a sealed subagent task that a Magpie-served model cannot read. Use a Magpie-served model for the lead, or choose an OpenAI subagent.")
|
||||
return
|
||||
}
|
||||
body, compact := codexInput(body, true)
|
||||
if compact {
|
||||
s.codexCompact(w, r, body)
|
||||
@@ -99,6 +105,38 @@ func (s *Server) codexBackend(w http.ResponseWriter, r *http.Request) {
|
||||
s.codexUpstream(w, r, rest, body)
|
||||
}
|
||||
|
||||
// Only native sealed agent tasks need this guidance. Other encrypted_content
|
||||
// fields (including ordinary model history) keep their existing handling.
|
||||
func hasSealedAgentMessage(body []byte) bool {
|
||||
var request map[string]json.RawMessage
|
||||
if json.Unmarshal(body, &request) != nil {
|
||||
return false
|
||||
}
|
||||
var items []json.RawMessage
|
||||
if json.Unmarshal(request["input"], &items) != nil {
|
||||
return false
|
||||
}
|
||||
for _, raw := range items {
|
||||
var item struct {
|
||||
Type string `json:"type"`
|
||||
Content []json.RawMessage `json:"content"`
|
||||
}
|
||||
if json.Unmarshal(raw, &item) != nil || item.Type != "agent_message" {
|
||||
continue
|
||||
}
|
||||
for _, content := range item.Content {
|
||||
var part struct {
|
||||
Type string `json:"type"`
|
||||
EncryptedContent string `json:"encrypted_content"`
|
||||
}
|
||||
if json.Unmarshal(content, &part) == nil && part.Type == "encrypted_content" && nativeSealedAgentPayload.MatchString(part.EncryptedContent) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// codexBody reads a request's body as it was before Codex compressed it
|
||||
// (zstd, for the ChatGPT backend), so it can be read and passed on plain.
|
||||
func codexBody(r *http.Request) ([]byte, error) {
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
const sealedHandoff = `{"type":"agent_message","author":"/root","recipient":"/root/worker","content":[{"type":"input_text","text":"Message Type: NEW_TASK\nPayload:\n"},{"type":"encrypted_content","encrypted_content":"gAAAAATest_ciphertext=="}]}`
|
||||
|
||||
func TestCodexSealedAgentHandoffGuidesBeforeRouting(t *testing.T) {
|
||||
for _, encoding := range []string{"identity", "gzip", "zstd"} {
|
||||
t.Run(encoding, func(t *testing.T) {
|
||||
f := &fake{t: t}
|
||||
setup(t, provider.Responses, f)
|
||||
var nativeCalls int
|
||||
chatgpt(t, func(w http.ResponseWriter, r *http.Request) { nativeCalls++ })
|
||||
body := `{"model":"fake/m1","stream":true,"input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"Start"}]},` + sealedHandoff + `,{"type":"compaction_trigger"}]}`
|
||||
req := httptest.NewRequest("POST", CodexPath+"/responses", strings.NewReader(string(encodedBody(t, []byte(body), encoding))))
|
||||
req.Header.Set("Content-Encoding", encoding)
|
||||
rec := httptest.NewRecorder()
|
||||
New().Handler().ServeHTTP(rec, req)
|
||||
var response struct {
|
||||
Error struct {
|
||||
Type string `json:"type"`
|
||||
Message string `json:"message"`
|
||||
} `json:"error"`
|
||||
}
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if rec.Code != 400 || response.Error.Type != "invalid_request_error" ||
|
||||
!strings.Contains(response.Error.Message, "OpenAI lead") ||
|
||||
!strings.Contains(response.Error.Message, "Magpie-served model for the lead") ||
|
||||
!strings.Contains(response.Error.Message, "OpenAI subagent") {
|
||||
t.Fatalf("guidance: status=%d response=%s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if strings.Contains(rec.Body.String(), "gAAAAA") || f.calls != 0 || nativeCalls != 0 {
|
||||
t.Fatalf("ciphertext leaked or request forwarded: fake=%d native=%d", f.calls, nativeCalls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCodexSealedAgentHandoffDoesNotAffectOtherMessages(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name, input string
|
||||
}{
|
||||
{"plain agent task", `[{"type":"agent_message","content":[{"type":"input_text","text":"Message Type: NEW_TASK\nPayload:\nreply PONG"}]}]`},
|
||||
{"non-native encrypted part", `[{"type":"agent_message","content":[{"type":"input_text","text":"Payload:\n"},{"type":"encrypted_content","encrypted_content":"plain task"}]}]`},
|
||||
{"other encrypted item", `[{"type":"message","role":"user","content":[{"type":"input_text","text":"hello"},{"type":"encrypted_content","encrypted_content":"gAAAAATest_ciphertext=="}]}]`},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f := &fake{t: t, reply: sse(`data: {"type":"response.completed","response":{"id":"r1","status":"completed","output":[]}}`)}
|
||||
setup(t, provider.Responses, f)
|
||||
body := `{"model":"fake/m1","stream":true,"input":` + tc.input + `}`
|
||||
code, response := post(t, CodexPath+"/responses", body)
|
||||
if code != 200 || f.calls != 1 || strings.Contains(response, "sealed subagent task") {
|
||||
t.Fatalf("normal request: status=%d upstream=%d response=%s", code, f.calls, response)
|
||||
}
|
||||
if tc.name == "plain agent task" && !strings.Contains(string(f.got), "reply PONG") {
|
||||
t.Fatal("plain task was not delivered")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCodexSealedAgentHandoffNativePassthrough(t *testing.T) {
|
||||
var got []byte
|
||||
chatgpt(t, func(w http.ResponseWriter, r *http.Request) {
|
||||
got, _ = io.ReadAll(r.Body)
|
||||
io.WriteString(w, sse(`data: {"type":"response.completed","response":{"id":"r1","status":"completed","output":[]}}`))
|
||||
})
|
||||
body := `{"model":"gpt-5.5","stream":true,"input":[` + sealedHandoff + `]}`
|
||||
code, response := codexPost(t, body)
|
||||
if code != 200 || !strings.Contains(string(got), "gAAAAATest_ciphertext==") || strings.Contains(response, "sealed subagent task") {
|
||||
t.Fatalf("native request: status=%d forwarded=%v response=%s", code, len(got) > 0, response)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// This explicit check uses the signed-in account for one native Codex turn.
|
||||
func TestLiveCodexSealedAgentGuidance(t *testing.T) {
|
||||
bin, home, codexHome := os.Getenv("MAGPIE_LIVE_CODEX_BIN"), os.Getenv("MAGPIE_LIVE_HOME"), os.Getenv("MAGPIE_LIVE_CODEX_HOME")
|
||||
if bin == "" || home == "" || codexHome == "" {
|
||||
t.Skip("live Codex environment not set")
|
||||
}
|
||||
var upstreamCalls atomic.Int32
|
||||
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
upstreamCalls.Add(1)
|
||||
http.Error(w, "unexpected child upstream request", 500)
|
||||
}))
|
||||
defer up.Close()
|
||||
if err := provider.Save(provider.Provider{ID: "fake", Name: "Fake", Key: "fake", Models: []string{"m1"}, Responses: up.URL + "/v1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
s := New()
|
||||
handler := s.Handler()
|
||||
var mu sync.Mutex
|
||||
var sawCiphertext, sawGuidance, leaked bool
|
||||
var childStatus int
|
||||
gateway := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
isChild := false
|
||||
if r.Method == http.MethodPost && r.URL.Path == CodexPath+"/responses" {
|
||||
body, err := codexBody(r)
|
||||
if err != nil {
|
||||
http.Error(w, "could not decode request", 400)
|
||||
return
|
||||
}
|
||||
isChild = bytes.Contains(body, []byte(`"model":"fake/m1"`))
|
||||
if isChild && bytes.Contains(body, []byte("gAAAAA")) {
|
||||
mu.Lock()
|
||||
sawCiphertext = true
|
||||
mu.Unlock()
|
||||
}
|
||||
r.Body = io.NopCloser(bytes.NewReader(body))
|
||||
}
|
||||
if !isChild {
|
||||
handler.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, r)
|
||||
mu.Lock()
|
||||
childStatus = rec.Code
|
||||
sawGuidance = sawGuidance || strings.Contains(rec.Body.String(), "Magpie-served model for the lead")
|
||||
leaked = leaked || bytes.Contains(rec.Body.Bytes(), []byte("gAAAAA"))
|
||||
mu.Unlock()
|
||||
for key, values := range rec.Header() {
|
||||
w.Header()[key] = values
|
||||
}
|
||||
w.WriteHeader(rec.Code)
|
||||
w.Write(rec.Body.Bytes())
|
||||
}))
|
||||
defer gateway.Close()
|
||||
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 4*time.Minute)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, bin, "exec", "--ignore-user-config", "--ephemeral", "--sandbox", "read-only", "--skip-git-repo-check",
|
||||
"-C", t.TempDir(), "-m", "gpt-6-sol", "-c", fmt.Sprintf("openai_base_url=%q", gateway.URL+CodexPath),
|
||||
"-c", "features.multi_agent_v2=true", "Spawn one worker subagent on model fake/m1 with fork_turns=none. Tell it to reply PONG-LIVE-AGENT. Wait for it. If the tool fails, report its exact error message. Do not use other tools.")
|
||||
cmd.Env = append(os.Environ(), "HOME="+home, "CODEX_HOME="+codexHome)
|
||||
output, err := cmd.CombinedOutput()
|
||||
mu.Lock()
|
||||
gotCiphertext, gotGuidance, gotLeak, status := sawCiphertext, sawGuidance, leaked, childStatus
|
||||
mu.Unlock()
|
||||
cliGuidance := strings.Contains(string(output), "Magpie-served model for the lead")
|
||||
if !gotCiphertext || !gotGuidance || gotLeak || status != 400 || upstreamCalls.Load() != 0 || !cliGuidance || err != nil {
|
||||
t.Errorf("live guidance: sealed=%v status=%d errorShown=%v leaked=%v upstreamCalls=%d cliShowsGuidance=%v cliError=%v", gotCiphertext, status, gotGuidance, gotLeak, upstreamCalls.Load(), cliGuidance, err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user