diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index dbdb4d03a..db94c6616 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -198,6 +198,7 @@ recorded as a prediction failure (`noPrediction`). - A 2xx from Zhipu or Z.ai holding the platform's refusal envelope (`{"code":1000,"msg":…,"success":false}`, which their Responses API at `/api/v1` answers a refused key) is the refusal it stands for (`provider.ZhipuEnveloped` in `forwardOnce`): 401 for a key refused, 429 for a limit or no balance, as Zhipu's error codes give, so it fails over and rests as those do and the agent is told why. `TestZhipuResponsesRefusalIsRefusal`. - A request refused for its bytes (`byteCapRefusal` in [`body_cap.go`](../../internal/gateway/body_cap.go): a 413, or words such as Command Code's 400 "Request body is 40.1 MB, over the 32 MB limit for one request (33554432 bytes)", EDwinpzy on Discord; never a 401, 403, 429 or a context overflow) is asked again in `forward` with its oldest history images left out (`refitOverCap`), up to three times. The cap is the smallest size the refusal names below what was sent, else three quarters of what was sent, and it is kept per provider id for as long as magpie runs (`bodyCaps`), so the next request near it is fitted in `forwardOnce` before it goes (`withinCap`). A request is fitted to three quarters of the cap. Each left-out image becomes a text part, "[An earlier image was left out here to keep this request under its size limit.]", which names neither magpie nor the vendor. The latest user message's images (`latestUser`: not a tool result, not Codex's compaction prompt) and every text, tool output included, stay; the rest of the body keeps its bytes. When leaving out every earlier image can't bring it under, or it is refused at every size, the agent gets a 413 `request_too_large` naming the size, the cap and what was kept (`overCap`), so Codex is told `context_length_exceeded` and its compaction goes on to the text-only ask (`summaryTooLarge`, `plainCompact`) instead of sending the same body into the compaction guard's hold. Every route reaches it, magpie's own (compaction, titles, the classifier, search, vision) included, since they all go through `forward`. - 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`. +- The agent's request headers a provider passes on (`PassHeaders`, see [providers and accounts](providers-accounts.md); 3jRzfF52Qx on X) go with every try `forwardOnce` makes, so chat, responses, messages, count_tokens, a group's members, fallbacks, signed-in accounts and a plugin's fetch all take them: `forwardOnce` puts the agent's headers in the try's context under the try's provider id (`provider.WithClientHeaders`), and `Provider.Sign` passes the ones that provider lists and no other's. Not carried: embeddings, images, video and the Codex backend relay, which don't go through `forwardOnce`. `TestPassHeadersReachTheProvider`, `TestPassHeadersOnlyToTheirProvider`. - 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 Chat stream a vendor ends with `finish_reason:"error"` — WorkBuddy's and a DeepSeek harness's word for a turn it failed, not finished (#2471) — is the failure the word says, held for the group's next candidate, and nobody rests, as an empty reply's (`TestFinishReasonErrorFailsOver`); 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, and the half event itself is dropped: a relayed stream holds the line the upstream never ended back, puts it out when the reply ends whole or is gathered (`TestGrokPluginNonStreamLastLineUnended`), and throws it away when a failure is appended in its place, for no client can parse it — pi read "malformed server-sent event JSON" off a stream Z.ai reset mid-line, and died before the error after it; a line whose data parses (its JSON whole, or `[DONE]`) is no half event and goes out before the failure (#2446, #2580, `TestPassthroughStreamCutMidLine`, `TestChatStreamCutMidLineLeavesNoHalfEvent`, `TestChatStreamCutAfterWholeEventKeepsIt`, `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`). only one with no usage at its end is a cut, `TestGeminiCompatRelayEndedShort`, `TestGeminiCompatTranslatedEndedShort`), and a Chat one from Command Code's API (`commandCodeHost`), whose slow starts a killed worker ends with no closing chunk at all, relayed (esp32gallery on #2471: 20 of 665 requests in a day, every ledger row a 200 with no stop and no error while the client read "Stream ended without finish_reason"; `TestCommandCodeRelayEndedShort`, `TestCommandCodeTaillessFailsOver`) — 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 relayed one is read the same way once: a Responses stream whose `response.completed` carries no output and counted no token is no reply either, failed before it is let through, held for the group's next candidate, and nobody rests (#2471, MurmuredVelpro: WorkBuddy AI's account ended Codex's turn completed with `output: []` and all-zero usage three times running, the healthy members never asked; `TestEmptyCompletedFailsOver`). A reply passed through in its own protocol isn't read this way, but for that completed. - 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 `(: 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`). Responses' `response.failed` code for it is `context_length_exceeded`, the one code Codex compacts on: with `server_error` it sent the same body five more times ("reconnecting 5/5"), each refused, and never compacted (celestial_eagle_99230 on Discord, an nginx 413 page in front of a DeepSeek model; `TestCodexByteCapInStreamCompacts`). An overload told so (a 529, or a 5xx whose words say overloaded, `saidOverloaded`) is `server_is_overloaded` there, as the ChatGPT backend says one in a stream: Codex shows the model at capacity and stops, where `server_error` had it reconnect five times, each turn asked again by magpie, and end on the last error alone (wjh66 on Discord; `TestCodexKeptAliveOverloadSaysServerIsOverloaded`). Codex reads a 413, or a 400 `context_length_exceeded`, told by HTTP status as an unexpected status or an invalid request and compacts on neither, so when Codex (`fromCodex`) asked for a stream, a byte cap or an overflow is told in a stream even before one began (`keptAlive.compactsInStream`, `failTo`; `TestCodexByteCapBeforeStreamCompacts`). Another client keeps its status (`TestByteCapBeforeStreamStaysStatusForOthers`). Nobody rests for either. 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). diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index d1354f432..7d3230e47 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -27,6 +27,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | Headers' conversation ids | `${sessionId}`, `${threadId}` and `${subagentId}` in a value of the provider's `Headers` (Axel Burks on Discord: a gateway in front of several Azure accounts routes one conversation to one account by a session header) are the ids extraBody gets, on every request `Sign` signs: the gateway carries the conversation to it in the request's context (`WithConversation`), on every API and `count_tokens` too. A request that is no turn of a conversation (a model list, a balance, an embedding, image or video, System One's decision model, a search) gets an id of its own, `magpie-` and 12 random letters, new each time (`OwnConversation`); Test and Detect's is their `magpie-test-` id, the same in headers and body. A literal placeholder is never sent. In a header the ids go without control characters (`headerSafe`): an agent's session id with CR or LF in it would split the header, or Go would fail the request. A value with neither placeholder goes as written (`SentHeaders`). | [`conversation.go`](../../internal/provider/conversation.go), [`account.go`](../../internal/provider/account.go), [`gateway.go`](../../internal/gateway/gateway.go), [`codex_resume.go`](../../internal/gateway/codex_resume.go) | | A remote magpie's headers | Every request magpie makes to a Remote magpie carries the provider's `Headers` (Yirasumi on Discord: the Usage page's read went without the header a proxy in front of the remote asks for): its API requests and model list as any provider's (`Sign`, `listHeaders`), and its cards, a card's refresh, its quota history and each gateway key's limit (`signRemote`), the last four as no turn of a conversation (`${sessionId}` an id of its own). The key always reaches the remote as `x-api-key` (`remoteKey`), which a gateway reads beside `Authorization`: a user's `Authorization` (a proxy's own scheme) goes in place of magpie's `Bearer` copy without taking the key away, and a user's `x-api-key` is never sent to a remote magpie, so a key's limit is read with that key. A user's `Authorization` that is itself another gateway key of that magpie is read first there, as on any request. | [`remote_quotas.go`](../../internal/provider/remote_quotas.go), [`remote_key_limits.go`](../../internal/provider/remote_key_limits.go), [`remote_magpie.go`](../../internal/provider/remote_magpie.go), [`account.go`](../../internal/provider/account.go) | | Reply headers | `ReplyHeaders` (`replyHeaders` in providers.json, the editor's *Reply headers* under Advanced, a comma-separated list, #4145) names headers of the vendor's reply the gateway passes on to the agent, matched whatever their case and saved canonical (`cleanReplyHeaders`). `DefaultReplyHeaders` (`Request-Id`, `X-Request-Id`, `X-Oneapi-Request-Id`) go from every provider without being listed: opaque request ids, under names magpie sets nothing of its own. Never passed on, listed or not (`ReplyHeaderPassable`): the reply's framing (`Content-*`, `Transfer-Encoding`, hop-by-hop), cookies and sign-ins (`Set-Cookie`, `Authorization`, `WWW-Authenticate`, `Proxy-*`), CORS (`Access-Control-*`), `Sec-*`, redirects and browser policy (`Location`, `Strict-Transport-Security`, `Content-Security-Policy`…), `Retry-After`/`Cache-Control`/`Date`/`Server`/`Vary` (magpie writes those) and `X-Magpie-*` (the gateway reads them as notes of the try). Save refuses such a name (`ReplyHeadersOK`), the editor says so before the save (`replyHeadersOf`, its list held to Go's by `TestReplyHeadersNeverAsTheProvidersAre`), and one written into providers.json by hand is dropped on read. A preset's provider and a signed-in account's requests take it too (`withPicks`). How the gateway carries them is in [gateway routing](gateway-routing.md). | [`replyheaders.go`](../../internal/provider/replyheaders.go), [`reply_headers.go`](../../internal/gateway/reply_headers.go) | +| Request headers to pass | `PassHeaders` (`passHeaders` in providers.json, the editor's *Request headers to pass* right after *Reply headers* under Advanced, a comma-separated list; 3jRzfF52Qx on X) names headers of the agent's request passed on to this provider as the agent sent them, matched whatever their case and saved canonical (`cleanRequestHeaders`). The agent's value stands over a fixed *Headers* value of the same name; when the agent sends none, the fixed one goes. `Sign` puts them first (`passClientHeaders`), so an account's own signing still has the last word. Never passed on, listed or not (`RequestHeaderPassable`): magpie's own key as an agent sends it (`Authorization`, `X-Api-Key`, `X-Goog-Api-Key`, `Api-Key`), cookies and sign-ins (`Cookie`, `Set-Cookie`, `WWW-Authenticate`, `Proxy-*`), the connection's fields (`Host`, hop-by-hop, `Expect`), what magpie writes for the body it sends (`Content-*`, `Accept`, `Accept-Encoding`), `Origin`, `Sec-*` and `X-Magpie-*`. Save refuses such a name (`RequestHeadersOK`), the editor says so before the save (`replyHeadersOf(…, true)`, its list held to Go's by `TestReplyHeadersNeverAsTheProvidersAre`), and one written by hand is dropped on read. Only the provider that lists them gets them: the agent's headers ride the request's context under that provider's id (`WithClientHeaders`), so a fallback, a group's other members, a side model or a searcher get none. A preset's provider, a signed-in account's requests and a plugin's fetch take it too. Wire headers are masked when read, so a passed one shows in a call's log as any header does. | [`requestheaders.go`](../../internal/provider/requestheaders.go), [`gateway.go`](../../internal/gateway/gateway.go) | | Native compaction | `NativeCompaction` (`nativeCompaction` in providers.json, the editor's *Compaction* row, `magpie provider set compaction=native\|magpie`; #1099) has Codex's compaction asked of the provider as Codex sent it and its sealed item returned unchanged. Off by default. Only a provider whose wire carries it can be set so (`CarriesCompaction`: a Responses API, a ChatGPT account, GitHub Copilot; not another agent's sign-in or a plugin's), and `CompactsOn(model)` also needs the model asked on Responses. `SetNativeCompaction`, the CLI and the GUI's save refuse it elsewhere. An account keeps it through `Save`'s picks (`withPicks`), and `AddCopy` carries it. The gateway's half is in [gateway-routing](gateway-routing.md). | [`native_compaction.go`](../../internal/provider/native_compaction.go) | | providers.json | `Path` is `providers.json` in magpie's config folder. A read that fails returns `ErrUnreadable` and is never treated as empty. `store` writes atomically through a rename and drops the cached catalog (`catalog.Touched`). | [`provider.go`](../../internal/provider/provider.go) | | A provider renamed | `Rename` (the editor's id field, `magpie provider set id=`) keeps the old id in `Was`, so a model still picked by it reaches the provider. Usage is recorded under the id a call went out by and never rewritten; whatever reads it names the provider by its id now through `UsageRenames().Of(id, time)`: the summary, the Requests page (its blocks, the probe rows, other computers' days), the Sessions tab's vias, window holds, `NewPricer`/`NewCoster` and the gateway's `loggedAnswers` (cybercaius on Discord: a renamed provider was listed under both ids). `Visit` hands records out as recorded, so `Of` is taken once. An id another provider takes later (a rename onto it, or `Save` of a new provider under it) moves from the first one's `Was` to its `Gave` with the time (`giveID`): calls recorded under it before then stay the first one's, later ones are the new one's. An id held by a provider or a subscription now is never renamed (`Renamed`), and `freeID` doesn't hand out an id in any `Was`, so adding a vendor again gets `-2`. Ids reused before `Gave` existed have no time and go to whoever holds the id now. A provider deleted (`Delete`) is kept in providers.json's `deleted` with its name, `Was`, `Gave` and when (`provider.Deleted`): its calls stay under its id while no provider has that id, and once one is added under it (or a later deleted one had it) they go to `Deleted.UsageID`, `~`, so the new provider has only its own (cybercaius on Discord). The Usage page names either by the deleted provider's name and marks it with when it was deleted (`Renames.Gone`, `Named.Deleted`). Deletes before this was kept have no record and go to whoever holds the id now. A deleted provider's calls can be merged into a provider there is now, or named by the user, from a "…" beside the Requests page's Provider filter while it is picked (`ledProviderMore` in `plugins/usage/page.js`, `POST /api/usage/deleted`, `GET /api/usage/deleted/into`; CyberCaius on Discord, who had renamed a provider onto the old id to do it). Both are kept on its `Deleted` record, not in settings and never in the log: `MergeDeleted` sets `Into` and `MergedAt`, `NameDeleted` sets `Label` (`Deleted.Shown`), so a provider added later under the old id inherits neither. `Renames.Both(id, time)` gives the id a call is shown under (`Of`, merges followed) and the one it was made to (`Own`): a merged call is listed, filtered and summed under the target, but priced, held and answered by its own (`Record.priceID`, `block_price.go`'s `as`, window holds, `loggedAnswers`), so a merge moves no cost or token. The target's face lists what is merged into it (`Named.Merged`), and the same "…" parts each again (`into` ""). Renaming the target carries the merge; deleting it ends it (a merge older than the target's deletion is not followed). A providers.json that can't be read keeps the last renames read, not none. The summary and Requests caches key on `Renames.Key`, the vias cache too. | [`rename.go`](../../internal/provider/rename.go), [`block_price.go`](../../internal/usage/block_price.go) | diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 783ebcb4e..cd7f265c7 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -5104,6 +5104,9 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid conv.Thread = threadOf(in, body) } ctx = provider.WithConversation(ctx, conv) + // the agent's own headers the provider lists, which Sign passes on to + // it alone (PassHeaders) + ctx = provider.WithClientHeaders(ctx, p.ID, in) if !countsTokens(path) { // the user's own fields for the provider (#1604), last, so the // body is as it goes out when they fill in what it lacks, and diff --git a/internal/gateway/pass_headers_test.go b/internal/gateway/pass_headers_test.go new file mode 100644 index 000000000..440768850 --- /dev/null +++ b/internal/gateway/pass_headers_test.go @@ -0,0 +1,165 @@ +package gateway + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// heardHeaders' sibling for a fake vendor: the headers of each request it +// was sent. +type sentTo struct { + mu sync.Mutex + seen []http.Header +} + +func (s *sentTo) last() http.Header { + s.mu.Lock() + defer s.mu.Unlock() + if len(s.seen) == 0 { + return nil + } + return s.seen[len(s.seen)-1] +} + +func (s *sentTo) answer(vendor provider.Protocol, status int) http.HandlerFunc { + reply := vendorReply(vendor, status, "x") + return func(w http.ResponseWriter, r *http.Request) { + s.mu.Lock() + s.seen = append(s.seen, r.Header.Clone()) + s.mu.Unlock() + reply(w, r) + } +} + +// the agent's request, carrying a header to pass, one to pass that also +// has a fixed value, magpie's key in every place an agent puts it, and a +// header nobody lists +func passRequest(path, body string) *http.Request { + r := httptest.NewRequest("POST", path, strings.NewReader(body)) + r.Header.Set("X-Tenant", "tenant-from-client") + r.Header.Set("X-Route", "route-from-client") + r.Header.Set("X-Trace-Token", "trace-secret-0123456789") + r.Header.Set("X-Unlisted", "no") + r.Header.Set("Authorization", "Bearer magpie-gateway-key") + r.Header.Set("X-Api-Key", "magpie-gateway-key") + return r +} + +// 3jRzfF52Qx on X: a header the provider lists goes to it as the agent +// sent it, on every API (relayed, translated, count_tokens), standing over +// the provider's fixed Header of the same name; the fixed one goes when +// the agent sends none; magpie's key never goes. +func TestPassHeadersReachTheProvider(t *testing.T) { + for _, c := range []struct { + name, path, body string + vendor provider.Protocol + }{ + {"messages relayed", "/v1/messages", `{"model":"fake/sol","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}`, provider.Anthropic}, + {"messages to chat", "/v1/messages", `{"model":"fake/sol","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}`, provider.Chat}, + {"chat", "/v1/chat/completions", `{"model":"fake/sol","messages":[{"role":"user","content":"hi"}]}`, provider.Chat}, + {"chat stream", "/v1/chat/completions", `{"model":"fake/sol","stream":true,"messages":[{"role":"user","content":"hi"}]}`, provider.Chat}, + {"responses to chat", "/v1/responses", `{"model":"fake/sol","input":"hi"}`, provider.Chat}, + {"count_tokens", "/v1/messages/count_tokens", `{"model":"fake/sol","messages":[{"role":"user","content":"hi"}]}`, provider.Anthropic}, + } { + t.Run(c.name, func(t *testing.T) { + fresh(t) + up := &sentTo{} + p := provider.Provider{ID: "fake", Name: "Fake", Key: "sk-upstream-0123456789", Models: []string{"sol"}, + Headers: map[string]string{"X-Route": "route-fixed", "X-Fixed": "fixed"}, + PassHeaders: []string{"x-tenant", "X-ROUTE", "x-trace-token", "x-missing"}} + rhVendor(t, p, c.vendor, up.answer(c.vendor, 200)) + s := New() + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, passRequest(c.path, c.body)) + if rec.Code != 200 { + t.Fatalf("%d %s", rec.Code, rec.Body) + } + h := up.last() + if h == nil { + t.Fatal("the vendor was sent nothing") + } + for k, want := range map[string]string{ + "X-Tenant": "tenant-from-client", + "X-Route": "route-from-client", // the client's over the fixed one + "X-Trace-Token": "trace-secret-0123456789", + "X-Fixed": "fixed", + } { + if got := h.Values(k); len(got) != 1 || got[0] != want { + t.Errorf("%s = %q, want %q", k, got, want) + } + } + for _, k := range []string{"X-Unlisted", "X-Missing"} { + if got := h.Get(k); got != "" { + t.Errorf("%s = %q sent", k, got) + } + } + if a := h.Get("Authorization") + h.Get("X-Api-Key"); strings.Contains(a, "magpie-gateway-key") || !strings.Contains(a, "sk-upstream-0123456789") { + t.Errorf("the vendor's key headers %q, %q", h.Get("Authorization"), h.Get("X-Api-Key")) + } + }) + } +} + +// A listed header, and its fixed value, go to the provider that lists it +// alone: a fallback that lists nothing is sent neither, and a group's +// member that lists it is sent it. What the call log shows of a passed +// header is masked as any header is. +func TestPassHeadersOnlyToTheirProvider(t *testing.T) { + fresh(t) + noRests() + t.Cleanup(noRests) + first, spare := &sentTo{}, &sentTo{} + rhVendor(t, provider.Provider{ID: "ag", Name: "AG", Key: "k", Models: []string{"sol"}, Fallback: []string{"spare/sol"}, + PassHeaders: []string{"X-Tenant", "X-Trace-Token"}}, provider.Anthropic, first.answer(provider.Anthropic, 429)) + rhVendor(t, provider.Provider{ID: "spare", Name: "Spare", Key: "k", Models: []string{"sol"}}, + provider.Chat, spare.answer(provider.Chat, 200)) + s := New() + rec := httptest.NewRecorder() + s.Handler().ServeHTTP(rec, passRequest("/v1/messages", `{"model":"ag/sol","max_tokens":10,"messages":[{"role":"user","content":"hi"}]}`)) + if rec.Code != 200 { + t.Fatalf("%d %s", rec.Code, rec.Body) + } + if got := first.last().Get("X-Tenant"); got != "tenant-from-client" { + t.Errorf("the listing provider was sent X-Tenant %q", got) + } + if h := spare.last(); h == nil || h.Get("X-Tenant") != "" || h.Get("X-Trace-Token") != "" { + t.Errorf("the fallback that lists nothing was sent %v", h) + } + data, _ := json.Marshal(s.Recent()[0].Headers()) + if strings.Contains(string(data), "trace-secret-0123456789") { + t.Errorf("a passed token header shown unmasked:\n%s", data) + } + if !strings.Contains(string(data), "tenant-from-client") { + t.Errorf("the passed header isn't in the call's upstream headers:\n%s", data) + } + + // a group: its first member lists nothing and is refused, the next + // lists it + fresh(t) + noRests() + other, member := &sentTo{}, &sentTo{} + rhVendor(t, provider.Provider{ID: "oth", Name: "Oth", Key: "k", Models: []string{"sol"}}, + provider.Chat, other.answer(provider.Chat, 429)) + rhVendor(t, provider.Provider{ID: "mem", Name: "Mem", Key: "k", Models: []string{"sol"}, PassHeaders: []string{"X-Tenant"}}, + provider.Chat, member.answer(provider.Chat, 200)) + if err := provider.SaveGroup(provider.Group{Name: "Grp", Members: []string{"oth/sol", "mem/sol"}, Routing: provider.Ordered}); err != nil { + t.Fatal(err) + } + rec = httptest.NewRecorder() + New().Handler().ServeHTTP(rec, passRequest("/v1/chat/completions", `{"model":"group/grp","messages":[{"role":"user","content":"hi"}]}`)) + if rec.Code != 200 { + t.Fatalf("group: %d %s", rec.Code, rec.Body) + } + if h := other.last(); h == nil || h.Get("X-Tenant") != "" { + t.Errorf("the member that lists nothing was sent %v", h) + } + if h := member.last(); h == nil || h.Get("X-Tenant") != "tenant-from-client" { + t.Errorf("the member that lists it was sent %v", h) + } +} diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index ad2ab4b9c..e3016ddd1 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -7829,7 +7829,7 @@ document.addEventListener("click", (e) => { // advancedSet says whether a setting under the editor's Advanced is set, // which opens it: none hides behind a fold function advancedSet(d, p) { - return (d.headers || []).some(([k]) => (k || "").trim()) || !!(d.extraBody || "").trim() || !!(d.replyHeaders || "").trim() || + return (d.headers || []).some(([k]) => (k || "").trim()) || !!(d.extraBody || "").trim() || !!(d.replyHeaders || d.passHeaders || "").trim() || !!d.proxyMode || Object.values(d.accountProxies || {}).some((x) => x?.mode) || [d.concurrency, d.maxAccounts, d.queueLimit, d.queueWait, d.maxRPM, d.priceRate, d.contexts, d.outputs, d.compacts].some((v) => String(v ?? "").trim()) || !!d.rateWindows?.length || @@ -8157,29 +8157,23 @@ function setNewAPIUser(rows, id) { row[1] = id; } -// A provider's extra body fields (#1604): a JSON object the gateway merges -// into the top of every request's body to the vendor, filling in what the -// body lacks, or replacing it for a name written "!name"; ${sessionId} is -// the conversation's id. The fields magpie sets itself — the model, stream, -// the conversation — are refused, as provider.ExtraBodyReserved refuses -// them on a save. The draft keeps the text as typed; extraBodyOf reads it. +// extra body fields (#1604): provider.ExtraBodyReserved's are refused const EXTRA_BODY_RESERVED = ["model", "stream", "messages", "input", "contents", "system", "systemInstruction", "system_instruction", "instructions", "tools"]; function extraBodyText(obj) { return obj && Object.keys(obj).length ? JSON.stringify(obj, null, 2) : ""; } -// Reply headers magpie never passes on to the agent, listed or not, as -// provider.ReplyHeaderPassable refuses them on a save (reply-headers' Go -// test holds the two lists the same): the reply's framing, cookies, -// sign-ins, CORS and magpie's own (#4145). +// headers never passed on: ReplyHeaderPassable's (#4145), RequestHeaderPassable's const REPLY_NEVER = ["alt-svc", "api-key", "authentication-info", "authorization", "cache-control", "clear-site-data", "connection", "content-security-policy", "cookie", "date", "host", "keep-alive", "link", "location", "origin", "refresh", "retry-after", "server", "set-cookie", "set-cookie2", "strict-transport-security", "te", "trailer", "transfer-encoding", "upgrade", "vary", "www-authenticate", "x-accel-buffering", "x-api-key"]; const REPLY_NEVER_PREFIX = ["content-", "proxy-", "access-control-", "sec-", "x-magpie-"]; -// replyHeadersOf is the list a save sends, or why it can't be saved -function replyHeadersOf(text) { +const REQUEST_NEVER = ["accept", "accept-encoding", "api-key", "authentication-info", "authorization", "connection", "cookie", "expect", "host", "keep-alive", "origin", "set-cookie", "set-cookie2", "te", "trailer", "transfer-encoding", "upgrade", "www-authenticate", "x-api-key", "x-goog-api-key"]; +const REQUEST_NEVER_PREFIX = ["content-", "proxy-", "sec-", "x-magpie-"]; +// replyHeadersOf is the list a save sends, or why it can't +function replyHeadersOf(text, req) { const value = (text || "").split(",").map((x) => x.trim()).filter(Boolean); for (const n of value) { if (!/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(n)) return { value, error: t("\"{h}\" isn't a header name", { h: n }) }; const k = n.toLowerCase(); - if (REPLY_NEVER.includes(k) || REPLY_NEVER_PREFIX.some((x) => k.startsWith(x))) return { value, error: t("{h} is never passed on: magpie writes it, or it would act on magpie's own address", { h: n }) }; + if ((req ? REQUEST_NEVER : REPLY_NEVER).includes(k) || (req ? REQUEST_NEVER_PREFIX : REPLY_NEVER_PREFIX).some((x) => k.startsWith(x))) return { value, error: req ? t("{h} is never passed on: it carries a key, or magpie or the connection writes it", { h: n }) : t("{h} is never passed on: magpie writes it, or it would act on magpie's own address", { h: n }) }; } return { value }; } @@ -9040,7 +9034,7 @@ function baseAPIOf(p) { // draftOf is a saved provider as its editor's form holds it. function draftOf(p) { - return { id: p.id, name: p.name, preset: p.preset, chat: p.chat, responses: p.responses, anthropic: p.anthropic, gemini: p.gemini || "", catalog: p.catalog, decide: p.decide || "", key: "", api: baseAPIOf(p), chosen: pickedOf(p), none: !!p.noModels, best: !!p.bestInFamily, extra: [], headers: headerRows(p.headers), extraBody: extraBodyText(p.extraBody), replyHeaders: (p.replyHeaders || []).join(", "), icon: p.icon || "", iconFrom: p.iconFrom || "", fallback: [...(p.fallback || [])], unlisted: !!p.unlisted, hiddenDrawers: [...(p.hiddenDrawers || [])], searches: !!p.searches, unredacted: !!p.unredacted, countFree: !!p.countFree, insecureTLS: !!p.insecureTLS, limitRestOff: !!p.limitRestOff, nativeCompaction: !!p.nativeCompaction, passUserAgent: !!p.passUserAgent, pinUpstream: !!p.pinUpstream, authHeader: p.authHeader || "", balanceURL: p.balanceURL || "", balancePath: p.balancePath || "", balanceMethod: p.balanceMethod || "", modelsURL: p.modelsURL || "", contexts: contextsText(p.contexts), outputs: contextsText(p.outputs), compacts: contextsText(p.compacts), keysUrl: p.keysUrl || "", ...proxyDraft(p), ...concurrencyDraft(p), rateWindows: (p.rateWindows || []).map((w) => ({ ...w })) }; + return { id: p.id, name: p.name, preset: p.preset, chat: p.chat, responses: p.responses, anthropic: p.anthropic, gemini: p.gemini || "", catalog: p.catalog, decide: p.decide || "", key: "", api: baseAPIOf(p), chosen: pickedOf(p), none: !!p.noModels, best: !!p.bestInFamily, extra: [], headers: headerRows(p.headers), extraBody: extraBodyText(p.extraBody), replyHeaders: (p.replyHeaders || []).join(", "), passHeaders: (p.passHeaders || []).join(", "), icon: p.icon || "", iconFrom: p.iconFrom || "", fallback: [...(p.fallback || [])], unlisted: !!p.unlisted, hiddenDrawers: [...(p.hiddenDrawers || [])], searches: !!p.searches, unredacted: !!p.unredacted, countFree: !!p.countFree, insecureTLS: !!p.insecureTLS, limitRestOff: !!p.limitRestOff, nativeCompaction: !!p.nativeCompaction, passUserAgent: !!p.passUserAgent, pinUpstream: !!p.pinUpstream, authHeader: p.authHeader || "", balanceURL: p.balanceURL || "", balancePath: p.balancePath || "", balanceMethod: p.balanceMethod || "", modelsURL: p.modelsURL || "", contexts: contextsText(p.contexts), outputs: contextsText(p.outputs), compacts: contextsText(p.compacts), keysUrl: p.keysUrl || "", ...proxyDraft(p), ...concurrencyDraft(p), rateWindows: (p.rateWindows || []).map((w) => ({ ...w })) }; } // duplicateProvider opens the Add form on a copy of p (#268): its URLs, @@ -9578,6 +9572,10 @@ function drawEditor(p, presetID) { replyIn.classList.add("reply-headers"); replyIn.oninput = () => { draft.replyHeaders = replyIn.value; }; advIn.append(...field(t("Reply headers"), replyIn, t("Headers of the vendor's reply passed on to the agent, separated by commas, in any case. Request IDs (X-Request-Id, Request-Id, X-OneAPI-Request-ID) always are; cookies, CORS and the body's own headers never."))); + const passIn = input(draft.passHeaders || "", "X-Tenant-Id"); + passIn.classList.add("pass-headers"); + passIn.oninput = () => { draft.passHeaders = passIn.value; }; + advIn.append(...field(t("Request headers to pass"), passIn, t("Headers of the agent's request passed on as sent, separated by commas. The agent's value stands over a header above. Keys, cookies and the connection's own never are."))); const proxies = el("div", "stack"); proxies.append(proxyPicker()); const perKey = keyProxyPicker(p); @@ -9617,11 +9615,7 @@ function drawEditor(p, presetID) { advIn.append(...row); } - // a coding plan that serves only agents it names knows them by their - // User-Agent (#1851): a provider with a key may be sent the one the agent - // gave in place of magpie's. A signed-in account, and a vendor whose own - // client magpie goes as (OpenCode, Cline, Kilo, another magpie), keep - // the identity they sign with + // the agent's User-Agent (#1851); an account or ownClient keeps its own const uaPassable = () => !p?.account && !(p ? p.ownClient : pr?.ownClient); if (uaPassable()) { const [utk, ucb] = tick(t("Send the agent's own User-Agent"), !!draft.passUserAgent); @@ -9654,10 +9648,7 @@ function drawEditor(p, presetID) { advIn.append(...field(t("Rests"), rtk, t("Off: a 429 or an out-of-quota refusal doesn't rest its keys, and the next request is sent to it as usual. For a relay whose limits pass in a moment."))); } - // a vendor that tells the whole account's balance only to a token of its - // own (AiHubMix's system access token), where a key knows just its own - // — or a custom provider's, whose Balance URL may not be named yet: a - // token pasted there says at once which URL it wants (balanceFix) + // a balance token of the vendor's own (AiHubMix), or a custom one's (balanceFix) let balFix = null; if (p?.balanceToken?.takes || custom) { const saved = !!p?.balanceToken?.set; @@ -9706,11 +9697,8 @@ function drawEditor(p, presetID) { ed.append(...field(t("Team project ID"), proj, t("Only for a key on a team's GLM Coding Plan: both are in {p}'s console, under the team's organization and project. With them the Usage page shows the team's 5-hour and weekly windows.", { p: pr?.name || p.name }))); } - // Volcengine Ark tells a Coding or Agent Plan's windows only to the - // account's access key, never to the plan's key (#1427), and Tencent - // Cloud a Token Plan 企业版's only to its SecretId and SecretKey (#1574), - // asked only at the regions that are that plan; the saved Secret is - // never sent back here, only that one is saved + // plan windows told only to an access key (Volcengine #1427, Tencent #1574); + // the saved Secret never comes back here const access = p ? p.accessKey : pr?.accessKey ? { vendor: pr.accessKeyVendor || "volcengine", id: "", secretSet: false } : null; let accessAt = () => {}, accessShown = () => !!access; if (access) { @@ -9988,6 +9976,9 @@ function drawEditor(p, presetID) { const rh = replyHeadersOf(draft.replyHeaders); if (rh.error) { shown(ed.querySelector(".reply-headers"))?.focus(NO_SCROLL); return editorError(t("Reply headers: {why}", { why: rh.error }), "warn"); } body.replyHeaders = rh.value; + const ph = replyHeadersOf(draft.passHeaders, true); + if (ph.error) { shown(ed.querySelector(".pass-headers"))?.focus(NO_SCROLL); return editorError(t("Request headers to pass: {why}", { why: ph.error }), "warn"); } + body.passHeaders = ph.value; if (decides || custom) body.decide = (custom && draft.api !== "decide" && !p?.decide ? "" : draft.decide || "").trim(); if ((body.decide || "").includes(WORKSPACE)) { ed.querySelector(".workspace-id")?.focus(NO_SCROLL); return editorError(t("Give the workspace ID your API key belongs to, or pick the Token Plan"), "warn"); } if (custom) { diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 7c22b4f4e..278568b5c 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -2354,9 +2354,13 @@ const I18N = { "Extra body": "额外请求体", "JSON fields added to the body of every request to the vendor. A field the request has already is kept; write \"!name\" to replace it. ${sessionId} is the conversation's id; ${threadId} is the thread's, where the agent names one (Codex), else the same.": "加进发往供应商的每个请求体里的 JSON 字段。请求里已有的字段会保留;写成 \"!name\" 则替换它。${sessionId} 是会话的 ID;${threadId} 是线程的 ID(智能体单独给出时,如 Codex),否则与会话 ID 相同。", "Reply headers": "透传响应头", - "\"{h}\" isn't a header name": "“{h}”不是有效的响应头名称", + "\"{h}\" isn't a header name": "“{h}”不是有效的头名称", "{h} is never passed on: magpie writes it, or it would act on magpie's own address": "{h} 永不透传:它由 magpie 自己写入,或会作用于 magpie 自身的地址", "Reply headers: {why}": "透传响应头:{why}", + "Request headers to pass": "透传请求头", + "Headers of the agent's request passed on as sent, separated by commas. The agent's value stands over a header above. Keys, cookies and the connection's own never are.": "agent 请求中要按原值透传给供应商的请求头,用逗号分隔,不区分大小写。与上方「请求头」同名时,以 agent 发来的值为准。密钥、Cookie 和连接自身的头永不透传。", + "{h} is never passed on: it carries a key, or magpie or the connection writes it": "{h} 永不透传:它带着 magpie 的密钥,或由 magpie 或连接自己写入", + "Request headers to pass: {why}": "透传请求头:{why}", "Headers of the vendor's reply passed on to the agent, separated by commas, in any case. Request IDs (X-Request-Id, Request-Id, X-OneAPI-Request-ID) always are; cookies, CORS and the body's own headers never.": "供应商响应中要透传给 agent 的响应头,用逗号分隔,不区分大小写。请求 ID(X-Request-Id、Request-Id、X-OneAPI-Request-ID)总会透传;Cookie、CORS 和响应体自身的头永不透传。", "not valid JSON": "不是有效的 JSON", "write a JSON object, like {\"prompt_cache_key\": \"${sessionId}\"}": "请写一个 JSON 对象,例如 {\"prompt_cache_key\": \"${sessionId}\"}", @@ -6838,6 +6842,10 @@ const I18N = { "\"{h}\" isn't a header name": "「{h}」不是有效的標頭名稱", "{h} is never passed on: magpie writes it, or it would act on magpie's own address": "{h} 一律不透傳:它由 magpie 自己寫入,或會作用於 magpie 自身的位址", "Reply headers: {why}": "透傳回應標頭:{why}", + "Request headers to pass": "透傳請求頭", + "Headers of the agent's request passed on as sent, separated by commas. The agent's value stands over a header above. Keys, cookies and the connection's own never are.": "agent 請求中要按原值透傳給供應商的請求頭,以逗號分隔,不分大小寫。與上方「請求頭」同名時,以 agent 送來的值為準。金鑰、Cookie 和連線本身的標頭一律不透傳。", + "{h} is never passed on: it carries a key, or magpie or the connection writes it": "{h} 一律不透傳:它帶著 magpie 的金鑰,或由 magpie 或連線自己寫入", + "Request headers to pass: {why}": "透傳請求頭:{why}", "Headers of the vendor's reply passed on to the agent, separated by commas, in any case. Request IDs (X-Request-Id, Request-Id, X-OneAPI-Request-ID) always are; cookies, CORS and the body's own headers never.": "供應商回應中要透傳給 agent 的標頭,以逗號分隔,不分大小寫。請求 ID(X-Request-Id、Request-Id、X-OneAPI-Request-ID)一律透傳;Cookie、CORS 與回應本體自身的標頭一律不透傳。", "not valid JSON": "不是有效的 JSON", "write a JSON object, like {\"prompt_cache_key\": \"${sessionId}\"}": "請寫一個 JSON 物件,例如 {\"prompt_cache_key\": \"${sessionId}\"}", @@ -11295,6 +11303,10 @@ const I18N = { "\"{h}\" isn't a header name": "「{h}」はヘッダー名ではありません", "{h} is never passed on: magpie writes it, or it would act on magpie's own address": "{h} は決して渡しません:magpie 自身が書くか、magpie 自身のアドレスに作用するためです", "Reply headers: {why}": "レスポンスヘッダー: {why}", + "Request headers to pass": "引き継ぐリクエストヘッダー", + "Headers of the agent's request passed on as sent, separated by commas. The agent's value stands over a header above. Keys, cookies and the connection's own never are.": "エージェントのリクエストのこれらのヘッダーを、送られたままベンダーへ渡します。カンマ区切り、大文字小文字は問いません。上の同名ヘッダーよりエージェントの値が優先されます。キー、Cookie、接続自身のヘッダーは決して渡しません。", + "{h} is never passed on: it carries a key, or magpie or the connection writes it": "{h} は決して渡しません:magpie のキーを運ぶか、magpie か接続自身が書くためです", + "Request headers to pass: {why}": "引き継ぐリクエストヘッダー: {why}", "Headers of the vendor's reply passed on to the agent, separated by commas, in any case. Request IDs (X-Request-Id, Request-Id, X-OneAPI-Request-ID) always are; cookies, CORS and the body's own headers never.": "ベンダーのレスポンスからエージェントへ渡すヘッダー。カンマ区切りで、大文字小文字は問いません。リクエスト ID(X-Request-Id、Request-Id、X-OneAPI-Request-ID)は常に渡し、Cookie、CORS、ボディ自身のヘッダーは決して渡しません。", "not valid JSON": "有効な JSON ではありません", "write a JSON object, like {\"prompt_cache_key\": \"${sessionId}\"}": "JSON オブジェクトを書いてください(例: {\"prompt_cache_key\": \"${sessionId}\"})", @@ -15783,6 +15795,10 @@ const I18N = { "\"{h}\" isn't a header name": "„{h}“ ist kein Header-Name", "{h} is never passed on: magpie writes it, or it would act on magpie's own address": "{h} wird nie weitergegeben: magpie schreibt ihn selbst, oder er würde auf magpies eigene Adresse wirken", "Reply headers: {why}": "Antwort-Header: {why}", + "Request headers to pass": "Weiterzugebende Anfrage-Header", + "Headers of the agent's request passed on as sent, separated by commas. The agent's value stands over a header above. Keys, cookies and the connection's own never are.": "Header der Anfrage des Agenten, die unverändert an den Anbieter weitergehen, durch Kommas getrennt, Groß-/Kleinschreibung egal. Der Wert des Agenten gilt vor einem gleichnamigen Header oben. Schlüssel, Cookies und die Header der Verbindung selbst nie.", + "{h} is never passed on: it carries a key, or magpie or the connection writes it": "{h} wird nie weitergegeben: er trägt magpies Schlüssel, oder magpie oder die Verbindung schreibt ihn selbst", + "Request headers to pass: {why}": "Weiterzugebende Anfrage-Header: {why}", "Headers of the vendor's reply passed on to the agent, separated by commas, in any case. Request IDs (X-Request-Id, Request-Id, X-OneAPI-Request-ID) always are; cookies, CORS and the body's own headers never.": "Header der Antwort des Anbieters, die an den Agenten weitergegeben werden, durch Kommas getrennt, Groß- und Kleinschreibung egal. Anfrage-IDs (X-Request-Id, Request-Id, X-OneAPI-Request-ID) immer; Cookies, CORS und die Header des Bodys selbst nie.", "not valid JSON": "kein gültiges JSON", "write a JSON object, like {\"prompt_cache_key\": \"${sessionId}\"}": "schreib ein JSON-Objekt, etwa {\"prompt_cache_key\": \"${sessionId}\"}", diff --git a/internal/gui/providers.go b/internal/gui/providers.go index 66635d12f..8b67be8e1 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -101,6 +101,8 @@ type providerJSON struct { ExtraBody provider.ExtraBody `json:"extraBody,omitempty"` // headers of the vendor's reply passed on (provider.ReplyHeaders, #4145) ReplyHeaders []string `json:"replyHeaders,omitempty"` + // headers of the agent's request passed on (provider.PassHeaders) + PassHeaders []string `json:"passHeaders,omitempty"` // the API the user gave a custom provider's Base URL as (BaseAPI) BaseAPI string `json:"baseAPI,omitempty"` // the vendor searches the web by itself (provider.Searches) @@ -681,7 +683,7 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs ID: p.ID, Name: p.Name, Icon: p.Icon, IconFrom: p.IconFrom, Preset: p.Preset, Host: p.Host(), Chat: p.Chat, Responses: p.Responses, Anthropic: p.Anthropic, Gemini: p.Gemini, Decide: p.Decide, BaseAPI: p.BaseAPI, ModelTest: p.ModelTest(), TestsAs: p.TestClients(), DecideTest: p.AsksDecideModels(), MarksKinds: p.MarksKinds(), Catalog: p.Catalog, Website: p.Website, KeysURL: p.KeysURL, - Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, ReplyHeaders: p.ReplyHeaders, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, CountFree: p.CountFree, InsecureTLS: p.InsecureTLS, TakesInsecureTLS: p.TakesInsecureTLS(), LimitRestOff: p.LimitRestOff, NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: p.PassUserAgent, OwnClient: p.OwnClient(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, BalanceMethod: p.BalanceMethod, ModelsURL: p.ModelsURL, + Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, ReplyHeaders: p.ReplyHeaders, PassHeaders: p.PassHeaders, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, CountFree: p.CountFree, InsecureTLS: p.InsecureTLS, TakesInsecureTLS: p.TakesInsecureTLS(), LimitRestOff: p.LimitRestOff, NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: p.PassUserAgent, OwnClient: p.OwnClient(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, BalanceMethod: p.BalanceMethod, ModelsURL: p.ModelsURL, Ready: p.Ready(), Chosen: p.PicksOf(avail), Agents: make([]providerAgent, 0, len(agents)), Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, CapStop: p.CapStop, CapCareful: p.CapCareful, Unlisted: p.Unlisted, NoModels: p.ServesNone(), BestInFamily: p.BestInFamily && len(p.Models) == 0 && !p.NoModels, Off: p.Off, Contexts: p.Contexts, MaxConcurrency: p.MaxConcurrency, PluginConcurrency: p.PluginConcurrency(), MaxAccounts: p.MaxAccounts, PluginAccounts: p.PluginAtOnce(), PriceRate: p.PriceRate, @@ -1619,6 +1621,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) { pr.BestInFamily = in.BestInFamily pr.ExtraBody = in.ExtraBody pr.ReplyHeaders = in.ReplyHeaders + pr.PassHeaders = in.PassHeaders pr.SecretAccessKey = in.SecretAccessKey pr.Vertex = in.Vertex pr.Searches = in.Searches @@ -1662,6 +1665,12 @@ func providerRoutes(mux *http.ServeMux, w Windows) { fail(rw, errors.New(why)) return } + // and request headers that carry magpie's key or the + // connection's own + if why := provider.RequestHeadersOK(in.PassHeaders); why != "" { + fail(rw, errors.New(why)) + return + } cc, keepCC, err := concurrencyOf(req.MaxConcurrency) if err != nil { fail(rw, err) @@ -1884,6 +1893,9 @@ func providerRoutes(mux *http.ServeMux, w Windows) { if in.ReplyHeaders == nil && old != nil { in.ReplyHeaders = old.ReplyHeaders } + if in.PassHeaders == nil && old != nil { + in.PassHeaders = old.PassHeaders + } // Select none likewise, while nothing is picked (#1818) if req.NoModels == nil && old != nil { in.NoModels = old.NoModels diff --git a/internal/gui/reply_headers_test.go b/internal/gui/reply_headers_test.go index de05811f0..a5f649500 100644 --- a/internal/gui/reply_headers_test.go +++ b/internal/gui/reply_headers_test.go @@ -11,8 +11,9 @@ import ( "github.com/yetone/magpie/internal/provider" ) -// The editor refuses the reply headers a save would (#4145): its lists are -// provider.ReplyHeaderPassable's. +// The editor refuses the reply headers, and the request headers to pass, a +// save would (#4145): its lists are provider.ReplyHeaderPassable's and +// RequestHeaderPassable's. func TestReplyHeadersNeverAsTheProvidersAre(t *testing.T) { js, err := os.ReadFile("assets/app.js") if err != nil { @@ -45,4 +46,12 @@ func TestReplyHeadersNeverAsTheProvidersAre(t *testing.T) { if got, want := listOf("REPLY_NEVER_PREFIX"), lower(prefixes); !slices.Equal(got, want) { t.Errorf("app.js REPLY_NEVER_PREFIX %q, provider %q", got, want) } + // and the request headers to pass, provider.RequestHeaderPassable's + names, prefixes = provider.RequestHeadersNever() + if got, want := listOf("REQUEST_NEVER"), lower(names); !slices.Equal(got, want) { + t.Errorf("app.js REQUEST_NEVER %q, provider %q", got, want) + } + if got, want := listOf("REQUEST_NEVER_PREFIX"), lower(prefixes); !slices.Equal(got, want) { + t.Errorf("app.js REQUEST_NEVER_PREFIX %q, provider %q", got, want) + } } diff --git a/internal/gui/tests/pass-headers.test.cjs b/internal/gui/tests/pass-headers.test.cjs new file mode 100644 index 000000000..31eb68e3d --- /dev/null +++ b/internal/gui/tests/pass-headers.test.cjs @@ -0,0 +1,126 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// A provider's Request headers to pass (3jRzfF52Qx on X: the agent's own +// header values, not a fixed one), right after Reply headers: the editor +// shows the saved list, a Save sends what is typed as a list, refuses a +// name that carries magpie's key or the connection's own (Authorization, +// x-api-key, Host, Content-*, a name that isn't one) and says why, and an +// emptied box clears it ([]). It fits a narrow window. In English, +// Chinese, Traditional Chinese, Japanese and German, Chromium and WebKit. +const assert = require("node:assert/strict"); +const fs = require("node:fs/promises"); +const path = require("node:path"); +const { test } = require("node:test"); +const { chromium, webkit } = require("playwright"); + +const assets = path.resolve(__dirname, "../assets"); +const relay = { + id: "relay", name: "Relay", preset: "", icon: "generic", chat: "https://relay.example.com/v1", responses: "", anthropic: "", catalog: "", baseAPI: "chat", + models: [{ id: "gpt-5.1", name: "gpt-5.1", on: true }], agents: [], fallback: [], headers: {}, + passHeaders: ["X-Tenant"], + key: { set: true, masked: "sk-…one" }, keyList: [{ id: "k1", name: "", masked: "sk-…one", on: true, active: true }], + balanceToken: { takes: false, set: false }, proxy: "", +}; + +function serve(lang, calls) { + const providers = { providers: [relay], presets: [], excluded: [], gateway: { running: true, window: true } }; + const state = { agents: [], profiles: [], settings: { lang, theme: "light" } }; + return async (route) => { + const url = new URL(route.request().url()); + const json = (data) => route.fulfill({ json: data }); + if (url.pathname === "/boot.js") return route.fulfill({ contentType: "text/javascript", body: `window.bootPrefs = {lang:"${lang}",theme:"light",web:true};` }); + if (url.pathname === "/wails/runtime.js") return route.fulfill({ contentType: "text/javascript", body: "export const Window = {};" }); + if (url.pathname === "/api/state") return json(state); + if (url.pathname === "/api/providers") return json(providers); + if (url.pathname === "/api/groups") return json({ groups: [] }); + if (url.pathname.startsWith("/api/provider/")) { + calls.push([url.pathname.slice(14), route.request().postDataJSON()]); + if (url.pathname === "/api/provider/save") return json(providers); + } + if (url.pathname.startsWith("/api/")) return json({}); + const file = path.join(assets, url.pathname === "/" ? "index.html" : url.pathname); + const contentType = { ".html": "text/html", ".js": "text/javascript", ".css": "text/css", ".svg": "image/svg+xml", ".png": "image/png" }[path.extname(file)]; + try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); } + }; +} + +const words = { + en: { label: "Request headers to pass", reply: "Reply headers", save: "Save", never: "carries a key", name: "isn't a header name" }, + zh: { label: "透传请求头", reply: "透传响应头", save: "保存", never: "带着 magpie 的密钥", name: "不是有效的头名称" }, + "zh-TW": { label: "透傳請求頭", reply: "透傳回應標頭", save: "儲存", never: "帶著 magpie 的金鑰", name: "不是有效的標頭名稱" }, + ja: { label: "引き継ぐリクエストヘッダー", reply: "レスポンスヘッダー", save: "保存", never: "magpie のキーを運ぶ", name: "ヘッダー名ではありません" }, + de: { label: "Weiterzugebende Anfrage-Header", reply: "Antwort-Header", save: "Speichern", never: "trägt magpies Schlüssel", name: "ist kein Header-Name" }, +}; + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of Object.keys(words)) { + const w = words[lang]; + test(`${engine} ${lang}: Request headers to pass are shown, refused, saved and cleared`, async (t) => { + const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width: 900, height: 900 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + page.setDefaultNavigationTimeout(60000); + const errors = []; + page.on("pageerror", (e) => errors.push(e.message)); + const calls = []; + await page.route("**/*", serve(lang, calls)); + await page.goto("http://magpie.test/?view=providers"); + const open = async () => { + await page.locator(".row.provider", { hasText: "Relay" }).click(); + const ed = page.locator(".editor"); + await ed.locator("input.pass-headers").waitFor(); + return ed; + }; + const save = async (ed) => { + await ed.locator(".bar").getByRole("button", { name: w.save, exact: true }).click(); + for (let i = 0; i < 20 && !calls.some((c) => c[0] === "save"); i++) await page.waitForTimeout(50); + }; + let ed = await open(); + const box = ed.locator("input.pass-headers"); + assert.equal(await page.locator(`label[for="${await box.getAttribute("id")}"]`).textContent(), w.label, "labelled"); + assert.equal(await box.inputValue(), "X-Tenant", "the saved list is shown"); + // right after Reply headers + const after = await box.evaluate((b) => { + const fields = [...document.querySelectorAll(".editor label")].map((l) => l.textContent); + return fields[fields.indexOf(document.querySelector(`label[for="${b.id}"]`).textContent) - 1]; + }); + assert.equal(after, w.reply, "beside Reply headers"); + + // refused before a Save, with why, the box focused + for (const [text, want] of [["x-tenant, Authorization", w.never], ["x-api-key", w.never], ["Host", w.never], ["Content-Length", w.never], ["x tenant", w.name]]) { + await box.fill(text); + await save(ed); + assert.deepEqual(calls.map((c) => c[0]), [], `${text}: nothing saved`); + const said = await ed.locator(".editor-error").textContent(); + assert.ok(said.includes(want) && said.includes(w.label), `${text}: ${said}`); + assert.ok(await box.evaluate((e) => e === document.activeElement), "the box is focused"); + } + + // the narrow window: the box stays inside the editor + await page.setViewportSize({ width: 420, height: 900 }); + const fits = await page.evaluate(() => { + const ed = document.querySelector(".editor").getBoundingClientRect(); + const r = document.querySelector("input.pass-headers").getBoundingClientRect(); + return r.left >= ed.left - 0.5 && r.right <= ed.right + 0.5; + }); + assert.ok(fits, "fits a narrow window"); + assert.ok(await page.evaluate(() => document.documentElement.scrollWidth <= document.documentElement.clientWidth), "no sideways scroll"); + await page.setViewportSize({ width: 900, height: 900 }); + + await box.fill(" x-tenant ,X-Session-Route,, "); + await save(ed); + const saved = calls.find((c) => c[0] === "save"); + assert.ok(saved, "saved"); + assert.deepEqual(saved[1].passHeaders, ["x-tenant", "X-Session-Route"], "saved as a list"); + + // emptied: a Save clears it + calls.length = 0; + await page.locator(".editor").waitFor({ state: "hidden" }); + ed = await open(); + await ed.locator("input.pass-headers").fill(""); + await save(ed); + assert.deepEqual(calls.find((c) => c[0] === "save")?.[1].passHeaders, [], "an empty box clears it"); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/gui/tests/reply-headers.test.cjs b/internal/gui/tests/reply-headers.test.cjs index 0b7a0e6e2..065ce4815 100644 --- a/internal/gui/tests/reply-headers.test.cjs +++ b/internal/gui/tests/reply-headers.test.cjs @@ -44,7 +44,7 @@ function serve(lang, calls) { const words = { en: { label: "Reply headers", save: "Save", never: "is never passed on", name: "isn't a header name" }, - zh: { label: "透传响应头", save: "保存", never: "永不透传", name: "不是有效的响应头名称" }, + zh: { label: "透传响应头", save: "保存", never: "永不透传", name: "不是有效的头名称" }, "zh-TW": { label: "透傳回應標頭", save: "儲存", never: "一律不透傳", name: "不是有效的標頭名稱" }, ja: { label: "レスポンスヘッダー", save: "保存", never: "決して渡しません", name: "ヘッダー名ではありません" }, de: { label: "Antwort-Header", save: "Speichern", never: "wird nie weitergegeben", name: "ist kein Header-Name" }, diff --git a/internal/provider/account.go b/internal/provider/account.go index 93285ca65..26203b144 100644 --- a/internal/provider/account.go +++ b/internal/provider/account.go @@ -219,6 +219,9 @@ func (p Provider) Sign(ctx context.Context, req *http.Request, proto Protocol, b return errAccountDiscoveryOff } ctx = p.Via(ctx) // a sign-in refreshed on the way goes through its proxy + // the agent's own headers the provider lists (PassHeaders), before an + // account's signing, which has the last word on its own + passed := p.passClientHeaders(ctx, req.Header) if p.Account != nil && p.Account.sign != nil { return p.Account.sign(ctx, req, body) } @@ -249,6 +252,9 @@ func (p Provider) Sign(ctx context.Context, req *http.Request, proto Protocol, b // ${sessionId} and ${threadId} in a value are the conversation's // (conversation.go). for k, v := range p.SentHeaders(ctx) { + if slices.ContainsFunc(passed, func(n string) bool { return strings.EqualFold(n, k) }) { + continue // the agent sent its own, which stands over the user's fixed one + } if ListHeader(k) { MergeList(req.Header, k, v) continue diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 1190fe6b9..f7ddb435b 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -274,6 +274,16 @@ type Provider struct { // act on magpie's address, never is (ReplyHeaderPassable). ReplyHeaders []string `json:"replyHeaders,omitempty"` + // PassHeaders are headers of the agent's request passed on to the + // vendor as it sent them, whatever their case (3jRzfF52Qx on X): a + // value that changes per request or per client, which a fixed Header + // can't give. The client's stands over a Header of the same name; + // with none sent the Header goes. Every API, count_tokens, a group's + // member, a plugin's fetch; a signed-in account's signing has the + // last word. One that carries magpie's key or the connection's own + // never is (RequestHeaderPassable). + PassHeaders []string `json:"passHeaders,omitempty"` + // Searches says the vendor answers a web search tool offered on its // Anthropic or Responses API by itself (web_search_20250305, // web_search): a relay in front of Anthropic's or OpenAI's API, which @@ -775,6 +785,7 @@ func (p Provider) clone() Provider { p.Headers = maps.Clone(p.Headers) p.ExtraBody = maps.Clone(p.ExtraBody) p.ReplyHeaders = slices.Clone(p.ReplyHeaders) + p.PassHeaders = slices.Clone(p.PassHeaders) p.AccountProxies = maps.Clone(p.AccountProxies) p.AccountCaps = maps.Clone(p.AccountCaps) p.AccountNames = maps.Clone(p.AccountNames) @@ -912,6 +923,8 @@ func accountSettings(a, pk Provider) Provider { a.HiddenDrawers = pk.HiddenDrawers // and the headers of its replies passed on (#4145) a.ReplyHeaders = pk.ReplyHeaders + // and the headers of the agent's requests passed on + a.PassHeaders = pk.PassHeaders return a } @@ -1656,6 +1669,7 @@ func normalize(p Provider) Provider { p.Headers = cleanHeaders(p.Headers) p.ExtraBody = cleanExtraBody(p.ExtraBody) p.ReplyHeaders = cleanReplyHeaders(p.ReplyHeaders) + p.PassHeaders = cleanRequestHeaders(p.PassHeaders) if pr := Preset(p.Preset); pr != nil { if p.Icon == "" { p.Icon = pr.Icon diff --git a/internal/provider/replyheaders_test.go b/internal/provider/replyheaders_test.go index 4c17090a0..8ca1c2090 100644 --- a/internal/provider/replyheaders_test.go +++ b/internal/provider/replyheaders_test.go @@ -1,6 +1,7 @@ package provider import ( + "context" "net/http" "slices" "testing" @@ -36,3 +37,55 @@ func TestReplyHeadersList(t *testing.T) { t.Error("passed headers nobody listed") } } + +// A provider's request headers to pass are kept canonical and once each, +// never one that carries magpie's key or the connection's own (3jRzfF52Qx +// on X). +func TestRequestHeadersList(t *testing.T) { + got := cleanRequestHeaders([]string{" x-tenant ", "X-TENANT", "authorization", "x-api-key", "host", "content-length", "x-magpie-agent", "bad name", "", "x-trace"}) + if want := []string{"X-Tenant", "X-Trace"}; !slices.Equal(got, want) { + t.Errorf("cleaned %q, want %q", got, want) + } + for _, bad := range [][]string{{"Authorization"}, {"x-api-key"}, {"X-Goog-Api-Key"}, {"api-key"}, {"Cookie"}, {"Host"}, {"Content-Length"}, + {"Connection"}, {"Transfer-Encoding"}, {"Proxy-Authorization"}, {"Accept-Encoding"}, {"X-Magpie-Session"}, {"a b"}} { + if RequestHeadersOK(bad) == "" { + t.Errorf("%q passed as OK", bad) + } + } + if msg := RequestHeadersOK([]string{"x-tenant", " ", "User-Agent", "Anthropic-Beta"}); msg != "" { + t.Errorf("OK list refused: %s", msg) + } +} + +// Sign passes on what the provider lists, the agent's over the fixed +// Header, to that provider alone, and never magpie's key, even listed in a +// file written by hand (3jRzfF52Qx on X). +func TestSignPassesClientHeaders(t *testing.T) { + in := http.Header{"X-Tenant": {"t1"}, "Authorization": {"Bearer magpie-key"}, "X-Api-Key": {"magpie-key"}, "x-route": {"r1"}} + p := Provider{ID: "fake", Key: "sk-up", Chat: "https://up.example/v1", Headers: map[string]string{"X-Route": "fixed", "X-Only": "o"}, + PassHeaders: []string{"X-Tenant", "Authorization", "X-Api-Key", "X-Route"}} + sign := func(p Provider, ctx context.Context) http.Header { + req, _ := http.NewRequest("POST", "https://up.example/v1/chat/completions", nil) + if err := p.Sign(ctx, req, Chat, nil); err != nil { + t.Fatal(err) + } + return req.Header + } + h := sign(p, WithClientHeaders(context.Background(), "fake", in)) + if h.Get("X-Tenant") != "t1" || h.Get("X-Route") != "r1" || h.Get("X-Only") != "o" || len(h.Values("X-Route")) != 1 { + t.Errorf("sent %v", h) + } + if h.Get("Authorization") != "Bearer sk-up" || h.Get("X-Api-Key") == "magpie-key" { + t.Errorf("magpie's key passed on: %v", h) + } + // the agent's headers carried for another provider + h = sign(p, WithClientHeaders(context.Background(), "other", in)) + if h.Get("X-Tenant") != "" || h.Get("X-Route") != "fixed" { + t.Errorf("another's request passed on %v", h) + } + // none sent: the fixed Header goes + h = sign(p, context.Background()) + if h.Get("X-Route") != "fixed" || h.Get("X-Tenant") != "" { + t.Errorf("with nothing sent %v", h) + } +} diff --git a/internal/provider/requestheaders.go b/internal/provider/requestheaders.go new file mode 100644 index 000000000..b1ef2bb48 --- /dev/null +++ b/internal/provider/requestheaders.go @@ -0,0 +1,151 @@ +package provider + +// Headers of the agent's request passed on to the vendor (PassHeaders, +// 3jRzfF52Qx on X): a value that changes from request to request or from +// client to client, which a provider's fixed Headers can't say, goes as the +// agent sent it. The mirror of ReplyHeaders (replyheaders.go). + +import ( + "context" + "net/http" + "slices" + "strings" +) + +// requestHeadersNever are never passed on, listed or not: magpie's own key +// as an agent sends it (Authorization, x-api-key, x-goog-api-key, api-key) +// and the sign-ins and cookies beside it, the connection's own fields, and +// what magpie writes for the body it sends (a translated body has another +// type, length and encoding, and the transport asks for compression +// itself). The prefixes below go with them. +var requestHeadersNever = map[string]bool{ + "Authorization": true, "X-Api-Key": true, "X-Goog-Api-Key": true, "Api-Key": true, + "Cookie": true, "Set-Cookie": true, "Set-Cookie2": true, "Www-Authenticate": true, "Authentication-Info": true, + "Host": true, "Connection": true, "Keep-Alive": true, "Te": true, "Trailer": true, "Transfer-Encoding": true, + "Upgrade": true, "Expect": true, "Accept": true, "Accept-Encoding": true, "Origin": true, +} + +// requestHeadersNeverPrefix: Content-Length, -Type and the rest; +// Proxy-Authorization and the rest; Sec- fetch metadata; and magpie's own, +// which carry who asked and the conversation to a plugin or another +// magpie. +var requestHeadersNeverPrefix = []string{"Content-", "Proxy-", "Sec-", "X-Magpie-"} + +// RequestHeaderPassable says whether a header of the agent's request may be +// passed on to the vendor at all. +func RequestHeaderPassable(name string) bool { + k := http.CanonicalHeaderKey(strings.TrimSpace(name)) + if !validHeaderName(k) || requestHeadersNever[k] { + return false + } + for _, p := range requestHeadersNeverPrefix { + if strings.HasPrefix(k, p) { + return false + } + } + return true +} + +// RequestHeadersOK says what is wrong with a list of request headers to +// pass on, "" when nothing is. +func RequestHeadersOK(names []string) string { + for _, n := range names { + n = strings.TrimSpace(n) + if n == "" { + continue + } + if !validHeaderName(n) { + return "\"" + n + "\" isn't a header name" + } + if !RequestHeaderPassable(n) { + return n + " is never passed on: it carries a key, or magpie or the connection writes it" + } + } + return "" +} + +// cleanRequestHeaders is the list as saved: names trimmed and canonical, +// each once, what can't be passed on dropped; nil when nothing is left. +func cleanRequestHeaders(names []string) []string { + var out []string + for _, n := range names { + k := http.CanonicalHeaderKey(strings.TrimSpace(n)) + if RequestHeaderPassable(k) && !slices.Contains(out, k) { + out = append(out, k) + } + } + return out +} + +// RequestHeadersNever are the names and prefixes RequestHeaderPassable +// refuses, for the GUI's own check of a list typed. +func RequestHeadersNever() (names, prefixes []string) { + for k := range requestHeadersNever { + names = append(names, k) + } + slices.Sort(names) + return names, slices.Clone(requestHeadersNeverPrefix) +} + +type agentHeadersKey struct{} + +type agentHeaders struct { + id string + h http.Header +} + +// WithClientHeaders is ctx carrying h, the headers of the agent's request, +// for Sign to pass on to the provider id those it lists (PassHeaders): +// that provider's request alone, never another's made under the same ctx. +func WithClientHeaders(ctx context.Context, id string, h http.Header) context.Context { + if len(h) == 0 { + return ctx + } + return context.WithValue(ctx, agentHeadersKey{}, agentHeaders{id: id, h: h}) +} + +// passClientHeaders puts into h the headers of the agent's request ctx +// carries that p lists, as sent, in place of any value h has under the +// name in any case. It gives the names it put. +func (p Provider) passClientHeaders(ctx context.Context, h http.Header) []string { + if len(p.PassHeaders) == 0 { + return nil + } + c, ok := ctx.Value(agentHeadersKey{}).(agentHeaders) + if !ok || c.id != p.ID { + return nil + } + var put []string + for _, n := range p.PassHeaders { + k := http.CanonicalHeaderKey(strings.TrimSpace(n)) + if slices.Contains(put, k) || !RequestHeaderPassable(k) { + continue + } + vs := valuesFold(c.h, k) + if len(vs) == 0 { + continue + } + for hk := range h { + if strings.EqualFold(hk, k) { + delete(h, hk) + } + } + h[k] = slices.Clone(vs) + put = append(put, k) + } + return put +} + +// valuesFold is h's values under k, whatever the case of h's keys (a +// header map filled by hand). +func valuesFold(h http.Header, k string) []string { + if vs := h.Values(k); len(vs) > 0 { + return vs + } + for hk, hv := range h { + if strings.EqualFold(hk, k) { + return hv + } + } + return nil +}