codex: a client's access_programs and the account's extraBody reach the ChatGPT backend, and its refusal comes back as it said it (magpie-releases#18)
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).
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -21,7 +21,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
|
||||
| Anthropic key header | A provider of the user's own on a third-party Anthropic API is sent its key as both `x-api-key` and `Authorization: Bearer` (`AuthHeaders`); Anthropic's own API, Bedrock, Azure, Vertex and every subscription account have their own and never this choice (`BothAuth` is false). Some services refuse the two together with a 401 (Aloha on Discord: "鉴权 header, x-api-key 和 Authorization 不可以同时存在"), so `Provider.AuthHeader` (`authHeader`: empty for both, `x-api-key` or `bearer`; anything else is read as empty) sends one alone, picked in the editor's Key header row (shown while `bothAuth` is true, or a custom provider's Anthropic URL is a third party's). Left at both, a 401 whose body `catalog.BothAuthRefused` tells as that refusal (it names both headers and says they can't be together, in Chinese or English) is asked once more with x-api-key alone, then Bearer alone (`RetryOneAuth`, in the gateway's `forwardOnce` and the provider test's `probe`; `catalog.fetchOne` for the model list through `listAuth`); the first not answered 401 or 403 is kept with `LearnAuthHeader`, which never changes a pick the user made. A request carrying the user's own `Authorization` or `x-api-key` header is never retried. | [`authheader.go`](../../internal/provider/authheader.go), [`test.go`](../../internal/provider/test.go), [`catalog/authheader.go`](../../internal/catalog/authheader.go), [`catalog/live.go`](../../internal/catalog/live.go) |
|
||||
| GLM Coding Plan key at pay as you go | Zhipu's and Z.ai's presets offer Pay as you go first (`/api/paas/v4`) and the Coding Plan (`/api/coding/paas/v4`, Responses at `/api/v1`); both share `/api/anthropic`, which bills the plan, so a plan's key left at Pay as you go worked in Claude Code and was refused 429 code 1113 "余额不足或无可用资源包" in Codex (@cleverpigo on X). Nothing in the key tells the two apart, so a Chat request to `open.bigmodel.cn` or `api.z.ai` at `/api/paas/v4` refused 1113 is asked once more at `/api/coding/paas/v4` (`RetryZhipuCoding`, in the gateway's `forwardOnce` and the provider test's `probe`). Served there, `LearnZhipuCoding` moves a saved provider with that one key, still at that URL, to the plan's OpenAI URL (and the preset's plan Responses URL when it has none); one with other keys stays and is asked again each time. Refused there too, the 1113 body keeps its code and gets both URLs and what to change in its message (`ZhipuNoBalanceHint`). A pay-as-you-go key with a balance is never answered 1113 and never sent to the plan's endpoint. | [`zhipu_coding.go`](../../internal/provider/zhipu_coding.go), [`test.go`](../../internal/provider/test.go) |
|
||||
| Zhipu's 200 refusals | Zhipu's and Z.ai's `/api/v1` (the GLM Coding Plan's Responses API, from their Codex pages) and `/api/monitor` answer a refusal 200 in the platform's envelope, `{"code":1000,"msg":"身份验证失败。","success":false}`, where their OpenAI and Anthropic endpoints answer the same key 401 (@xanahopper on X: a refused key tested green on the Responses row only). `ZhipuEnveloped` turns a 2xx JSON body from `open.bigmodel.cn` or `api.z.ai` with `success: false` into `{"error":{"code","message"}}` at the status Zhipu's error-code table gives (1000–1005 → 401, 1113 and 1302–1399 → 429, 1220 → 403, 1210–1229, 1261 and 1301 → 400, anything else → 502), in the provider test's `probe` (endpoint tests, model tests, Detect APIs) and the gateway's `forwardOnce`. A stream, a compressed body, a body over 64 KB and every other host pass as they came. The plan's quota card for a key refused there (1000–1005, or a 401) says `<Zhipu or Z.ai> didn't take this key (<their words>): …` with the vendor's API-keys page (`zhipuRefused`), not asked again as a team's key, and the GUI shows it as that (`quotaError`) rather than "Allowance unavailable". | [`zhipu_envelope.go`](../../internal/provider/zhipu_envelope.go), [`planquota.go`](../../internal/provider/planquota.go), [`test.go`](../../internal/provider/test.go) |
|
||||
| Extra body | `ExtraBody` (`extraBody` in providers.json, the editor's *Extra body*, #1604) is a JSON object whose fields `WithExtraBody` adds at the top level of every JSON body sent to the provider: Messages, Chat, Responses and Gemini, relayed as they came or translated, in the gateway's `forwardOnce` and in Test and Detect (`tested`). A field the body has already is kept; a name written `"!name"` replaces it. Values are put in as written, objects whole, not merged. `${sessionId}` in any string, at any depth, becomes the request's session: the agent's session header (`sessionOf`), else the id `conversationID` derives from the first user message (`magpie-` and its hash), so it stays the same through one conversation; Test and Detect send `magpie-test-` and 12 random letters, a new one each time. `model`, `stream` and the conversation (`messages`, `input`, `contents`, `system`, `systemInstruction`, `system_instruction`, `instructions`, `tools`, `ExtraBodyReserved`) are magpie's: Save refuses them with or without `!` (`ExtraBodyOK`), the editor says so as they are typed, and one written into providers.json by hand is dropped on read (`cleanExtraBody`). Not sent with it: `count_tokens`, embeddings, images, video and System One's decision model (other APIs), and a signed-in account's requests. One object goes to every API; fields for one API alone are not a thing yet. | [`extrabody.go`](../../internal/provider/extrabody.go), [`gateway.go`](../../internal/gateway/gateway.go) |
|
||||
| Extra body | `ExtraBody` (`extraBody` in providers.json, the editor's *Extra body*, #1604) is a JSON object whose fields `WithExtraBody` adds at the top level of every JSON body sent to the provider: Messages, Chat, Responses and Gemini, relayed as they came or translated, in the gateway's `forwardOnce` and in Test and Detect (`tested`). A field the body has already is kept; a name written `"!name"` replaces it. Values are put in as written, objects whole, not merged. `${sessionId}` in any string, at any depth, becomes the request's session: the agent's session header (`sessionOf`), else the id `conversationID` derives from the first user message (`magpie-` and its hash), so it stays the same through one conversation; Test and Detect send `magpie-test-` and 12 random letters, a new one each time. `model`, `stream` and the conversation (`messages`, `input`, `contents`, `system`, `systemInstruction`, `system_instruction`, `instructions`, `tools`, `ExtraBodyReserved`) are magpie's: Save refuses them with or without `!` (`ExtraBodyOK`), the editor says so as they are typed, and one written into providers.json by hand is dropped on read (`cleanExtraBody`). Not sent with it: `count_tokens`, embeddings, images, video and System One's decision model (other APIs), and a signed-in account's requests, except a ChatGPT (Codex) account's (magpie-releases#18): its requests are built as Codex CLI's (`codexBody`) and take the fields Codex CLI adds by choice, such as `access_programs` (OpenAI's Daybreak), while `store`, `tool_choice` and `include`, which the backend needs as `codexBody` sets them, can't be set (`codexOwned`). Its extraBody is written into providers.json by hand under the account's entry and kept onto the account by `withPicks`; the editor has no box for it. A client's own top-level `access_programs` on Responses or Chat is carried to a Responses build as it came (`Request.AccessPrograms`), so a request translated (a Codex account is streamed, so a whole Responses request is made again) keeps it as a relayed one does. One object goes to every API; fields for one API alone are not a thing yet. | [`extrabody.go`](../../internal/provider/extrabody.go), [`gateway.go`](../../internal/gateway/gateway.go) |
|
||||
| Native compaction | `NativeCompaction` (`nativeCompaction` in providers.json, the editor's *Compaction* row, `magpie provider set <id> compaction=native\|magpie`; #1099) has Codex's compaction asked of the provider as Codex sent it and its sealed item returned unchanged. Off by default. Only a provider whose wire carries it can be set so (`CarriesCompaction`: a Responses API, a ChatGPT account, GitHub Copilot; not another agent's sign-in or a plugin's), and `CompactsOn(model)` also needs the model asked on Responses. `SetNativeCompaction`, the CLI and the GUI's save refuse it elsewhere. An account keeps it through `Save`'s picks (`withPicks`), and `AddCopy` carries it. The gateway's half is in [gateway-routing](gateway-routing.md). | [`native_compaction.go`](../../internal/provider/native_compaction.go) |
|
||||
| providers.json | `Path` is `providers.json` in magpie's config folder. A read that fails returns `ErrUnreadable` and is never treated as empty. `store` writes atomically through a rename and drops the cached catalog (`catalog.Touched`). | [`provider.go`](../../internal/provider/provider.go) |
|
||||
| The list | `All` merges stored providers with `Accounts()`. An entry with no URL stores the user's picks for an account. The order is `file.Order`. Reads within one request share one build (`Hold`, #746). | [`provider.go`](../../internal/provider/provider.go) |
|
||||
|
||||
@@ -1490,6 +1490,7 @@ func (e *anthropicEncoder) event(ev Event) {
|
||||
if ev.Code != "" {
|
||||
failed["code"] = ev.Code // preserve the upstream error type, including refusals
|
||||
}
|
||||
saidError(failed, ev.Said)
|
||||
e.w.event("error", map[string]any{"type": "error", "error": failed})
|
||||
}
|
||||
e.col.add(ev)
|
||||
|
||||
@@ -64,6 +64,10 @@ type cRequest struct {
|
||||
ServiceTier string `json:"service_tier,omitempty"`
|
||||
PromptCacheKey string `json:"prompt_cache_key,omitempty"`
|
||||
ResponseFormat json.RawMessage `json:"response_format,omitempty"`
|
||||
// not a Chat field: OpenCode merges a model's options into its body
|
||||
// whichever API it speaks, and a Codex model it asks on Chat is asked
|
||||
// on Responses (Request.AccessPrograms)
|
||||
AccessPrograms json.RawMessage `json:"access_programs,omitempty"`
|
||||
}
|
||||
|
||||
func parseChat(body []byte) (*Request, error) {
|
||||
@@ -73,7 +77,7 @@ func parseChat(body []byte) (*Request, error) {
|
||||
}
|
||||
r := &Request{Model: c.Model, MaxTokens: c.MaxCompletionTokens, Temp: c.Temperature, TopP: c.TopP,
|
||||
Stream: c.Stream, Effort: effortOf(c.ReasoningEffort), Parallel: c.ParallelToolCalls, Fast: c.ServiceTier == "priority", Tier: c.ServiceTier,
|
||||
CacheKey: c.PromptCacheKey, Format: openAIFormat(c.ResponseFormat)}
|
||||
CacheKey: c.PromptCacheKey, Format: openAIFormat(c.ResponseFormat), AccessPrograms: c.AccessPrograms}
|
||||
if r.MaxTokens == 0 {
|
||||
r.MaxTokens = c.MaxTokens
|
||||
}
|
||||
@@ -1191,6 +1195,7 @@ func (e *chatEncoder) event(ev Event) {
|
||||
if ev.Code != "" {
|
||||
failed["code"] = ev.Code // preserve the upstream error type, including refusals
|
||||
}
|
||||
saidError(failed, ev.Said)
|
||||
e.w.event("", map[string]any{"error": failed})
|
||||
}
|
||||
e.col.add(ev)
|
||||
|
||||
@@ -0,0 +1,267 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// daybreakBackend stands in for the ChatGPT backend as OpenAI's Daybreak
|
||||
// guide has the Responses API answer access_programs: a cyber program it
|
||||
// doesn't know is a 400 invalid_access_program, null is refused as well.
|
||||
// daybreak_red stands for a program the workspace hasn't got, which the
|
||||
// real backend refuses inside a 200 stream. It keeps every body it was sent.
|
||||
type daybreakBackend struct {
|
||||
mu sync.Mutex
|
||||
bodies [][]byte
|
||||
}
|
||||
|
||||
func (d *daybreakBackend) last(t *testing.T) []byte {
|
||||
t.Helper()
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
if len(d.bodies) == 0 {
|
||||
t.Fatal("the ChatGPT backend was asked nothing")
|
||||
}
|
||||
return d.bodies[len(d.bodies)-1]
|
||||
}
|
||||
|
||||
func (d *daybreakBackend) asked() int {
|
||||
d.mu.Lock()
|
||||
defer d.mu.Unlock()
|
||||
return len(d.bodies)
|
||||
}
|
||||
|
||||
func daybreak(t *testing.T) *daybreakBackend {
|
||||
t.Helper()
|
||||
d := &daybreakBackend{}
|
||||
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if strings.HasSuffix(r.URL.Path, "/models") {
|
||||
io.WriteString(w, `{"models":[{"slug":"gpt-daybreak-blue-latest","display_name":"Daybreak Blue","visibility":"list","supported_reasoning_levels":[{"effort":"medium"}],"context_window":272000}]}`)
|
||||
return
|
||||
}
|
||||
b, _ := io.ReadAll(r.Body)
|
||||
d.mu.Lock()
|
||||
d.bodies = append(d.bodies, b)
|
||||
d.mu.Unlock()
|
||||
if ap := gjson.GetBytes(b, "access_programs"); ap.Exists() {
|
||||
if c := ap.Get("cyber"); ap.Type == gjson.Null || c.Exists() && c.String() != "standard" && c.String() != "daybreak_blue" && c.String() != "daybreak_red" {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(400)
|
||||
io.WriteString(w, `{"error":{"message":"Invalid access program for access_programs.cyber.","type":"invalid_request_error","param":"access_programs.cyber","code":"invalid_access_program"}}`)
|
||||
return
|
||||
}
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/event-stream")
|
||||
if gjson.GetBytes(b, "access_programs.cyber").String() == "daybreak_red" {
|
||||
// what the real backend said for daybreak_blue to a workspace
|
||||
// without it: a 200 stream whose error event names the program
|
||||
io.WriteString(w, sse(
|
||||
`event: error`+"\n"+`data: {"type":"error","error":{"message":"The requested Cyber access program is not authorized for this workspace.","type":"invalid_request_error","param":"access_programs.cyber","code":"access_program_not_enabled"}}`))
|
||||
return
|
||||
}
|
||||
io.WriteString(w, sse(
|
||||
`data: {"type":"response.created","response":{"id":"r1","model":"gpt-daybreak-blue-latest"}}`,
|
||||
`data: {"type":"response.output_item.done","output_index":0,"item":{"type":"message","id":"msg_1","role":"assistant","content":[{"type":"output_text","text":"OK"}]}}`,
|
||||
`data: {"type":"response.completed","response":{"id":"r1","status":"completed","output":[],"usage":{"input_tokens":5,"output_tokens":1}}}`))
|
||||
}))
|
||||
t.Cleanup(up.Close)
|
||||
was := provider.CodexBase
|
||||
provider.CodexBase = up.URL + "/backend-api/codex"
|
||||
t.Cleanup(func() { provider.CodexBase = was })
|
||||
return d
|
||||
}
|
||||
|
||||
// magpie-releases#18 (NonMirror, OpenCode): a client's access_programs, the
|
||||
// Daybreak program Codex CLI sends the ChatGPT backend on each turn it was
|
||||
// picked for (codex-rs ResponsesApiRequest.access_programs), reaches the
|
||||
// backend on a Codex account's model on every path that asks it: Responses
|
||||
// relayed (streamed) and made again (one body, which the account is
|
||||
// streamed for), and Chat made again as Responses. The value goes as it
|
||||
// came, so the backend's 400 invalid_access_program for a value it doesn't
|
||||
// take reaches the client, the reporter's probe among them.
|
||||
func TestCodexAccessProgramsReachBackend(t *testing.T) {
|
||||
codexSignedIn(t, "spare@example.com")
|
||||
d := daybreak(t)
|
||||
const blue = `{"cyber":"daybreak_blue"}`
|
||||
for _, c := range []struct{ name, path, body string }{
|
||||
{"responses streamed", "/v1/responses", `{"model":"codex/gpt-daybreak-blue-latest","stream":true,"input":"Respond with OK.","access_programs":` + blue + `}`},
|
||||
{"responses whole", "/v1/responses", `{"model":"codex/gpt-daybreak-blue-latest","stream":false,"input":"Respond with OK.","access_programs":` + blue + `}`},
|
||||
{"chat streamed", "/v1/chat/completions", `{"model":"codex/gpt-daybreak-blue-latest","stream":true,"messages":[{"role":"user","content":"Respond with OK."}],"access_programs":` + blue + `}`},
|
||||
{"chat whole", "/v1/chat/completions", `{"model":"codex/gpt-daybreak-blue-latest","messages":[{"role":"user","content":"Respond with OK."}],"access_programs":` + blue + `}`},
|
||||
} {
|
||||
code, out := post(t, c.path, c.body)
|
||||
if code != 200 {
|
||||
t.Fatalf("%s: %d %s", c.name, code, out)
|
||||
}
|
||||
if got := gjson.GetBytes(d.last(t), "access_programs").Raw; got != blue {
|
||||
t.Errorf("%s: the backend got access_programs %q in %s", c.name, got, d.last(t))
|
||||
}
|
||||
}
|
||||
|
||||
// the reporter's probe, and null, which the guide says is refused: the
|
||||
// backend's own 400, its code and param as it said them, not a 200
|
||||
// from a request it never saw them in. The request is at fault, not
|
||||
// the account: the spare signed in beside it is never asked, and
|
||||
// nobody rests.
|
||||
for _, c := range []struct{ name, path, body string }{
|
||||
{"probe, responses whole", "/v1/responses", `{"model":"codex/gpt-daybreak-blue-latest","input":"Respond with OK.","stream":false,"access_programs":{"cyber":"__daybreak_forwarding_probe__"}}`},
|
||||
{"probe, responses streamed", "/v1/responses", `{"model":"codex/gpt-daybreak-blue-latest","input":"Respond with OK.","stream":true,"access_programs":{"cyber":"__daybreak_forwarding_probe__"}}`},
|
||||
{"probe, chat", "/v1/chat/completions", `{"model":"codex/gpt-daybreak-blue-latest","messages":[{"role":"user","content":"Respond with OK."}],"access_programs":{"cyber":"__daybreak_forwarding_probe__"}}`},
|
||||
{"probe, chat streamed", "/v1/chat/completions", `{"model":"codex/gpt-daybreak-blue-latest","stream":true,"messages":[{"role":"user","content":"Respond with OK."}],"access_programs":{"cyber":"__daybreak_forwarding_probe__"}}`},
|
||||
{"null, responses whole", "/v1/responses", `{"model":"codex/gpt-daybreak-blue-latest","input":"Respond with OK.","access_programs":null}`},
|
||||
} {
|
||||
before := d.asked()
|
||||
code, out := post(t, c.path, c.body)
|
||||
if code != 400 || gjson.Get(out, "error.code").String() != "invalid_access_program" || gjson.Get(out, "error.param").String() != "access_programs.cyber" {
|
||||
t.Errorf("%s: %d %s\nthe backend got %s", c.name, code, out, d.last(t))
|
||||
}
|
||||
if n := d.asked() - before; n != 1 {
|
||||
t.Errorf("%s: the backend was asked %d times, want once", c.name, n)
|
||||
}
|
||||
if r := restingNow(t); len(r) > 0 {
|
||||
t.Errorf("%s: resting after the request's own 400: %v", c.name, r)
|
||||
}
|
||||
}
|
||||
|
||||
// a program the workspace hasn't got is refused inside the stream: a
|
||||
// client answered whole gets that refusal as a 400 with its code and
|
||||
// param, not a 502 after the same request was sent three times; one
|
||||
// answered as a stream gets it inside the stream. Asked once either
|
||||
// way, and nobody rests.
|
||||
for _, c := range []struct {
|
||||
name, path, body string
|
||||
whole bool
|
||||
}{
|
||||
{"not enabled, responses whole", "/v1/responses", `{"model":"codex/gpt-daybreak-blue-latest","input":"Respond with OK.","stream":false,"access_programs":{"cyber":"daybreak_red"}}`, true},
|
||||
{"not enabled, chat whole", "/v1/chat/completions", `{"model":"codex/gpt-daybreak-blue-latest","messages":[{"role":"user","content":"Respond with OK."}],"access_programs":{"cyber":"daybreak_red"}}`, true},
|
||||
{"not enabled, chat streamed", "/v1/chat/completions", `{"model":"codex/gpt-daybreak-blue-latest","stream":true,"messages":[{"role":"user","content":"Respond with OK."}],"access_programs":{"cyber":"daybreak_red"}}`, false},
|
||||
{"not enabled, responses streamed", "/v1/responses", `{"model":"codex/gpt-daybreak-blue-latest","input":"Respond with OK.","stream":true,"access_programs":{"cyber":"daybreak_red"}}`, false},
|
||||
} {
|
||||
before := d.asked()
|
||||
code, out := post(t, c.path, c.body)
|
||||
if c.whole {
|
||||
if code != 400 || gjson.Get(out, "error.code").String() != "access_program_not_enabled" || gjson.Get(out, "error.param").String() != "access_programs.cyber" {
|
||||
t.Errorf("%s: %d %s", c.name, code, out)
|
||||
}
|
||||
} else if !strings.Contains(out, "not authorized for this workspace") {
|
||||
t.Errorf("%s: %d %s", c.name, code, out)
|
||||
}
|
||||
if n := d.asked() - before; n != 1 {
|
||||
t.Errorf("%s: the backend was asked %d times, want once", c.name, n)
|
||||
}
|
||||
if r := restingNow(t); len(r) > 0 {
|
||||
t.Errorf("%s: resting after the request's own refusal: %v", c.name, r)
|
||||
}
|
||||
}
|
||||
|
||||
// none sent, none added
|
||||
if code, out := post(t, "/v1/responses", `{"model":"codex/gpt-daybreak-blue-latest","input":"hi"}`); code != 200 {
|
||||
t.Fatalf("without: %d %s", code, out)
|
||||
}
|
||||
if gjson.GetBytes(d.last(t), "access_programs").Exists() {
|
||||
t.Errorf("access_programs added: %s", d.last(t))
|
||||
}
|
||||
}
|
||||
|
||||
// magpie-releases#18: the extraBody written for the built-in codex
|
||||
// provider (by hand: its editor has no box for it) goes on its requests,
|
||||
// as a key provider's does — filling in what the client left out, a
|
||||
// "!name" replacing it — on every API the request came in on. What Codex
|
||||
// CLI's request needs to be answered at all (store false, tool_choice
|
||||
// auto, its sealed reasoning asked back) stays magpie's.
|
||||
func TestCodexAccountTakesExtraBody(t *testing.T) {
|
||||
codexSignedIn(t)
|
||||
d := daybreak(t)
|
||||
os.MkdirAll(filepath.Dir(provider.Path()), 0o755)
|
||||
os.WriteFile(provider.Path(), mustJSON(map[string]any{"providers": []any{map[string]any{
|
||||
"id": "codex",
|
||||
"extraBody": map[string]any{
|
||||
"access_programs": map[string]any{"cyber": "__daybreak_forwarding_probe__"},
|
||||
"!store": true,
|
||||
"!tool_choice": "none",
|
||||
"!include": []string{},
|
||||
"client_metadata": map[string]any{"session": "${sessionId}"},
|
||||
}}}}), 0o600)
|
||||
provider.ForgetAccounts()
|
||||
|
||||
// the reporter's: a benign request, the probe from extraBody alone
|
||||
code, out := post(t, "/v1/responses", `{"model":"codex/gpt-daybreak-blue-latest","input":"Respond with OK.","stream":false}`)
|
||||
if code != 400 || gjson.Get(out, "error.code").String() != "invalid_access_program" {
|
||||
t.Fatalf("extraBody's probe: %d %s\nthe backend got %s", code, out, d.last(t))
|
||||
}
|
||||
if ap := gjson.GetBytes(d.last(t), "access_programs.cyber").String(); ap != "__daybreak_forwarding_probe__" {
|
||||
t.Fatalf("extraBody's access_programs didn't reach the backend: %s", d.last(t))
|
||||
}
|
||||
got := d.last(t)
|
||||
if gjson.GetBytes(got, "store").Bool() || gjson.GetBytes(got, "tool_choice").String() != "auto" ||
|
||||
!strings.Contains(gjson.GetBytes(got, "include").Raw, "reasoning.encrypted_content") {
|
||||
t.Errorf("extraBody set what Codex's request must carry: %s", got)
|
||||
}
|
||||
if !gjson.GetBytes(got, "client_metadata.session").Exists() || strings.Contains(string(got), "${sessionId}") {
|
||||
t.Errorf("client_metadata: %s", got)
|
||||
}
|
||||
|
||||
// the client's own value is kept over extraBody's unforced one, on
|
||||
// Chat and on Anthropic's Messages too
|
||||
for _, c := range []struct{ name, path, body string }{
|
||||
{"responses", "/v1/responses", `{"model":"codex/gpt-daybreak-blue-latest","input":"hi","stream":true,"access_programs":{"cyber":"daybreak_blue"}}`},
|
||||
{"chat", "/v1/chat/completions", `{"model":"codex/gpt-daybreak-blue-latest","messages":[{"role":"user","content":"hi"}],"access_programs":{"cyber":"daybreak_blue"}}`},
|
||||
} {
|
||||
if code, out := post(t, c.path, c.body); code != 200 {
|
||||
t.Fatalf("%s: %d %s\nthe backend got %s", c.name, code, out, d.last(t))
|
||||
}
|
||||
}
|
||||
code, out = post(t, "/v1/messages", `{"model":"codex/gpt-daybreak-blue-latest","max_tokens":64,"messages":[{"role":"user","content":"hi"}]}`)
|
||||
// Anthropic's error shape has no code: the backend's words are said
|
||||
if code != 400 || !strings.Contains(out, "Invalid access program for access_programs.cyber") ||
|
||||
gjson.GetBytes(d.last(t), "access_programs.cyber").String() != "__daybreak_forwarding_probe__" {
|
||||
t.Errorf("messages: %d %s\nthe backend got %s", code, out, d.last(t))
|
||||
}
|
||||
|
||||
// a program the workspace hasn't got, which the backend refuses inside
|
||||
// its stream, reaches a Messages client as the request's refusal,
|
||||
// whole or streamed: asked once, nobody resting
|
||||
os.WriteFile(provider.Path(), mustJSON(map[string]any{"providers": []any{map[string]any{
|
||||
"id": "codex", "extraBody": map[string]any{"access_programs": map[string]any{"cyber": "daybreak_red"}}}}}), 0o600)
|
||||
provider.ForgetAccounts()
|
||||
for _, stream := range []bool{false, true} {
|
||||
before := d.asked()
|
||||
code, out := post(t, "/v1/messages", `{"model":"codex/gpt-daybreak-blue-latest","max_tokens":64,"stream":`+map[bool]string{false: "false", true: "true"}[stream]+`,"messages":[{"role":"user","content":"hi"}]}`)
|
||||
if !strings.Contains(out, "invalid_request_error") || !strings.Contains(out, "not authorized for this workspace") || !stream && code != 400 {
|
||||
t.Errorf("not enabled, messages (stream %v): %d %s", stream, code, out)
|
||||
}
|
||||
if n := d.asked() - before; n != 1 {
|
||||
t.Errorf("not enabled, messages (stream %v): the backend was asked %d times, want once", stream, n)
|
||||
}
|
||||
if r := restingNow(t); len(r) > 0 {
|
||||
t.Errorf("not enabled, messages (stream %v): resting after the request's own refusal: %v", stream, r)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// json.RawMessage keeps a null the client sent as "null" (the guide's
|
||||
// refused value), which Request.AccessPrograms carries on.
|
||||
func TestAccessProgramsNullKept(t *testing.T) {
|
||||
r, err := parseResponses([]byte(`{"model":"m","input":"hi","access_programs":null}`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(r.AccessPrograms) != "null" {
|
||||
t.Fatalf("access_programs %q", r.AccessPrograms)
|
||||
}
|
||||
var m map[string]json.RawMessage
|
||||
json.Unmarshal(buildResponses(r, "m", "chatgpt.com", false), &m)
|
||||
if string(m["access_programs"]) != "null" {
|
||||
t.Fatalf("built %s", m["access_programs"])
|
||||
}
|
||||
}
|
||||
@@ -441,7 +441,7 @@ func (s *Server) streamTranslated(w http.ResponseWriter, r *http.Request, p prov
|
||||
if turnedAway {
|
||||
u.ErrType = turnedAwayErrType
|
||||
}
|
||||
return writeError(w, from, res.StatusCode, failed), failed
|
||||
return writeVendorError(w, from, res.StatusCode, failed, b), failed
|
||||
}
|
||||
}
|
||||
if err == nil && res.StatusCode < 400 {
|
||||
|
||||
@@ -4235,7 +4235,7 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
|
||||
}
|
||||
keepRetry(w.Header(), res.Header, b)
|
||||
u.ErrType = provider.ErrorType(b)
|
||||
return writeError(w, proto, res.StatusCode, msg), msg, true
|
||||
return writeVendorError(w, proto, res.StatusCode, msg, b), msg, true
|
||||
}
|
||||
rd, sse := eventStream(res)
|
||||
client := w
|
||||
@@ -5285,7 +5285,7 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr
|
||||
if turnedAway {
|
||||
u.ErrType = turnedAwayErrType
|
||||
}
|
||||
return writeError(w, from, res.StatusCode, msg), msg
|
||||
return writeVendorError(w, from, res.StatusCode, msg, b), msg
|
||||
}
|
||||
dec := decoder(actual)
|
||||
rd, sse := eventStream(res)
|
||||
@@ -5328,7 +5328,10 @@ func (s *Server) translate(w http.ResponseWriter, r *http.Request, p provider.Pr
|
||||
said += " — " + antigravityTurnedAwayHint
|
||||
u.ErrType = turnedAwayErrType
|
||||
}
|
||||
return writeError(w, from, 502, p.Name+": "+said), said
|
||||
// a request the vendor refused in its stream is answered as
|
||||
// refused, with its code (magpie-releases#18); anything else is
|
||||
// the vendor failing
|
||||
return writeVendorError(w, from, cmp.Or(col.errStatus, 502), p.Name+": "+said, col.errSaid), said
|
||||
}
|
||||
if col.err == "" && !ended && (actual == provider.Anthropic || actual == provider.Responses || geminiKin(actual)) && r.Context().Err() == nil {
|
||||
// an Anthropic stream that just stopped — no stop_reason, no
|
||||
@@ -6202,6 +6205,30 @@ func streamError(w http.ResponseWriter, proto provider.Protocol, status int, msg
|
||||
|
||||
// writeError answers in the client's own error shape.
|
||||
func writeError(w http.ResponseWriter, proto provider.Protocol, status int, msg string) int {
|
||||
return writeErrorSaid(w, proto, status, msg, nil, nil)
|
||||
}
|
||||
|
||||
// writeVendorError answers a vendor's error status in the client's own
|
||||
// shape, as writeError does, keeping the code and param the vendor named
|
||||
// (an OpenAI-shaped error's strings) for a client of OpenAI's shape: the
|
||||
// ChatGPT backend's invalid_access_program on access_programs.cyber
|
||||
// (magpie-releases#18) reaches the agent as the backend said it.
|
||||
func writeVendorError(w http.ResponseWriter, proto provider.Protocol, status int, msg string, body []byte) int {
|
||||
var code, param any
|
||||
if e := gjson.GetBytes(body, "error"); e.IsObject() {
|
||||
if c := e.Get("code"); c.Type == gjson.String && c.String() != "" {
|
||||
code = c.String()
|
||||
}
|
||||
if p := e.Get("param"); p.Type == gjson.String && p.String() != "" {
|
||||
param = p.String()
|
||||
}
|
||||
}
|
||||
return writeErrorSaid(w, proto, status, msg, code, param)
|
||||
}
|
||||
|
||||
// writeErrorSaid is writeError with the code and param an OpenAI-shaped
|
||||
// answer names, nil for none.
|
||||
func writeErrorSaid(w http.ResponseWriter, proto provider.Protocol, status int, msg string, code, param any) int {
|
||||
typ := "api_error"
|
||||
switch {
|
||||
case status == 400:
|
||||
@@ -6219,7 +6246,6 @@ func writeError(w http.ResponseWriter, proto provider.Protocol, status int, msg
|
||||
case status == 529:
|
||||
typ = "overloaded_error"
|
||||
}
|
||||
var code any
|
||||
if tooLong(status, msg) {
|
||||
// said the way the client's own API says it, so the agent
|
||||
// compacts the conversation and tries again rather than stopping
|
||||
@@ -6246,7 +6272,7 @@ func writeError(w http.ResponseWriter, proto provider.Protocol, status int, msg
|
||||
}
|
||||
v = map[string]any{"error": map[string]any{"code": status, "message": msg, "status": st}}
|
||||
default:
|
||||
v = map[string]any{"error": map[string]any{"message": msg, "type": typ, "code": code, "param": nil}}
|
||||
v = map[string]any{"error": map[string]any{"message": msg, "type": typ, "code": code, "param": param}}
|
||||
}
|
||||
writeJSON(w, status, v)
|
||||
return status
|
||||
|
||||
+15
-1
@@ -189,6 +189,15 @@ type Request struct {
|
||||
// them. text's format is read into Format.
|
||||
ClientMetadata json.RawMessage
|
||||
Text json.RawMessage
|
||||
// AccessPrograms is a client's access_programs, the program a request
|
||||
// asks the model under (OpenAI's Daybreak: {"cyber":"daybreak_blue"}),
|
||||
// which Codex CLI sends the ChatGPT backend on every turn it picked one
|
||||
// for (codex-rs's ResponsesApiRequest.access_programs). It goes on as it
|
||||
// was sent, null and all, when the request is built again for a
|
||||
// Responses upstream, whose answer to a value it doesn't take
|
||||
// (invalid_access_program) is the client's to read; no other API takes
|
||||
// it (magpie-releases#18).
|
||||
AccessPrograms json.RawMessage
|
||||
// Metadata is an Anthropic client's metadata (Claude Code's user_id),
|
||||
// which goes on as it was sent when the request is built again for an
|
||||
// Anthropic upstream: a relay that serves only Claude Code turns a
|
||||
@@ -296,6 +305,10 @@ type Event struct {
|
||||
// Wait: for KError, how long the vendor said to wait before asking
|
||||
// again, when it said; sent on as Retry-After
|
||||
Wait time.Duration
|
||||
// Said: for KError, the vendor's own error as {"error":{…}}, when it
|
||||
// said the request itself is at fault; its code and param go to a
|
||||
// client answered whole (writeVendorError)
|
||||
Said json.RawMessage
|
||||
}
|
||||
|
||||
// Usage counts tokens.
|
||||
@@ -425,6 +438,7 @@ type collector struct {
|
||||
// the error's status and kind, as its event gave them
|
||||
errStatus int
|
||||
errCode string
|
||||
errSaid json.RawMessage
|
||||
}
|
||||
|
||||
func (c *collector) last(k Kind) *Part {
|
||||
@@ -522,7 +536,7 @@ func (c *collector) add(ev Event) {
|
||||
c.res.Usage.add(ev.Usage)
|
||||
c.res.Usage.add(Usage{RequestID: ev.RequestID})
|
||||
case KError:
|
||||
c.err, c.errStatus, c.errCode = ev.Text, ev.Status, ev.Code
|
||||
c.err, c.errStatus, c.errCode, c.errSaid = ev.Text, ev.Status, ev.Code, ev.Said
|
||||
case KSearch:
|
||||
c.closeTool()
|
||||
c.res.Parts = append(c.res.Parts, Part{Kind: Search, Text: ev.Text, Hits: ev.Hits})
|
||||
|
||||
@@ -5,10 +5,12 @@ import (
|
||||
"cmp"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/tidwall/gjson"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
@@ -213,6 +215,7 @@ type rRequest struct {
|
||||
PromptCacheKey string `json:"prompt_cache_key,omitempty"`
|
||||
Include []string `json:"include,omitempty"`
|
||||
ClientMetadata json.RawMessage `json:"client_metadata,omitempty"`
|
||||
AccessPrograms json.RawMessage `json:"access_programs,omitempty"`
|
||||
Text json.RawMessage `json:"text,omitempty"`
|
||||
Reasoning *struct {
|
||||
Effort string `json:"effort,omitempty"`
|
||||
@@ -257,7 +260,7 @@ func parseResponses(body []byte) (*Request, error) {
|
||||
}
|
||||
r := &Request{Model: q.Model, System: q.Instructions, MaxTokens: q.MaxOutputTokens, Temp: q.Temperature,
|
||||
TopP: q.TopP, Stream: q.Stream, Parallel: q.ParallelToolCalls, Fast: q.ServiceTier == "priority" || q.ServiceTier == "ultrafast", Ultrafast: q.ServiceTier == "ultrafast", Tier: q.ServiceTier, CacheKey: q.PromptCacheKey, Include: q.Include,
|
||||
ClientMetadata: sentRaw(q.ClientMetadata)}
|
||||
ClientMetadata: sentRaw(q.ClientMetadata), AccessPrograms: q.AccessPrograms}
|
||||
r.Text, r.Format = textFormat(sentRaw(q.Text))
|
||||
if q.Reasoning != nil {
|
||||
r.Effort = effortOf(q.Reasoning.Effort)
|
||||
@@ -1135,6 +1138,9 @@ func buildResponses(r *Request, model, host string, rejectTemp bool) []byte {
|
||||
if len(r.ClientMetadata) > 0 {
|
||||
out["client_metadata"] = r.ClientMetadata
|
||||
}
|
||||
if len(r.AccessPrograms) > 0 {
|
||||
out["access_programs"] = r.AccessPrograms
|
||||
}
|
||||
if len(r.Text) > 0 || r.Format != nil {
|
||||
text := map[string]any{}
|
||||
decodeJSON(r.Text, &text)
|
||||
@@ -1406,7 +1412,8 @@ func (d *responsesDecoder) decode(data string, emit func(Event)) error {
|
||||
if ev.Response.Error != nil {
|
||||
msg = ev.Response.Error.Message
|
||||
}
|
||||
emit(Event{Kind: KError, Text: cmp.Or(msg, streamErrorText(data)), Code: refusedCode(data)})
|
||||
status, said := requestRefused(data)
|
||||
emit(Event{Kind: KError, Text: cmp.Or(msg, streamErrorText(data)), Code: refusedCode(data), Status: status, Said: said})
|
||||
return nil
|
||||
}
|
||||
stop := "stop"
|
||||
@@ -1433,11 +1440,44 @@ func (d *responsesDecoder) decode(data string, emit func(Event)) error {
|
||||
if ev.Error != nil {
|
||||
msg = cmp.Or(ev.Error.Message, msg)
|
||||
}
|
||||
emit(Event{Kind: KError, Text: cmp.Or(msg, streamErrorText(data)), Code: refusedCode(data)})
|
||||
status, said := requestRefused(data)
|
||||
emit(Event{Kind: KError, Text: cmp.Or(msg, streamErrorText(data)), Code: refusedCode(data), Status: status, Said: said})
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// requestRefused is 400 and the vendor's error, as {"error":{…}}, when a
|
||||
// Responses stream's error event or failed response says the request
|
||||
// itself is at fault (type invalid_request_error): the ChatGPT backend
|
||||
// answers an access program the workspace doesn't have with a 200 stream
|
||||
// whose error event is access_program_not_enabled (magpie-releases#18).
|
||||
// Asked again, on this account or another, it is refused the same way, so
|
||||
// it is neither retried nor resumed, and a client answered whole gets its
|
||||
// code and param. Read by the error object's type, never by its words.
|
||||
func requestRefused(data string) (int, json.RawMessage) {
|
||||
for _, path := range []string{"error", "response.error"} {
|
||||
e := gjson.Get(data, path)
|
||||
if e.IsObject() && e.Get("type").String() == "invalid_request_error" {
|
||||
return http.StatusBadRequest, json.RawMessage(`{"error":` + e.Raw + `}`)
|
||||
}
|
||||
}
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// saidError puts the type, code and param of the vendor's own error (an
|
||||
// Event's Said) on the error a stream encoder writes, so a request the
|
||||
// vendor refused reads as refused (invalid_request_error) to the agent and
|
||||
// to the hold that decides whether to ask again, not as magpie's api_error
|
||||
// (magpie-releases#18). Without Said it is left as it was.
|
||||
func saidError(failed map[string]any, said json.RawMessage) {
|
||||
e := gjson.GetBytes(said, "error")
|
||||
for _, k := range []string{"type", "code", "param"} {
|
||||
if v := e.Get(k); v.Type == gjson.String && v.String() != "" {
|
||||
failed[k] = v.String()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// responsesEncoder writes events as a Responses stream. Codex reads the
|
||||
// full item from output_item.done and usage from response.completed.
|
||||
type responsesEncoder struct {
|
||||
@@ -1693,7 +1733,9 @@ func (e *responsesEncoder) event(ev Event) {
|
||||
if ev.Code != "" {
|
||||
code = ev.Code
|
||||
}
|
||||
e.send("response.failed", map[string]any{"response": e.response("failed", map[string]any{"error": map[string]any{"code": code, "message": ev.Text}})})
|
||||
failed := map[string]any{"code": code, "message": ev.Text}
|
||||
saidError(failed, ev.Said)
|
||||
e.send("response.failed", map[string]any{"response": e.response("failed", map[string]any{"error": failed})})
|
||||
}
|
||||
e.col.add(ev)
|
||||
}
|
||||
|
||||
@@ -26,7 +26,13 @@ package provider
|
||||
// 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.
|
||||
// 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"
|
||||
@@ -60,6 +66,24 @@ func (e *ExtraBody) UnmarshalJSON(b []byte) error {
|
||||
// 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}"
|
||||
@@ -118,7 +142,8 @@ func cleanExtraBody(e ExtraBody) ExtraBody {
|
||||
// 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 {
|
||||
if len(p.ExtraBody) == 0 || p.Account != nil {
|
||||
owned, takes := p.extraBodyTakes()
|
||||
if len(p.ExtraBody) == 0 || !takes {
|
||||
return body
|
||||
}
|
||||
dec := json.NewDecoder(bytes.NewReader(body))
|
||||
@@ -130,7 +155,7 @@ func (p Provider) WithExtraBody(body []byte, session string) []byte {
|
||||
changed := false
|
||||
for k, raw := range p.ExtraBody {
|
||||
n, forced := extraName(k)
|
||||
if n == "" || slices.Contains(ExtraBodyReserved, n) {
|
||||
if n == "" || slices.Contains(ExtraBodyReserved, n) || slices.Contains(owned, n) {
|
||||
continue
|
||||
}
|
||||
if _, has := m[n]; has && !forced {
|
||||
|
||||
@@ -661,6 +661,9 @@ func withPicks(a, pk Provider) Provider {
|
||||
a.MaxConcurrency, a.PinUpstream = pk.MaxConcurrency, pk.PinUpstream
|
||||
a.AccountConcurrency, a.QueueLimit, a.QueueWait = pk.AccountConcurrency, pk.QueueLimit, pk.QueueWait
|
||||
a.MaxRPM = pk.MaxRPM
|
||||
// the extra body fields written for it, which a ChatGPT account's
|
||||
// requests take (WithExtraBody, magpie-releases#18)
|
||||
a.ExtraBody = pk.ExtraBody
|
||||
return a
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user