gateway: Codex gives Claude its signed thinking back through encrypted_content

Codex calling a Claude model through magpie (mysterious_dove_96933 on
Discord): a reply's reasoning items carried only the summary, so Claude's
thinking signature and a redacted_thinking block's data were gone. On
the next request of a tool loop magpie sent Anthropic the turn as
[tool_use] alone, with thinking on, which Anthropic documents as a 400
("final assistant message must start with a thinking block"), and the
model lost its reasoning across calls either way.

Now the Anthropic decoders name a signature as Claude's (KSig with
sealAnthropic, Part.SignedBy). The Responses encoder and renderResponses
give each thinking block a reasoning item whose encrypted_content is
"magpie-claude1:" and the block's JSON in base64 (internal/claudeseal):
its summary beside it, an empty summary for a block signed with no
text, and redacted_thinking as an item of its own. parseResponses reads
it back into the block as Claude wrote it, in order, so anthropicBody
sends it as before for an Anthropic client. A Gemini thought's
signature isn't named and isn't sealed.

The envelope never reaches a Responses API: withoutClaudeSeals in
passthrough and forwardOnce (the item keeps its summary, one with none
goes), codexInputAs leaves such an item out for Codex's own models, and
codexUpstreamOn takes it out before the ChatGPT backend. OpenAI's own
encrypted_content is untouched. sessions.PortCodexRollouts writes such
an item as its summary, so a thread resumed against OpenAI itself isn't
refused. redact.MaskJSON already keeps a reasoning item's seal whole
(no change); TestMaskJSONKeepsClaudeBlocks holds that.

Run, at 5e3dd1d52 plus this change:
- go test -count=1 -timeout 45m ./internal/gateway/ ./internal/sessions/
  ./internal/redact/ ./internal/claudeseal/: sessions, redact,
  claudeseal ok; gateway ok but for TestResponsesStreamToolThenHiddenThinking
  (#1786), whose hidden cases wanted no reasoning item, the loss this
  fixes. They now want one item carrying the sealed block with an empty
  summary, and its guarantee (a whole stream, no panic) is unchanged;
  re-run green.
- gofmt -l clean; go vet (darwin) on the touched packages, GOOS=linux
  go vet -tags nogui ./internal/..., GOOS=windows go vet on the touched
  packages: clean.
- TestCodexToolLoopGivesClaudeItsThinkingBack (a fake Anthropic: signed
  thinking, redacted_thinking, a text-less signed block, tool_use; a
  Codex-shaped request with store false and the encrypted_content
  include; then the follow-up) fails on 5e3dd1d52: "stream=true:
  Anthropic was sent 1 assistant blocks, want 4". Passes now, streamed
  and not.
- Real: a sandbox HOME with only OpenRouter's key (Anthropic endpoint,
  anthropic/claude-opus-5.5, served by Claude Platform on AWS), magpie
  serve on its own port, a Codex-shaped two-turn tool loop at effort
  high, streamed and not: turn 1 gave a reasoning item with
  magpie-claude1: (3.1KB), turn 2 was 200 through /v1/responses →
  /v1/messages and answered from the tool output.

Broken by hand:
- withoutClaudeSeals a no-op: TestClaudeBlocksNeverGoToAResponsesAPI
  red, the relay sent magpie-claude1: items.
- codexInputAs not leaving them out: red, "ChatGPT backend would be
  sent …".
- sealing any signature (no sealAnthropic check):
  TestGeminiSignatureIsNotSealedAsClaudes red.
- portValue's reasoning branch off: TestPortLineDropsClaudeBlocks red.

