diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index e26e2fbaf..e406041be 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -105,6 +105,7 @@ recorded as a prediction failure (`noPrediction`). - A 2xx that can't be an API's answer is the 502 it stands for (`notAnAPIReply`, #1012): a web page (`text/html`, or a body that begins as one: a sign-in page, Cloudflare's challenge), a body with nothing in it, or one sent as JSON that doesn't begin as JSON. Every upstream request goes through it (`forwardOnce`, and the built-in clients' own: the ChatGPT backend's `/responses`, Kiro, Zed, Qoder, Devin, Cursor, Command Code), so it fails over, rests and is logged as a 502 does, its reason naming the page's title. Only the first bytes are peeked, which a stream waits for anyway, and a compressed body is left as it came. - A 2xx from Zhipu or Z.ai holding the platform's refusal envelope (`{"code":1000,"msg":…,"success":false}`, which their Responses API at `/api/v1` answers a refused key) is the refusal it stands for (`provider.ZhipuEnveloped` in `forwardOnce`): 401 for a key refused, 429 for a limit or no balance, as Zhipu's error codes give, so it fails over and rests as those do and the agent is told why. `TestZhipuResponsesRefusalIsRefusal`. - A streamed request is never left silent while its vendor says nothing. `holdWriter.watch` runs beside each try: past `keepHeldAfter` (15s) it sends a held try's agent the stream's 200 and SSE comments (`keepAlive`), none of the try, so another candidate may still answer in the same stream; once the reply passes, it puts a comment between two of its lines after `keepaliveEvery` of quiet. It stops after `keepaliveLongest` (5 minutes) with nothing from the vendor. A try waiting for its key's or account's slot or for room in its minute (`lanes.take`, `rpms.wait`) is kept alive the same way (`keepQueued`), for as long as it waits; once the 200 is out, the try is held, and its failure or its queue turning it away reaches the agent as the stream's error (`failTo`), not a status (coeo91 on Discord). A wait shorter than `keepHeldAfter` sends nothing, so its 429 keeps its `Retry-After`. A proxy in front such as Cloudflare (125s) otherwise ends the request (#947). Gemini streams get no comments (#934). A vendor that then ignores `stream:true` and answers 200 with its reply whole has it sent as the agent's stream (`wholeAsStream`: Chat, Responses, Anthropic), not as the stream's error, while a reply under a type that says neither JSON nor a stream is held as a stream when its first bytes are one (`sseStart`), read event by event like one that says so, so an error among its frames still goes to the next candidate (#1418: it went through at once); a 200 that is no reply of the protocol's fails as a translated reply that didn't stream does (502, "… did not stream"), for the next candidate to answer, and the last one's reaches the agent as the stream's error. A held stream that has sent nothing but the frames before a reply (`response.created`, `response.in_progress`, `codex.rate_limits`, pings, an empty part begun, and any event `streamEvent` doesn't know to carry text, reasoning, a call or a reply's end (`replyEvent`), or an item not known that isn't a call or a tool's (`streamPart.said`): `eventLead`; Aliceonly on #1418: an unknown event was taken for content and let a frames-only 200 through, and its `server_is_overloaded` reached Codex with five candidates left) stays held as long as its agent is kept alive, up to `holdLead` (4 minutes, under the 300s Codex waits for an event; `keptQuiet`), so a `server_is_overloaded` that comes after it is a failure the next candidate answers (#1418: let through at 15s, the ChatGPT backend's failure 36s in ended Codex's turn with sub2api, next in the group, never asked). A stream whose agent can't be kept alive (Gemini's) is let through after `holdLongest` (15s), as before. Codex counts only events toward that 300s, not comments, so the bound is the request's, not each try's: once Codex on Responses has heard no event for `agentQuietMost` (4 minutes) since the request began or its last event (`keptAlive.tooQuiet`), the try in hand is let through (`scan`, `keepQuiet`), and no group replan or same-one retry is taken whose pause would end past it (fadenoob on Discord: held tries and replan pauses added up past 300s and Codex reconnected on "idle timeout waiting for SSE"). A translated reply whose upstream stream stops before it said its reply had — an Anthropic one with no stop_reason and no message_stop, a Responses one with no `response.completed`, the same two a relayed one is told by (`sniff.whole`; a Chat stream may end without `[DONE]` and be whole), a Gemini or Code Assist one whose last chunk has no candidate's `finishReason` (`geminiEnds`, #1643: `usageMetadata` is no end, Vertex AI sends it on every chunk; a chunk with no candidate at all is the empty reply's to answer, #667), and a relayed Gemini one told the same way (#1644; it ends in Gemini's own `{"error":{"code":502,…,"status":"UNAVAILABLE"}}` data line from `streamFailure`, `TestGeminiRelayEndedShort`) — ends the turn with "the reply ended before it was complete" (`errEndedShort`, `TestResponsesUpstreamEndedShort`, `TestGeminiUpstreamEndedShort`), asked again in place where the upstream goes on from a prefill (`continuation.go`). A client that asked for no stream is told the same 502 of such a cut (`translate`, `TestNonStreamEndedShort`, `TestGeminiNonStreamEndedShort`), rather than handed what came as its whole reply. A translated reply from an Anthropic or Responses upstream that ended but said nothing (no text, call, search or image) and counted no token at all is no reply either, whatever its end says (`repliesCounted`, #2086: an Anthropic-compatible proxy's 200 ended a Codex turn as `response.completed` with no output, no usage and no served model, and Codex didn't ask again). It is the empty reply's to answer (#667): asked again in place, then failed with "an empty reply", streamed or not, for every client (`TestUncountedEmptyReplyFails`, `TestUncountedEmptyReplyFailsEveryClient`). Claude's own empty `end_turn` counts its prompt and stays a whole reply (`TestWellFormedStreamsStillComplete`). A reply passed through in its own protocol isn't read this way. +- A vendor's error keeps its `code` and `param` on its way to an OpenAI-shaped client (`writeVendorError`), where `writeError` used to set both to null: a status error relayed or translated, and a request refused inside a Responses stream. A Responses stream's `error` event or failed response whose error is of type `invalid_request_error` is the request at fault (`requestRefused`, read by its type, not its words): its `Event` carries status 400 and the vendor's error (`Event.Said`), so a client answered whole gets the vendor's 400 with its code and param (the whole-translated path wrote 502 `api_error`), a reply cut by it isn't resumed (`continuation.again`), and a translated stream's error says the vendor's type, code and param (`saidError`), so `holdWriter` reads it as the 400 it is. Before, the hold read magpie's `api_error` as a 502: the same request was sent three times, then to the other accounts, and every one rested (magpie-releases#18: the ChatGPT backend answers `access_programs` naming a program the workspace hasn't got with a 200 stream whose error is `access_program_not_enabled`). Asked once, nobody rests ([`codex_access_programs_test.go`](../../internal/gateway/codex_access_programs_test.go)). - Claude's, GPT's and Gemini's reasoning is held (`refusesAfterThinking`, up to `holdThinking`, 4 minutes) so that a refusal after it goes to the next candidate unseen (#248). It is held only while one could: on the last candidate a refusal isn't asked again, so Claude's and GPT's reasoning streams as it comes there, and a refusal after it reaches the agent as the vendor's own. Held there, a lone relay's Claude or GPT showed Claude Code its thinking all at once with the text, and Codex none until then (iTianbao on X). Gemini's stays held on the last candidate too, for a reply that only reasoned to be asked again (#667). Any other model's reasoning is never held. - A streamed reply stuck in a loop is ended, not let run to its output limit (#1359, Moody-Sin: WorkBuddy's DeepSeek v4.1 flash reasoned round "Now." "Writing." "Go." "Let me write." "OK." until max tokens while dsh and Pi waited). `holdWriter.Write` feeds every streamed try, passed through or translated, a key's, a built-in subscription's or a plugin's (a moved WorkBuddy's fetch in the plugin host, `TestLoopEndsWorkBuddysReply`), in each of the agent's protocols, to a `loopGuard` ([`loop_guard.go`](../../internal/gateway/loop_guard.go)). It cuts the reasoning and the text, each apart, into units, its lines and sentences (a list's `1.` or a decimal is no sentence's end), compared without case or a closing stop. A unit with no word in it (a letter run with no digit: not a brace, a rule, `0x00`, a hash or a row of numbers) isn't counted. When the last `loopWindow` (256) counted units of either are among no more than `loopDistinct` (24) different ones, the try is cut (`cutLoop`): what came with that write goes out, then the protocol's stream error (`streamError`, 502) naming the loop and quoting its units, and the vendor's request is cancelled. It falls back to nobody and rests nobody (`failLoop`); its usage record's error type is `reply_loop` (`usage.LoopErrType`), and Usage counts them per model (`Totals.Loops`), as "{n} looped" beside the model's failures in the Overview's rows and the Requests ranking (#1858, `TestLoopsCountedPerModel`, `usage-loops.test.cjs`). A reply magpie translates into the agent's protocol (`streamTranslated`) whose *reasoning* loops before it has said a text or a call, and isn't a continuation, is asked again once in place instead (`loopReasks`, through `holdWriter.onLoop`; cdredfox on X, WorkBuddy AI's DeepSeek v4 flash): the agent keeps the reasoning it has, the next try's follows it in the same stream, as an empty reply's re-ask does (#667), and only a loop on that try ends the reply with the error (`TestReasoningLoopIsAskedAgain`). A loop in the text, or after a text or call, is ended at once (`TestLoopAfterTextIsNotAskedAgain`), and so is a Chat stream passed through as it comes, whose bytes aren't magpie's to splice. A cycle need not be exact. Code, tables, lists, logs, CSV and base64 differ line to line or have no words, and don't trip it (`TestLoopGuardLeavesOrdinaryRepliesAlone` feeds magpie's own sources and docs through it). A reply sent whole (no stream, or Gemini without `alt=sse`) isn't read. Settings › Models › Replies › *Stop looping replies* (`noLoopGuard`) turns it off. - A Chat request's earlier turns carry the assistant's thinking back in the spelling its own client used: `reasoning_content` (DeepSeek's, which OpenCode and most clients send), `reasoning` (OpenRouter's) or `reasoning_details` (OpenRouter's structured one). A request translated to a non-Chat upstream reads whichever of the three the turn has, in that order, as the turn's thinking (`messageReasoning`, `reasoningText`, read by `parseChat` in [chat.go](../../internal/gateway/chat.go)); the passthrough has read all three since `mistralThinking` (#494), which was the one place that did. Before that the parse layer read `reasoning_content` alone, so a tool-calling session whose client spelled it another way went on from its second turn without the model's own reasoning. diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index c1f0bfcd2..e9e5946cd 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -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 ` didn't take this key (): …` 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 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) | diff --git a/internal/gateway/anthropic.go b/internal/gateway/anthropic.go index b02e77ed8..725c94a7f 100644 --- a/internal/gateway/anthropic.go +++ b/internal/gateway/anthropic.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) diff --git a/internal/gateway/chat.go b/internal/gateway/chat.go index 08af4f308..5403ea359 100644 --- a/internal/gateway/chat.go +++ b/internal/gateway/chat.go @@ -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) diff --git a/internal/gateway/codex_access_programs_test.go b/internal/gateway/codex_access_programs_test.go new file mode 100644 index 000000000..d0e2bb6ce --- /dev/null +++ b/internal/gateway/codex_access_programs_test.go @@ -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"]) + } +} diff --git a/internal/gateway/continuation.go b/internal/gateway/continuation.go index b650d81d3..a6c2cf4b3 100644 --- a/internal/gateway/continuation.go +++ b/internal/gateway/continuation.go @@ -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 { diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 63db761e7..6f04cf59e 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -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 diff --git a/internal/gateway/ir.go b/internal/gateway/ir.go index 497498f5a..6340a4b14 100644 --- a/internal/gateway/ir.go +++ b/internal/gateway/ir.go @@ -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}) diff --git a/internal/gateway/responses.go b/internal/gateway/responses.go index d42edbd53..54bcb67eb 100644 --- a/internal/gateway/responses.go +++ b/internal/gateway/responses.go @@ -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) } diff --git a/internal/provider/extrabody.go b/internal/provider/extrabody.go index 5d769248c..ac41082a3 100644 --- a/internal/provider/extrabody.go +++ b/internal/provider/extrabody.go @@ -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 { diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 4b0f5c35b..17b1d852c 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -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 }