gateway: a plugin's non-streaming Responses request is relayed streamed and given back whole, so Grok's x_search runs (plugins#112, Watchyourback)

Plugin accounts only stream (Account.Stream), so a stream:false request
was translated: parsed to the IR and rebuilt. The Responses parser keeps
only function and web_search tools, so x_search never reached the Grok
plugin, and Grok answered "let me look that up" without searching. The
rendered reply also hardcoded "tools": [], dropped
usage.server_side_tool_usage_details, and dropped web_search's open_page
item. Watchyourback's capture of the plugin's fetch showed this (no tools
field, input wrapped into message[], store:false); CodeAlex52's code read
agreed.

Now a plugin's request on Responses that asked for one body is relayed
like a streamed one (gathers, used by serve's relay decision and by
passthrough):
- It is asked with stream:true, and the stream goes through the relay's
  usual tidies.
- The client gets the `response` of the stream's response.completed (or
  response.incomplete) as one application/json body. Its output is
  filled from response.output_item.done items, or else the streamed
  text, when that event's output is empty (gathered.go).
- A non-200 goes back as before.
- A whole reply goes back as it came.
- A stream that fails, or ends without its last event, is a 502, as a
  translated one is, never an empty 200.
- Usage is counted from the stream, as for a streamed relay.

Left as it was:
- Messages: its stream has no event holding the whole reply, so
  gathering it means assembling the message from deltas. That is not a
  simple sibling.
- Subscriptions magpie signs in to itself (ChatGPT backend, Qoder,
  MiMo...): their own code fits their requests, and their fakes end in a
  response.completed with no output. A first version that covered every
  stream-only account broke 7 Codex/ChatGPT-API tests, so it was
  narrowed to plugins.

TestGrokPluginGetsNamespacedTools now expects the namespace's freeform
custom tool to be left out (grokBody), as the built-in and the streamed
plugin already did. The translation had offered it as a function.

Tests (fake grok plugin through the plugin host):
- TestGrokPluginNonStreamKeepsHostedTools: upstream SSE with a
  custom_tool_call, tools [x_search] and server_side_tool_usage_details.
  Asserts the plugin was asked stream:true with tools [x_search]; the
  client gets application/json with the custom_tool_call, message,
  tools and details; usage is recorded at 50/7.
- TestGrokPluginNonStreamEndedShort: no response.completed gives 502.
- TestGatheredTextOnlyStream: deltas only.
Each was broken by hand and went red:
- the relay condition reverted: "the plugin was offered null";
- the missing-completed check removed: 200;
- the text fallback removed.