Not tried: the 400 itself. Through OpenRouter, Opus 5.5 answered turn 2
with the envelope stripped too (the old shape), so this route shows
only the lost reasoning, not the refusal. Not tried on api.anthropic.com
directly, Bedrock or Vertex keys, or Claude's subscription (whose tool
loop stays inside Claude Code's run). Codex resuming a ported thread
against OpenAI with such items wasn't run.
This commit is contained in:
yetone
2026-10-27 11:26:54 +08:00
parent 39238183da
commit 79c8667c92
14 changed files with 614 additions and 33 deletions
File diff suppressed because one or more lines are too long
+47
View File
@@ -0,0 +1,47 @@
// Package claudeseal carries Claude's signed reasoning through a Responses
// client (mysterious_dove_96933 on Discord).
//
// Claude signs each thinking block and seals a redacted_thinking block
// whole, and Anthropic wants both back as they came on the next request
// of a tool loop. A Responses client such as Codex, with store off, keeps
// only what a reply's reasoning items carry, and of those only
// encrypted_content is opaque. So magpie writes the block there: "magpie-
// claude1:" and the block's JSON in base64, which only magpie reads. Sent
// to OpenAI it would be refused as invalid_encrypted_content, so the
// gateway drops it before any Responses upstream, and a rollout is made
// portable by dropping it there (sessions.PortCodexRollouts).
package claudeseal
import (
"encoding/base64"
"encoding/json"
"strings"
)
// Mark begins the encrypted_content of a reasoning item carrying a
// Claude block.
const Mark = "magpie-claude1:"
// Seal is the encrypted_content carrying block, a Messages content block
// (thinking with its signature, or redacted_thinking).
func Seal(block []byte) string {
return Mark + base64.StdEncoding.EncodeToString(block)
}
// Open is the block an encrypted_content carries: ours is false for one
// magpie didn't seal, and block nil for one of magpie's that can't be
// read.
func Open(encrypted string) (block json.RawMessage, ours bool) {
b64, ok := strings.CutPrefix(encrypted, Mark)
if !ok {
return nil, false
}
b, err := base64.StdEncoding.DecodeString(b64)
if err != nil || !json.Valid(b) {
return nil, true
}
return b, true
}
// Is reports whether encrypted is one magpie sealed.
func Is(encrypted string) bool { return strings.HasPrefix(encrypted, Mark) }
+2 -2
View File
@@ -1295,7 +1295,7 @@ func decodeAnthropic(data string, emit func(Event)) error {
emit(Event{Kind: KThink, Text: ev.ContentBlock.Thinking})
}
if ev.ContentBlock.Signature != "" {
emit(Event{Kind: KSig, Text: ev.ContentBlock.Signature})
emit(Event{Kind: KSig, Name: sealAnthropic, Text: ev.ContentBlock.Signature})
}
case "redacted_thinking":
// sealed whole: it goes on as it came, to Messages only
@@ -1315,7 +1315,7 @@ func decodeAnthropic(data string, emit func(Event)) error {
case "thinking_delta":
emit(Event{Kind: KThink, Text: ev.Delta.Thinking})
case "signature_delta":
emit(Event{Kind: KSig, Text: ev.Delta.Signature})
emit(Event{Kind: KSig, Name: sealAnthropic, Text: ev.Delta.Signature})
}
case "message_delta":
if ev.Delta.StopReason != "" {
+95
View File
@@ -0,0 +1,95 @@
package gateway
import (
"bytes"
"encoding/json"
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/claudeseal"
)
// Claude's signed reasoning through a Responses client (mysterious_dove_96933
// on Discord): a reply's reasoning item carries Claude's thinking block,
// signature and all, or its redacted_thinking block, in encrypted_content
// (claudeseal), and the next request reads it back into the block as
// Claude wrote it, which Anthropic wants back on a tool loop's next turn.
// claudeThinking is the encrypted_content of a reasoning item for Claude's
// thinking block with its signature.
func claudeThinking(text, signature string) string {
b, _ := json.Marshal(struct {
Type string `json:"type"`
Thinking string `json:"thinking"`
Signature string `json:"signature"`
}{"thinking", text, signature})
return claudeseal.Seal(b)
}
// claudePart is the reasoning a block magpie sealed stands for: Claude's
// thinking, signed, or its redacted_thinking whole; summary (the item's
// own reasoning, as it is without one) when the block can't be read.
func claudePart(block json.RawMessage, summary Part) Part {
var b struct {
Type string `json:"type"`
Thinking string `json:"thinking"`
Signature string `json:"signature"`
Data string `json:"data"`
}
if block == nil || decodeJSON(block, &b) != nil {
return summary
}
switch {
case b.Type == "thinking" && b.Signature != "":
return Part{Kind: Thinking, Text: b.Thinking, Signature: b.Signature, SignedBy: sealAnthropic}
case b.Type == "redacted_thinking" && b.Data != "":
return Part{Kind: Thinking, Sealed: block, SealedBy: sealAnthropic}
}
return summary
}
// withoutClaudeSeals is a Responses request body with no Claude block in
// its reasoning items, for a Responses API: OpenAI would refuse the
// envelope as invalid_encrypted_content, and Claude's thinking is no other
// vendor's to read. An item keeps its summary, as it was before magpie
// carried the block; one with none (a block signed with no text, or
// redacted) goes. Every other item, and a body with none, goes byte for
// byte.
func withoutClaudeSeals(body []byte) []byte {
if !bytes.Contains(body, []byte(claudeseal.Mark)) {
return body
}
var q map[string]json.RawMessage
var input []json.RawMessage
if decodeJSON(body, &q) != nil || decodeJSON(q["input"], &input) != nil {
return body
}
out := make([]json.RawMessage, 0, len(input))
changed := false
for _, it := range input {
r := gjson.ParseBytes(it)
if r.Get("type").String() != "reasoning" || !claudeseal.Is(r.Get("encrypted_content").String()) {
out = append(out, it)
continue
}
changed = true
if len(r.Get("summary").Array()) == 0 && len(r.Get("content").Array()) == 0 {
continue
}
var m map[string]json.RawMessage
if decodeJSON(it, &m) != nil {
continue
}
delete(m, "encrypted_content")
b, _ := json.Marshal(m)
out = append(out, b)
}
if !changed {
return body
}
q["input"], _ = json.Marshal(out)
b, err := json.Marshal(q)
if err != nil {
return body
}
return b
}
+2 -2
View File
@@ -2506,7 +2506,7 @@ func (r *subscriptionRun) readOutput(rd io.Reader) {
r.emit(Event{Kind: KThink, Text: c.Thinking})
}
if c.Signature != "" {
r.emit(Event{Kind: KSig, Text: c.Signature})
r.emit(Event{Kind: KSig, Name: sealAnthropic, Text: c.Signature})
}
case "text":
said(c.Text)
@@ -2585,7 +2585,7 @@ func (r *subscriptionRun) readOutput(rd io.Reader) {
case "thinking_delta":
r.emit(Event{Kind: KThink, Text: e.Delta.Thinking})
case "signature_delta":
r.emit(Event{Kind: KSig, Text: e.Delta.Signature})
r.emit(Event{Kind: KSig, Name: sealAnthropic, Text: e.Delta.Signature})
case "input_json_delta":
if !own[e.Index] {
r.emit(Event{Kind: KToolArgs, Text: e.Delta.PartialJSON})
+9 -2
View File
@@ -20,6 +20,7 @@ import (
"github.com/yetone/magpie/internal/access"
"github.com/yetone/magpie/internal/catalog"
"github.com/yetone/magpie/internal/claudeseal"
"github.com/yetone/magpie/internal/codexcat"
"github.com/yetone/magpie/internal/codexsummary"
"github.com/yetone/magpie/internal/provider"
@@ -897,6 +898,9 @@ func (s *Server) codexUpstreamOn(w http.ResponseWriter, r *http.Request, rest st
start := time.Now()
usage.Saw(agentOf(r))
w0, body0 := w, body // as they came, for the fallbacks (codexFallBack)
// Claude's blocks magpie gave Codex (claudeseal) are Claude's alone:
// to OpenAI each item is its summary, as before magpie carried them
body = withoutClaudeSeals(body)
var maskedHits maskHits
if r.Method == http.MethodPost {
var unmask func()
@@ -2102,7 +2106,10 @@ func codexInputAs(body []byte, magpieModel, native bool) (_ []byte, compact bool
// Nor reasoning with nothing sealed in it — another vendor's,
// only an id (rs_…): OpenAI, which keeps nothing (store is
// false), looks the id up and answers 404 "Item … not found".
if enc, _ := it["encrypted_content"].(string); enc == "" {
// Nor Claude's block magpie carried in one (claudeseal),
// which OpenAI would refuse as invalid_encrypted_content:
// before magpie carried it, the item had nothing sealed
if enc, _ := it["encrypted_content"].(string); enc == "" || claudeseal.Is(enc) {
changed = true
continue
}
@@ -2179,7 +2186,7 @@ func codexInputItemChanges(it []byte, magpieModel, native bool) bool {
}
}
enc, _ := stringBytes(memberOrNil(it, "encrypted_content"))
return len(enc) == 0
return len(enc) == 0 || hasPrefix(enc, claudeseal.Mark)
}
return false
}
+9
View File
@@ -4126,6 +4126,10 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid
body = kimiLockedSampling(p, to, body)
body = clinePin(p, to, body)
body = codexImagesFit(p, to, body)
if to == provider.Responses {
// whatever the route, Claude's blocks never reach a Responses API
body = withoutClaudeSeals(body)
}
if to == provider.Responses && !keepsAccessPrograms(p, in) {
// Codex's Cyber program, relayed or built, goes to OpenAI alone
// (#3172); before the user's own fields, which may name one
@@ -4405,6 +4409,11 @@ func codexClientHeader(k string) bool {
func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.Provider, proto provider.Protocol, model string, body []byte, u *Usage) (status int, msg string, done bool) {
upstream := provider.UpstreamNameIn(wiresOf(r.Context()), p.ID, model)
body = rewriteModel(body, upstream)
if proto == provider.Responses {
// Claude's blocks magpie gave a Responses client go back to Claude
// alone; to this API the item is its summary, as before
body = withoutClaudeSeals(body)
}
// a client that asked for one body, of an account that only streams:
// asked streamed, the stream read here (gathered)
var gather *gathered
+10 -2
View File
@@ -64,6 +64,11 @@ type Part struct {
// comes only from Google, as gemini_signature.go carries it, and
// text's only from a Gemini API (#1445)
Signature string
// SignedBy is the API that signed a thinking Part (sealAnthropic for
// Claude's), empty when it isn't known: only Claude's signature goes
// to a Responses client, in its reasoning item's encrypted_content
// (claudeseal)
SignedBy string
// thinking an upstream sealed, as its API wrote it: Anthropic's
// redacted_thinking block, a Responses reasoning item with its id,
// summary and encrypted_content. Only that API's builder, encoder and
@@ -302,7 +307,7 @@ const (
KStart EventKind = iota // MsgID, Model, Usage (input side)
KText // Text
KThink // Text (reasoning)
KSig // Text (thinking signature)
KSig // Text (thinking signature), Name the API that signed it if known
KToolStart // ID, Name
KToolArgs // Text (partial JSON of the arguments)
KStop // Stop
@@ -601,9 +606,12 @@ func (c *collector) add(ev Event) {
// display is omitted) is a block all the same (#1445)
if p := c.open(); p != nil {
p.Signature += ev.Text
if ev.Name != "" {
p.SignedBy = ev.Name
}
} else if c.fresh {
c.closeTool()
c.res.Parts = append(c.res.Parts, Part{Kind: Thinking, Signature: ev.Text})
c.res.Parts = append(c.res.Parts, Part{Kind: Thinking, Signature: ev.Text, SignedBy: ev.Name})
}
case KSealed:
// a Responses item's summary came before it as reasoning of its
@@ -0,0 +1,275 @@
package gateway
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
"github.com/yetone/magpie/internal/claudeseal"
"github.com/yetone/magpie/internal/provider"
)
// Codex calling a Claude model through magpie (mysterious_dove_96933 on
// Discord): Claude's thinking is signed, and a redacted_thinking block is
// sealed whole, and Anthropic wants both back intact on the next request
// of a tool loop. Codex keeps only what a reply's reasoning items carry,
// so they carry Claude's blocks in encrypted_content, and the next
// request has them back, in order, as Claude wrote them.
// claudeToolTurn is a Messages stream as Anthropic's extended thinking
// docs give one ending in a tool call: a signed thinking block, a
// redacted_thinking block, a block signed with no text (display omitted),
// then the call.
var claudeToolTurn = []string{
`{"type":"message_start","message":{"id":"msg_01","type":"message","role":"assistant","model":"claude-sonnet-4-5","content":[],"usage":{"input_tokens":10,"output_tokens":1}}}`,
`{"type":"content_block_start","index":0,"content_block":{"type":"thinking","thinking":"","signature":""}}`,
`{"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"I should list "}}`,
`{"type":"content_block_delta","index":0,"delta":{"type":"thinking_delta","thinking":"the files."}}`,
`{"type":"content_block_delta","index":0,"delta":{"type":"signature_delta","signature":"ErUBCkYIBxgCIkB2signed"}}`,
`{"type":"content_block_stop","index":0}`,
`{"type":"content_block_start","index":1,"content_block":` + redactedBlock + `}`,
`{"type":"content_block_stop","index":1}`,
`{"type":"content_block_start","index":2,"content_block":{"type":"thinking","thinking":"","signature":""}}`,
`{"type":"content_block_delta","index":2,"delta":{"type":"signature_delta","signature":"EqQBCkYIBxgCKkDomitted"}}`,
`{"type":"content_block_stop","index":2}`,
`{"type":"content_block_start","index":3,"content_block":{"type":"tool_use","id":"toolu_01","name":"shell","input":{}}}`,
`{"type":"content_block_delta","index":3,"delta":{"type":"input_json_delta","partial_json":"{\"command\":[\"ls\"]}"}}`,
`{"type":"content_block_stop","index":3}`,
`{"type":"message_delta","delta":{"stop_reason":"tool_use","stop_sequence":null},"usage":{"output_tokens":30}}`,
`{"type":"message_stop"}`,
}
// claudeTurnBlocks are the blocks claudeToolTurn's message is made of.
var claudeTurnBlocks = []string{
`{"type":"thinking","thinking":"I should list the files.","signature":"ErUBCkYIBxgCIkB2signed"}`,
redactedBlock,
`{"type":"thinking","thinking":"","signature":"EqQBCkYIBxgCKkDomitted"}`,
`{"type":"tool_use","id":"toolu_01","name":"shell","input":{"command":["ls"]}}`,
}
// claudeUp answers a request without a tool result with claudeToolTurn,
// and one with a result with a line of text, keeping what it was sent.
type claudeUp struct {
mu sync.Mutex
sent []string
}
func (u *claudeUp) ServeHTTP(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
u.mu.Lock()
u.sent = append(u.sent, string(b))
u.mu.Unlock()
w.Header().Set("Content-Type", "text/event-stream")
lines := claudeToolTurn
if strings.Contains(string(b), `"tool_result"`) {
lines = []string{
`{"type":"message_start","message":{"id":"msg_02","type":"message","role":"assistant","model":"claude-sonnet-4-5","content":[],"usage":{"input_tokens":10,"output_tokens":1}}}`,
`{"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`,
`{"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"Two files."}}`,
`{"type":"content_block_stop","index":0}`,
`{"type":"message_delta","delta":{"stop_reason":"end_turn","stop_sequence":null},"usage":{"output_tokens":3}}`,
`{"type":"message_stop"}`,
}
}
for _, l := range lines {
var ev struct {
Type string `json:"type"`
}
json.Unmarshal([]byte(l), &ev)
io.WriteString(w, "event: "+ev.Type+"\ndata: "+l+"\n\n")
}
}
// codexLoopAsk is a request as Codex sends one with store off: the reasoning
// items of a reply come back in input with their encrypted_content.
func codexLoopAsk(stream bool, input string) string {
s := "false"
if stream {
s = "true"
}
return `{"model":"a/claude-sonnet-4-5","instructions":"You are a coding agent.","input":` + input + `,` +
`"tools":[{"type":"function","name":"shell","description":"Runs a command","strict":false,"parameters":{"type":"object","properties":{"command":{"type":"array","items":{"type":"string"}}},"required":["command"]}}],` +
`"tool_choice":"auto","parallel_tool_calls":false,"reasoning":{"effort":"medium","summary":"auto"},"store":false,"stream":` + s +
`,"include":["reasoning.encrypted_content"],"prompt_cache_key":"t1"}`
}
// replyItems are a Responses reply's output items, from its
// response.output_item.done events when it streamed.
func replyItems(t *testing.T, body []byte, stream bool) []map[string]any {
t.Helper()
var items []map[string]any
if !stream {
var out struct {
Output []map[string]any `json:"output"`
}
if err := json.Unmarshal(body, &out); err != nil {
t.Fatalf("%v: %s", err, body)
}
return out.Output
}
for _, ev := range sseData(t, body) {
if ev["type"] == "response.output_item.done" {
items = append(items, ev["item"].(map[string]any))
}
}
return items
}
// The tool loop as Codex runs it against a Claude model on an Anthropic
// API key: the second request reaches Anthropic with the first reply's
// signed thinking, redacted_thinking and text-less signed block, in
// order and as Claude wrote them, before the tool_use, streamed or not.
func TestCodexToolLoopGivesClaudeItsThinkingBack(t *testing.T) {
for _, stream := range []bool{true, false} {
fresh(t)
up := &claudeUp{}
srv := httptest.NewServer(up)
t.Cleanup(srv.Close)
if err := provider.Save(provider.Provider{ID: "a", Name: "A", Key: "k", Anthropic: srv.URL, Models: []string{"claude-sonnet-4-5"}}); err != nil {
t.Fatal(err)
}
s := New()
user := `{"type":"message","role":"user","content":[{"type":"input_text","text":"What is here?"}]}`
rec := httptest.NewRecorder()
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(codexLoopAsk(stream, "["+user+"]"))))
if rec.Code != 200 {
t.Fatalf("stream=%t turn 1: %d %s", stream, rec.Code, rec.Body)
}
// Codex keeps each item as it came, less a reasoning item's id
// (it doesn't send one back with store off), then the call's output
input := []string{user}
var call string
for _, it := range replyItems(t, rec.Body.Bytes(), stream) {
delete(it, "status")
if it["type"] == "reasoning" {
delete(it, "id")
}
if it["type"] == "function_call" {
call, _ = it["call_id"].(string)
}
b, _ := json.Marshal(it)
input = append(input, string(b))
}
if call == "" {
t.Fatalf("stream=%t: no call in %s", stream, rec.Body)
}
input = append(input, `{"type":"function_call_output","call_id":"`+call+`","output":"a.go\nb.go"}`)
rec = httptest.NewRecorder()
s.Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(codexLoopAsk(stream, "["+strings.Join(input, ",")+"]"))))
if rec.Code != 200 || !strings.Contains(rec.Body.String(), "Two files.") {
t.Fatalf("stream=%t turn 2: %d %s", stream, rec.Code, rec.Body)
}
up.mu.Lock()
last := up.sent[len(up.sent)-1]
up.mu.Unlock()
var q struct {
Messages []struct {
Role string `json:"role"`
Content []json.RawMessage `json:"content"`
} `json:"messages"`
}
if err := json.Unmarshal([]byte(last), &q); err != nil {
t.Fatal(err)
}
var got []json.RawMessage
for _, m := range q.Messages {
if m.Role == "assistant" {
got = append(got, m.Content...)
}
}
if len(got) != len(claudeTurnBlocks) {
t.Fatalf("stream=%t: Anthropic was sent %d assistant blocks, want %d:\n%s", stream, len(got), len(claudeTurnBlocks), last)
}
for i, w := range claudeTurnBlocks {
var g map[string]any
json.Unmarshal(got[i], &g)
delete(g, "cache_control")
if !jsonIs(t, g, w) {
t.Fatalf("stream=%t: block %d:\n got %s\nwant %s\nsent %s", stream, i, got[i], w, last)
}
}
}
}
// claudeConversation is a Codex conversation that went through Claude and
// now goes on with another model: a reasoning item with a summary and
// Claude's block, one with Claude's block alone, and one OpenAI sealed.
func claudeConversation() string {
think := claudeThinking("I should list the files.", "ErUBCkYIBxgCIkB2signed")
redacted := claudeseal.Seal([]byte(redactedBlock))
return `{"type":"message","role":"user","content":[{"type":"input_text","text":"What is here?"}]},` +
`{"type":"reasoning","summary":[{"type":"summary_text","text":"I should list the files."}],"encrypted_content":"` + think + `"},` +
`{"type":"reasoning","summary":[],"encrypted_content":"` + redacted + `"},` +
`{"type":"function_call","call_id":"call_1","name":"shell","arguments":"{\"command\":[\"ls\"]}"},` +
`{"type":"function_call_output","call_id":"call_1","output":"a.go"},` +
`{"type":"reasoning","id":"rs_openai","summary":[],"encrypted_content":"gAAAA-openai-sealed"},` +
`{"type":"message","role":"user","content":[{"type":"input_text","text":"and now?"}]}`
}
// Claude's blocks are Claude's: a Responses API (a relay here, the
// ChatGPT backend for Codex's own models) is sent each item as it was
// before magpie carried them, its summary alone or nothing, and never the
// envelope, which OpenAI would refuse as invalid_encrypted_content. What
// OpenAI sealed goes on untouched.
func TestClaudeBlocksNeverGoToAResponsesAPI(t *testing.T) {
fresh(t)
u := &relayUpstream{}
saveRelay(t, u)
body := `{"model":"relay/gpt-5.4","stream":true,"store":false,"include":["reasoning.encrypted_content"],"input":[` + claudeConversation() + `]}`
if rec := codexPostTo(New(), body); rec.Code != 200 {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
asked := u.asked()
if len(asked) != 1 {
t.Fatalf("relay asked %d times", len(asked))
}
sent, _ := json.Marshal(asked[0])
if strings.Contains(string(sent), claudeseal.Mark) || !strings.Contains(string(sent), "gAAAA-openai-sealed") {
t.Fatalf("relay was sent %s", sent)
}
if !strings.Contains(string(sent), "I should list the files.") {
t.Fatalf("the summary went missing: %s", sent)
}
// Codex's own model on the ChatGPT backend
out, _ := codexInputAs([]byte(`{"model":"gpt-5.4","input":[`+claudeConversation()+`]}`), false, false)
if strings.Contains(string(out), claudeseal.Mark) || !strings.Contains(string(out), "gAAAA-openai-sealed") {
t.Fatalf("ChatGPT backend would be sent %s", out)
}
if strings.Count(string(out), `"reasoning"`) != 1 {
t.Fatalf("want only OpenAI's reasoning item: %s", out)
}
// and nothing to take out, the body goes byte for byte
plain := []byte(`{"input":[{"type":"reasoning","summary":[],"encrypted_content":"gAAAA"}],"x":1}`)
if got := withoutClaudeSeals(plain); string(got) != string(plain) {
t.Fatalf("%s became %s", plain, got)
}
}
// Only Claude's signature goes in encrypted_content: a Gemini thought's
// (an unnamed KSig, or a Part with no SignedBy) isn't sealed as Claude's,
// streamed or not.
func TestGeminiSignatureIsNotSealedAsClaudes(t *testing.T) {
rec := httptest.NewRecorder()
enc := &responsesEncoder{w: newSSEWriter(rec), model: "m"}
enc.event(Event{Kind: KThinkStart})
enc.event(Event{Kind: KThink, Text: "thought"})
enc.event(Event{Kind: KSig, Text: "gemini-sig"})
enc.event(Event{Kind: KThinkStart})
enc.event(Event{Kind: KSig, Text: "gemini-bare"})
enc.event(Event{Kind: KText, Text: "hi"})
enc.event(Event{Kind: KStop, Stop: "stop"})
enc.finish()
if strings.Contains(rec.Body.String(), "encrypted_content") || strings.Contains(rec.Body.String(), "gemini-") {
t.Fatalf("stream: %s", rec.Body)
}
b := renderResponses(Result{Parts: []Part{{Kind: Thinking, Text: "thought", Signature: "gemini-sig"}, {Kind: Thinking, Signature: "gemini-bare"}, {Kind: Text, Text: "hi"}}}, "m", nil)
if strings.Contains(string(b), "encrypted_content") || strings.Contains(string(b), "gemini-") {
t.Fatalf("render: %s", b)
}
}
+78 -14
View File
@@ -11,6 +11,7 @@ import (
"time"
"github.com/tidwall/gjson"
"github.com/yetone/magpie/internal/claudeseal"
"github.com/yetone/magpie/internal/provider"
)
@@ -439,7 +440,13 @@ func readResponses(body []byte, facts bool) (*Request, error) {
}
}
part := Part{Kind: Thinking, Text: b.String()}
if it.EncryptedContent != "" {
if block, ours := claudeseal.Open(it.EncryptedContent); ours {
// Claude's block, which magpie gave the client to carry
// back: as Claude wrote it, and never to a Responses API
// (withoutClaudeSeals). One that can't be read is its
// summary, as before.
part = claudePart(block, part)
} else if it.EncryptedContent != "" {
// sealed: the item goes back to a Responses API as it
// came, id, summary and all (#1445)
if rawItems == nil {
@@ -449,7 +456,7 @@ func readResponses(body []byte, facts bool) (*Request, error) {
part.Sealed, part.SealedBy = rawItems[i], sealResponses
}
}
if b.Len() > 0 || part.Sealed != nil {
if part.Text != "" || part.Sealed != nil || part.Signature != "" {
r.Messages = append(r.Messages, Message{Role: "assistant", Parts: []Part{part}})
}
}
@@ -1689,9 +1696,14 @@ type responsesEncoder struct {
// opens an item of its own, by thinkID when the upstream named it
thinkNew bool
thinkID string
output []any
col collector
named map[string]nsTool // the request's namespaced tools
// sig is Claude's signature of the open reasoning item's block, which
// its encrypted_content carries back (claudeseal); bare is an item of
// a block signed with no text, opened with no summary part
sig strings.Builder
bare bool
output []any
col collector
named map[string]nsTool // the request's namespaced tools
// call is the open function_call item's id and name, kept here: the
// collector's last part isn't it once a hidden thinking block (signed
// with no text, or redacted) has come after the call (#1786)
@@ -1845,10 +1857,19 @@ func (e *responsesEncoder) closeAs(sealed json.RawMessage) {
item, e.heldMsg = m, m
case Thinking:
t := e.text.String()
e.send("response.reasoning_summary_text.done", map[string]any{"item_id": e.itemID, "output_index": e.item, "summary_index": 0, "text": t})
part := map[string]any{"type": "summary_text", "text": t}
e.send("response.reasoning_summary_part.done", map[string]any{"item_id": e.itemID, "output_index": e.item, "summary_index": 0, "part": part})
item = map[string]any{"id": e.itemID, "type": "reasoning", "status": "completed", "summary": []map[string]any{part}}
summary := []map[string]any{}
if !e.bare {
e.send("response.reasoning_summary_text.done", map[string]any{"item_id": e.itemID, "output_index": e.item, "summary_index": 0, "text": t})
part := map[string]any{"type": "summary_text", "text": t}
e.send("response.reasoning_summary_part.done", map[string]any{"item_id": e.itemID, "output_index": e.item, "summary_index": 0, "part": part})
summary = append(summary, part)
}
m := map[string]any{"id": e.itemID, "type": "reasoning", "status": "completed", "summary": summary}
if e.sig.Len() > 0 {
// Claude's block, signed, for the next request to give back
m["encrypted_content"] = claudeThinking(t, e.sig.String())
}
item = m
if sealed != nil {
item = sealed
}
@@ -1871,6 +1892,7 @@ func (e *responsesEncoder) closeAs(sealed json.RawMessage) {
e.send("response.output_item.done", map[string]any{"output_index": e.item, "item": item})
e.output = append(e.output, item)
e.open, e.text = "", strings.Builder{}
e.sig, e.bare = strings.Builder{}, false
}
func (e *responsesEncoder) openItem(k Kind, prefix string, item map[string]any) {
@@ -1911,8 +1933,11 @@ func (e *responsesEncoder) event(ev Event) {
if ev.Text == "" {
return
}
if e.open != Thinking || e.thinkNew {
e.openItem(Thinking, "rs_", map[string]any{"type": "reasoning", "summary": []any{}})
if e.open != Thinking || e.thinkNew || e.bare {
if e.open != Thinking || e.thinkNew {
e.openItem(Thinking, "rs_", map[string]any{"type": "reasoning", "summary": []any{}})
}
e.bare = false
e.send("response.reasoning_summary_part.added", map[string]any{"item_id": e.itemID, "output_index": e.item, "summary_index": 0,
"part": map[string]any{"type": "summary_text", "text": ""}})
}
@@ -1923,7 +1948,32 @@ func (e *responsesEncoder) event(ev Event) {
if strings.HasPrefix(ev.ID, "rs_") {
e.thinkID = ev.ID
}
case KSig:
if ev.Name != sealAnthropic || ev.Text == "" {
break // Gemini's, which goes back on its own path
}
if e.open != Thinking || e.thinkNew {
// a block signed with no text in it: an item all the same,
// with no summary, for its signature to come back
e.openItem(Thinking, "rs_", map[string]any{"type": "reasoning", "summary": []any{}})
e.bare = true
}
e.sig.WriteString(ev.Text)
case KSealed:
if ev.Name == sealAnthropic {
// Claude's redacted_thinking: an item with no summary, the
// block whole in its encrypted_content
e.closeItem()
e.item++
e.thinkNew, e.thinkID = false, ""
id := "rs_" + newID()
e.send("response.output_item.added", map[string]any{"output_index": e.item,
"item": map[string]any{"id": id, "type": "reasoning", "status": "in_progress", "summary": []any{}}})
item := map[string]any{"id": id, "type": "reasoning", "status": "completed", "summary": []any{}, "encrypted_content": claudeseal.Seal([]byte(ev.Text))}
e.send("response.output_item.done", map[string]any{"output_index": e.item, "item": item})
e.output = append(e.output, item)
break
}
if ev.Name != sealResponses {
break // another API's, which a Responses client can't read
}
@@ -2059,11 +2109,25 @@ func renderResponses(res Result, model string, named map[string]nsTool) []byte {
output = append(output, p.Sealed)
continue
}
if p.Text == "" {
if p.sealedBy(sealAnthropic) {
// Claude's redacted_thinking, whole, to come back (claudeseal)
output = append(output, map[string]any{"id": "rs_" + newID(), "type": "reasoning", "status": "completed",
"summary": []any{}, "encrypted_content": claudeseal.Seal(p.Sealed)})
continue
}
claude := p.SignedBy == sealAnthropic && p.Signature != ""
if p.Text == "" && !claude {
continue // another API's sealed thinking, or only its signature
}
output = append(output, map[string]any{"id": "rs_" + newID(), "type": "reasoning", "status": "completed",
"summary": []map[string]any{{"type": "summary_text", "text": p.Text}}})
summary := []map[string]any{}
if p.Text != "" {
summary = append(summary, map[string]any{"type": "summary_text", "text": p.Text})
}
item := map[string]any{"id": "rs_" + newID(), "type": "reasoning", "status": "completed", "summary": summary}
if claude {
item["encrypted_content"] = claudeThinking(p.Text, p.Signature)
}
output = append(output, item)
case ToolCall:
id := p.ID
if id == "" {
@@ -8,6 +8,7 @@ import (
"strings"
"testing"
"github.com/yetone/magpie/internal/claudeseal"
"github.com/yetone/magpie/internal/provider"
)
@@ -66,7 +67,7 @@ func TestResponsesStreamToolThenHiddenThinking(t *testing.T) {
}
var completed map[string]any
var call map[string]any
var reasoning int
var reasoning []map[string]any
for _, ev := range events(string(body)) {
switch ev["type"] {
case "response.completed":
@@ -77,7 +78,7 @@ func TestResponsesStreamToolThenHiddenThinking(t *testing.T) {
case "function_call":
call = item
case "reasoning":
reasoning++
reasoning = append(reasoning, item)
}
}
}
@@ -88,8 +89,19 @@ func TestResponsesStreamToolThenHiddenThinking(t *testing.T) {
b, _ := json.Marshal(call)
t.Fatalf("function_call = %s, want toolu_01 shell {\"command\":[\"ls\"]}\n%s", b, body)
}
if want := map[bool]int{true: 1, false: 0}[c.visible]; reasoning != want {
t.Errorf("%d reasoning items, want %d", reasoning, want)
// Thinking Claude didn't show is still given back to it on the
// next request (mysterious_dove_96933 on Discord): one reasoning
// item carrying the block, its summary empty unless shown.
if len(reasoning) != 1 {
t.Fatalf("%d reasoning items, want 1\n%s", len(reasoning), body)
}
enc, _ := reasoning[0]["encrypted_content"].(string)
if !claudeseal.Is(enc) {
t.Errorf("reasoning item's encrypted_content = %q, want Claude's block sealed", enc)
}
summary, _ := reasoning[0]["summary"].([]any)
if shown := len(summary) > 0; shown != c.visible {
t.Errorf("reasoning summary = %v, want shown %v", summary, c.visible)
}
})
}
+17
View File
@@ -6,6 +6,8 @@ import (
"net/http/httptest"
"strings"
"testing"
"github.com/yetone/magpie/internal/claudeseal"
)
const (
@@ -207,6 +209,21 @@ func TestMaskJSONSignedGoesBackAsWritten(t *testing.T) {
}
}
// Claude's block magpie gave a Responses client to carry back
// (claudeseal) goes back byte for byte: Claude's own text in it, with the
// placeholders Claude was sent, is what its signature is checked against.
func TestMaskJSONKeepsClaudeBlocks(t *testing.T) {
o := Options{Secrets: true, Personal: true}
const email = "jeremy.zhou@gmail.com"
pe, _ := Mask(email, o)
sealed := claudeseal.Seal([]byte(`{"type":"thinking","thinking":"Write to ` + pe + `, or call 13800138000.","signature":"Eqk1"}`))
body := `{"input":[{"role":"user","content":"I am ` + email + `"},{"type":"reasoning","summary":[{"type":"summary_text","text":"Write to ` + email + `"}],"encrypted_content":"` + sealed + `"}]}`
out, _ := MaskJSON([]byte(body), o)
if !strings.Contains(string(out), `"`+sealed+`"`) || strings.Contains(string(out), email) {
t.Errorf("Claude's block not as it was sent, or a value went out:\n%s", out)
}
}
// An id goes as the vendor gave it, on both sides of what it matches.
func TestMaskJSONKeepsIDs(t *testing.T) {
o := Options{Secrets: true, Personal: true}
+25 -5
View File
@@ -17,6 +17,7 @@ import (
"github.com/klauspost/compress/zstd"
"github.com/yetone/magpie/internal/claudeseal"
"github.com/yetone/magpie/internal/codexsummary"
"github.com/yetone/magpie/internal/filelock"
"github.com/yetone/magpie/internal/settings"
@@ -32,10 +33,15 @@ import (
// local compaction keeps, and what the gateway sends for it anyway, so a
// rollout so written reads the same through magpie and goes on without it.
//
// Only magpie's compaction items change, in whichever line holds them (a
// response_item, a compacted line's replacement_history); every other
// line keeps its bytes, and the file its line count, mode and time. A
// rollout is changed as Codex publishes a compressed one
// A reasoning item magpie gave Codex with Claude's block in its
// encrypted_content (claudeseal) is refused the same way; it is written
// as its summary, as the gateway sends it to OpenAI.
//
// Only magpie's compaction items and those reasoning items change, in
// whichever line holds them (a response_item, a compacted line's
// replacement_history); every other line keeps its bytes, and the file
// its line count, mode and time. A rollout is changed as Codex publishes
// a compressed one
// (codex-rs/rollout/src/writer_lock.rs, try_acquire_for_publication):
// under its home's coordination lock, and only when no Codex holds the
// thread's writer lock, so never under a Codex that has the thread open.
@@ -204,6 +210,10 @@ func codexThreadOf(name string) string {
var magpieMark = []byte(codexsummary.Mark)
// claudeMark begins a reasoning item's encrypted_content carrying Claude's
// block (claudeseal), which only magpie reads.
var claudeMark = []byte(claudeseal.Mark)
// portRollout writes the rollout at path portable, if it has magpie's
// compaction item, and says whether it did.
func portRollout(ctx context.Context, home, path string) (bool, error) {
@@ -321,7 +331,7 @@ func portRollout(ctx context.Context, home, path string) (bool, error) {
// gateway leaves it out; a line that is one alone stays as it is, as
// leaving a line out would move every line after it.
func portLine(line []byte) ([]byte, bool) {
if !bytes.Contains(line, magpieMark) {
if !bytes.Contains(line, magpieMark) && !bytes.Contains(line, claudeMark) {
return line, false
}
body := bytes.TrimRight(line, "\r\n")
@@ -360,6 +370,16 @@ func portValue(v any) (_ any, changed, drop bool) {
}
return x, false, false
}
if t, _ := x["type"].(string); t == "reasoning" {
// Claude's block magpie gave Codex to carry back: sent to
// OpenAI it would be refused as invalid_encrypted_content, so
// the item goes as its summary, as magpie sends it to OpenAI
if enc, _ := x["encrypted_content"].(string); claudeseal.Is(enc) {
delete(x, "encrypted_content")
return x, true, false
}
return x, false, false
}
for k, c := range x {
list, isList := c.([]any)
if !isList {
+26
View File
@@ -13,6 +13,7 @@ import (
"github.com/klauspost/compress/zstd"
"github.com/yetone/magpie/internal/claudeseal"
"github.com/yetone/magpie/internal/codexsummary"
"github.com/yetone/magpie/internal/filelock"
)
@@ -237,3 +238,28 @@ func TestPortLineLeavesOthers(t *testing.T) {
t.Errorf("compaction_summary: %q", got)
}
}
// A reasoning item carrying Claude's block (claudeseal) is written as its
// summary, as the gateway sends it to OpenAI, in a response_item and in a
// compacted line's replacement_history; OpenAI's own encrypted_content and
// a mention of the mark in text keep their bytes.
func TestPortLineDropsClaudeBlocks(t *testing.T) {
sealed := claudeseal.Seal([]byte(`{"type":"thinking","thinking":"hm","signature":"sig"}`))
for _, l := range []string{
`{"type":"response_item","payload":{"type":"reasoning","summary":[],"encrypted_content":"gAAAAopenai"}}` + "\n",
`{"type":"response_item","payload":{"type":"message","role":"user","content":[{"type":"input_text","text":"` + sealed + `"}]}}` + "\n",
} {
if got, ok := portLine([]byte(l)); ok || string(got) != l {
t.Errorf("%q became %q", l, got)
}
}
for _, l := range []string{
`{"type":"response_item","payload":{"type":"reasoning","summary":[{"type":"summary_text","text":"hm"}],"encrypted_content":"` + sealed + `"}}` + "\n",
`{"type":"compacted","payload":{"message":"","replacement_history":[{"type":"reasoning","summary":[],"encrypted_content":"` + sealed + `"}]}}` + "\n",
} {
got, ok := portLine([]byte(l))
if !ok || bytes.Contains(got, []byte(claudeseal.Mark)) || bytes.Contains(got, []byte("encrypted_content")) || !bytes.Contains(got, []byte(`"reasoning"`)) {
t.Errorf("%q became %q", l, got)
}
}
}