NonMirror (0.1.1239, OpenCode, codex/gpt-daybreak-blue-latest on a ChatGPT
sign-in): a top-level Responses access_programs never reached upstream,
and the codex provider's extraBody wasn't applied.
Cause:
- A Codex account is streamed upstream, so a whole (stream:false)
Responses request and every Chat or Messages request is translated
(parseResponses/parseChat -> Request -> buildResponses). Request had no
field for access_programs, so the rebuilt body dropped it. Only a
streamed Responses request, relayed through codexBody, kept it.
- WithExtraBody skipped every signed-in account, and withPicks didn't
copy the providers.json ExtraBody onto the account.
- writeError rewrapped every vendor error with code and param null, so
even a forwarded refusal lost what it was about.
- The backend refuses a program the workspace hasn't got inside a 200
stream (error event, invalid_request_error, access_program_not_enabled).
The whole-translated path answered that 502 api_error, and translated
streams wrote it as api_error, which holdWriter reads as 502: the same
request went three times, then to the other accounts, and every one
rested.
Fix:
- Request.AccessPrograms (Responses and Chat), built into the Responses
body as it came; a null is kept.
- A ChatGPT (Codex) account takes extraBody; store, tool_choice and
include stay magpie's (codexOwned). withPicks keeps ExtraBody.
- writeVendorError keeps the vendor's error.code and error.param on the
relayed, whole-translated and streamed-translated status-error paths.
- requestRefused: a Responses stream error/failed whose error type is
invalid_request_error carries status 400 and the vendor's error
(Event.Said). The whole path answers that 400 with code and param; the
Chat, Anthropic and Responses encoders write its type/code/param
(saidError). Read by the type, never by words.
- Codex CLI sends access_programs as a top-level object on its Responses
request (codex-rs ResponsesApiRequest.access_programs); OpenAI's Daybreak
guide documents the same field.
Run:
- New: internal/gateway/codex_access_programs_test.go
(TestCodexAccessProgramsReachBackend, TestCodexAccountTakesExtraBody,
TestAccessProgramsNullKept), passes -count=3.
- Broken by hand, each went red: buildResponses not emitting the field
(probe answered 200, the reporter's symptom); extraBodyTakes' Codex case;
withPicks' line; codexOwned emptied; writeVendorError ignoring the body;
the continuation site alone; retryable(400) true (asked twice, rested);
requestRefused returning nothing (502, asked 4 times, both accounts
rested); saidError a no-op (streamed: asked 4 times, rested); the whole
site back to 502 (same).
- go test -timeout 30m ./...: all 62 packages ok (gateway 1559s at load
~26; an earlier run at the default 10m timed out in gateway under that
load, not a failure). gofmt -l clean. GOOS=linux and GOOS=windows
go vet -tags nogui ./... clean.
Real account (sandbox HOME, own port 3486, copied auth.json with a dead
refresh token; owner's ChatGPT Pro account, model codex/gpt-5.6-luna):
- "__daybreak_forwarding_probe__": 400 invalid_value, param
access_programs.cyber ("Supported values are: 'standard',
'daybreak_blue', and 'daybreak_red'") on Responses whole and streamed,
Chat whole and streamed. The backend says invalid_value, not the
guide's invalid_access_program.
- standard: 200. null: 400 invalid_type.
- daybreak_blue (not enabled for this workspace): 400
access_program_not_enabled with param on Responses and Chat whole, the
error event with that code on Responses and Chat streamed; ~1s each,
one try (was 3 tries and a 502 before this change).
- The next plain request was served 200 by the same account: nothing
rested.
Not verified: the Daybreak model itself (not listed for this account),
so no 200 with daybreak_blue; OpenCode's own wire; the Messages route
against the real backend (fake backend only).
208 lines
7.1 KiB
Go
208 lines
7.1 KiB
Go
package provider
|
|
|
|
// A provider's extraBody (Luc-xz, #1604): JSON fields the user adds to the
|
|
// body of every request magpie sends the provider — a relay that turns a
|
|
// Responses request away without a prompt_cache_key, say — as Headers adds
|
|
// headers. They are merged at the top level of the body as it goes out,
|
|
// whichever API it is on (Chat, Responses, Messages, Gemini) and whether it
|
|
// was relayed or translated (gateway.forwardOnce):
|
|
//
|
|
// - A field the body has already — the client's own, or what magpie put
|
|
// there for it — is kept: the user's value fills in what is missing.
|
|
// - A name written with a "!" before it ("!prompt_cache_key") is forced:
|
|
// it replaces the body's own.
|
|
// - ${sessionId} in a string value, at any depth, is the conversation's
|
|
// id: the session the agent names (its session header), else one
|
|
// magpie derives from the conversation's first user message — the same
|
|
// for every turn of it. A fixed string would put every session on one
|
|
// cache key.
|
|
// - The fields that carry the conversation, or that magpie must decide
|
|
// for routing and streaming to work (ExtraBodyReserved), can't be set:
|
|
// a save naming one is refused, and one written into the file by hand
|
|
// is left out.
|
|
//
|
|
// The editor's Test and Detect send them too, on their own session
|
|
// (tested), so a relay that turns a request away without them still
|
|
// answers its Test. A request that only counts tokens gets none of them,
|
|
// nor one to another API (embeddings, images, video, a decision API's):
|
|
// the fields are for asking the model for a reply. Neither does a
|
|
// signed-in account's: its body is the agent's own, as its headers are —
|
|
// except a ChatGPT (Codex) account's, whose requests magpie builds as Codex
|
|
// CLI would (codexBody), and which take fields Codex CLI adds by choice
|
|
// (access_programs, OpenAI's Daybreak, magpie-releases#18). On it the
|
|
// fields codexBody decides for the backend to answer at all — not stored,
|
|
// tool_choice auto, its reasoning carried — can't be set either
|
|
// (codexOwned).
|
|
|
|
import (
|
|
"bytes"
|
|
"crypto/rand"
|
|
"encoding/json"
|
|
"fmt"
|
|
"maps"
|
|
"slices"
|
|
"strings"
|
|
)
|
|
|
|
// ExtraBody is a provider's extra body fields, each value as the user
|
|
// wrote it, a name that begins with "!" forced.
|
|
type ExtraBody map[string]json.RawMessage
|
|
|
|
// UnmarshalJSON reads an object; anything else written by hand (a string,
|
|
// a list) is read as none, rather than failing the whole providers file.
|
|
func (e *ExtraBody) UnmarshalJSON(b []byte) error {
|
|
var m map[string]json.RawMessage
|
|
if json.Unmarshal(b, &m) != nil {
|
|
*e = nil
|
|
return nil
|
|
}
|
|
*e = m
|
|
return nil
|
|
}
|
|
|
|
// ExtraBodyReserved are the fields extraBody can't set: the model and
|
|
// whether to stream, which magpie decides for routing and reads the reply
|
|
// by, and the conversation itself — its messages, input or contents, its
|
|
// system prompt and instructions, its tools.
|
|
var ExtraBodyReserved = []string{"model", "stream", "messages", "input", "contents", "system", "systemInstruction", "system_instruction", "instructions", "tools"}
|
|
|
|
// codexOwned are the fields of a ChatGPT account's request that extraBody
|
|
// can't set beside ExtraBodyReserved: codexBody sets them on every request
|
|
// as Codex CLI does, and the backend turns a request away without them
|
|
// (store true, a request that keeps nothing without its sealed reasoning).
|
|
var codexOwned = []string{"store", "tool_choice", "include"}
|
|
|
|
// extraBodyTakes says p's requests take extraBody's fields, and which
|
|
// fields beside ExtraBodyReserved it can't set.
|
|
func (p Provider) extraBodyTakes() (owned []string, ok bool) {
|
|
switch {
|
|
case p.Account == nil:
|
|
return nil, true
|
|
case p.Account.Agent == "codex":
|
|
return codexOwned, true
|
|
}
|
|
return nil, false
|
|
}
|
|
|
|
// SessionPlaceholder is what a string value of extraBody writes for the
|
|
// conversation's id.
|
|
const SessionPlaceholder = "${sessionId}"
|
|
|
|
// extraName is a field's name without its "!", and whether it is forced.
|
|
func extraName(k string) (string, bool) {
|
|
n, forced := strings.CutPrefix(strings.TrimSpace(k), "!")
|
|
return strings.TrimSpace(n), forced
|
|
}
|
|
|
|
// ExtraBodyOK says what is wrong with an extraBody, "" when nothing is.
|
|
func ExtraBodyOK(e ExtraBody) string {
|
|
seen := map[string]bool{}
|
|
for _, k := range slices.Sorted(maps.Keys(e)) {
|
|
n, _ := extraName(k)
|
|
switch {
|
|
case n == "":
|
|
return "an extra body field needs a name"
|
|
case slices.Contains(ExtraBodyReserved, n):
|
|
return fmt.Sprintf("extra body can't set %q: magpie sets the model, stream and the conversation itself", n)
|
|
case seen[n]:
|
|
return fmt.Sprintf("extra body names %q twice", n)
|
|
case !json.Valid(e[k]):
|
|
return fmt.Sprintf("extra body's %q is not JSON", n)
|
|
}
|
|
seen[n] = true
|
|
}
|
|
return ""
|
|
}
|
|
|
|
// cleanExtraBody drops what can't be sent (ExtraBodyOK's faults, for a
|
|
// file written by hand), and is nil when nothing is left.
|
|
func cleanExtraBody(e ExtraBody) ExtraBody {
|
|
out := ExtraBody{}
|
|
seen := map[string]bool{}
|
|
for _, k := range slices.Sorted(maps.Keys(e)) {
|
|
n, forced := extraName(k)
|
|
if n == "" || slices.Contains(ExtraBodyReserved, n) || seen[n] || !json.Valid(e[k]) {
|
|
continue
|
|
}
|
|
seen[n] = true
|
|
v := bytes.TrimSpace(e[k])
|
|
if forced {
|
|
out["!"+n] = slices.Clone(v)
|
|
} else {
|
|
out[n] = slices.Clone(v)
|
|
}
|
|
}
|
|
if len(out) == 0 {
|
|
return nil
|
|
}
|
|
return out
|
|
}
|
|
|
|
// WithExtraBody is body with the provider's extra fields merged in, as the
|
|
// package's comment says; session is the conversation's id for
|
|
// ${sessionId}. A body that isn't a JSON object goes as it came.
|
|
func (p Provider) WithExtraBody(body []byte, session string) []byte {
|
|
owned, takes := p.extraBodyTakes()
|
|
if len(p.ExtraBody) == 0 || !takes {
|
|
return body
|
|
}
|
|
dec := json.NewDecoder(bytes.NewReader(body))
|
|
dec.UseNumber()
|
|
var m map[string]any
|
|
if dec.Decode(&m) != nil || m == nil {
|
|
return body
|
|
}
|
|
changed := false
|
|
for k, raw := range p.ExtraBody {
|
|
n, forced := extraName(k)
|
|
if n == "" || slices.Contains(ExtraBodyReserved, n) || slices.Contains(owned, n) {
|
|
continue
|
|
}
|
|
if _, has := m[n]; has && !forced {
|
|
continue
|
|
}
|
|
d := json.NewDecoder(bytes.NewReader(raw))
|
|
d.UseNumber()
|
|
var v any
|
|
if d.Decode(&v) != nil {
|
|
continue
|
|
}
|
|
m[n], changed = withSession(v, session), true
|
|
}
|
|
if !changed {
|
|
return body
|
|
}
|
|
var out bytes.Buffer
|
|
enc := json.NewEncoder(&out)
|
|
enc.SetEscapeHTML(false) // <, > and & as the agent wrote them
|
|
if enc.Encode(m) != nil {
|
|
return body
|
|
}
|
|
return bytes.TrimSuffix(out.Bytes(), []byte("\n"))
|
|
}
|
|
|
|
// withSession is v with ${sessionId} in its strings, at any depth, as
|
|
// session.
|
|
func withSession(v any, session string) any {
|
|
switch x := v.(type) {
|
|
case string:
|
|
return strings.ReplaceAll(x, SessionPlaceholder, session)
|
|
case map[string]any:
|
|
for k, e := range x {
|
|
x[k] = withSession(e, session)
|
|
}
|
|
case []any:
|
|
for i, e := range x {
|
|
x[i] = withSession(e, session)
|
|
}
|
|
}
|
|
return v
|
|
}
|
|
|
|
// tested is a test's or a detection's tiny request body for p as it goes
|
|
// out: the extra fields, on a session of the test's own, then what the
|
|
// backend adjusts.
|
|
func (p Provider) tested(body string) []byte {
|
|
return p.Prepare(p.WithExtraBody([]byte(body), "magpie-test-"+strings.ToLower(rand.Text()[:12])))
|
|
}
|