Skip to content

Every agent's model. One place. Codex on DeepSeek, Claude Code on Kimi, from the menu bar.

gateway: serve OpenAI's text to speech, POST /v1/audio/speech

yetonef6263439af61
diff --git a/docs/reference.md b/docs/reference.md
index a737d38ec..41f9cd543 100644
--- a/docs/reference.md
+++ b/docs/reference.md
@@ -1961,6 +1961,7 @@ It exposes:
| `/v1/messages/count_tokens` | Anthropic token counting |
| `/v1beta/models/{model}:generateContent` | Google Gemini (also `:streamGenerateContent`, `:countTokens`) |
| `/v1/audio/transcriptions`, `/v1/audio/translations` | OpenAI speech to text (multipart, passed through) |
+| `/v1/audio/speech` | OpenAI text to speech (JSON in, the vendor's audio or SSE streamed back) |
| `/v1/models`, `/v1beta/models` | the catalog |
| `/v1/codex/models` | the catalog as Codex's `model_catalog_url` reads it ([Codex on another computer](#providers-and-the-gateway)) |
| `/api/version`, `/api/tags`, `/api/show` | the catalog as an Ollama server lists it, for a client that takes a custom endpoint only as Ollama (below) |
@@ -2024,7 +2025,19 @@ models are named `provider/model`.
provider's own id, and a `prompt` masked as your redaction settings say.
The answer comes back in the vendor's own format (`json`, `text`, `srt`,
`vtt`). A provider with no OpenAI-style API is refused; one that has no
- such endpoint answers its own 404. Text to speech is not served.
+ such endpoint answers its own 404.
+- Text to speech (`/v1/audio/speech`) takes OpenAI's JSON body
+ (`model`, `input`, `voice`, `response_format`, `speed`, `instructions`,
+ `stream_format`), its `model` a magpie id such as
+ `openai/gpt-4o-mini-tts` or `groq/playai-tts`. The body goes to that
+ provider's OpenAI-style base with only the model set to the provider's
+ own id; any other field (Mistral's `voice_id`) goes as sent. The answer
+ is passed on as it comes, in the vendor's own type: audio (`mp3`,
+ `opus`, `aac`, `flac`, `wav`, `pcm`), SSE for `stream_format: "sse"`,
+ or the vendor's own JSON (Mistral answers `{"audio_data": base64}`).
+ `input` and `instructions` are masked as your redaction settings say;
+ the answer is audio, so a masked value is read aloud as its
+ placeholder.
- Every reply names who answered in `X-Magpie-Provider` (the provider)
and `X-Magpie-Model` (`provider/model`), and so does the usage log.
diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md
index a0956c617..bf32a9189 100644
--- a/docs/subsystems/gateway-routing.md
+++ b/docs/subsystems/gateway-routing.md
@@ -39,7 +39,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md).
| 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. Volcengine Ark (`isArk`: an `ark.*.volces.com` base, the preset's plans or one added by hand) is asked at `/images/generations` only, as its doc (https://www.volcengine.com/docs/82379/1541523) takes it (`drawArk`): `watermark: false`, since it marks every image otherwise; reference images as JSON `image` (a URL or data URL, an array for several), never a multipart edit; no `n`, so one request per image (`eachDrawing`); no ratio as `size`, so a ratio its doc lists is sent as that ratio's 2K size and any other is a 400 that says to put it in the prompt; no mask, no quality (JL on Discord, `TestArkDrawsWithoutWatermarkOncePerImage`). 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. A failed drawing rests no member and no key. An account out of quota for the image model (`failure` reads `failQuota`) rests that model on it alone (`restDrawer`, keyed by `restID`), until the reset its refusal names (`resetsAt`: Antigravity's "Your quota will reset after 3h19m30s.") or `quotaRest`, so the next drawing asks the accounts that still have it first (`restLast`), and the account's text models stay in. Antigravity also tells a model's quota used up as a 200 whose stream is the error; `drawCodeAssist` gives such an error the status its words stand for (`saidStatus`: quota or rate 429, credit 402, else 502), as the images API's 200 with no image does, so a spent account hands the drawing to the next one as its 429 does (01huadalang on Discord: a 502 ended the drawing on the spent account; `TestAntigravityDrawingOutOfQuotaInsideTheReplyGoesOn`, `TestAntigravityDrawingQuotaRestsTheImageModel`). `TestImageGroupMovesOnToTheNextMember`, `TestVideoGroupMovesOnToTheNextMember`. Such a group may be Settings → Images → Image generation's pick (7up6666 on X): the list offers each routing group with a member among its provider's `Drawers` (`GroupDraws`), so a request naming no model, the Magpie Image MCP's included, draws on the group; a picked group none of whose members draws any more is `DrawerMissing` (`drawerMissing`), the row says so and Automatic draws in its place. `TestImageGroupPickedInSettingsDraws`, `TestImageGenOffersDrawingGroups`. An account's own list of models (#474) never bars a ChatGPT account's GPT Image, a Grok subscription's Grok Imagine or a WorkBuddy plan's image models (`listsCantName`): the list is picked from the editor's chat models, which they are never among, so a list kept for some chat models had every drawing refused as "set not to be served by any account" (heyiwei5 on X). A key's list, picked from models that include its image ones, still bars them. `TestCodexDrawsPastAccountModelLists`. A drawing is given Settings → Images → Image generation timeout (`imageTimeout`, 1 to 60 minutes, 5 when unset; neighbads on X: a slow image endpoint needed more) as its context's deadline (`drawTimeout`, `drawWithin`), and so is downloading an image answered as a link (`imageLongest`, never under `ImageLongest`). A drawing's request goes through a transport with no `ResponseHeaderTimeout` (`drawsApart`), since an images API sends its headers only once it has drawn, and every other request keeps `upstreamHeaderWait` (10 minutes). A video's submit, status and download calls keep 5 minutes each (`videoTimeout`). The `magpie mcp image` process, which may not read these settings (WSL), waits on a call up to `callLongest` (two hours and a minute), so it never cuts one the gateway still waits on. `TestLongImageTimeoutLetsASlowVendorFinish`, `TestImageTimeoutSettingReachesTheVendor`, `TestOnlyDrawingsWaitPastTheHeaderWait`. | [`draw.go`](../../internal/gateway/draw.go), [`draw_volcengine.go`](../../internal/gateway/draw_volcengine.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`. A conversation is kept by its id (`conversationID`), and a Claude Code subagent's apart from its lead's by `x-claude-code-agent-id` (`stickKey`): Claude Code sends the session's id with its subagents' requests too, and a subagent's answer took the lead's stick over, so the lead's next turn was judged by the subagent's cache and moved to another account, where its whole conversation was written again (slkassinthehood on X, `TestClaudeConversationKeepsItsAccountsCache`). Behind a remote magpie, the key or account is the remote's key and the provider there that serves the model, its id's first part (`remoteUpstream`, `candidate.vendor`, `sameVendor`): the remote is one key here, but each of its providers keeps its own cache and seals, so a conversation is kept, held strictly, told its sealed reasoning was refused and given its native compaction's reader by that pair, as the same group on the remote does (fremontdango on Discord: a group of one model from two of the remote's providers kept a conversation on the second as the same account when the first was gone, and a strict one failed over to it; `TestRemoteMagpieStrictKeepsTheRemotesProvider`, `TestRemoteMagpieOtherProviderIsNotTheSameAccount`). A remote's group is one vendor by its whole id, its own routing deciding inside it; a model named without a provider is the key alone. Lanes and requests a minute still go by the key here, the limits the user set on it. | [`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 provider of the user's set not to check its certificate (`InsecureTLS`, #2383) has it skipped for its own base URLs' hosts alone, through `p.Via` ([Providers and accounts](providers-accounts.md)). Every request to one vendor's host shares one HTTP/2 connection (`upstreamTransport`); one with no frame for 20s is pinged, and dropped when no answer comes within 10s (`netproxy.HTTP2Health`, on `http.DefaultTransport` too), so a connection gone silent without closing (a proxy's way out died, a NAT forgot the flow) fails the requests on it, which move on as a 502 does, and the next request dials a new one. A live vendor answers a ping whatever its streams are doing, so a long wait for a first byte is not cut by it (#2843: a group's requests hung with no first byte until a restart; `TestGroupMovesOnFromSilentHTTP2Connection`). A large body (64KB or more, or of no stated length) is pinged too, as a silent connection takes a body that fits its send buffer, but its ping's answer is queued behind the body's own DATA, so on a slow uplink a working connection loses it (#3909: a ~680KB turn on a 2-10KB/s uplink failed every try). Such a body whose connection was dropped for a lost ping is sent once more, through `GetBody`, on a new connection that is not pinged and is given up on when a write moves no bytes for a minute (`uploadTransport`); for 30 minutes after, large bodies go there at once (`drawsApart.slow`; `TestUploadStillUnderwayIsNotCutByHealthPing`, `TestSlowUplinkSkipsTheLostTry`, `TestLargeBodyOnSilentConnectionIsSentAgain`). 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`, `catalog.WrongEndpoint`: the English wordings and AgentRouter's Chinese one, #3766, read escaped too; a model's test reads them as well, see [Providers and accounts](providers-accounts.md)) is remembered in `unfit` until magpie restarts. A Chat API that refuses function tools with reasoning, with no other API to take them to, is asked once more with `reasoning_effort` `none` (#176), unless `none` is known refused (`turnedAway`); `none` refused naming the levels, the tools refusal is the answer, not a retry at the lowest level (#2670). 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) A request outside the chat path gets a route of its own too ([`media_route.go`](../../internal/gateway/media_route.go), `sideRoute`): an image (`images`, each account `drawOnAccounts` asks a try), a video's start (`videosCreate`; its polls and download are the same video and add none) and an embedding, rerank or transcription (`retrieve`). Each try's key or account is put in `Order` so the page finds its seat, the route's `Kind` stays empty, and the one usage row names it in `RouteID` (zzzkl3994 on Discord: a video the magpie-image MCP made was in Usage's requests and not on Routing; `TestVideoIsOnRoutingOnce`, `TestImageIsOnRouting`, `TestEmbeddingAndRerankAreOnRouting`). |
+| 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) A request outside the chat path gets a route of its own too ([`media_route.go`](../../internal/gateway/media_route.go), `sideRoute`): an image (`images`, each account `drawOnAccounts` asks a try), a video's start (`videosCreate`; its polls and download are the same video and add none) and an embedding, rerank, transcription or speech (`retrieve`). Each try's key or account is put in `Order` so the page finds its seat, the route's `Kind` stays empty, and the one usage row names it in `RouteID` (zzzkl3994 on Discord: a video the magpie-image MCP made was in Usage's requests and not on Routing; `TestVideoIsOnRoutingOnce`, `TestImageIsOnRouting`, `TestEmbeddingAndRerankAreOnRouting`). |
| 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 body is kept as it went and masked when `PromptText` first reads it, so the request itself never waits on masking (#3973). `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`). A session's line and its compactions are its own turns': a call with a `Kind`, a Claude Code subagent's (`Route.Sub`, from `x-claude-code-agent-id`), and, in a session whose turns carry tool definitions, a request without any (auto mode's classifier, the title, the quota check) are left out, so a classifier's 40K after a 100K turn is no compaction (`toolSessions`, `TestContextSideCallsAreNoCompaction`). | [`prompt.go`](../../internal/gateway/prompt.go) |
| Vertex AI | A [Google Vertex AI provider](providers-accounts.md#responsibilities-and-sources-of-truth) speaks Gemini for its Gemini models, and chat completions for its partner models. A partner model (`provider.VertexPartner`: a `publisher/model` id such as `deepseek-ai/deepseek-v4.1-flash-maas`) goes to Google's OpenAI-compatible `<base>/endpoints/openapi/chat/completions` (`Base(Chat)`, `ListedAPIs`), signed with the same token, its full id in the body. It is relayed or translated there as any chat completions vendor is, and none of the Gemini rules below (`vertexEffort`, `vertexThinking`, signatures) touch it (`TestVertexPartnerModel`). A Gemini model's 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) |
| Bedrock Mantle | A request on chat completions or Responses to an [Amazon Bedrock Mantle provider](providers-accounts.md#responsibilities-and-sources-of-truth) goes to the prefix that serves its model (`mantleRoutes`, `provider.MantleBase` in `forwardOnce`): `/openai/v1` for OpenAI's closed GPTs and xAI's Grok, `/v1` for the rest. A model Mantle refuses there with "model `x` isn't supported on this route" (a maker the rule doesn't know yet) is asked once more at the other prefix, and when it is taken there that prefix is remembered for the model in `unfit` (`mantleRouteKey`) until the gateway restarts. A model refused at both gets the first refusal and nothing is remembered (`mantleReroute`). Messages go to `/anthropic` alone. | [`mantle.go`](../../internal/gateway/mantle.go), [`gateway.go`](../../internal/gateway/gateway.go) |
@@ -186,7 +186,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`), so it fails over, rests and is logged as a 502 does, its reason naming the page's title.
- An error status whose body holds no message of its own says what it was (`provider.Unsaid`, through `APIError` and the plan-quota and drawing readers): a web page by its title as plain words, a firewall's block page (`EdgeBlocked`: Alibaba Cloud's, Cloudflare's "you have been blocked", "used Cloudflare to restrict access" and `error code: 1005`–`1020`) with `BlockedHint` after it, and an empty body under an HTTP status as refused with no details, often a firewall or proxy in front of the API (`NoDetails`; an empty `response.failed` event, whose fallback is no status, still reads "upstream stream failed"). A bare "403 Forbidden" told a relay's user nothing (maralica on Discord). A JSON error still reads as its message. `TestAPIErrorUnsaid`, `TestRelayRefusalSaysWhatItWas`. 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`.
-- The vendor's reply headers a provider passes on (`ReplyHeaders` and the default request ids, see [providers and accounts](providers-accounts.md), #4145) reach the agent from the reply it is given alone. Every request that can become the agent's reply goes out through `forward` (relayed, translated, a plugin's fetch, a signed-in account) or `retrieveAs` (embeddings, audio), and each tells its reply's passed headers to the try that asked through the try's context (`withReplySink`, `heardReply` in [`reply_headers.go`](../../internal/gateway/reply_headers.go)). The sink is the try's `holdWriter` (`heardUpstream`), so a try that fails and is let go takes its vendor's headers with it, a fallback's reply carries the provider that answered's, and a failure `release`d to the agent carries its own vendor's. A reply to another provider (a side model, a searcher) is not heard: the sink takes its own provider's alone. Within a try the last reply replaces the earlier ones (an ask again without a refused beta, a Mantle reroute), and once the try has its status nothing more is heard (a cut reply's continuation). count_tokens writes them straight (`passReplyHeaders`), and embeddings through `heardHeaders`. A stream whose headers `keepAlive` sent before the vendor answered (past `keepHeldAfter`) has none: they can't follow a status already sent. Not carried: images, video and the Codex backend relay, which copies its reply's headers whole already. `TestReplyHeadersPassedOn`, `TestReplyHeadersOfTheReplyGiven`, `TestReplyHeadersOnCountTokens`, `TestReplyHeadersOnEmbeddings`.
+- The vendor's reply headers a provider passes on (`ReplyHeaders` and the default request ids, see [providers and accounts](providers-accounts.md), #4145) reach the agent from the reply it is given alone. Every request that can become the agent's reply goes out through `forward` (relayed, translated, a plugin's fetch, a signed-in account) or `retrieveAs`/`retrieveOpen` (embeddings, audio), and each tells its reply's passed headers to the try that asked through the try's context (`withReplySink`, `heardReply` in [`reply_headers.go`](../../internal/gateway/reply_headers.go)). The sink is the try's `holdWriter` (`heardUpstream`), so a try that fails and is let go takes its vendor's headers with it, a fallback's reply carries the provider that answered's, and a failure `release`d to the agent carries its own vendor's. A reply to another provider (a side model, a searcher) is not heard: the sink takes its own provider's alone. Within a try the last reply replaces the earlier ones (an ask again without a refused beta, a Mantle reroute), and once the try has its status nothing more is heard (a cut reply's continuation). count_tokens writes them straight (`passReplyHeaders`), and embeddings through `heardHeaders`. A stream whose headers `keepAlive` sent before the vendor answered (past `keepHeldAfter`) has none: they can't follow a status already sent. Not carried: images, video and the Codex backend relay, which copies its reply's headers whole already. `TestReplyHeadersPassedOn`, `TestReplyHeadersOfTheReplyGiven`, `TestReplyHeadersOnCountTokens`, `TestReplyHeadersOnEmbeddings`.
- A streamed request is never left silent while its vendor says nothing. `holdWriter.watch` runs beside each try: past `keepHeldAfter` (3s) it sends a held try's agent the stream's 200 and SSE comments (`keepAlive`), one every `keepHeldEvery` (5s), none of the try, so another candidate may still answer in the same stream. It was 15s, and a proxy between the agent and magpie that hangs up on a request with nothing back for about 10s ended every turn slower to its first event: Codex on Windows sends 127.0.0.1 through a Clash-style app's system proxy, `127.*` in its bypass list or not, and its turns ended 499 (mrten_95615 on Discord; `TestHeldStreamHeardBeforeAProxyCuts`). A failure before it is still a status; 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 translated stream (`streamTranslated`) whose upstream has begun its reply and then says nothing at all, not even a comment (a relay that sends the rest of a long reply in one burst at its end), is kept alive in the client's own protocol by a ticker beside its reader (`keepThroughSilence`): every `keepaliveEvery` it sends the client's keepalive (`enc.keepalive`: a ping for Anthropic, `response.in_progress` for Responses, a comment for Chat, nothing for Gemini), which also counts as the try heard from, so the held stream's comments go on too; it stops once the upstream has been silent for `translatedQuietLongest` (30 minutes), past the 10 minutes `upstreamHeaderWait` gives a vendor to begin and long enough for a long reasoning turn sent whole at its end, after which the client's own timeout ends the wait (youyo.p on Discord: before, Claude Code heard only comments, which its event watchdog doesn't count, and gave up 300s on; `TestTranslatedSilenceKeptAliveForABound`). An upstream that has answered its headers but sent no byte yet is still waited for under the held stream's comments alone (`notAnAPIReply` reads its first bytes before the reply is translated). An Anthropic client is sent a ping at most once each `pingEvery` (1 minute), comments between, and none before `message_start`: Claude Code's watchdog counts only 30 pings in a row as life, and a ping on every upstream keepalive spent them in the first minute; the SDKs' `MessageStream` fails on any event before `message_start` (`anthropicEncoder.keepalive`, `TestTranslatedStreamKeepsClientAlive`). 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`; whatever a relayed stream gets appended, that error or a filled-in `finish_reason`, begins after a blank line, two newlines when the upstream's last write stopped inside a line, so it is an event of its own rather than more of the half-written one, #2446, `TestPassthroughStreamCutMidLine`, `TestGeminiCompatFinishAfterPartialLine`), and a Chat one from Gemini's OpenAI-compatible API (`geminiCompat`) with no `finish_reason`, relayed or translated (`saysItsEnd`; Linka on Discord: the upstream hung up between a whole function call and its `finish_reason`, and Pi threw the call away as "Stream ended without finish_reason"; that API counts the usage only once the generation is done, so when the last chunk carried it only the `finish_reason` was lost and it is filled in, `tool_calls` after a call and `stop` otherwise, as a relayed chunk before `[DONE]` or a translated reply's end, and the reply counts as whole (`chatTail`); only one with no usage at its end is a cut, `TestGeminiCompatRelayEndedShort`, `TestGeminiCompatTranslatedEndedShort`) — 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)).
- An error that reaches the agent in a stream already begun can't carry its status, so `streamError` says it in the words (`saysPassing`, #2372, zminds): for a status that may pass (408, 429, 5xx) whose text names none of the words a text-judging agent retries on (Pi decides by its `errorMessage` alone), it appends `(<status>: you can retry your request)`; a request's own fault (400, 401, 404 …) and a text that already says so are left as they were. `TestStreamErrorSaysItPasses` holds Pi's own lists; `TestGroupLastFailureInStreamSaysItPasses` runs a group whose last member fails after the keepalive. A 413 byte cap in that stream says `request_too_large` in the error text, and Chat and Anthropic name that type, so Pi compacts; Gemini keeps its own status shape (`TestStreamedByteCapSaysRequestTooLargeToPi`, `TestStreamErrorByteCapInEveryShape`). Wherever the protocol says a model with the error (Chat's first chunk, Anthropic's `message_start`, Responses' `response.created` and the events after it), it is the model the agent asked for, as `serve` has it, an effort on it kept (`keptAlive.model`; on Codex's own sign-in, the one Codex wrote) (#3728, jilen: with `"model":""` fx took Chat's first chunk for a broken one and stopped there; `TestStreamErrorNamesTheModel`, `TestKeptAliveChatErrorNamesTheModel`, `TestKeptAliveChatOnCodexErrorNamesTheModel`, `TestKeptAliveCodexErrorNamesTheModel`). An error after a reply that already went, a loop cut's, still starts a message of its own after the vendor's, under a new id and no model (#3792).
@@ -473,7 +473,11 @@ before its route began (`TestDecisionTriesShareTheClassifierWait`). A gateway ke
bodies and options (`serveRetrieval`), and
[`transcribe.go`](../../internal/gateway/transcribe.go) speech-to-text's
multipart forms through it as sent, rewriting only the model and a masked
-prompt under the form's own boundary (#2053), [`draw.go`](../../internal/gateway/draw.go) sends images
+prompt under the form's own boundary (#2053), and
+[`speech.go`](../../internal/gateway/speech.go) text-to-speech's JSON with
+the model rewritten and `input` and `instructions` masked; its answer,
+audio or SSE, is copied to the client as it comes (`retrieveOpen`,
+`copyAnswer`), never read whole (`TestSpeechStreamsAsItComes`), [`draw.go`](../../internal/gateway/draw.go) sends images
to the remote's images API, and [`video.go`](../../internal/gateway/video.go)
wraps remote task ids for later polls and downloads. `passOnCaller` in
[`remote_magpie.go`](../../internal/gateway/remote_magpie.go) supplies
diff --git a/docs/subsystems/plugin-runtime.md b/docs/subsystems/plugin-runtime.md
index f47eafec4..f51f268b0 100644
--- a/docs/subsystems/plugin-runtime.md
+++ b/docs/subsystems/plugin-runtime.md
@@ -225,7 +225,7 @@ failure policy, in [`internal/gwmw`](../../internal/gwmw/gwmw.go):
| --- | --- | --- |
| `gwmw.Agent` | A middleware on a request an agent sent, in the agent's own API, before the gateway routes it, and on its reply as the agent gets it: `Begin(Info) Run`, and the run's `Request` (a `Reject` ends the request in the agent's error shape), `Wrap` and `End`. `Use(a)` registers one until its remove; `Agents` lists them in order. `serveAgent` runs each in turn; with none it calls `serve` directly. It fails open, as the JS middleware always did. | [`gwmw.go`](../../internal/gwmw/gwmw.go), [`middleware.go`](../../internal/gateway/middleware.go) |
| `plugins/middleware` | Requires `gateway`, Essential. Apply registers `middleware.Chain`, the JS gateway middleware ([Gateway middleware](gateway-middleware.md)), whose place, API, limits and fail-open policy are unchanged. `InUse` is `middleware.On()`, the middleware plugins.json has on. Off, agents' requests go as they came and no middleware is called, while plugins.json is left as it is. The gateway's `KeepFresh` watches plugins.json too, so a middleware added from the CLI or the window turns it on within 2s, and a request before then asks the gate's refresh itself (`gwmw.AgentsWanted`: with no agent middleware registered and `middleware.On()` above 0, at most once a second), so the middleware runs on that request, as it did within a second before it was a plugin. | [`middleware.go`](../../plugins/middleware/middleware.go), [`run.go`](../../internal/middleware/run.go) |
-| `gwmw.Masker` | Masks what magpie sends a vendor and puts the values back in what comes back: `JSON`, `Text`, `Restore` and `Writer`. `Mask(m)` serves one until its remove (the last registered serves). It fails closed: `Masking(wanted)` is the masker for a request, or `ErrUnmasked` when the settings ask for masking and none serves, and `Safely` makes a masker that panics an error. The gateway's call sites (`serve`, count_tokens, embeddings and audio, transcriptions, images, video, the search stand-ins and their queries, the Codex backend) answer either with 503 "…nothing was sent", and the vendor gets nothing. `Served`, with none, asks the gate's refresh (the gateway's is `pluginrt.Refresh`, set by `gwmw.Refresh` in `ListenAndServe`) at most once a second and never from inside one, then looks again, so masking turned on a moment ago turns the plugin on for the request that needs it. | [`gwmw.go`](../../internal/gwmw/gwmw.go), [`redact.go`](../../internal/gateway/redact.go), [`gateway.go`](../../internal/gateway/gateway.go) |
+| `gwmw.Masker` | Masks what magpie sends a vendor and puts the values back in what comes back: `JSON`, `Text`, `Restore` and `Writer`. `Mask(m)` serves one until its remove (the last registered serves). It fails closed: `Masking(wanted)` is the masker for a request, or `ErrUnmasked` when the settings ask for masking and none serves, and `Safely` makes a masker that panics an error. The gateway's call sites (`serve`, count_tokens, embeddings and audio, transcriptions, text to speech, images, video, the search stand-ins and their queries, the Codex backend) answer either with 503 "…nothing was sent", and the vendor gets nothing. `Served`, with none, asks the gate's refresh (the gateway's is `pluginrt.Refresh`, set by `gwmw.Refresh` in `ListenAndServe`) at most once a second and never from inside one, then looks again, so masking turned on a moment ago turns the plugin on for the request that needs it. | [`gwmw.go`](../../internal/gwmw/gwmw.go), [`redact.go`](../../internal/gateway/redact.go), [`gateway.go`](../../internal/gateway/gateway.go) |
| `gwmw.Teller` | What a masker can say besides masking: `JSONHits` and `TextHits` mask as `JSON` and `Text` do and also return each placeholder made or reused (`Hit`: placeholder, kind, finder, head, length), and `Value` is what a placeholder stood for while this masker remembers it. Optional: the gateway records a request's masking only when the served masker is one (`masking.Masker` is), and Settings → Privacy's records and values need it; a masker without it masks the same and leaves no record. | [`gwmw.go`](../../internal/gwmw/gwmw.go), [`masked.go`](../../internal/gateway/masked.go), [`masking.go`](../../internal/masking/masking.go) |
| `plugins/redact` | Requires `settings` and `gateway`, Essential. Apply serves `masking.Masker`, which reads settings.json on each call and masks with `internal/redact` as before (it lives in `internal/masking` because `settings` imports `redact`). `InUse` is `masking.Wanted`: *Mask secrets*, *Mask personal data* or a word of the user's own; settings.json that can't be read is an error, so it stays on. Since it is in use whenever masking is asked for, it can only be off while nothing is; the 503 is for a refresh not yet seen or a plugins.yml edited by hand. | [`redact.go`](../../plugins/redact/redact.go), [`masking.go`](../../internal/masking/masking.go) |
diff --git a/internal/gateway/cors_test.go b/internal/gateway/cors_test.go
index 49d89d274..9b2d0739e 100644
--- a/internal/gateway/cors_test.go
+++ b/internal/gateway/cors_test.go
@@ -239,6 +239,7 @@ func TestForeignPagesRefused(t *testing.T) {
{"POST", "/v1/embeddings", `{"model":"plan/m1","input":"hi"}`},
{"POST", "/v1/rerank", `{"model":"plan/m1","query":"hi","documents":["a"]}`},
{"POST", "/v1/audio/transcriptions", "--b\r\nContent-Disposition: form-data; name=\"model\"\r\n\r\nplan/m1\r\n--b--\r\n"},
+ {"POST", "/v1/audio/speech", `{"model":"plan/m1","input":"hi","voice":"coral"}`},
{"POST", "/v1/images/generations", `{"model":"plan/m1","prompt":"hi"}`},
{"POST", "/v1/videos", `{"model":"plan/m1","prompt":"hi"}`},
{"POST", CodexPath + "/responses", `{"model":"plan/m1","input":"hi"}`},
diff --git a/internal/gateway/embeddings.go b/internal/gateway/embeddings.go
index d06604d0a..314d04414 100644
--- a/internal/gateway/embeddings.go
+++ b/internal/gateway/embeddings.go
@@ -199,7 +199,8 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op
return
}
what := "embeddings"
- if _, audio := req.(*audioForm); audio {
+ switch req.(type) {
+ case *audioForm, *speechRequest:
what = "audio"
}
// the record names the try that had it last, not the first
@@ -240,8 +241,20 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op
// the headers of the vendor's reply passed on (#4145)
var heard heardHeaders
ctx = withReplySink(ctx, c.p.ID, heard.put)
- b, got, code, err := s.retrieveAs(ctx, c.p, base+path, ctype, out)
- cancel()
+ var b []byte
+ var got string
+ var code int
+ var res *http.Response // a streamed answer, not read yet
+ if st, ok := req.(streamedRetrieval); ok && st.streams() {
+ res, b, got, code, err = s.retrieveOpen(ctx, c.p, base+path, ctype, "", out)
+ } else {
+ b, got, code, err = s.retrieveAs(ctx, c.p, base+path, ctype, out)
+ }
+ if res == nil {
+ cancel()
+ } else {
+ defer cancel() // once the answer is copied
+ }
tried(code, err)
call.Millis = time.Since(start).Milliseconds()
if err != nil && !last && r.Context().Err() == nil {
@@ -250,6 +263,19 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op
}
call.Status = code
in, outTokens := retrievedTokens(b), answeredTokens(b)
+ if res != nil {
+ // passed on as it comes: audio, or SSE, is never held whole
+ heard.into(w.Header())
+ w.Header().Set("Content-Type", req.answerType(got))
+ w.WriteHeader(code)
+ var cut error
+ in, outTokens, cut = copyAnswer(w, res.Body)
+ res.Body.Close()
+ call.Millis = time.Since(start).Milliseconds()
+ if cut != nil {
+ call.Error = "the answer was cut off: " + cut.Error()
+ }
+ }
call.Usage.Input, call.Usage.Output = in, outTokens
call.Fallback = strings.Join(skipped, "; ")
providerKeyID, providerKeyName := "", ""
@@ -271,6 +297,9 @@ func (s *Server) serveRetrieval(w http.ResponseWriter, r *http.Request, path, op
return
}
s.record(call)
+ if res != nil {
+ return
+ }
heard.into(w.Header())
w.Header().Set("Content-Type", req.answerType(got))
w.WriteHeader(code)
@@ -312,14 +341,34 @@ func (s *Server) retrieveFrom(ctx context.Context, p provider.Provider, url stri
// retrieveAs is retrieveFrom with a body of its own Content-Type, a
// multipart form's with its boundary; it also gives the answer's.
func (s *Server) retrieveAs(ctx context.Context, p provider.Provider, url, ctype string, body []byte) ([]byte, string, int, error) {
+ accept := ""
+ if ctype == "application/json" {
+ accept = "application/json"
+ }
+ res, b, got, code, err := s.retrieveOpen(ctx, p, url, ctype, accept, body)
+ if res == nil {
+ return b, got, code, err
+ }
+ defer res.Body.Close()
+ b, err = io.ReadAll(io.LimitReader(res.Body, 256<<20))
+ if err != nil {
+ return nil, "", 502, err
+ }
+ return b, got, code, nil
+}
+
+// retrieveOpen posts body as retrieveAs does, with an Accept of its own
+// (none when empty). A success's answer is left unread in res, for the
+// caller to read and close; a failure's is read into b, res nil.
+func (s *Server) retrieveOpen(ctx context.Context, p provider.Provider, url, ctype, accept string, body []byte) (*http.Response, []byte, string, int, error) {
ctx = s.metered(p.Via(ctx), p, "") // counted against its MaxRPM (rpm.go)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))
if err != nil {
- return nil, "", 500, err
+ return nil, nil, "", 500, err
}
req.Header.Set("Content-Type", ctype)
- if ctype == "application/json" {
- req.Header.Set("Accept", "application/json")
+ if accept != "" {
+ req.Header.Set("Accept", accept)
}
// magpie's, or the agent's own where the provider passes it on (#1851)
stampUA(ctx, p, req.Header)
@@ -328,30 +377,30 @@ func (s *Server) retrieveAs(ctx context.Context, p provider.Provider, url, ctype
passOnCaller(ctx, req)
}
if err := p.Sign(ctx, req, provider.Chat, body); err != nil {
- return nil, "", 502, err
+ return nil, nil, "", 502, err
}
res, err := p.Do(s.client, req)
heardReply(ctx, p, res)
if err != nil {
if ctx.Err() != nil {
- return nil, "", 504, fmt.Errorf("%s didn't answer in %s", p.Name, retrieveTimeout)
+ return nil, nil, "", 504, fmt.Errorf("%s didn't answer in %s", p.Name, retrieveTimeout)
}
- return nil, "", 502, err
+ return nil, nil, "", 502, err
+ }
+ got := res.Header.Get("Content-Type")
+ if res.StatusCode < 300 {
+ return res, nil, got, res.StatusCode, nil
}
defer res.Body.Close()
b, err := io.ReadAll(io.LimitReader(res.Body, 256<<20))
if err != nil {
- return nil, "", 502, err
+ return nil, nil, "", 502, err
}
- got := res.Header.Get("Content-Type")
- if res.StatusCode >= 300 {
- hint := ""
- if res.StatusCode == http.StatusNotFound || res.StatusCode == http.StatusMethodNotAllowed {
- hint = " — " + p.Name + " may not serve this API"
- }
- return b, got, res.StatusCode, fmt.Errorf("%s: %d %s%s%s", provider.HostOf(url), res.StatusCode, http.StatusText(res.StatusCode), errorSaid(b), hint)
+ hint := ""
+ if res.StatusCode == http.StatusNotFound || res.StatusCode == http.StatusMethodNotAllowed {
+ hint = " — " + p.Name + " may not serve this API"
}
- return b, got, res.StatusCode, nil
+ return nil, b, got, res.StatusCode, fmt.Errorf("%s: %d %s%s%s", provider.HostOf(url), res.StatusCode, http.StatusText(res.StatusCode), errorSaid(b), hint)
}
// retrievedTokens is what an answer says it counted: OpenAI's
diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go
index a939215cd..bf1e4fa62 100644
--- a/internal/gateway/gateway.go
+++ b/internal/gateway/gateway.go
@@ -822,6 +822,8 @@ func (s *Server) Handler() http.Handler {
mux.HandleFunc("POST /audio/transcriptions", s.transcribe("/audio/transcriptions", "transcriptions"))
mux.HandleFunc("POST /v1/audio/translations", s.transcribe("/audio/translations", "translations"))
mux.HandleFunc("POST /audio/translations", s.transcribe("/audio/translations", "translations"))
+ mux.HandleFunc("POST /v1/audio/speech", s.speak)
+ mux.HandleFunc("POST /audio/speech", s.speak)
mux.HandleFunc("POST /v1/videos", s.videosCreate)
mux.HandleFunc("POST /videos", s.videosCreate)
mux.HandleFunc("GET /v1/videos/{id}", s.videosGet)
@@ -843,7 +845,7 @@ func (s *Server) Handler() http.Handler {
mux.HandleFunc("GET /v1beta/models", s.geminiModels)
mux.HandleFunc("POST /v1beta/models/{call...}", s.gemini)
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
- writeError(w, provider.Chat, http.StatusNotFound, "magpie serves /v1/chat/completions, /v1/responses, /v1/messages, /v1/systemone, /v1/images/generations, /v1/images/edits, /v1/videos, /v1/embeddings, /v1/rerank, /v1/audio/transcriptions, /v1/audio/translations and /v1beta/models/*")
+ writeError(w, provider.Chat, http.StatusNotFound, "magpie serves /v1/chat/completions, /v1/responses, /v1/messages, /v1/systemone, /v1/images/generations, /v1/images/edits, /v1/videos, /v1/embeddings, /v1/rerank, /v1/audio/transcriptions, /v1/audio/translations, /v1/audio/speech and /v1beta/models/*")
})
// the goroutine dump first, ahead of every lock the rest can be stuck
// on (dumpFirst)
@@ -874,7 +876,7 @@ var catalogSize stamped[struct{}, int]
func (s *Server) info(w http.ResponseWriter, r *http.Request) {
out := map[string]any{"name": "magpie", "version": Version, "models": catalogSize.get(struct{}{}, func() int { return len(provider.Catalog()) }), "window": Window,
- "apis": []string{"/v1/chat/completions", "/v1/responses", "/v1/messages", "/v1/systemone", "/v1beta/models/{model}:generateContent", "/v1/images/generations", "/v1/images/edits", "/v1/videos", "/v1/embeddings", "/v1/rerank", "/v1/audio/transcriptions", "/v1/audio/translations", "/v1/magpie/quotas", "/v1/magpie/quotas/history", "/v1/magpie/usage", "/v1/magpie/usage/requests", "/v1/magpie/route", "/v1/magpie/trace", SearchMCPPath, VisionMCPPath, ImageMCPPath, ToolsMCPPath, HubMCPAll, HubMCPPath + "{agent}"}}
+ "apis": []string{"/v1/chat/completions", "/v1/responses", "/v1/messages", "/v1/systemone", "/v1beta/models/{model}:generateContent", "/v1/images/generations", "/v1/images/edits", "/v1/videos", "/v1/embeddings", "/v1/rerank", "/v1/audio/transcriptions", "/v1/audio/translations", "/v1/audio/speech", "/v1/magpie/quotas", "/v1/magpie/quotas/history", "/v1/magpie/usage", "/v1/magpie/usage/requests", "/v1/magpie/route", "/v1/magpie/trace", SearchMCPPath, VisionMCPPath, ImageMCPPath, ToolsMCPPath, HubMCPAll, HubMCPPath + "{agent}"}}
// which process serves, for another magpie on this computer to name it
// on its Routing page (#2606); not told to another machine
if local(r) {
diff --git a/internal/gateway/lan_test.go b/internal/gateway/lan_test.go
index 3d381613f..19823e421 100644
--- a/internal/gateway/lan_test.go
+++ b/internal/gateway/lan_test.go
@@ -342,7 +342,7 @@ func TestNetworkGatewayGuardsEveryRoute(t *testing.T) {
{"POST", "/v1/systemone"},
{"POST", "/v1/images/generations"}, {"POST", "/v1/images/edits"},
{"POST", "/v1/embeddings"}, {"POST", "/v1/rerank"},
- {"POST", "/v1/audio/transcriptions"}, {"POST", "/v1/audio/translations"},
+ {"POST", "/v1/audio/transcriptions"}, {"POST", "/v1/audio/translations"}, {"POST", "/v1/audio/speech"},
{"POST", "/v1/videos"}, {"GET", "/v1/videos/v1"}, {"GET", "/v1/videos/v1/content"},
{"POST", "/_magpie/claude-mcp/tok"}, {"POST", "/mcp/neon"},
{"POST", CodexPath + "/responses"}, {"GET", CodexCatalogPath},
diff --git a/internal/gateway/speech.go b/internal/gateway/speech.go
new file mode 100644
index 000000000..f14ca4c4c
--- /dev/null
+++ b/internal/gateway/speech.go
@@ -0,0 +1,161 @@
+package gateway
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "io"
+ "net/http"
+ "time"
+
+ "github.com/yetone/magpie/internal/provider"
+)
+
+// speak serves OpenAI's text-to-speech API: POST /v1/audio/speech. The
+// body is JSON ({model, input, voice, response_format, speed,
+// instructions, stream_format…}); it goes to the model's provider at its
+// OpenAI-style base + path with only the model rewritten to the
+// provider's own id, and input and instructions masked as the settings
+// say. The answer is audio (mp3, opus, aac, flac, wav, pcm), SSE when
+// stream_format is sse, or a vendor's own JSON (Mistral's audio_data):
+// it comes back as it comes, in the vendor's own type, never held whole.
+// It is routed, limited and recorded as an embeddings call is
+// (serveRetrieval).
+func (s *Server) speak(w http.ResponseWriter, r *http.Request) {
+ body, admitted := s.requestBody(w, r, provider.Chat)
+ if !admitted {
+ return
+ }
+ start := time.Now()
+ var req map[string]json.RawMessage
+ if json.Unmarshal(body, &req) != nil || req == nil {
+ writeError(w, provider.Chat, 400, "the body isn't a JSON object: /v1/audio/speech takes {\"model\", \"input\", \"voice\"…} as OpenAI's does")
+ return
+ }
+ var asked string
+ json.Unmarshal(req["model"], &asked)
+ if asked == "" {
+ writeError(w, provider.Chat, 400, "name the model: \"model\" is a magpie model id, provider/model (openai/gpt-4o-mini-tts, groq/playai-tts)")
+ return
+ }
+ s.serveRetrieval(w, r, "/audio/speech", "speech", start, asked, &speechRequest{req: req})
+}
+
+// speechRequest is a text-to-speech body: a JSON object, its text fields
+// the only ones masked.
+type speechRequest struct{ req map[string]json.RawMessage }
+
+// spoken are the fields of a speech request that carry the user's text:
+// what is read aloud, and OpenAI's instructions for how. Nothing else is
+// masked: a voice, a format or a voice-cloning clip is no text of theirs.
+var spoken = []string{"input", "instructions"}
+
+// mask masks input and instructions where they are strings. The answer is
+// audio, so nothing is put back: a masked value is read aloud as its
+// placeholder.
+func (sp *speechRequest) mask(ctx context.Context, w http.ResponseWriter) (http.ResponseWriter, func(), maskHits, string, error) {
+ var all maskHits
+ var sent []string
+ for _, k := range spoken {
+ var v string
+ if json.Unmarshal(sp.req[k], &v) != nil || v == "" {
+ continue
+ }
+ _, masked, h, err := maskTextHits(ctx, v)
+ if err != nil {
+ return w, func() {}, maskHits{}, "", err
+ }
+ all.add(h)
+ sent = append(sent, masked)
+ if masked != v {
+ sp.req[k], _ = json.Marshal(masked)
+ }
+ }
+ text := ""
+ for i, t := range sent {
+ if i > 0 {
+ text += "\n\n"
+ }
+ text += t
+ }
+ return w, func() {}, all, text, nil
+}
+
+func (sp *speechRequest) forModel(model string) ([]byte, string, error) {
+ sp.req["model"], _ = json.Marshal(model)
+ out, err := json.Marshal(sp.req)
+ return out, "application/json", err
+}
+
+// answerType is the vendor's; OpenAI's default format is mp3.
+func (sp *speechRequest) answerType(got string) string {
+ if got == "" {
+ return "audio/mpeg"
+ }
+ return got
+}
+
+// streams: the answer is copied to the client as it comes.
+func (sp *speechRequest) streams() bool { return true }
+
+// streamedRetrieval is a retrieval whose answer goes to the client as it comes,
+// not read whole first (serveRetrieval).
+type streamedRetrieval interface{ streams() bool }
+
+// speechTail is how much of an answer's end is kept to read its usage:
+// gpt-4o-mini-tts's SSE ends with a speech.audio.done event that has it.
+const speechTail = 16 << 10
+
+// copyAnswer copies an answer to w as it comes, flushing each read, and
+// gives the tokens its last event says it counted, and the error that cut
+// it short, if any.
+func copyAnswer(w http.ResponseWriter, body io.Reader) (in, out int, err error) {
+ rc := http.NewResponseController(w)
+ var tail []byte
+ buf := make([]byte, 32<<10)
+ for {
+ n, rerr := body.Read(buf)
+ if n > 0 {
+ if _, werr := w.Write(buf[:n]); werr != nil {
+ return 0, 0, werr
+ }
+ rc.Flush()
+ tail = append(tail, buf[:n]...)
+ if len(tail) > speechTail {
+ tail = append(tail[:0], tail[len(tail)-speechTail:]...)
+ }
+ }
+ if rerr == io.EOF {
+ break
+ }
+ if rerr != nil {
+ return 0, 0, rerr
+ }
+ }
+ in, out = speechUsage(tail)
+ return in, out, nil
+}
+
+// speechUsage is the usage an answer's last JSON line or SSE data line
+// says: {"type":"speech.audio.done","usage":{"input_tokens":…}}. Audio
+// bytes say none.
+func speechUsage(tail []byte) (int, int) {
+ lines := bytes.Split(tail, []byte("\n"))
+ for i := len(lines) - 1; i >= 0; i-- {
+ l := bytes.TrimSpace(lines[i])
+ l = bytes.TrimSpace(bytes.TrimPrefix(l, []byte("data:")))
+ if !bytes.Contains(l, []byte(`"usage"`)) {
+ continue
+ }
+ var a struct {
+ Usage struct {
+ Input int `json:"input_tokens"`
+ Output int `json:"output_tokens"`
+ } `json:"usage"`
+ }
+ if json.Unmarshal(l, &a) == nil {
+ return a.Usage.Input, a.Usage.Output
+ }
+ }
+ return 0, 0
+}
diff --git a/internal/gateway/speech_test.go b/internal/gateway/speech_test.go
new file mode 100644
index 000000000..a4f9b6530
--- /dev/null
+++ b/internal/gateway/speech_test.go
@@ -0,0 +1,242 @@
+package gateway
+
+import (
+ "bufio"
+ "bytes"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/yetone/magpie/internal/provider"
+ "github.com/yetone/magpie/internal/settings"
+ "github.com/yetone/magpie/internal/usage"
+)
+
+// mp3 is audio as a vendor sends it: bytes no text has.
+var mp3 = append([]byte("ID3\x04\x00\x00\x00\x00\x00\x00\xff\xfb\x90\x64"), bytes.Repeat([]byte{0, 0xff, 0xfb, '{', '}', '\r', '\n'}, 2048)...)
+
+// speaker is a vendor with OpenAI's text-to-speech API. What it was sent
+// is kept; an SSE answer sends its first event, then waits for more to be
+// let through, so a test can see the first reach the client before the
+// rest is written.
+type speaker struct {
+ mu sync.Mutex
+ sent [][]byte
+ accepts []string
+ more chan struct{}
+}
+
+func (sp *speaker) ServeHTTP(w http.ResponseWriter, r *http.Request) {
+ body, _ := io.ReadAll(r.Body)
+ sp.mu.Lock()
+ sp.sent = append(sp.sent, body)
+ sp.accepts = append(sp.accepts, r.Header.Get("Accept"))
+ sp.mu.Unlock()
+ if r.Header.Get("Authorization") != "Bearer key" {
+ w.WriteHeader(401)
+ return
+ }
+ if r.URL.Path != "/v1/audio/speech" {
+ w.WriteHeader(404)
+ return
+ }
+ var req map[string]any
+ json.Unmarshal(body, &req)
+ switch {
+ case req["model"] == "refused":
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(400)
+ io.WriteString(w, `{"error":{"message":"voice nova isn't one of this model's"}}`)
+ case req["stream_format"] == "sse":
+ w.Header().Set("Content-Type", "text/event-stream")
+ io.WriteString(w, "data: {\"type\":\"speech.audio.delta\",\"audio\":\"SUQz\"}\n\n")
+ w.(http.Flusher).Flush()
+ select {
+ case <-sp.more:
+ case <-time.After(30 * time.Second):
+ }
+ io.WriteString(w, "data: {\"type\":\"speech.audio.delta\",\"audio\":\"//uQ\"}\n\n")
+ io.WriteString(w, "data: {\"type\":\"speech.audio.done\",\"usage\":{\"input_tokens\":12,\"output_tokens\":340,\"total_tokens\":352}}\n\n")
+ case req["voice_id"] != nil:
+ // Mistral's: the audio as base64 in JSON
+ w.Header().Set("Content-Type", "application/json")
+ io.WriteString(w, `{"audio_data":"UklGRg=="}`)
+ default:
+ w.Header().Set("Content-Type", "audio/mpeg")
+ w.Write(mp3)
+ }
+}
+
+func (sp *speaker) got() ([][]byte, []string) {
+ sp.mu.Lock()
+ defer sp.mu.Unlock()
+ return append([][]byte(nil), sp.sent...), append([]string(nil), sp.accepts...)
+}
+
+func speakerUp(t *testing.T) (*Server, *speaker) {
+ t.Helper()
+ fresh(t)
+ sp := &speaker{more: make(chan struct{})}
+ up := httptest.NewServer(sp)
+ t.Cleanup(up.Close)
+ if err := provider.Save(provider.Provider{ID: "voice", Name: "Voice", Chat: up.URL + "/v1", Key: "key", Models: []string{"gpt-4o-mini-tts", "refused"}}); err != nil {
+ t.Fatal(err)
+ }
+ return New(), sp
+}
+
+func postSpeech(t *testing.T, s *Server, path, body string) (int, http.Header, []byte) {
+ t.Helper()
+ rec := httptest.NewRecorder()
+ req := httptest.NewRequest("POST", path, strings.NewReader(body))
+ req.Header.Set("Content-Type", "application/json")
+ s.Handler().ServeHTTP(rec, req)
+ return rec.Code, rec.Header(), rec.Body.Bytes()
+}
+
+// A speech request goes to the model's provider with only its model
+// rewritten, every other field as sent, and the vendor's audio comes back
+// byte for byte in its own type; it is in the usage ledger. The bare
+// /audio/speech path an SDK given magpie's root posts to works too.
+func TestSpeechGoesToTheModelsProvider(t *testing.T) {
+ s, sp := speakerUp(t)
+ body := `{"model":"voice/gpt-4o-mini-tts","input":"Hello from the magpie.","voice":"coral","response_format":"mp3","speed":1.25,"instructions":"Speak cheerfully."}`
+ code, h, got := postSpeech(t, s, "/v1/audio/speech", body)
+ if code != 200 || !bytes.Equal(got, mp3) || h.Get("Content-Type") != "audio/mpeg" {
+ t.Fatalf("%d %q, %d bytes back of %d", code, h.Get("Content-Type"), len(got), len(mp3))
+ }
+ sent, accepts := sp.got()
+ if len(sent) != 1 || accepts[0] == "application/json" {
+ t.Fatalf("vendor was sent %d bodies, Accept %v", len(sent), accepts)
+ }
+ var vendor, asked map[string]any
+ json.Unmarshal(sent[0], &vendor)
+ json.Unmarshal([]byte(body), &asked)
+ asked["model"] = "gpt-4o-mini-tts"
+ a, _ := json.Marshal(asked)
+ v, _ := json.Marshal(vendor)
+ if !bytes.Equal(a, v) {
+ t.Fatalf("vendor was sent %s", sent[0])
+ }
+ var recs []usage.Record
+ for i := 0; i < 50; i++ {
+ if recs = usage.Load(time.Time{}); len(recs) >= 1 {
+ break
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+ if len(recs) != 1 || recs[0].Operation != "speech" || recs[0].Provider != "voice" || recs[0].Model != "gpt-4o-mini-tts" || recs[0].Requested != "voice/gpt-4o-mini-tts" || recs[0].Status != 200 {
+ t.Fatalf("usage %+v", recs)
+ }
+ // the bare path, and a field only one vendor has (Mistral's voice_id)
+ // with its JSON answer passed on as JSON
+ code, h, got = postSpeech(t, s, "/audio/speech", `{"model":"voice/gpt-4o-mini-tts","input":"hi","voice_id":"gb_jane_neutral","response_format":"wav"}`)
+ if code != 200 || string(got) != `{"audio_data":"UklGRg=="}` || h.Get("Content-Type") != "application/json" {
+ t.Fatalf("Mistral's shape: %d %q %s", code, h.Get("Content-Type"), got)
+ }
+ if sent, _ = sp.got(); len(sent) != 2 || !bytes.Contains(sent[1], []byte(`"voice_id":"gb_jane_neutral"`)) || !bytes.Contains(sent[1], []byte(`"model":"gpt-4o-mini-tts"`)) {
+ t.Fatalf("vendor was sent %s", sent[len(sent)-1])
+ }
+}
+
+// stream_format sse: each event reaches the client as the vendor sends
+// it, before the vendor has sent the rest, and the done event's usage is
+// counted.
+func TestSpeechStreamsAsItComes(t *testing.T) {
+ s, sp := speakerUp(t)
+ gw := httptest.NewServer(s.Handler())
+ t.Cleanup(gw.Close)
+ res, err := http.Post(gw.URL+"/v1/audio/speech", "application/json", strings.NewReader(`{"model":"voice/gpt-4o-mini-tts","input":"hi","voice":"coral","stream_format":"sse"}`))
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer res.Body.Close()
+ if res.StatusCode != 200 || res.Header.Get("Content-Type") != "text/event-stream" {
+ t.Fatalf("%d %q", res.StatusCode, res.Header.Get("Content-Type"))
+ }
+ rd := bufio.NewReader(res.Body)
+ first := make(chan string, 1)
+ go func() {
+ l, _ := rd.ReadString('\n')
+ first <- l
+ }()
+ select {
+ case l := <-first:
+ if !strings.Contains(l, `"audio":"SUQz"`) {
+ t.Fatalf("first line %q", l)
+ }
+ case <-time.After(20 * time.Second):
+ close(sp.more)
+ t.Fatal("the first event didn't reach the client while the vendor held the rest: the answer was held whole")
+ }
+ close(sp.more)
+ rest, _ := io.ReadAll(rd)
+ if !bytes.Contains(rest, []byte(`"audio":"//uQ"`)) || !bytes.Contains(rest, []byte("speech.audio.done")) {
+ t.Fatalf("rest %q", rest)
+ }
+ var recs []usage.Record
+ for i := 0; i < 100; i++ {
+ if recs = usage.Load(time.Time{}); len(recs) >= 1 {
+ break
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+ if len(recs) != 1 || recs[0].Operation != "speech" || recs[0].Input != 12 || recs[0].Output != 340 {
+ t.Fatalf("usage %+v", recs)
+ }
+}
+
+// A vendor's refusal comes back as an error with its status and message.
+func TestSpeechVendorRefusalPassedOn(t *testing.T) {
+ s, _ := speakerUp(t)
+ code, _, got := postSpeech(t, s, "/v1/audio/speech", `{"model":"voice/refused","input":"hi","voice":"nova"}`)
+ if code != 400 || !strings.Contains(string(got), "voice nova isn't one of this model's") {
+ t.Fatalf("%d %s", code, got)
+ }
+}
+
+// A request magpie can't route is told why, and nothing reaches a vendor.
+func TestSpeechRefusals(t *testing.T) {
+ s, sp := speakerUp(t)
+ if code, _, got := postSpeech(t, s, "/v1/audio/speech", `not json`); code != 400 || !strings.Contains(string(got), "JSON object") {
+ t.Fatalf("not json: %d %s", code, got)
+ }
+ if code, _, got := postSpeech(t, s, "/v1/audio/speech", `{"input":"hi"}`); code != 400 || !strings.Contains(string(got), "name the model") {
+ t.Fatalf("no model: %d %s", code, got)
+ }
+ if code, _, got := postSpeech(t, s, "/v1/audio/speech", `{"model":"nobody/tts-1","input":"hi"}`); code != 404 || !strings.Contains(string(got), "nobody/tts-1") {
+ t.Fatalf("unknown: %d %s", code, got)
+ }
+ if sent, _ := sp.got(); len(sent) != 0 {
+ t.Fatalf("vendor was sent %d", len(sent))
+ }
+}
+
+// With secrets kept, input and instructions go out masked, wherever in
+// them the secret is; the voice and the rest go as sent.
+func TestSpeechInputMasked(t *testing.T) {
+ s, sp := speakerUp(t)
+ if err := settings.Save(settings.Settings{Redact: true}); err != nil {
+ t.Fatal(err)
+ }
+ secret := "sk-ant-api03-" + strings.Repeat("Ab3x", 20)
+ other := "sk-ant-api03-" + strings.Repeat("Zq9w", 20)
+ body, _ := json.Marshal(map[string]any{"model": "voice/gpt-4o-mini-tts", "input": "Read this: " + secret, "instructions": "never say " + other, "voice": "coral"})
+ if code, _, got := postSpeech(t, s, "/v1/audio/speech", string(body)); code != 200 || !bytes.Equal(got, mp3) {
+ t.Fatalf("%d, %d bytes", code, len(got))
+ }
+ sent, _ := sp.got()
+ if len(sent) != 1 || bytes.Contains(sent[0], []byte(secret)) || bytes.Contains(sent[0], []byte(other)) {
+ t.Fatalf("vendor was sent a secret: %s", sent)
+ }
+ var vendor map[string]string
+ json.Unmarshal(sent[0], &vendor)
+ if !strings.HasPrefix(vendor["input"], "Read this: ") || !strings.HasPrefix(vendor["instructions"], "never say ") || vendor["voice"] != "coral" || vendor["model"] != "gpt-4o-mini-tts" {
+ t.Fatalf("vendor was sent %v", vendor)
+ }
+}
diff --git a/internal/provider/remote_magpie.go b/internal/provider/remote_magpie.go
index 28a07a680..b437d03b9 100644
--- a/internal/provider/remote_magpie.go
+++ b/internal/provider/remote_magpie.go
@@ -93,7 +93,7 @@ func (p *Provider) remoteMagpieEndpoints() {
"/v1/messages/count_tokens", "/v1/messages",
"/v1/chat/completions", "/v1/responses", "/v1/systemone",
"/v1/embeddings", "/v1/rerank",
- "/v1/audio/transcriptions", "/v1/audio/translations",
+ "/v1/audio/transcriptions", "/v1/audio/translations", "/v1/audio/speech",
"/v1/images/generations", "/v1/images/edits",
"/v1/videos", "/v1",
} {
diff --git a/site/public/docs/ja/remote.html b/site/public/docs/ja/remote.html
index b0ae5c9dd..111e360d4 100644
--- a/site/public/docs/ja/remote.html
+++ b/site/public/docs/ja/remote.html
@@ -123,7 +123,7 @@ magpie provider refresh office <span class="c"># 一覧を再取得</span></pr
<li><b>すべての API。</b>リクエストはエージェントが使った API のまま転送されます(Anthropic Messages とトークン計数、Responses、Chat Completions)。共有側のプロバイダが別の API でしか提供しないモデルは、変換が 1 回だけ行われ、両方のコンピューターで変換されることはありません。Responses は WebSocket ではなく HTTP(SSE を含む)で送られます。</li>
<li><b>画像と動画。</b>画像・動画モデルは自動で見つかり、向こうの画像生成・編集・動画 API を通して使えます。</li>
<li><b>System One。</b>決定モデル(Jev、Clef、自分で名前を付けたモデル)は向こうの <code>/v1/systemone</code> につながり、チャットモデルではなく決定モデルとして現れます。新しいものはプロバイダの一覧を更新すると見つかります。<code>office</code> だけを指定すると一覧の最初の決定モデルに問い合わせます。</li>
- <li><b>Embeddings、rerank、音声の文字起こし</b>は向こうの対応する API に送られます。エージェントの一覧ではリモートでの扱いのままです。一覧にあっても会話に使えるわけではありません。</li>
+ <li><b>Embeddings、rerank、音声の文字起こしと音声合成</b>は向こうの対応する API に送られます。エージェントの一覧ではリモートでの扱いのままです。一覧にあっても会話に使えるわけではありません。</li>
<li><b>価格。</b>各モデルは共有する magpie の計算どおり(向こうで手動設定した価格、なければプロバイダの定価)になるので、2 台の集計は一致します。このコンピューターで設定した価格が優先されます。</li>
</ul>
diff --git a/site/public/docs/remote.html b/site/public/docs/remote.html
index 76e2da152..42c486539 100644
--- a/site/public/docs/remote.html
+++ b/site/public/docs/remote.html
@@ -123,7 +123,7 @@ magpie provider refresh office <span class="c"># fetch its list again</span></
<li><b>Every API.</b> A request goes on in the API the agent spoke (Anthropic Messages and token counting, Responses, Chat Completions). A model that the shared magpie’s provider serves on another API only is turned into that API once, never on both computers. Responses go over HTTP, SSE included, not WebSocket.</li>
<li><b>Images and video.</b> Its image and video models are found by themselves and served through its image generation and edit, and video, APIs.</li>
<li><b>System One.</b> Its decision models (Jev, Clef, and models with names of your own) are set up at its <code>/v1/systemone</code> and appear as decision models, not chat models. Refresh the provider’s list to find new ones. A bare <code>office</code> asks the first decision model listed.</li>
- <li><b>Embeddings, rerank and speech to text</b> go to its matching APIs. They stay in agents’ lists as they are on the remote; being listed doesn’t make them able to hold a conversation.</li>
+ <li><b>Embeddings, rerank, speech to text and text to speech</b> go to its matching APIs. They stay in agents’ lists as they are on the remote; being listed doesn’t make them able to hold a conversation.</li>
<li><b>Prices.</b> Each model costs here what the shared magpie counts it at (a price set there by hand, else its provider’s list price), so the two computers count the same. A price you set here comes first.</li>
</ul>
diff --git a/site/public/docs/zh/remote.html b/site/public/docs/zh/remote.html
index 884b1beb5..4f51bc4a5 100644
--- a/site/public/docs/zh/remote.html
+++ b/site/public/docs/zh/remote.html
@@ -123,7 +123,7 @@ magpie provider refresh office <span class="c"># 重新获取列表</span></pr
<li><b>所有 API。</b>请求按 Agent 使用的 API 原样转发(Anthropic Messages 和 token 计数、Responses、Chat Completions)。共享 magpie 的供应商只用另一种 API 提供的模型,只转换一次,不会在两台电脑上各转一次。Responses 走 HTTP(包括 SSE),不走 WebSocket。</li>
<li><b>图像和视频。</b>它的图像和视频模型会被自动识别,经由它的图像生成、编辑和视频 API 提供。</li>
<li><b>System One。</b>它的决策模型(Jev、Clef,以及你自己命名的模型)接到它的 <code>/v1/systemone</code>,作为决策模型而不是对话模型出现。刷新供应商列表可以发现新的。只写 <code>office</code> 时使用列表里的第一个决策模型。</li>
- <li><b>Embeddings、rerank 和语音转文字</b>发往它对应的 API。它们在 Agent 列表里保持远程上的样子;出现在列表里并不代表能用来对话。</li>
+ <li><b>Embeddings、rerank、语音转文字和文字转语音</b>发往它对应的 API。它们在 Agent 列表里保持远程上的样子;出现在列表里并不代表能用来对话。</li>
<li><b>价格。</b>每个模型在本机按共享 magpie 的计价(那边手动设的价格,否则是供应商的标价),两台电脑算出来一样。在本机设的价格优先。</li>
</ul>