Run: gofmt -l; go vet ./internal/gateway on darwin, GOOS=linux -tags
nogui and GOOS=windows; go test ./internal/gateway -count=1 (ok, 1400s,
load ~200).
Not tried: a real Grok account or the real grok plugin; the reporter's
allowed_x_handles case.
This commit is contained in:
yetone
2026-10-14 20:25:21 +08:00
parent f3ea4bd69e
commit 5ccc05afe7
4 changed files with 294 additions and 5 deletions
+2 -2
View File
@@ -25,7 +25,7 @@ served by a plugin are in [Provider and plugin ownership](provider-plugins.md).
| Sink | With `Sink` on, a key or account that answers 429 while it still has quota goes to the back, behind every one not rate limited since. Held in memory until restart. | [`sink.go`](../../internal/gateway/sink.go) |
| Image generation | `/v1/images/generations` and `/v1/images/edits` are translated to the selected model's image API. OpenRouter image-only models use its `/images` endpoint and send reference images as `input_references`; OpenRouter models that return images through chat stay on Chat Completions. A routing group named for a drawing or a video (`drawingGroup`: `group/<id>`, or a bare id the group goes by that resolved to one of its members) is tried member by member in the order its routing plans for a chat (`drawingTries` over `planGroup`), each member over its own keys or accounts (`drawOnAccounts`, `startVideo`); the next member is asked while one fails as a chat's would move on (`retryable`: its vendor 5xx, out of quota, the model not served), never for a refusal of the request itself, and the call's `Fallback` names those tried first (#2005, tianxia3111: a group of two relays answered the first one's 502). Pause rules and a gateway key's group hold apply as for a chat. Nothing rests for a failed drawing. `TestImageGroupMovesOnToTheNextMember`, `TestVideoGroupMovesOnToTheNextMember`. | [`draw.go`](../../internal/gateway/draw.go), [`video.go`](../../internal/gateway/video.go), [`catalog.go`](../../internal/catalog/catalog.go) |
| Affinity | A conversation stays with the key or account that answered it, so the vendor's prompt cache is read again. Modes: auto (""), `session`, `turn`, `off`, `strict`. Stored in `affinity.json` next to `providers.json`. | [`affinity.go`](../../internal/gateway/affinity.go) |
| One try | `attempt` sends one candidate the request. It goes through the proxy of the account or key it uses, else the provider's (`p.Via`, `ProxyChoice`: `AccountProxies` holds an account's by its name, a key's by its `KeyID`). A request magpie makes for one provider while serving another's (a web search, an image description, a classifier call) takes its own provider's proxy or the global one, never the outer one: `netproxy.With` replaces a choice the context already names, "" too, and `webSearch` starts from none, so the search APIs follow the global proxy (#1522). A subscription with its own client is served specially, such as Claude through the genuine Claude Code. The request is relayed as is (`passthrough`) when the model is usable on the agent's API, except that a Claude model where the provider has an Anthropic URL is translated to Messages from Chat or Responses too (`OnMessages`: OpenCode speaks Chat for every model, and a relay drops cache_control there), unless the user set the model's API or the vendor's list names its APIs. A request offering web search to a provider that doesn't search by itself is translated too, so magpie can search for it (`search.go`; a provider that searches for some of its models only, Command Code's Provider API, lists them in `searchModels` by API, and none count under its `x-cmd-zdr` header, #1590), but on the agent's own API where the provider serves it and no `ResponsesFirst`/`MessagesFirst` rule prefers another: Codex offers web_search on every turn, and each went out as Chat (#997). Otherwise it is translated (`translate`) to the first API `usable` gives: Chat, except Responses for OpenAI's models where their maker serves them (`ResponsesFirst`), Responses for every model at ModelScope, whose Chat API reports neither the tokens its cache answered nor reasoning while its Responses API reports both (`ResponsesTellsCache`, #1578; a 404 there sends the model to Chat, and only there), and Anthropic's Messages for a Claude model where the provider has an Anthropic URL (`MessagesFirst`, which keeps its cache breakpoints, #997). An API that answers the model is not served there (`wrongEndpoint`) is remembered in `unfit` until magpie restarts. When every API has turned the model away, the API the user picked for it (`ModelAPI`) is asked again, and without a pick each API the provider has a URL for (`Speaks`), Chat first. `Provider.Native`, the API agents with a per-model API (Pi, omp, droid) are wired to ask on, follows the same order. A custom provider with a Gemini URL (#1346) has Gemini last among the APIs it speaks: a Gemini client's request is relayed there, and any other is translated to it when it has no other, or when the user set Gemini as the model's API (`SetModelAPI` takes chat, responses, anthropic or gemini, each only where the provider has its URL; a model set to Gemini has no `Native`, so those agents ask it on their own API and it is translated). Upstream it is always asked `models/{model}:streamGenerateContent?alt=sse` under the base (`upstreamPath`), the model only in the path (`forwardOnce` drops the body's), so a Gemini client that asked for one JSON body is translated, as for Factory's generate route. | [`gateway.go`](../../internal/gateway/gateway.go) |
| One try | `attempt` sends one candidate the request. It goes through the proxy of the account or key it uses, else the provider's (`p.Via`, `ProxyChoice`: `AccountProxies` holds an account's by its name, a key's by its `KeyID`). A request magpie makes for one provider while serving another's (a web search, an image description, a classifier call) takes its own provider's proxy or the global one, never the outer one: `netproxy.With` replaces a choice the context already names, "" too, and `webSearch` starts from none, so the search APIs follow the global proxy (#1522). A subscription with its own client is served specially, such as Claude through the genuine Claude Code. The request is relayed as is (`passthrough`) when the model is usable on the agent's API, except that a Claude model where the provider has an Anthropic URL is translated to Messages from Chat or Responses too (`OnMessages`: OpenCode speaks Chat for every model, and a relay drops cache_control there), unless the user set the model's API or the vendor's list names its APIs. An account that only streams (`Account.Stream`: a plugin's, and most subscriptions magpie signs in to) has a request that asked for one body translated, which magpie always asks streamed, except a plugin's on Responses (`gathers`): that is relayed all the same, asked with `stream:true`, and the client given the `response` of the stream's `response.completed` (or `response.incomplete`) as one JSON body (`gathered` in [`gathered.go`](../../internal/gateway/gathered.go); its `output` filled from the stream's `response.output_item.done` items, or else its text, when that event's is empty). So the tools the vendor runs itself, and its response's `tools` and usage details, reach the client (plugins#112: a translation dropped Grok's `x_search`, and Grok answered without searching; `TestGrokPluginNonStreamKeepsHostedTools`). A stream that fails or ends before that event is a 502 (`TestGrokPluginNonStreamEndedShort`), never an empty 200. A Messages request is still translated, its stream having no event that holds the whole reply, and so is a subscription magpie signs in to itself (the ChatGPT backend's, Qoder's): its own code fits its requests. A request offering web search to a provider that doesn't search by itself is translated too, so magpie can search for it (`search.go`; a provider that searches for some of its models only, Command Code's Provider API, lists them in `searchModels` by API, and none count under its `x-cmd-zdr` header, #1590), but on the agent's own API where the provider serves it and no `ResponsesFirst`/`MessagesFirst` rule prefers another: Codex offers web_search on every turn, and each went out as Chat (#997). Otherwise it is translated (`translate`) to the first API `usable` gives: Chat, except Responses for OpenAI's models where their maker serves them (`ResponsesFirst`), Responses for every model at ModelScope, whose Chat API reports neither the tokens its cache answered nor reasoning while its Responses API reports both (`ResponsesTellsCache`, #1578; a 404 there sends the model to Chat, and only there), and Anthropic's Messages for a Claude model where the provider has an Anthropic URL (`MessagesFirst`, which keeps its cache breakpoints, #997). An API that answers the model is not served there (`wrongEndpoint`) is remembered in `unfit` until magpie restarts. When every API has turned the model away, the API the user picked for it (`ModelAPI`) is asked again, and without a pick each API the provider has a URL for (`Speaks`), Chat first. `Provider.Native`, the API agents with a per-model API (Pi, omp, droid) are wired to ask on, follows the same order. A custom provider with a Gemini URL (#1346) has Gemini last among the APIs it speaks: a Gemini client's request is relayed there, and any other is translated to it when it has no other, or when the user set Gemini as the model's API (`SetModelAPI` takes chat, responses, anthropic or gemini, each only where the provider has its URL; a model set to Gemini has no `Native`, so those agents ask it on their own API and it is translated). Upstream it is always asked `models/{model}:streamGenerateContent?alt=sse` under the base (`upstreamPath`), the model only in the path (`forwardOnce` drops the body's), so a Gemini client that asked for one JSON body is translated, as for Factory's generate route. | [`gateway.go`](../../internal/gateway/gateway.go) |
| Trace | The Routing view's record of each decision, written where the decision is made: candidates, rests, which try answered. `Route.Folder` is the folder the agent says it works in (`workDir`), its last two levels only (`shortFolder`, e.g. `workspace/magpie`), never the full path; a request that says none (a title, a topic check) takes its session's as said last (`trace.sessionFolder`), one without a session id has none (#1068). It is kept in the routing history on disk for as long as the route is (`history.go`: 30 days, 200 MB). The GUI shows it in By session's headings, a request row's tooltip, the stage's agent working in more than one folder, and the tray panel's agent tooltip. | [`trace.go`](../../internal/gateway/trace.go) |
| Prompt | What each request's prompt held, part by part: the agent's system prompt, tool definitions (an MCP server's tools as one item), instruction files and skills, files its tools read, their other output, and the conversation. `inspectPrompt` reads it from the body as the agent sent it, before translation; `calibrated` scales the estimate to the prompt the vendor counted and sets the window of the model that answered. The route keeps names and sizes only, never the text, so the routing history on disk holds none. For the card's text (masaka on Discord), the trace keeps the last `promptBodies` (10) request bodies in memory only (at most 32 MiB each, 64 MiB together), masked as the vendor got them; for a model let have it unmasked, the masked copy is kept all the same. `PromptText` reads a part's items and their text from that body again (`prompt_text.go`), served to the GUI as `/api/context/text`; once a body is dropped, or magpie quits, its text is gone. It goes on the trace as `Route.Prompt`, with `Route.Conv` naming a conversation that has no session id. The GUI's `/api/context` scores each agent from it (`internal/gui/context.go`). | [`prompt.go`](../../internal/gateway/prompt.go) |
| Vertex AI | A [Google Vertex AI provider](providers-accounts.md#responsibilities-and-sources-of-truth) speaks Gemini alone. A request goes to `<base>/publishers/google/models/<model>:streamGenerateContent?alt=sse` (`provider.VertexPath`, `upstreamPath`), the model named as the user's upstream name for it says (`UpstreamNameIn`, which the usage log's endpoint names too), with no `model` or `stream` field in its body (`passthrough`, `forwardOnce`, `geminiRequest`). A Gemini client's request is relayed as it came, its own `thinkingConfig`, `safetySettings` and the rest kept: streamed there, asked whole to `:generateContent` (`provider.VertexWholePath`), which answers one JSON body (Factory's rule of translating a whole request, as its route only streams, isn't Vertex AI's). Every other API's is translated (`buildFor`, `buildVertex`) and its stream read by `codeAssistDecoder`, which gives thought parts as reasoning, never as the answer's text. Effort: `vertexEffort` fits it to the model's levels, reasoning turned off going as `minimal` fitted the same way, and holds a model whose levels aren't known to `low`…`high`. `vertexThinking` sends Gemini 3 a `thinkingLevel` (`includeThoughts` false with reasoning off) and 2.5 a `thinkingBudget` in the model's range (`vertexBudgets`): turned off, the budget that stops its thinking, or Pro's least, as Pro can't stop. Thought signatures are every Gemini path's (#1445): a call's signature reaches the client in its id (`signedID`) and goes back on the call it came on, while a call with none in a step Vertex AI signed goes without; a step with nothing to give back has every call sent `skip_thought_signature_validator`. A 400 `Invalid thought signature.` is asked again with every call sent so (`withoutSignatures`), for that request only. A 400 refusing `minimal` (`geminiRefusedLevel`) is asked again at the model's lowest other level (`onEffort`), and `markUnfit(offRefused)` keeps that level until magpie restarts. Both retries are the translated path's. Vertex AI's own Google Search grounding isn't used: `searchHosts` names only `generativelanguage.googleapis.com` for Gemini, so magpie searches for it (`search.go`). | [`vertex.go`](../../internal/gateway/vertex.go), [`gateway.go`](../../internal/gateway/gateway.go), [`codeassist.go`](../../internal/gateway/codeassist.go), [`gemini.go`](../../internal/gateway/gemini.go), [`gemini_signature.go`](../../internal/gateway/gemini_signature.go), [`search.go`](../../internal/gateway/search.go) |
@@ -115,7 +115,7 @@ recorded as a prediction failure (`noPrediction`).
- A request built for a Messages upstream (`buildAnthropic`: a Chat, Responses or Gemini client translated, and Zed's bridge) has its tool exchanges mended after its messages are built (`pairToolBlocks`, #1558, ggbdpq), since Anthropic answers 400 for a `tool_use` the next message doesn't answer and for a `tool_result` naming no call of the message before it. A call left unanswered gets the synthetic interrupted result, `is_error` set, first in the user message after it or in one of its own; a result that answers no call goes as a text block with what it said (its images as they came); a second answer to one call is dropped. A well-formed exchange goes as it was built. An Anthropic client relayed to a Messages upstream isn't mended. [`anthropic_tool_pairing_test.go`](../../internal/gateway/anthropic_tool_pairing_test.go).
- A Responses request bound for anything but a ChatGPT sign-in has its tool exchanges mended in `attempt`, before it is relayed or translated, plugins included ([`responses.go`](../../internal/gateway/responses.go)). An item inside a run of calls and results (after one of the run's results and before the last, or before any result when the model didn't write it) moves to the end of that run (`joinToolRuns`, #1752, Edward4226): Codex writes its `<image_resize_notice>` right after each result whose image it resized, so a batch of two calls had it between their results, and a strict upstream answered 400 (OpenCode Go/DeepSeek "No tool output found for tool call …", Volcengine's "must be followed by tool messages", #1822); a Chat translation answered the second call with a synthetic result. An item carrying a `call_id` never moves, the model's own reasoning between its calls stays, and its text between them (an assistant message, with the reasoning right before it) goes ahead of the run's first call, so the step's calls stand together: OpenCode Go opens a new assistant message at such text and answered the call before it "No tool output found for tool call …" (#2100). A call opens a run only when a result after it answers it. A result with no call id becomes a user message after its run (`orphanedToolOutputs`), and a call nothing answers gets a synthetic result at the end of its run (`pairToolItems`, #1341). `TestRelayedCodexImageBatchKeepsItsResultsTogether`, `TestJoinToolRunsOnlyMovesWhatBreaksARun`, `TestRelayedTextBetweenABatchsCallsIsAnswered`.
- Codex's model list from the backend path (`codexModels`) is the ChatGPT backend's for its sign-in and then magpie's (`provider.CodexListed`), its ETag and every reply's `X-Models-Etag` tagged with `provider.CodexListTag` so a change has Codex ask again. A Codex there only for account failover, not connected (`CodexOwnOnly`, `agent.CodexOwnOnly`; #1385), gets the backend's alone, tagged with `provider.CodexOwnListTag`; neither tag contains the other, so connecting or disconnecting has Codex fetch the list again. The user's picks on the codex provider (`provider.CodexNativePicked`) narrow the backend's listed models. They keep its hidden ones (`visibility: "hide"`), which no picker shows. One of those is `codex-auto-review`: when the list lacks it and no reviewer is set, Codex's auto-review runs on the conversation's model at low effort (#1460, `TestCodexModelListPicksKeepHidden`). The account's own models kept out of agents' lists for routing groups (`provider.CodexNativeUnlisted`) are dropped from it too, hidden ones kept: every one when the codex provider is "Only through routing groups" (`Provider.Unlisted`), and those a group that unlists its members names (`Group.Unlists`). A Codex there only for failover keeps them, as it is handed no groups; `spawnChoices` drops the same ones (#1602, `TestCodexModelListUnlistedForGroups`).
- Reasoning state goes through magpie's translation as the vendor wrote it when the agent and the upstream speak the same API (#1445, XYenon): a non-streaming request to a stream-only account, web search on the agent's own API, a plugin, failover. The IR carries it sealed (`Part.Sealed`, `SealedBy`; events `KThinkStart`, `KSealed`, `KTextSig` in [`ir.go`](../../internal/gateway/ir.go)), so each thinking block or reasoning item stays apart, whole or streamed, and a seal is written only for its own API (`sealedBy`). Anthropic's `redacted_thinking` goes back raw (to DeepSeek as a thinking block, below), and a thinking block signed with no text keeps its signature (`aBlock` still writes `"thinking": ""`, #1447), on Claude's subscription too. A Responses reasoning item keeps its id, summary and `encrypted_content`, and goes back to a Responses upstream as it came when it has no reasoning text (`sealedReasoning`; text, another vendor's, is still left out for OpenAI, #1411). Gemini's `thoughtSignature` stays on the call it signed and on text; a later call of a signed step goes without one, and only an unsigned step or Claude on Antigravity gets `skip_thought_signature_validator`. Another API's agent gets the call's signature in its id, as on chat (#687), with its length in the mark (`__ts<n>__`), so an id a client shortened carries no signature and the call goes as unsigned (#1536); it gets no one else's seal. Carrying reasoning across APIs (an envelope) isn't done.
- Reasoning state goes through magpie's translation as the vendor wrote it when the agent and the upstream speak the same API (#1445, XYenon): a non-streaming Messages request to a stream-only account, web search on the agent's own API, a plugin, failover. The IR carries it sealed (`Part.Sealed`, `SealedBy`; events `KThinkStart`, `KSealed`, `KTextSig` in [`ir.go`](../../internal/gateway/ir.go)), so each thinking block or reasoning item stays apart, whole or streamed, and a seal is written only for its own API (`sealedBy`). Anthropic's `redacted_thinking` goes back raw (to DeepSeek as a thinking block, below), and a thinking block signed with no text keeps its signature (`aBlock` still writes `"thinking": ""`, #1447), on Claude's subscription too. A Responses reasoning item keeps its id, summary and `encrypted_content`, and goes back to a Responses upstream as it came when it has no reasoning text (`sealedReasoning`; text, another vendor's, is still left out for OpenAI, #1411). Gemini's `thoughtSignature` stays on the call it signed and on text; a later call of a signed step goes without one, and only an unsigned step or Claude on Antigravity gets `skip_thought_signature_validator`. Another API's agent gets the call's signature in its id, as on chat (#687), with its length in the mark (`__ts<n>__`), so an id a client shortened carries no signature and the call goes as unsigned (#1536); it gets no one else's seal. Carrying reasoning across APIs (an envelope) isn't done.
- A translated Responses reply gives Codex the reasoning items a Responses upstream sent, as it sent them; any other upstream's reasoning becomes items magpie made: an `rs_` id and a summary, nothing sealed. Codex hands them back on every turn. A request relayed as is to OpenAI's API or Azure OpenAI goes without them (`withoutBareReasoning`) unless `store` is true, because both look the id up among stored items and answer 400 "Item with id 'rs_…' not found" (#1008). Any other Responses upstream gets them, because a DeepSeek model wants its reasoning back (#388). When one answers 400 naming the input (`refusesInput`: `param` is `input`, or the error names an item by id), as a relay in front of OpenAI does with a message of its own, `passthrough` asks once more without them and, once that works, leaves them out for that provider and model from then on (`bareReasoningRefused`, #1044). Codex's compaction offers no tools, so it is relayed even when its turns were translated. When a provider answers its summary request 404, or 400 for an item it didn't find (`itemNotFound`, a relay in front of either), `codexCompact` asks once more with the conversation as text (`plainCompact`), then compacts locally (#866, #1008). So does the ChatGPT backend's 502 "response protection is unavailable" (`protectionRefused`): a long history refused so was answered as text. Codex also compacts remotely, a `compaction_trigger` on `/responses` that wants exactly one compaction item back, on any provider table named "OpenAI", as CC Switch names its relay tables. magpie points those at `/v1` while a magpie model is on, so `handle` makes the summary there too (`codexInput`, `codexCompact`), and magpie's summaries go back to the model as text (#1301).
- A Responses request Codex sends a Responses provider is fitted for a backend that isn't OpenAI's before it goes (`passthrough`): Responses Lite's `additional_tools` item lifted into `tools` (`liftAdditionalTools`, #350), the tool search as a function, OpenAI-only fields left out. A relay that checks a request is Codex's own turns that shape away (#1758: 400 "Codex 客户端请求特征无效", 10014). A provider set `codexAsSent` (`magpie provider set <id> codex=as-sent`) gets a request from Codex (`fromCodex`) as Codex sent it, its model name alone swapped, with Codex's own headers (`codexClientHeader`). Off is the default, and a subscription account is never sent so. `TestCodexAsSent`.
- Every request to a key+URL provider goes with magpie's User-Agent (`magpie/<Version>`, `userAgentFor` in [`user_agent.go`](../../internal/gateway/user_agent.go)), except a provider set `passUserAgent` (#1851, `magpie provider set <id> user-agent=agent`, the editor's "Send the agent's own User-Agent"): it gets the User-Agent the inbound request carried, unchanged, for a coding plan that serves only the agents it names. One the agent didn't send, and magpie's own (`magpiesOwn`: another magpie's `magpie/…`, `magpie-router/1`, `magpie-vision/1`, `magpie-search/1`, and the image tool's `<client> magpie-image/1`, built from MCP's clientInfo, not a User-Agent), go as magpie; magpie never makes up another client's. `forwardOnce` sets it for chat, Anthropic, Responses, Gemini and count_tokens; embeddings, images and videos (`retrieveFrom`, `sendWith`, `remoteVideoContent`) set it with `stampUA` from the caller the request came with (`caller.ua`, `withCaller`), and before #1851 went with Go's default. Claude Code's and Codex's own headers are copied after, as before, and the user's `header.User-Agent` is put on when the request is signed, so it wins. `provider.PassesUserAgent` refuses it for a signed-in account, a plugin's, and a vendor whose own client magpie goes as (`OwnClient`: OpenCode, Cline, Kilo, another magpie); their signing sets their own. `TestUserAgentPassedOn`, `TestUserAgentAccountUntouched`, `TestUserAgentFor`, `TestPassesUserAgent`, `provider-user-agent.test.cjs`.
+23 -2
View File
@@ -3198,8 +3198,10 @@ func (s *Server) attempt(w http.ResponseWriter, r *http.Request, from provider.P
noteMember(w, r, p, model)
}
// a backend that only streams gets a non-streaming request translated
// (the provider is always streamed on that path) rather than relayed
relay := slices.Contains(s.usable(p, model), from) && (p.Account == nil || !p.Account.Stream || streamOf(body))
// (the provider is always streamed on that path) rather than relayed,
// except a plugin's on Responses, which is relayed streamed and given
// back whole (gathers)
relay := slices.Contains(s.usable(p, model), from) && (p.Account == nil || !p.Account.Stream || streamOf(body) || gathers(p, from, body))
// a Claude model is asked on Messages whatever API the client spoke,
// for the cache breakpoints the translation adds: OpenCode speaks Chat
// for every model, and a relay drops cache_control on Chat, so every
@@ -3622,6 +3624,13 @@ func codexClientHeader(k string) bool {
func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.Provider, proto provider.Protocol, model string, body []byte, u *Usage) (status int, msg string, done bool) {
upstream := provider.UpstreamNameIn(wiresOf(r.Context()), p.ID, model)
body = rewriteModel(body, upstream)
// a client that asked for one body, of an account that only streams:
// asked streamed, the stream read here (gathered)
var gather *gathered
if gathers(p, proto, body) {
gather = &gathered{h: http.Header{}, status: http.StatusOK}
body = withFields(body, map[string]any{"stream": true})
}
searchFn := false // Codex's tool search sent as a function
geminiWhole := false // a Gemini client's generateContent
// a model that wants its reasoning text back (#388, #1104)
@@ -4072,6 +4081,10 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
return writeError(w, proto, res.StatusCode, msg), msg, true
}
rd, sse := eventStream(res)
client := w
if gather != nil {
w = gather
}
h := w.Header()
for _, k := range []string{"Content-Type", "Request-Id", "X-Request-Id"} {
if v := res.Header.Get(k); v != "" {
@@ -4209,6 +4222,14 @@ func (s *Server) passthrough(w http.ResponseWriter, r *http.Request, p provider.
if sse {
sniff.drain()
}
if gather != nil {
cut := ""
if rerr != nil && rerr != io.EOF {
cut = cutMidReply(p.Name, rerr)
}
status, msg := gather.finish(client, p, sse, cut, sniff.failed)
return status, msg, true
}
if sse && r.Context().Err() == nil && !sniff.whole() {
// the upstream died mid-reply, or ended it short of its last
// event: say so in the stream rather than end it as if whole,
+146
View File
@@ -0,0 +1,146 @@
package gateway
import (
"bytes"
"encoding/json"
"net/http"
"sort"
"strings"
"github.com/yetone/magpie/internal/provider"
)
// gathers is whether a request to p on proto that asked for one body is
// relayed streamed and given back whole (gathered) rather than translated:
// a plugin's account, which only streams, on Responses (plugins#112:
// translating it dropped the tools the vendor runs itself, Grok's x_search,
// so Grok answered without searching, and the response's tools and usage
// details). A subscription magpie signs in to itself (Codex's ChatGPT
// backend, Qoder) is translated as before: its own code fits its requests,
// and no report asks for more. Messages isn't gathered, as its stream has
// no event that holds the whole reply.
func gathers(p provider.Provider, proto provider.Protocol, body []byte) bool {
return proto == provider.Responses && p.IsPlugin() && p.Account.Stream && !streamOf(body)
}
// gathered holds a relayed Responses stream that the client asked for
// whole, and gives the client the response the stream ends with.
type gathered struct {
h http.Header
status int
buf bytes.Buffer
}
func (g *gathered) Header() http.Header { return g.h }
func (g *gathered) WriteHeader(status int) { g.status = status }
func (g *gathered) Write(b []byte) (int, error) { return g.buf.Write(b) }
// finish writes the reply to w: the response of the stream's
// response.completed (or response.incomplete), its output filled from the
// stream's items, or else its text, when the event left it empty.
// A reply that came whole goes as it came. A stream that failed, or ended
// before saying its reply had, is a 502, as a translated one is
// (TestNonStreamEndedShort), never an empty 200.
func (g *gathered) finish(w http.ResponseWriter, p provider.Provider, sse bool, cut string, failed string) (int, string) {
if !sse {
for k, vs := range g.h {
w.Header()[k] = vs
}
w.WriteHeader(g.status)
w.Write(g.buf.Bytes())
return g.status, failed
}
var resp json.RawMessage
items := map[int]json.RawMessage{}
var text strings.Builder // the reply's text, for a stream with no items
streamErr := ""
readSSE(bytes.NewReader(g.buf.Bytes()), func(event, data string) error {
var e struct {
Type string `json:"type"`
Response json.RawMessage `json:"response"`
Item json.RawMessage `json:"item"`
OutputIndex int `json:"output_index"`
Delta string `json:"delta"`
}
if json.Unmarshal([]byte(data), &e) != nil {
return nil
}
if e.Type == "" {
e.Type = event
}
switch e.Type {
case "response.output_text.delta":
text.WriteString(e.Delta)
case "response.output_item.done":
if len(e.Item) > 0 {
items[e.OutputIndex] = e.Item
}
case "response.completed", "response.incomplete":
resp = e.Response
case "response.failed", "error":
streamErr = provider.APIError([]byte(data), "upstream stream failed")
}
return nil
})
if len(resp) == 0 || resp[0] != '{' {
msg := failed
switch {
case streamErr != "":
msg = p.Name + ": " + streamErr
case cut != "":
msg = cut
case msg == "":
msg = p.Name + ": the reply ended before it was complete"
}
return writeError(w, provider.Responses, 502, msg), msg
}
if len(items) == 0 && text.Len() > 0 {
msg, _ := json.Marshal(map[string]any{"type": "message", "id": "msg_" + newID(), "role": "assistant", "status": "completed",
"content": []any{map[string]any{"type": "output_text", "text": text.String(), "annotations": []any{}}}})
items[0] = msg
}
resp = withStreamedOutput(resp, items)
for _, k := range []string{"Request-Id", "X-Request-Id"} {
if v := g.h.Get(k); v != "" {
w.Header().Set(k, v)
}
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write(resp)
return http.StatusOK, ""
}
// withStreamedOutput is resp with the stream's items as its output when
// its own output is missing or empty.
func withStreamedOutput(resp json.RawMessage, items map[int]json.RawMessage) json.RawMessage {
if len(items) == 0 {
return resp
}
var m map[string]json.RawMessage
if json.Unmarshal(resp, &m) != nil {
return resp
}
var out []json.RawMessage
if json.Unmarshal(m["output"], &out) == nil && len(out) > 0 {
return resp
}
idx := make([]int, 0, len(items))
for i := range items {
idx = append(idx, i)
}
sort.Ints(idx)
out = out[:0]
for _, i := range idx {
out = append(out, items[i])
}
b, err := json.Marshal(out)
if err != nil {
return resp
}
m["output"] = b
if nb, err := json.Marshal(m); err == nil {
return nb
}
return resp
}
+123 -1
View File
@@ -16,6 +16,7 @@ import (
"github.com/yetone/magpie/internal/plugin"
"github.com/yetone/magpie/internal/provider"
"github.com/yetone/magpie/internal/testenv"
"github.com/yetone/magpie/internal/usage"
)
// besideFake installs the fake plugin as the plugin of the built-in id,
@@ -94,6 +95,9 @@ func TestGrokPluginDraws(t *testing.T) {
// Codex's namespaced tools reach the Grok plugin flat, and its call comes
// back under the namespace, as with the built-in (TestGrokGetsNamespacedTools).
// The request asks for one body, which is relayed streamed (plugins#112), so
// the namespace's freeform tool is left out as the built-in leaves it
// (grokBody): no longer offered as the function a translation made of it.
func TestGrokPluginGetsNamespacedTools(t *testing.T) {
var mu sync.Mutex
var sent []map[string]any
@@ -138,7 +142,7 @@ func TestGrokPluginGetsNamespacedTools(t *testing.T) {
tm := tl.(map[string]any)
names = append(names, tm["type"].(string)+":"+tm["name"].(string))
}
if got := strings.Join(names, ","); got != "function:exec_command,function:collaboration__spawn_agent,function:collaboration__freeform" {
if got := strings.Join(names, ","); got != "function:exec_command,function:collaboration__spawn_agent" {
t.Fatalf("Grok was offered %s", got)
}
if c := q["input"].([]any)[1].(map[string]any); c["name"] != "collaboration__spawn_agent" || c["namespace"] != nil {
@@ -229,3 +233,121 @@ func TestGrokPluginCallsGiveCodexIntegers(t *testing.T) {
checkResponses(t, c, askGrok(t, "/v1/responses", codexShellTurn(pid+"/grok-4.7", stream)), stream)
}
}
// A non-streaming Responses request to the Grok plugin, an account that
// only streams, is relayed streamed and given back whole (plugins#112): the
// hosted x_search reaches the vendor, and its custom_tool_call items, the
// response's tools and its usage details reach the client. A translation
// dropped all three, so Grok answered without searching.
func TestGrokPluginNonStreamKeepsHostedTools(t *testing.T) {
var mu sync.Mutex
var sent []map[string]any
call := `{"type":"custom_tool_call","id":"ctc_1","call_id":"xs_1","name":"x_keyword_search","input":"{\"query\":\"magpie\"}","status":"completed"}`
msg := `{"type":"message","id":"msg_1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"Found it.","annotations":[]}]}`
done := `{"id":"r1","object":"response","status":"completed","model":"grok-4.7","tools":[{"type":"x_search"}],"output":[` + call + `,` + msg + `],"usage":{"input_tokens":50,"output_tokens":7,"total_tokens":57,"server_side_tool_usage_details":{"web_search_calls":0,"x_search_calls":1}}}`
pid := besideFake(t, "grok", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
b, _ := io.ReadAll(r.Body)
var q map[string]any
json.Unmarshal(b, &q)
mu.Lock()
sent = append(sent, q)
mu.Unlock()
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, sse(
`event: response.created`+"\n"+`data: {"type":"response.created","response":{"id":"r1","object":"response","status":"in_progress","output":[]}}`,
`event: response.output_item.done`+"\n"+`data: {"type":"response.output_item.done","output_index":0,"item":`+call+`}`,
`event: response.output_item.done`+"\n"+`data: {"type":"response.output_item.done","output_index":1,"item":`+msg+`}`,
`event: response.completed`+"\n"+`data: {"type":"response.completed","response":`+done+`}`))
}))
body := `{"model":"` + pid + `/fake-resp","stream":false,"tools":[{"type":"x_search"}],"input":"What do people say about magpie?"}`
rec := httptest.NewRecorder()
New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(body)))
if rec.Code != 200 {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
if ct := rec.Header().Get("Content-Type"); ct != "application/json" {
t.Fatalf("Content-Type %q: %s", ct, rec.Body)
}
mu.Lock()
if len(sent) != 1 {
t.Fatalf("asked %d times", len(sent))
}
q := sent[0]
mu.Unlock()
if q["stream"] != true {
t.Fatalf("the plugin was asked stream=%v", q["stream"])
}
if tools, _ := json.Marshal(q["tools"]); string(tools) != `[{"type":"x_search"}]` {
t.Fatalf("the plugin was offered %s", tools)
}
var res struct {
Object string `json:"object"`
Tools []map[string]any `json:"tools"`
Output []map[string]any `json:"output"`
Usage struct {
Details map[string]any `json:"server_side_tool_usage_details"`
} `json:"usage"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &res); err != nil {
t.Fatalf("%v: %s", err, rec.Body)
}
if res.Object != "response" || len(res.Tools) != 1 || res.Tools[0]["type"] != "x_search" {
t.Fatalf("tools %v: %s", res.Tools, rec.Body)
}
if len(res.Output) != 2 || res.Output[0]["type"] != "custom_tool_call" || res.Output[0]["name"] != "x_keyword_search" || res.Output[1]["type"] != "message" {
t.Fatalf("output %v", res.Output)
}
if res.Usage.Details["x_search_calls"] != float64(1) {
t.Fatalf("usage details %v", res.Usage.Details)
}
// and the stream's usage is what the request is counted at
recs := usage.Load(time.Time{})
if len(recs) == 0 || recs[len(recs)-1].Input != 50 || recs[len(recs)-1].Output != 7 {
t.Fatalf("recorded %+v", recs)
}
}
// A stream that ends before its response.completed is a 502 to a client
// that asked for one body, never an empty 200 (TestNonStreamEndedShort's,
// for the relayed path, plugins#112).
func TestGrokPluginNonStreamEndedShort(t *testing.T) {
pid := besideFake(t, "grok", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, sse(
`event: response.created`+"\n"+`data: {"type":"response.created","response":{"id":"r1","object":"response","status":"in_progress","output":[]}}`,
`event: response.output_text.delta`+"\n"+`data: {"type":"response.output_text.delta","output_index":0,"content_index":0,"delta":"Found"}`))
}))
body := `{"model":"` + pid + `/fake-resp","stream":false,"input":"hi"}`
rec := httptest.NewRecorder()
New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", "/v1/responses", strings.NewReader(body)))
if rec.Code != 502 || !strings.Contains(rec.Body.String(), "ended before it was complete") {
t.Fatalf("%d %s", rec.Code, rec.Body)
}
}
// A stream whose response.completed names no output, and which sent no
// output_item.done either, still gives the client the text it streamed.
func TestGatheredTextOnlyStream(t *testing.T) {
g := &gathered{h: http.Header{}, status: 200}
g.h.Set("Content-Type", "text/event-stream")
io.WriteString(g, sse(
`data: {"type":"response.created","response":{"id":"r1","model":"m"}}`,
`data: {"type":"response.output_text.delta","delta":"po"}`,
`data: {"type":"response.output_text.delta","delta":"ng"}`,
`data: {"type":"response.completed","response":{"id":"r1","object":"response","status":"completed","usage":{"input_tokens":7,"output_tokens":1}}}`))
rec := httptest.NewRecorder()
if code, _ := g.finish(rec, provider.Provider{Name: "p"}, true, "", ""); code != 200 {
t.Fatalf("%d %s", code, rec.Body)
}
var res struct {
Output []struct {
Type string `json:"type"`
Content []struct {
Text string `json:"text"`
} `json:"content"`
} `json:"output"`
}
if json.Unmarshal(rec.Body.Bytes(), &res) != nil || len(res.Output) != 1 || res.Output[0].Type != "message" || len(res.Output[0].Content) != 1 || res.Output[0].Content[0].Text != "pong" {
t.Fatalf("%s", rec.Body)
}
}