diff --git a/README.md b/README.md index 885411ffd..56aa8ea0a 100644 --- a/README.md +++ b/README.md @@ -125,7 +125,7 @@ Click a value and a searchable list opens: every model of every provider you add Pick a preset, paste a key. Model lists come from the vendor, with names and reasoning levels filled in from [models.dev](https://models.dev), so a model released this morning is in your picker on the next refresh. -> **Presets include** Anthropic · OpenAI · Google Gemini · Google Vertex AI · DeepSeek · Kimi · Zhipu GLM · MiniMax · StepFun · Qwen · Baidu Qianfan · Tencent Cloud · Huawei Cloud MaaS · Volcengine Ark · Mistral · Groq · Nous Portal · xAI · OpenRouter · Together · Fireworks · SiliconFlow · NVIDIA NIM · ModelScope · Ollama · LM Studio … and any OpenAI- or Anthropic-compatible URL. +> **Presets include** Anthropic · OpenAI · Google Gemini · Google Vertex AI · Amazon Bedrock (runtime and Mantle) · DeepSeek · Kimi · Zhipu GLM · MiniMax · StepFun · Qwen · Baidu Qianfan · Tencent Cloud · Huawei Cloud MaaS · Volcengine Ark · Mistral · Groq · Nous Portal · xAI · OpenRouter · Together · Fireworks · SiliconFlow · NVIDIA NIM · ModelScope · Ollama · LM Studio … and any OpenAI- or Anthropic-compatible URL. **Import** brings in the providers from CC Switch, Claude Code, Codex and Alma. **[Add to magpie](https://usemagpie.ai/docs/import)** links let a provider's website hand its config to magpie in one click. Each key and each account can go through a proxy of its own. diff --git a/README.zh-CN.md b/README.zh-CN.md index 5a80550d7..9b0ecc390 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -125,7 +125,7 @@ export GOOGLE_GEMINI_BASE_URL=http://127.0.0.1:3425 GEMINI_API_KEY=magpie 选一个预设,粘贴 key。模型列表直接来自厂商,名称和推理档位从 [models.dev](https://models.dev) 补全,今天早上刚发布的模型,下次刷新就出现在你的选择器里。 -> **预设包括** Anthropic · OpenAI · Google Gemini · DeepSeek · Kimi · 智谱 GLM · MiniMax · 阶跃星辰 · 通义千问 · 百度千帆 · 腾讯云 · 华为云 MaaS · 火山方舟 · Mistral · Groq · Nous Portal · xAI · OpenRouter · Together · Fireworks · 硅基流动 · NVIDIA NIM · 魔搭 · Ollama · LM Studio …… 以及任何兼容 OpenAI 或 Anthropic 的地址。 +> **预设包括** Anthropic · OpenAI · Google Gemini · Amazon Bedrock(runtime 与 Mantle)· DeepSeek · Kimi · 智谱 GLM · MiniMax · 阶跃星辰 · 通义千问 · 百度千帆 · 腾讯云 · 华为云 MaaS · 火山方舟 · Mistral · Groq · Nous Portal · xAI · OpenRouter · Together · Fireworks · 硅基流动 · NVIDIA NIM · 魔搭 · Ollama · LM Studio …… 以及任何兼容 OpenAI 或 Anthropic 的地址。 **导入**能读取你在 CC Switch、Claude Code、Codex 和 Alma 里配置的 provider。[**「添加到 magpie」链接**](https://usemagpie.ai/docs/zh/import)让 provider 网站一键把配置交给 magpie。每个 key 和每个账号都可以走自己的代理。 diff --git a/docs/reference.md b/docs/reference.md index 1ba9de68b..45514ea04 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -54,7 +54,7 @@ line; agents connected to magpie lose it when it quits. use its models through the gateway, with nothing copied and no key to paste. - **Providers with one field.** Pick a preset (Anthropic, OpenAI, Gemini, - DeepSeek, Kimi, GLM, MiniMax, StepFun, Qwen, Baidu Qianfan, Tencent Cloud Token Plan, + Amazon Bedrock and its Mantle endpoint, DeepSeek, Kimi, GLM, MiniMax, StepFun, Qwen, Baidu Qianfan, Tencent Cloud Token Plan, Huawei Cloud MaaS, Volcengine Ark, Mistral, Groq, Nous Portal, xAI, OpenRouter, Together, Fireworks, SiliconFlow, NVIDIA NIM, ModelScope, AiHubMix, PipeLLM, 302.AI, Ollama, LM Studio…), paste a key, done. Custom vendors need a name and a base URL. magpie never diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index a0d5d41b2..fc7877896 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -40,6 +40,7 @@ backfilled; see [Gateway Session Aggregation](gateway-sessions.md). | Trace | The Routing view's record of each decision, written where the decision is made: candidates, rests, which try answered. `Route.Folder` is the folder the agent says it works in (`workDir`), its last two levels only (`shortFolder`, e.g. `workspace/magpie`), never the full path; a request that says none (a title, a topic check) takes its session's as said last (`trace.sessionFolder`), one without a session id has none (#1068). It is kept in the routing history on disk for as long as the route is (`history.go`: 30 days, 200 MB). The GUI shows it in By session's headings, a request row's tooltip, the stage's agent working in more than one folder, and the tray panel's agent tooltip. | [`trace.go`](../../internal/gateway/trace.go) | | Prompt | What each request's prompt held, part by part: the agent's system prompt, tool definitions (an MCP server's tools as one item), instruction files and skills, files its tools read, their other output, and the conversation. `inspectPrompt` reads it from the body as the agent sent it, before translation; `calibrated` scales the estimate to the prompt the vendor counted and sets the window of the model that answered. The route keeps names and sizes only, never the text, so the routing history on disk holds none. For the card's text (masaka on Discord), the trace keeps the last `promptBodies` (10) request bodies in memory only (at most 32 MiB each, 64 MiB together), masked as the vendor got them; for a model let have it unmasked, the masked copy is kept all the same. `PromptText` reads a part's items and their text from that body again (`prompt_text.go`), served to the GUI as `/api/context/text`; once a body is dropped, or magpie quits, its text is gone. It goes on the trace as `Route.Prompt`, with `Route.Conv` naming a conversation that has no session id. The GUI's `/api/context` scores each agent from it (`internal/gui/context.go`). 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 alone. A request goes to `/publishers/google/models/: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) | ## Codex titles, descriptions and predictions @@ -709,6 +710,7 @@ the row of the entry that id reaches, with its label, under the bare id. go test -tags nogui ./internal/gateway -run 'TestGroupAsksOneRestingMemberNotEach|TestLoneRestingMemberStillAsked|TestRetrievalGroupAsksOneRestingMember|TestProbeOne|TestLoop|TestLongReplyThatDoesNotLoop|TestQuiet|TestSilentHeld|TestRotateSpreadsSessions|TestRouting|TestSmartRouting|TestFallback|TestNoFallbackForOtherErrors|TestLastFallbackErrorReachesTheAgent|TestRateLimitedSinksToTheBack|TestGroupRateLimitedSinks|TestAffinity|TestSeveralKeysOnTakeOverFromEachOther|TestModelNotInPlanRestsTheModelNotTheKey|TestSubscriptionAccountsTakeOver|TestGroup|TestTrace|TestImageTool|TestCodexNoCredits|TestWindowCapsHoldTheAccount|TestAccountCap|TestClaudeGoesOnMessagesWhereTheRelayHasThem|TestAutoRelaysOnTheClientsOwnAPI|TestSearchOfferedStaysOnTheClientsAPI|TestSearchFollowsTheSearchersProxy|TestCodexSearchAnsweredOnResponses|TestAgentEffortOnCursorLocal|TestAzureCompactionWithoutMagpiesReasoning|TestCodexCompact|TestProtection|TestSearchedConversation|TestUnsearchedConversationUnchanged|TestNotAnAPIReply|TestAPIReplyUntouched|TestCodexBackendWebPage|TestSub2APIKeyLimitIsQuota|TestKeysWeighedByTheirWindows|TestGroupWeighsKeyWindows|TestKeyOutOfItsWindowRestsUntilReset|TestKeyPoolErrorDoesNotRestForWindow|TestKeyBackOnceItsWindowIsNotFull|TestRestingKeyReadAgainInAnOrderedGroup|TestClaudeAccountBackOnceItsWindowRenews|TestThinkingStreams|TestHeldThinkingKeepsTheAgentAlive|TestCodexHeardWithinItsIdleTimeout|TestRefusalAfterThinkingFailsOver|TestGeminiEmptyRepliesAskedAgain|TestLocalUnredacted|TestCORS|TestForeignPagesRefused|TestAIStudioThinking|TestGeminiThoughtsThroughLocalProxy|TestGeminiRefusedLevel|TestGeminiThinkingOffAtItsLowest|TestThinkingOff|TestTranslatedEffortLoggedAsSent|TestTranslatedThinkingOffRefused|TestSub2APIThinkingOffRefused|TestRefusesThinkingOff|TestClaudeFiveFiveThinkingOffOnTheWire|TestSamplingAsTheModelTakesIt|TestHaikuFiveFiveSamplingOnTheWire|TestGeminiThoughtsMarkedInExtraContent|TestGeminiThinkingLevelRefused|TestGeminiMinimalRefusedTwiceAtOnce|TestPassthroughGeminiMinimalRefused|TestPassthroughEffortNoneRefused|TestPassthroughMinimalRefusedNoneTaken|TestOtherOffNamed|TestClaudeSignInNotToldItsSignInFailed|TestSignInWriterReleasesA403|TestSignInBetaStaysWithMagpie|TestStructuredOutput|TestResponsesTextKeepsVerbosityBesideFormat|TestRefusedFormatToldInWords|RPM|TestQueued|TestCustomGeminiUpstream|TestWholeNums|TestGrokCalls|TestOnlyGrokCalls|TestGrokModel|TestGrokPluginCalls' go test -tags nogui ./internal/gateway -run 'TestMemberTooSmallIsNotAsked|TestConversationOutgrowingItsMemberMoves|TestRoomyLeavesWhatItCantJudge|TestPayloadTooLarge|TestOverflow|TestContextOverflow|TestRelayInputCap|TestEveryVendorsOverflow' go test -tags nogui ./internal/gateway -run 'TestVertex' +go test -tags nogui ./internal/gateway -run 'TestBedrock' go test -tags nogui ./internal/gateway -run 'TestPublicAddr|TestEditImageURL|TestPrivateDialer' go test -tags nogui ./internal/gateway ./internal/provider ./internal/cli ./internal/gui -run 'TestDisabled|TestModelDisableCmd' node --test internal/gui/tests/disabled-models.test.cjs diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index 4069dbeb2..751a23c41 100644 --- a/docs/subsystems/providers-accounts.md +++ b/docs/subsystems/providers-accounts.md @@ -30,6 +30,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi | Keys | Several keys per provider. Requests go to the first key that is on; the gateway moves on when it is out or rate limited. `Key` stays the first, so other code reads it as before. A key can be made for one protocol (`KeyProtocol`). A key made for a protocol its provider has no URL for is skipped (`perKeyBarred`); when every key is, the provider is still tried whole on the URLs it has, and the candidate carries `noURL` so it isn't quiet: Routing's row (`Weighed.NoURL`) says "key set to {api} only, no {api} URL · sent on the others", and the editor's key row shows a "No {api} URL" chip (`keyLacksURL`; #1702, `TestKeyForAProtocolWithNoURLIsSaid`, `key-nourl.test.cjs`). A key's value can be replaced in place (`ReplaceKey`, #1869: a key rotated at the vendor): it keeps its name, place, protocol, weight and on or off, and what was set for it by its fingerprint (`AccountModels`, `AccountProxies`, `AccountConcurrency`) and the gateway keys held to it (`access.ReplaceAccount`) move to the new one; the GUI's `keys/replace` also lifts its rests (`UnrestAll`). Its past requests stay under the old fingerprint, by the same name. A provider may hold thousands of keys (@NetRozee on X: a thousand froze magpie). Nothing goes over its keys once for each key: `KeysOn` drops a repeat by a set, a row's rest keys come from `RestKeys` (whether several are on, found once), and whether each key serves a model from `Serving`, which reads the lists once and keeps each model's keys as a set until the lists are read anew (`keyLists`). `KeysListed` and `ListsRead` count them for the tests (`TestProviderInfoListsKeysOnce`, `TestPerKeyReadsListsOnce`). A provider's keys have their balances, plans and remote limits read `keyReadsAtOnce` (8) at a time (`keySlots`); other providers' beside them. The editor's per-key proxy lines fold as its Accounts list does (`proxyLines`, `provider-many-keys-proxy.test.cjs`). Asking a key's models (`fetchPerKey`) still goes one key after another. | [`keys.go`](../../internal/provider/keys.go) | | Google Vertex AI | `google-vertex` (`VertexPreset`, `IsVertex`) is a provider of the user's own with no key. `Provider.Vertex` holds `project`, `location` (`global`, `us`, `eu` or a region; `global` when empty), `credentials` (a file; empty for Application Default Credentials) and `impersonate` (a service account's email). Save refuses a key given it, then normalizes them (`Normal`) and checks each (`check`); `normalize` clears the four URLs and any key put in `providers.json` by hand, which stands in for neither a token nor a project and leaves the provider as found savable, so the provider's one address is `vertexBase`, `https:///v1/projects//locations/`, its host following the location (`vertexHost`). It speaks Gemini alone (`Speaks`, `Base`). It is `Ready` once that address can be made, never from a key or an account; until then the app, `magpie providers` and the TUI say it needs a project, and `magpie provider ` says how to give it one. `hasEndpoint` counts it as a provider of the user's own, not a subscription's picks. An import link naming it is refused (`ParseImport`): its project and credentials are the user's own, which no link hands over. `Sign` refuses any other address and sets the bearer token before the user's `Headers`; `AuthHeaders` gives it no key header. Its models are its location's (`vertexModels`, in `planModels`): the preset has `NoList`, because Vertex AI has no list that says what a location serves. The lists are in the [reference](../reference.md#google-vertex-ai). | [`vertex.go`](../../internal/provider/vertex.go), [`provider.go`](../../internal/provider/provider.go), [`account.go`](../../internal/provider/account.go), [`rename.go`](../../internal/provider/rename.go), [`models.go`](../../internal/provider/models.go), [`importurl.go`](../../internal/provider/importurl.go) | | Vertex AI tokens | `vertexCredentialsFile` finds the credentials as Google's libraries find Application Default Credentials: the provider's `credentials`, else the file `GOOGLE_APPLICATION_CREDENTIALS` names, else `application_default_credentials.json` in gcloud's folder (`CLOUDSDK_CONFIG`, else `~/.config/gcloud`, `%APPDATA%\gcloud` on Windows); a `~/` that starts any of them is the home. `mint` reads three kinds: `authorized_user` (a refresh-token grant), `service_account` (an RS256 JWT, RFC 7523: `signed`) and gcloud's `impersonated_service_account`, whose `source_credentials` are minted and traded at IAM Credentials, along its `delegates`, for the account its `service_account_impersonation_url` names (`impersonationURL`: the token never goes to that URL's host). With `impersonate` set, the token those give is traded at IAM Credentials' `generateAccessToken` for a `cloud-platform` token of that account's, as gcloud's `--impersonate-service-account` does (`impersonateFor`); the credentials' account needs `roles/iam.serviceAccountTokenCreator` on it, which the 403 names. `vertexTokens` keeps one token per file and impersonated account, in memory only; requests made together mint it once, and those that waited through a mint that failed are given its error rather than each minting in turn (`mints`, `failed`). A mint cut short because its own request was given up on fails none of them: the next one mints. It is minted again within `vertexRefreshLead` (5 minutes) of expiry, or when the file's size or modification time has changed (gcloud signed in again). One mint, every exchange included, gets `vertexMintWait` (30 seconds). The file is only read. | [`vertex.go`](../../internal/provider/vertex.go), [`signin.go`](../../internal/provider/signin.go) | +| Amazon Bedrock Mantle | `bedrock-mantle` ("Amazon Bedrock (Mantle)", @marktoown on X) is a vendor preset beside the runtime's `bedrock`, with the same Bedrock API key and seventeen regions of its own (`mantleRegions`: the `bedrock-mantle.{region}.api.aws` hosts that answered on 2026-10-16). Chat completions and Responses are at `/v1`, Messages at `/anthropic`; unlike the runtime it lists its models (`GET /v1/models`; `NoList` stays the runtime's alone). Its OpenAI APIs serve each model under one of two prefixes: OpenAI's closed GPTs and xAI's Grok under `/openai/v1`, the rest under `/v1` (`MantleBase`, used by the gateway and the provider test's `tinyBody`). `IsBedrockMantle` is the preset or a provider added at a Mantle host (`mantleHost`), and `IsBedrock` includes it, so every Bedrock rule holds there too: Claude on Messages alone, the key as `x-api-key` alone, `max_completion_tokens`, no metadata, no Priority. A provider added at a Mantle address is given the APIs it wasn't (`mantleEndpoints`, in `normalize`), and a chat or Responses URL given at `/openai/v1` is moved to `/v1`, where the list is. | [`presets.go`](../../internal/provider/presets.go), [`provider.go`](../../internal/provider/provider.go), [`test.go`](../../internal/provider/test.go) | | Subscription accounts | `Accounts` reads the credentials each agent keeps on disk or in the macOS Keychain; nothing is stored twice. With account discovery off (#1535, below) none of them is read. A built-in that has moved to its plugin is dropped (`Moved`), and plugin accounts are placed in its slot (`placeMoved`). `Sign` adds the account's own auth, then the user's `Headers`. | [`account.go`](../../internal/provider/account.go) | | Token refresh | Each account refreshes through its vendor. For example, `codexToken` refreshes within 5 minutes of expiry and writes the rotated tokens back where it read them (`codexStore.write`: `~/.codex/auth.json`, or Codex's keychain item), every other field kept, for Codex CLI. Before refreshing a sign-in read from the keychain it asks the item again, so a rotation Codex made since isn't spent twice. A 400 or 401 from the vendor's refresh endpoint means it was refused (`refreshFailed`). | [`account.go`](../../internal/provider/account.go) | | Codex's credential store | Codex 0.162 keeps its ChatGPT sign-in where `cli_auth_credentials_store` in `$CODEX_HOME/config.toml` says (`codex-rs/login/src/auth/storage.rs`): `file` (default) is `auth.json`; `keyring` the system keychain alone; `auto` the keychain, else `auth.json`, on read and on save; `ephemeral` Codex's memory. Saved to the keychain, Codex removes `auth.json` (#2312, #2367, Dony2050). On macOS magpie reads that item through `security`, as it reads Claude Code's: service `Codex Auth`, account `cli|` + the first 16 hex digits of SHA-256 of the canonical CODEX_HOME (`codexKeychainAccount`), the value auth.json's JSON on one line. `readCodexLogin` is the one reader: `codexAccount`, `codexToken`, `liveLogin`, `CodexAPIKeySignedIn`, `codexLoginAuth`, the usage card's `codexUntil`, session identities and the agent's wiring (`provider.CodexSignIn`: `codexChatGPT`, `Agent.Source`) go through it. `keyring` with no item is signed out; `auto` with no item, or one the keychain wouldn't give, is `auth.json`, as Codex does. An item the keychain wouldn't give under `keyring` is not known (`codexStoreError`), never signed out. With `[features] secret_auth_storage` on (Codex's default on Windows) keyring and auto mean Codex's encrypted auth storage, which magpie doesn't read; nor does it read the Linux or Windows keychain. There `keyring` and `ephemeral` are not known, `auto` is `auth.json` when Codex left one, and the saved accounts' reason says to set `file` (`codexSignedOutWhy`). Requirements an admin manages (`requirements.cli_auth_credentials_store`) aren't read. Reading the secret can put up to two macOS prompts in front of the user, who may type their password, so one read per item is in flight at a time and waits up to 2 minutes for them (`keychainAsk`, `askCodexKeychain`), outside the cache's lock. A reader waits at most 5s from when that ask started (`keychainHold`) and is otherwise told magpie is waiting for an answer (`errKeychainWaiting`); no request or page waits out the prompt. `security` exit 44 is no item; 51 (errSecAuthFailed) or 128 (errSecUserCanceled) is denied or cancelled (`errKeychainRefused`); the 2 minutes running out is no answer (`errKeychainNoAnswer`); anything else is `errKeychainUnread`. Each says so in the saved accounts' reason, and none of them is signed out. A read the keychain gave is kept while the item is unchanged: after 10s a reader asks only the item's modification date (`Stat`, `find-generic-password` without `-w`, which shows no prompt) and reads the secret again only when Codex or magpie changed it (#2367: with "Allow" once, background polls asked again every ~30s). A refusal or no answer is kept 10 minutes (#2408). magpie's own writes (`codexStore.write`, `keepCodexKeychain`) keep the date of what they wrote; a switch, sign-out or refresh forgets a read (`forgetCodexKeychain`) so the next one checks the date, but keeps a refusal; switching and refreshing read afresh. Beside a refusal, no answer or waiting, the saved accounts' line has Try again (`Exclusion.Retry`, `keychain-retry`, `RetryCodexKeychain`), which reads once past the refusal, and the reason says "Always Allow" lets `/usr/bin/security` read the item, so macOS stops asking each time Codex changes it. A switch or a first sign-in (`saveCodexLogin`) writes the store Codex reads, and refuses when that store couldn't be read, when config.toml doesn't parse, or when it is one magpie doesn't read; it leaves an `auth.json` beside the item to Codex. Signing the last account out (`deleteCodexLogin`) removes the item, then `auth.json`, as `codex logout`. Not tried against an item Codex itself wrote: macOS may ask whether magpie can read it, and Codex whether it can read one magpie rewrote. | [`codex_store.go`](../../internal/provider/codex_store.go), [`codex_store_test.go`](../../internal/provider/codex_store_test.go), [`codex_keychain_ask_unix_test.go`](../../internal/provider/codex_keychain_ask_unix_test.go) | @@ -242,7 +243,7 @@ node --test internal/gui/tests/account-alias.test.cjs go test -tags nogui . -run TestAccountCapCmd node --test internal/gui/tests/account-cap.test.cjs internal/gui/tests/window-cap.test.cjs go test -tags nogui ./internal/provider -run 'TestRemoteMagpie' -go test -tags nogui ./internal/provider -run 'TestVolc|TestQianfan|TestBedrock|TestAddCopy|TestBackupBalanceToken' +go test -tags nogui ./internal/provider -run 'TestVolc|TestQianfan|TestBedrock|TestMantleBase|TestAddCopy|TestBackupBalanceToken' go test -tags nogui ./internal/gui -run TestProviderSaveKeepsVolcengineSecret go test -tags nogui ./internal/provider -run 'TestTC3|TestTencent' go test -tags nogui ./internal/gui -run TestProviderListTellsTencentAccessKey diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index c8beacd8e..55e274e12 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -3623,6 +3623,9 @@ func markAntigravityRefused(w http.ResponseWriter, p provider.Provider, system, // 403 or 400 it can mend (Provider.Retry) is asked again, a few times at most. func (s *Server) forward(ctx context.Context, p provider.Provider, to provider.Protocol, path string, body []byte, in http.Header) (*http.Response, error) { res, err := s.forwardOnce(ctx, p, to, path, body, in) + if err == nil && mantleRoutes(p, to) { + res, err = s.mantleReroute(ctx, p, to, path, body, in, res) + } if err == nil && (res.StatusCode == http.StatusForbidden || res.StatusCode == http.StatusBadRequest) && p.Retries() { // an account that can mend what the refusal names (a Factory org // the server won't take; a model Copilot's Auto picked that the @@ -3729,6 +3732,12 @@ func (s *Server) forwardOnce(ctx context.Context, p provider.Provider, to provid // Zen's free tier answers at the inference API's URL alone (zenfree.go) base = provider.OpenCodeFreeURL(base) } + if mantleRoutes(p, to) { + // Bedrock Mantle serves each model under /v1 or /openai/v1 + // (mantle.go) + m := gjson.GetBytes(body, "model").String() + base = provider.MantleBase(base, m, !s.fits(p.ID, mantleRouteKey(m), to)) + } req, err := http.NewRequestWithContext(ctx, http.MethodPost, base+path, bytes.NewReader(body)) if err != nil { return nil, err diff --git a/internal/gateway/mantle.go b/internal/gateway/mantle.go new file mode 100644 index 000000000..e0bb10204 --- /dev/null +++ b/internal/gateway/mantle.go @@ -0,0 +1,73 @@ +package gateway + +import ( + "bytes" + "context" + "io" + "net/http" + "regexp" + + "github.com/tidwall/gjson" + + "github.com/yetone/magpie/internal/provider" +) + +// Amazon Bedrock's Mantle endpoint (@marktoown on X) serves its OpenAI APIs +// under two prefixes, each model at one: most at /v1, OpenAI's closed GPT +// models and xAI's Grok at /openai/v1, as each model's card says. A model +// asked at the other is turned away with "model `x` isn't supported on +// this route". provider.MantleBase picks the prefix by the model's id; +// a model it guessed wrong (a maker the rule doesn't know yet) is asked +// again at the other one, and from then on there. + +// mantleRoutes is whether a request of p's on to is placed by MantleBase: +// Mantle's chat completions and Responses. Its Messages are at /anthropic +// alone. +func mantleRoutes(p provider.Provider, to provider.Protocol) bool { + return (to == provider.Chat || to == provider.Responses) && p.IsBedrockMantle() +} + +// mantleRouteKey is how unfit remembers that Mantle serves model at the +// prefix MantleBase doesn't guess for it. +func mantleRouteKey(model string) string { return "mantle-route:" + model } + +// mantleWrongRoute is Mantle's refusal of a model asked at the prefix that +// doesn't serve it. +var mantleWrongRoute = regexp.MustCompile(`(?i)(?:isn't|is not|not) supported on this route`) + +// mantleReroute asks a request Mantle refused for its route again at the +// other prefix, once, and remembers that prefix for the model when it is +// taken there. Any other answer is given back as it came. +func (s *Server) mantleReroute(ctx context.Context, p provider.Provider, to provider.Protocol, path string, body []byte, in http.Header, res *http.Response) (*http.Response, error) { + model := gjson.GetBytes(body, "model").String() + if res.StatusCode < 400 || res.StatusCode >= 500 || model == "" || !s.fits(p.ID, mantleRouteKey(model), to) { + return res, nil + } + b, _ := io.ReadAll(io.LimitReader(res.Body, 1<<20)) + res.Body.Close() + res.Body = io.NopCloser(bytes.NewReader(b)) + if !mantleWrongRoute.Match(b) { + return res, nil + } + s.markUnfit(p.ID, mantleRouteKey(model), to) + again, err := s.forwardOnce(ctx, p, to, path, body, in) + if err == nil && again.StatusCode < 400 { + return again, nil + } + var ab []byte + if err == nil { + ab, _ = io.ReadAll(io.LimitReader(again.Body, 1<<20)) + again.Body.Close() + again.Body = io.NopCloser(bytes.NewReader(ab)) + } + if err == nil && !mantleWrongRoute.Match(ab) { + // served there, and refused for something else: that answer + return again, nil + } + // served at neither prefix (a model this account or region hasn't): + // the guess stays, and the client gets the first refusal + s.mu.Lock() + delete(s.unfit, p.ID+"\x00"+mantleRouteKey(model)+"\x00"+string(to)) + s.mu.Unlock() + return res, nil +} diff --git a/internal/gateway/mantle_test.go b/internal/gateway/mantle_test.go new file mode 100644 index 000000000..1f6c03c43 --- /dev/null +++ b/internal/gateway/mantle_test.go @@ -0,0 +1,193 @@ +package gateway + +import ( + "encoding/json" + "io" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// mantle plays Bedrock's Mantle endpoint (@marktoown on X): Anthropic's +// Messages under /anthropic, and its OpenAI APIs under two prefixes, each +// model at one of them: those in openai at /openai/v1, the rest at /v1. A +// model asked at the other prefix, or one it serves at neither (none), is +// refused as Mantle refuses it. +type mantle struct { + openai, none map[string]bool + mu sync.Mutex + calls []bedrockCall +} + +func (b *mantle) ServeHTTP(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(r.Body) + var m map[string]any + json.Unmarshal(body, &m) + model, _ := m["model"].(string) + b.mu.Lock() + b.calls = append(b.calls, bedrockCall{r.URL.Path, r.Header.Clone(), model, m}) + b.mu.Unlock() + if r.URL.Path == "/anthropic/v1/messages" { + w.Header().Set("Content-Type", "text/event-stream") + io.WriteString(w, sse( + `event: message_start`+"\n"+`data: {"type":"message_start","message":{"id":"msg_1","model":"`+model+`","usage":{"input_tokens":5}}}`, + `data: {"type":"content_block_start","index":0,"content_block":{"type":"text","text":""}}`, + `data: {"type":"content_block_delta","index":0,"delta":{"type":"text_delta","text":"from claude"}}`, + `data: {"type":"content_block_stop","index":0}`, + `data: {"type":"message_delta","delta":{"stop_reason":"end_turn"},"usage":{"output_tokens":2}}`, + `data: {"type":"message_stop"}`)) + return + } + rest, openai := strings.CutPrefix(r.URL.Path, "/openai/v1/") + if !openai { + var ok bool + if rest, ok = strings.CutPrefix(r.URL.Path, "/v1/"); !ok { + w.WriteHeader(http.StatusNotFound) + return + } + } + if b.none[model] || b.openai[model] != openai { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusBadRequest) + io.WriteString(w, `{"error":{"code":"model_not_supported","message":"model `+"`"+model+"`"+` isn't supported on this route","param":"model","type":"invalid_request_error"}}`) + return + } + w.Header().Set("Content-Type", "text/event-stream") + switch rest { + case "chat/completions": + io.WriteString(w, sse( + `data: {"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":"from chat"}}]}`, + `data: {"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}],"usage":{"prompt_tokens":5,"completion_tokens":2}}`, + `data: [DONE]`)) + case "responses": + io.WriteString(w, sse( + `data: {"type":"response.created","response":{"id":"r1","status":"in_progress"}}`, + `data: {"type":"response.output_item.added","output_index":0,"item":{"type":"message","id":"m1","role":"assistant","content":[]}}`, + `data: {"type":"response.output_text.delta","output_index":0,"content_index":0,"item_id":"m1","delta":"from responses"}`, + `data: {"type":"response.output_item.done","output_index":0,"item":{"type":"message","id":"m1","role":"assistant","content":[{"type":"output_text","text":"from responses"}]}}`, + `data: {"type":"response.completed","response":{"id":"r1","status":"completed","usage":{"input_tokens":5,"output_tokens":2}}}`)) + default: + w.WriteHeader(http.StatusNotFound) + } +} + +// paths is where the requests since the n-th were asked. +func (b *mantle) paths(n int) []string { + b.mu.Lock() + defer b.mu.Unlock() + var out []string + for _, c := range b.calls[n:] { + out = append(out, c.path) + } + return out +} + +func (b *mantle) count() int { + b.mu.Lock() + defer b.mu.Unlock() + return len(b.calls) +} + +// The Mantle preset at a fake Mantle: each model is asked at the prefix +// that serves it (gpt-oss at /v1, OpenAI's closed GPTs at /openai/v1), +// Claude at /anthropic with the key as x-api-key and without metadata, as +// on Bedrock's runtime. A model whose prefix the id doesn't tell is asked +// again at the other when Mantle refuses it for its route, and from then +// on there; one served at neither gets Mantle's refusal, and is guessed +// again next time. +func TestBedrockMantleRoutes(t *testing.T) { + fresh(t) + up := &mantle{ + openai: map[string]bool{"openai.gpt-5.5": true, "newmaker.model-1": true}, + none: map[string]bool{"ghost.model-1": true}, + } + srv := httptest.NewServer(up) + t.Cleanup(srv.Close) + p, err := provider.FromPreset("bedrock-mantle") + if err != nil { + t.Fatal(err) + } + p.Key = "ABSK-test" + p.Chat, p.Responses, p.Anthropic = srv.URL+"/v1", srv.URL+"/v1", srv.URL+"/anthropic" + p.Models = []string{"anthropic.claude-opus-4-7", "openai.gpt-oss-120b", "openai.gpt-5.5", "newmaker.model-1", "ghost.model-1"} + if err := provider.Save(p); err != nil { + t.Fatal(err) + } + h := New().Handler() // one gateway: what it learns is kept between requests + ask := func(path, body string) (int, string) { + t.Helper() + rec := httptest.NewRecorder() + h.ServeHTTP(rec, httptest.NewRequest("POST", path, strings.NewReader(body))) + return rec.Code, rec.Body.String() + } + chat := func(model string) string { + return `{"model":"bedrock-mantle/` + model + `","max_tokens":20,"stream":true,"messages":[{"role":"user","content":"hi"}]}` + } + same := func(got []string, want ...string) bool { + return strings.Join(got, " ") == strings.Join(want, " ") + } + + n := up.count() + if code, body := ask("/v1/chat/completions", chat("openai.gpt-oss-120b")); code != 200 || !strings.Contains(body, "from chat") { + t.Fatalf("gpt-oss: %d %s", code, body) + } + if got := up.paths(n); !same(got, "/v1/chat/completions") { + t.Fatalf("gpt-oss asked at %v", got) + } + if c := up.calls[n]; c.head.Get("Authorization") != "Bearer ABSK-test" || c.body["max_completion_tokens"] != float64(20) { + t.Fatalf("gpt-oss: %v %v", c.head, c.body) + } + + n = up.count() + if code, body := ask("/v1/responses", `{"model":"bedrock-mantle/openai.gpt-5.5","stream":true,"input":[{"role":"user","content":[{"type":"input_text","text":"hi"}]}]}`); code != 200 || !strings.Contains(body, "from responses") { + t.Fatalf("gpt-5.5: %d %s", code, body) + } + if got := up.paths(n); !same(got, "/openai/v1/responses") { + t.Fatalf("gpt-5.5 asked at %v", got) + } + + n = up.count() + if code, body := ask("/v1/messages", `{"model":"bedrock-mantle/anthropic.claude-opus-4-7","max_tokens":20,"stream":true,"metadata":{"user_id":"{\"device_id\":\"d\"}"},"messages":[{"role":"user","content":"hi"}]}`); code != 200 || !strings.Contains(body, "from claude") { + t.Fatalf("claude: %d %s", code, body) + } + if got := up.paths(n); !same(got, "/anthropic/v1/messages") { + t.Fatalf("claude asked at %v", got) + } + if c := up.calls[n]; c.head.Get("x-api-key") != "ABSK-test" || c.head.Get("Authorization") != "" || c.body["metadata"] != nil { + t.Fatalf("claude: %v %v", c.head, c.body) + } + + // a maker the rule doesn't know, served at /openai/v1: asked there + // again, and remembered + n = up.count() + if code, body := ask("/v1/chat/completions", chat("newmaker.model-1")); code != 200 || !strings.Contains(body, "from chat") { + t.Fatalf("newmaker: %d %s", code, body) + } + if got := up.paths(n); !same(got, "/v1/chat/completions", "/openai/v1/chat/completions") { + t.Fatalf("newmaker asked at %v", got) + } + n = up.count() + if code, body := ask("/v1/chat/completions", chat("newmaker.model-1")); code != 200 || !strings.Contains(body, "from chat") { + t.Fatalf("newmaker again: %d %s", code, body) + } + if got := up.paths(n); !same(got, "/openai/v1/chat/completions") { + t.Fatalf("newmaker not remembered: %v", got) + } + + // served at neither: Mantle's refusal for its route, and nothing + // learned from it + for range 2 { + n = up.count() + code, body := ask("/v1/chat/completions", chat("ghost.model-1")) + if code != 400 || !strings.Contains(body, "isn't supported on this route") { + t.Fatalf("ghost: %d %s", code, body) + } + if got := up.paths(n); len(got) < 2 || got[0] != "/v1/chat/completions" || got[1] != "/openai/v1/chat/completions" { + t.Fatalf("ghost asked at %v", got) + } + } +} diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 11430a079..ddb7561f9 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -9215,8 +9215,8 @@ function drawEditor(p, presetID) { // which header the key goes in on a third-party Anthropic API: both by // default, one alone for a service that refuses the two together (Aloha // on Discord: "x-api-key 和 Authorization 不可以同时存在"), which magpie - // also learns from that refusal. Anthropic's, Bedrock's and Azure's own - // APIs take x-api-key alone already + // also learns from that refusal. Anthropic's, Bedrock's (its runtime and + // its Mantle endpoint) and Azure's own APIs take x-api-key alone already const twoKeyHeaders = () => { if (p?.account || vertex) return false; if (p && !custom) return !!p.bothAuth; @@ -9224,7 +9224,7 @@ function drawEditor(p, presetID) { if (!a) return false; let host = ""; try { host = new URL(/^[a-z]+:\/\//i.test(a) ? a : "https://" + a).hostname.toLowerCase(); } catch { return true; } - return !host.endsWith("anthropic.com") && !/^bedrock-runtime\..*\.amazonaws\.com$/.test(host) && !host.endsWith(".azure.com"); + return !host.endsWith("anthropic.com") && !/^bedrock-runtime\..*\.amazonaws\.com$/.test(host) && !/^bedrock-mantle\..*\.api\.aws$/.test(host) && !host.endsWith(".azure.com"); }; if (!p?.account && !vertex) { const seg = segs([["", t("Both")], ["x-api-key", "x-api-key"], ["bearer", "Authorization: Bearer"]], draft.authHeader || "", (v) => { draft.authHeader = v; }); @@ -9383,7 +9383,8 @@ function drawEditor(p, presetID) { // are served at their own: one selector, and the provider's base URLs follow it let refreshEndpoints = () => {}, onRegion = () => {}; if (pr?.regions?.length) { - // Bedrock's ten regions don't fit the editor's width: they scroll + // Bedrock's ten regions (Mantle's seventeen) don't fit the editor's + // width: they scroll const seg = el("div", "segs regions"); const cur = regionAt(pr, draft) || pr.regions.find((r) => r.decide && (r.id === draft.region || (!draft.region && workspaceOf(r.decide, draft.decide ?? p?.decide ?? pr.decide) !== null))) || pr.regions[0]; for (const r of pr.regions) { diff --git a/internal/gui/tests/provider-auth-header.test.cjs b/internal/gui/tests/provider-auth-header.test.cjs index 6fb77fc58..252e3c99f 100644 --- a/internal/gui/tests/provider-auth-header.test.cjs +++ b/internal/gui/tests/provider-auth-header.test.cjs @@ -3,8 +3,9 @@ // answering 401 "x-api-key 和 Authorization 不可以同时存在"): the editor has a // Key header row, Both, x-api-key or Authorization: Bearer, opening as it // was saved or learned; Save posts the pick. A relay with only a Chat -// address has no row until an Anthropic one is typed. Anthropic's own API -// (bothAuth false) and a signed-in account have none. In English and +// address has no row until an Anthropic one is typed, and none for +// Anthropic's own or Bedrock Mantle's. Anthropic's own API (bothAuth false) +// and a signed-in account have none. In English and // Chinese, and at a phone's width. const assert = require("node:assert/strict"); const fs = require("node:fs/promises"); @@ -138,6 +139,10 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.equal(await seg(page).isVisible(), true, "the row comes with an Anthropic address"); await url.fill("https://api.anthropic.com"); assert.equal(await seg(page).isVisible(), false, "Anthropic's own takes x-api-key alone"); + await url.fill("https://relay.example.com"); + assert.equal(await seg(page).isVisible(), true); + await url.fill("https://bedrock-mantle.us-east-1.api.aws/anthropic"); + assert.equal(await seg(page).isVisible(), false, "Bedrock Mantle's takes x-api-key alone (@marktoown on X)"); await url.fill(""); const saved = await save(page, posts); assert.equal("authHeader" in saved.body, false, "not said with no Anthropic address"); diff --git a/internal/provider/bedrock_mantle_test.go b/internal/provider/bedrock_mantle_test.go new file mode 100644 index 000000000..79433fc89 --- /dev/null +++ b/internal/provider/bedrock_mantle_test.go @@ -0,0 +1,154 @@ +package provider + +import ( + "slices" + "testing" +) + +// Amazon Bedrock's Mantle endpoint (@marktoown on X): its own preset, its +// own regions, its models listed, and a provider added at a Mantle address +// taken for Bedrock's too. +func TestBedrockMantlePreset(t *testing.T) { + t.Setenv("HOME", t.TempDir()) + t.Setenv("USERPROFILE", t.TempDir()) + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + t.Setenv("XDG_CACHE_HOME", t.TempDir()) + p, err := FromPreset("bedrock-mantle") + if err != nil { + t.Fatal(err) + } + if p.Chat != "https://bedrock-mantle.us-east-1.api.aws/v1" || p.Responses != p.Chat || + p.Anthropic != "https://bedrock-mantle.us-east-1.api.aws/anthropic" { + t.Fatalf("endpoints: %q %q %q", p.Chat, p.Responses, p.Anthropic) + } + if !p.IsBedrock() || !p.IsBedrockMantle() || p.Icon != "bedrock-color" { + t.Fatalf("not taken for Bedrock Mantle: %+v", p) + } + pr := Preset("bedrock-mantle") + if pr.NoList || len(pr.Models) != 0 || !p.lists() { + t.Fatalf("Mantle lists its models at /v1/models: NoList %v, models %v", pr.NoList, pr.Models) + } + if pr.Regions[0].Chat != pr.Chat || pr.Regions[0].Anthropic != pr.Anthropic { + t.Fatalf("the first region isn't the default: %+v", pr.Regions[0]) + } + i := slices.IndexFunc(pr.Regions, func(r Region) bool { return r.ID == "ap-southeast-1" }) + if i < 0 || pr.Regions[i].Chat != "https://bedrock-mantle.ap-southeast-1.api.aws/v1" || + pr.Regions[i].Responses != pr.Regions[i].Chat || + pr.Regions[i].Anthropic != "https://bedrock-mantle.ap-southeast-1.api.aws/anthropic" { + t.Fatalf("Singapore: %+v", pr.Regions) + } + // eu-west-3 has no Mantle host (it didn't resolve on 2026-10-16) + if slices.ContainsFunc(pr.Regions, func(r Region) bool { return r.ID == "eu-west-3" }) { + t.Fatalf("a region without Mantle: %+v", pr.Regions) + } + // the runtime's preset is left as it was + if rt := Preset("bedrock"); !rt.NoList { + t.Fatal("the runtime preset lists now") + } + rt, _ := FromPreset("bedrock") + if rt.IsBedrockMantle() { + t.Fatal("the runtime taken for Mantle") + } + + // Claude on Messages alone; OpenAI's GPTs on Responses and chat; + // the rest on chat + for model, want := range map[string][]Protocol{ + "anthropic.claude-opus-4-7": {Anthropic}, + "openai.gpt-5.5": {Responses, Chat}, + "openai.gpt-oss-120b": {Chat}, + "google.gemma-3-27b-it": {Chat}, + } { + if got := p.APIs(model); !slices.Equal(got, want) { + t.Errorf("%s: APIs %v, want %v", model, got, want) + } + } + // the key as x-api-key alone, as Mantle's own examples send it + p.Key = "ABSK-test" + if h := AuthHeaders(p, Anthropic); len(h) != 1 || h["x-api-key"] != "ABSK-test" { + t.Errorf("Messages headers: %v", h) + } + + // a model's test request is asked at the prefix that serves it + for _, tc := range []struct { + proto Protocol + model, url string + }{ + {Chat, "openai.gpt-oss-120b", "https://bedrock-mantle.us-east-1.api.aws/v1/chat/completions"}, + {Chat, "openai.gpt-5.5", "https://bedrock-mantle.us-east-1.api.aws/openai/v1/chat/completions"}, + {Responses, "openai.gpt-5.5", "https://bedrock-mantle.us-east-1.api.aws/openai/v1/responses"}, + {Responses, "xai.grok-4.3", "https://bedrock-mantle.us-east-1.api.aws/openai/v1/responses"}, + {Anthropic, "anthropic.claude-opus-4-7", "https://bedrock-mantle.us-east-1.api.aws/anthropic/v1/messages"}, + } { + if u, _ := tinyBody(p, tc.proto, tc.model); u != tc.url { + t.Errorf("%s on %s: %s, want %s", tc.model, tc.proto, u, tc.url) + } + } +} + +// A provider added by its address at a Mantle host is Mantle's: Bedrock's +// quirks, and the APIs it wasn't given filled in. +func TestBedrockMantleByAddress(t *testing.T) { + for _, tc := range []struct { + name string + in Provider + chat, resp, messages string + }{ + {"chat at /v1", Provider{ID: "m", Chat: "https://bedrock-mantle.eu-west-1.api.aws/v1"}, + "https://bedrock-mantle.eu-west-1.api.aws/v1", "https://bedrock-mantle.eu-west-1.api.aws/v1", "https://bedrock-mantle.eu-west-1.api.aws/anthropic"}, + {"chat at /openai/v1", Provider{ID: "m", Chat: "https://bedrock-mantle.eu-west-1.api.aws/openai/v1/"}, + "https://bedrock-mantle.eu-west-1.api.aws/v1", "https://bedrock-mantle.eu-west-1.api.aws/v1", "https://bedrock-mantle.eu-west-1.api.aws/anthropic"}, + {"messages alone", Provider{ID: "m", Anthropic: "https://bedrock-mantle.us-west-2.api.aws/anthropic"}, + "https://bedrock-mantle.us-west-2.api.aws/v1", "https://bedrock-mantle.us-west-2.api.aws/v1", "https://bedrock-mantle.us-west-2.api.aws/anthropic"}, + } { + t.Run(tc.name, func(t *testing.T) { + p := normalize(tc.in) + if !p.IsBedrock() || !p.IsBedrockMantle() { + t.Fatalf("not taken for Mantle: %+v", p) + } + if p.Chat != tc.chat || p.Responses != tc.resp || p.Anthropic != tc.messages { + t.Fatalf("endpoints: %q %q %q", p.Chat, p.Responses, p.Anthropic) + } + }) + } + for _, other := range []Provider{ + {ID: "o", Chat: "https://bedrock-mantle.example.com/v1"}, + {ID: "o", Chat: "https://api.aws/v1"}, + {ID: "o", Chat: "https://relay.example.com/bedrock-mantle.us-east-1.api.aws/v1"}, + } { + if p := normalize(other); p.IsBedrockMantle() || p.IsBedrock() || p.Anthropic != "" { + t.Errorf("%s taken for Mantle: %+v", other.Chat, p) + } + } + // another preset at a Mantle address keeps its own APIs + if p := normalize(Provider{ID: "c", Preset: "openrouter", Chat: "https://bedrock-mantle.us-east-1.api.aws/v1"}); p.Anthropic != "" { + t.Errorf("filled in for another preset: %+v", p) + } +} + +// Mantle serves each OpenAI-style model at one of two prefixes: OpenAI's +// closed GPTs and xAI's Grok at /openai/v1, every other at /v1. +func TestMantleBase(t *testing.T) { + const v1, oa = "https://bedrock-mantle.us-east-1.api.aws/v1", "https://bedrock-mantle.us-east-1.api.aws/openai/v1" + for _, tc := range []struct { + base, model string + other bool + want string + }{ + {v1, "openai.gpt-oss-120b", false, v1}, + {v1, "google.gemma-3-27b-it", false, v1}, + {v1, "openai.gpt-5.5", false, oa}, + {v1, "openai.gpt-6-sol", false, oa}, + {v1, "xai.grok-4.3", false, oa}, + {oa, "openai.gpt-oss-120b", false, v1}, + {oa + "/", "xai.grok-4.3", false, oa}, + // learned to be at the other one + {v1, "newmaker.model-1", true, oa}, + {v1, "openai.gpt-5.5", true, v1}, + // a URL the user typed some other way is theirs + {"https://proxy.example.com/mantle", "openai.gpt-5.5", false, "https://proxy.example.com/mantle"}, + } { + if got := MantleBase(tc.base, tc.model, tc.other); got != tc.want { + t.Errorf("MantleBase(%q, %q, %v) = %q, want %q", tc.base, tc.model, tc.other, got, tc.want) + } + } +} diff --git a/internal/provider/presets.go b/internal/provider/presets.go index a2d841dff..25ca6b3a4 100644 --- a/internal/provider/presets.go +++ b/internal/provider/presets.go @@ -388,6 +388,23 @@ var presets = []PresetDef{ "global.openai.gpt-6-astra", "global.openai.gpt-6-sol", "global.openai.gpt-6-luna", "openai.gpt-oss-120b-1:0", "openai.gpt-oss-20b-1:0", "qwen.qwen3-coder-480b-a35b-v1:0", "deepseek.v3.2", "moonshotai.kimi-k2.5", "zai.glm-5", "minimax.minimax-m2.5"}}, + // Amazon Bedrock's Mantle endpoint (@marktoown on X), with the same + // Bedrock API key: OpenAI's chat completions and Responses at /v1 (some + // models at /openai/v1, which the gateway picks per model: MantleBase) + // and Anthropic's Messages at /anthropic/v1/messages, in-region model + // ids alone (anthropic.claude-sonnet-5, openai.gpt-oss-120b; no + // global. or us. profiles). Unlike the runtime it lists its models at + // /v1/models, so the list is the account's own, Mantle-only models + // among them (Claude Mythos 5, GPT-5.5, Gemma 4, Grok 4.3). The regions + // are the commercial ones whose bedrock-mantle host answered on + // 2026-10-16; the runtime's eu-west-3 has none. + {ID: "bedrock-mantle", Name: "Amazon Bedrock (Mantle)", Short: "Bedrock Mantle", Icon: "bedrock-color", Kind: KindVendor, Hosts: true, + Chat: mantleOpenAIBase("us-east-1"), Responses: mantleOpenAIBase("us-east-1"), Anthropic: mantleAnthropic("us-east-1"), + Note: "Bedrock API key", + Website: "https://docs.aws.amazon.com/bedrock/latest/userguide/endpoints.html", KeysURL: "https://console.aws.amazon.com/bedrock/home#/api-keys", + Regions: mantleRegions("us-east-1", "us-east-2", "us-west-2", "eu-central-1", "eu-central-2", "eu-north-1", "eu-south-1", + "eu-west-1", "eu-west-2", "ap-northeast-1", "ap-northeast-2", "ap-south-1", "ap-southeast-1", "ap-southeast-2", + "ap-southeast-3", "ap-southeast-4", "sa-east-1")}, // Azure OpenAI, at the user's own resource (azure.go): its v1 API under // /openai/v1 for chat completions and Responses, the key in api-key, // its deployments' names as the model ids. It hosts other makers' @@ -601,6 +618,27 @@ func bedrockRegions(ids ...string) []Region { return out } +// mantleOpenAIBase is Mantle's base for chat completions and Responses +// in region: /v1, where most of its models are served. +func mantleOpenAIBase(region string) string { + return "https://bedrock-mantle." + region + ".api.aws/v1" +} + +// mantleAnthropic is Mantle's base the gateway's /v1/messages goes on. +func mantleAnthropic(region string) string { + return "https://bedrock-mantle." + region + ".api.aws/anthropic" +} + +// mantleRegions are Mantle's regions, named by their codes as +// bedrockRegions' are. +func mantleRegions(ids ...string) []Region { + out := make([]Region, len(ids)) + for i, id := range ids { + out[i] = Region{ID: id, Name: id, Chat: mantleOpenAIBase(id), Responses: mantleOpenAIBase(id), Anthropic: mantleAnthropic(id)} + } + return out +} + // Presets lists every preset, sponsored ones first within their kind. func Presets() []PresetDef { out := make([]PresetDef, 0, len(presets)) diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 9bd2395ce..71bf62633 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -15,6 +15,7 @@ import ( "fmt" "maps" "net" + "net/url" "os" "path/filepath" "regexp" @@ -1266,6 +1267,8 @@ func normalize(p Provider) Provider { p.azureEndpoints() // OpenCode Zen's or Go's other APIs, beside the one it was given (#1215) p.openCodeEndpoints() + // Bedrock Mantle's other APIs, beside the one it was given + p.mantleEndpoints() // a preset's provider keeps its headers too: the preset gives the // endpoints and catalog, the headers say which workspace or app it is p.Headers = cleanHeaders(p.Headers) @@ -1569,16 +1572,93 @@ func (p Provider) IsOpenCode() bool { return OpenCodeURL("//" + p.Host()) // its port, if it names one, aside } -// IsBedrock reports whether the provider is Amazon Bedrock's runtime: made -// from its preset, or at its host. +// IsBedrock reports whether the provider is Amazon Bedrock: its runtime +// (bedrock-runtime.{region}.amazonaws.com) or its Mantle endpoint +// (bedrock-mantle.{region}.api.aws), made from either's preset or at +// either's host. The two take the same Bedrock API key and share what +// Bedrock asks of a request: x-api-key alone on Messages, its own names +// for Anthropic's betas, no metadata.user_id, max_completion_tokens on +// chat completions, Claude on Messages and OpenAI's GPT models on +// Responses first. What only the runtime does (no list of models) is the +// preset's; what only Mantle does is IsBedrockMantle's. func (p Provider) IsBedrock() bool { - if p.Preset == "bedrock" { + if p.Preset == "bedrock" || p.IsBedrockMantle() { return true } h := p.Host() return strings.HasPrefix(h, "bedrock-runtime.") && strings.HasSuffix(h, ".amazonaws.com") } +// IsBedrockMantle reports whether the provider is Amazon Bedrock's Mantle +// endpoint (@marktoown on X): made from its preset, or added by its +// address at bedrock-mantle.{region}.api.aws. +func (p Provider) IsBedrockMantle() bool { + return p.Preset == "bedrock-mantle" || mantleHost(p.Host()) +} + +// mantleHost is a host of Bedrock's Mantle endpoint. +func mantleHost(h string) bool { + return strings.HasPrefix(h, "bedrock-mantle.") && strings.HasSuffix(h, ".api.aws") +} + +// mantleOpenAI is a model Mantle serves on its OpenAI APIs under +// /openai/v1 rather than /v1, as the model's card says: OpenAI's closed +// GPT models (GPT-6 Sol, GPT-5.5) and xAI's Grok. gpt-oss, Gemma and the +// other open models are at /v1. Asked at the other one, Mantle answers +// "model `x` isn't supported on this route". +func mantleOpenAI(model string) bool { + return bedrockGPT(model) || strings.HasPrefix(strings.ToLower(model), "xai.") +} + +// MantleBase is the base a request for model goes to on Mantle's chat +// completions or Responses API, given a Mantle provider's base for it +// (IsBedrockMantle): one ending /v1 or /openai/v1 goes at whichever of the +// two serves the model, or at the other when other is set (the model was +// refused at the first, so the gateway learned its prefix). A base ending +// otherwise, one the user typed, is given back as it is. +func MantleBase(base, model string, other bool) string { + root, ok := strings.CutSuffix(strings.TrimRight(strings.TrimSpace(base), "/"), "/v1") + if !ok { + return base + } + root = strings.TrimSuffix(root, "/openai") + if mantleOpenAI(model) != other { + return root + "/openai/v1" + } + return root + "/v1" +} + +// mantleEndpoints fills in the APIs of Bedrock's Mantle endpoint a +// provider added by its address was saved without: chat completions and +// Responses at /v1, Messages at /anthropic, as the preset gives them. A +// chat or Responses URL given at /openai/v1 is moved to /v1, where Mantle +// lists its models (/openai/v1/models is 404); the gateway still asks each +// model at the prefix that serves it (MantleBase). Any other URL the user +// gave an API keeps it. +func (p *Provider) mantleEndpoints() { + if p.Preset != "" && p.Preset != "bedrock-mantle" { + return + } + root := "" + for _, b := range []string{p.Chat, p.Responses, p.Anthropic} { + if u, err := url.Parse(strings.TrimSpace(b)); err == nil && u.Scheme != "" && mantleHost(strings.ToLower(u.Hostname())) { + root = u.Scheme + "://" + u.Host + break + } + } + if root == "" { + return + } + for _, b := range []*string{&p.Chat, &p.Responses} { + if strings.TrimRight(strings.TrimSpace(*b), "/") == root+"/openai/v1" { + *b = root + "/v1" + } + } + p.Chat = cmp.Or(p.Chat, root+"/v1") + p.Responses = cmp.Or(p.Responses, p.Chat) + p.Anthropic = cmp.Or(p.Anthropic, root+"/anthropic") +} + // bedrockClaude is a Bedrock id of a Claude model: a model id // (anthropic.claude-opus-4-8) or an inference profile's // (apac.anthropic.claude-opus-5-5). diff --git a/internal/provider/test.go b/internal/provider/test.go index a000ee994..8c519eec1 100644 --- a/internal/provider/test.go +++ b/internal/provider/test.go @@ -171,15 +171,24 @@ func (p Provider) AsksDecideModels() bool { return p.Decides() && (v == ViaSystemOne || v == ViaVercel || v == ViaCloudflare) } +// mantleBase is base for model at the prefix Mantle serves it under +// (MantleBase), for a Mantle provider; base for any other. +func (p Provider) mantleBase(base, model string) string { + if !p.IsBedrockMantle() { + return base + } + return MantleBase(base, model, false) +} + func tinyBody(q Provider, proto Protocol, model string) (url, body string) { switch proto { case Chat: if q.IsBedrock() || q.IsAzure() { - return q.Chat + "/chat/completions", fmt.Sprintf(`{"model":%q,"messages":[{"role":"user","content":"hi"}],"max_completion_tokens":16}`, model) + return q.mantleBase(q.Chat, model) + "/chat/completions", fmt.Sprintf(`{"model":%q,"messages":[{"role":"user","content":"hi"}],"max_completion_tokens":16}`, model) } return q.Chat + "/chat/completions", fmt.Sprintf(`{"model":%q,"messages":[{"role":"user","content":"hi"}],"max_tokens":16}`, model) case Responses: - return q.Responses + "/responses", fmt.Sprintf(`{"model":%q,"input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"hi"}]}],"max_output_tokens":16}`, model) + return q.mantleBase(q.Responses, model) + "/responses", fmt.Sprintf(`{"model":%q,"input":[{"type":"message","role":"user","content":[{"type":"input_text","text":"hi"}]}],"max_output_tokens":16}`, model) case Anthropic: return q.Anthropic + "/v1/messages", fmt.Sprintf(`{"model":%q,"max_tokens":16,"messages":[{"role":"user","content":"hi"}]}`, model) case Gemini: