diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index ead91a792..79ec7aa81 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -306,6 +306,7 @@ recorded as a prediction failure (`noPrediction`). - A provider can be set never to be a fallback for another model (sonnnnnnnnnnnna on X: an agent on a local uncensored model whose server is down or out of KV room must not have its request sent on to Claude or Codex, whose vendor may ban the account for it). *Never a fallback* on a provider row's right-click (GUI `provider/standin`, `magpie provider set fallback-for-others=no`, `provider.SetNoStandIn`, `Provider.NoStandIn`, copied onto its accounts by `accountSettings`) has `standInsOut` leave out, in `planPaused` and `planGroup`, each of its keys and accounts planned after one of a provider not so set. It runs on the planned order before `restLast` and `sinkPlanned`, so a local model that failed and rests still counts as first; a provider request whose own provider is unmarked starts as seen, so one with nothing planned (its model off, every account capped) still keeps them out, and a fallback group's marked members, a marked fallback's unlisted accounts and `groupsAfter`'s groups go the same way. A request that goes first to a marked provider moves on to another marked one, or an unmarked one, as before; a group routed by weight (Smart, Cheapest) that weighs a marked member first sends it the request as the group's pick. The left-out rows carry `Weighed.StandIn` (and `Unlisted`), and the Routing page says why (`leftWhy`, `unlistedWord`); they don't count toward the cap, held or barred refusals. No classifier reads the request: the model that would judge it is the local one that is down, and any other would send the text somewhere the user didn't choose. `TestNoStandInTakesNoOtherModelsRequest`, `stand-in.test.cjs`. - Different failures are classified separately: out of credit, out of quota, rate limit and other errors rest for different lengths. A fix must not merge them into one bucket (see #873). - A refusal of where the request comes from (`regionWords`: Google's 400 "User location is not supported for the API use.", as Antigravity and Code Assist pass it on, and OpenAI's `unsupported_country_region_territory` / "Country, region, or territory not supported"; `regionRefused`) is the network's and the edge's the connection reached, not the account's. It rests no account and counts no failure (`restAfterMarked` returns `Rest.By` `off`, `Until` now), and the next try goes out on a new connection: `regionFresh` (in `upstreamTransport`, around each of its three transports, so under every request the gateway sends through `s.client`) reads the head of each failed reply, and when it matches it closes the transport's idle connections as the body closes and again before the next request (`pending`), so the HTTP/2 or keep-alive connection that drew the refusal isn't reused. The last candidate is asked again after `retryPause` (`passing`). Refused a second time for the same provider and model within a request (`regionAsked` in the serve loop), it is the place, not a connection: Google serves some models to no request from where the user is while the same account's other models answer (taoxiaoxin, #5182: Antigravity's gemini-3.8-flash refused, its Claude models answered). Then none of the provider's other accounts is asked that model (`notMates`), the last isn't asked again (`protected`), another provider or model left is, and the agent is told the vendor's words with `regionNote` (through `explained`, beside `Provider.Explain`): the vendor doesn't serve that model to requests from that region, it is no account's fault, other models may answer, and a proxy in a served region or another provider gets past it. So a refused model costs two asks a request, not one per account and retries. Before, every Antigravity account was asked on the one kept-alive connection, each refused the same and rested, and the agent got a 400, while a new connection answered 12 seconds on (#5182, ggdayup; `TestRegionRefusalDropsItsConnection`, `TestAntigravityRegionRefusalAsksTheNextOnANewConnection`, `TestAntigravityRegionRefusalAsksTheLastAgain`, `TestRegionRefusalRestsNoAccount`, `TestRegionRefusalOfTheModelEndsAfterOneMoreAsk`, `TestRegionNote`). Not covered: an HTTP/2 connection carrying another stream at that moment outlives the close until it is idle, and the close drops other vendors' idle connections too (one handshake each). A user whose region is refused gets the refusal after the one more ask, a moment later than before. +- OpenRouter's 403 for a free model it serves only to the agent apps it lists ("… is only available on agentic harnesses", routing step "Gate Free Endpoints by Agentic Harness"; `provider.HarnessOnly`) is about the app the request came from, not the key or the model. It rests nothing and counts no failure (`restAfterMarked` returns `Rest.By` `off`), and a group's next member is asked as after any 403. Read as the key's 403, it set every model of the OpenRouter key aside (Wade111999 on X; `TestOpenRouterHarnessOnlyRestsNothing`). `APIError` puts `HarnessOnlyHint` after the words, so a model test, magpie's own request and no listed app's, says why it was refused and that the model without `:free` has no such gate (`TestHarnessOnlyTestSaysWhy`). magpie never names an app it isn't. Not covered: whether OpenRouter takes an agent's request through magpie as that agent's, since agents send OpenRouter's attribution headers only to openrouter.ai itself. - One of Codex's own models on the backend path with no routing to do (`codexAccounts` false: one ChatGPT account, no usage cap, no key holds, nothing pinned, and the sign-in not known to be out of its allowance, `provider.CodexUsedUpKnown`, which routes the turn as `codex/` as a restarted Codex's goes) is relayed as Codex sent it, on Codex's own sign-in, its bytes and headers unchanged and its reply streamed as it comes (`codexUpstreamOn` with no account): routing was built for more than one account, and that path also keeps the turn's native compaction with the backend. Before, nothing was asked again on it, so an overload went straight to Codex, which doesn't retry the backend's `server_is_overloaded` itself (夜松云 on Discord). Now a transient overload (`codexBusy`: what `busy` calls busy, a 529, a 503 saying overloaded, the backend's in-stream `response.failed` with `server_is_overloaded` (#1418); never a 429, a usage limit, an edge's drop of the connection (`edgeSaidDrop`) or a reset (`codexReset`)) is asked again of the same account, the same body and headers, up to `lastRetries` times after `retryPause<` with the account left out of the candidates, `fallbacksOnly`, and the same keepalive carried in `handedOnKey`); without fallbacks Codex gets the last try's failure as the backend said it. The account out of its allowance goes on to the same fallbacks at once, after the credits retry and the automatic reset are looked at (`codexAccountOut`: a quota, credit or rate refusal, as a status or as a stream's failure before any reply, and a 403 `usage_not_included`; never a 401, which Codex renews its sign-in on). Before that, Codex was handed the 429 with its fallbacks unused (adorable_piglet on Discord, `TestCodexOneAccountSpentFallsBack`); with none set it still is (`TestCodexOneAccountSpentNoFallbackRelayed`). A routing group the user built with the model in it counts as one more fallback after the subscription's own (`provider.GroupsAfter` in `codexFallsBack`, and in serve for a turn handed on), so a group of the Codex subscription first and an API after it takes the spent turn (`TestCodexOneAccountSpentGoesToItsGroup`). Codex's auto-review, on `codex-auto-review`, which no group or fallback names, goes on where its conversation's own turns go (`codexReviewAfter`, from `codexLeads`): to the fallbacks and groups of the conversation's model, or to the magpie model it is on, as `codexFallsBack` and serve's `groupsAfter` add them (riverleaf88 on X, `TestCodexReviewSpentFollowsTheGroup`, `TestCodexReviewSpentFollowsMagpieModel`). Each try is a `HandedOn` usage record and a try in the trace. The reply's `x-codex-*` windows are kept as the sign-in's usage and a `usage_limit_reached` refusal has it read again at once (`heardCodexLimits`, `codexMayBeUsedUp`), as on the accounts path. A success is relayed as before, with nothing held when no retry or fallback is left (`TestCodexOneAccountOverloadAskedAgain`, `…StreamOverloadAskedAgain`, `…OverloadBounded`, `…OverloadFallsBack`, `…OverloadKeptAlive`, `…RefusalNotAskedAgain` in [`codex_one_account_overload_test.go`](../../internal/gateway/codex_one_account_overload_test.go)). - A subscription account whose sign-in its vendor revoked (`provider.SignInRevoked`: 401 `token_revoked` and the like, #1793) fails as `failAuth`: the next member is asked at once, nothing rests, and the account is marked (`noteSignIn` in [`signin_revoked.go`](../../internal/gateway/signin_revoked.go)). Its later requests aren't sent while it has that credential: `forwardOnce` answers them with a 401 of magpie's own (`revokedReply`), so they too pass on. Compaction on an account of magpie's (`compactOn`) picks a marked one last. A key's provider answering the same words rests as before. - A ChatGPT 401 that says the token sent has expired and asks for a refresh (`provider.SignInExpired`, #2973) while its `exp` is ahead renews the account's sign-in once (`provider.NoteExpiredSignIn` from `noteSignIn`), keyed on the token sent, so the next request goes with a fresh one; nothing is marked, and the request fails over as any 401 does ([Providers and accounts](providers-accounts.md), A token called expired). diff --git a/internal/gateway/openrouter_harness_test.go b/internal/gateway/openrouter_harness_test.go new file mode 100644 index 000000000..3db2c807d --- /dev/null +++ b/internal/gateway/openrouter_harness_test.go @@ -0,0 +1,42 @@ +package gateway + +import ( + "net/http" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// openRouterHarness403 is OpenRouter's refusal of a free model to a +// request not from an agent app it lists, the reporter's words +// (Wade111999 on X) with the advice other clients quote after them. +const openRouterHarness403 = `{"error":{"message":"thinkingmachines/inkling-2-small:free is only available on agentic harnesses. Try plugging it into a coding agent or productivity app listed on https://openrouter.ai/apps","code":403}}` + +// OpenRouter turning a free model away from a request's app sets nothing +// aside: not the key, whose other models answer as before, nor the model, +// which an agent app OpenRouter lists is served. A key's own 403 still +// rests the key. +func TestOpenRouterHarnessOnlyRestsNothing(t *testing.T) { + clineRestsCleared(t) + s := &Server{} + or := provider.Provider{ID: "openrouter", Preset: "openrouter", Chat: "https://openrouter.ai/api/v1", Key: "sk-or-v1-test"} + at := func(model string) candidate { return candidate{p: or, model: model, rest: or.ID} } + gated := at("thinkingmachines/inkling-2-small:free") + r := s.restAfter(gated, http.StatusForbidden, http.Header{}, []byte(openRouterHarness403)) + if r.By != "off" { + t.Fatalf("the harness gate rests %+v", r) + } + for _, m := range []string{"thinkingmachines/inkling-2-small:free", "thinkingmachines/inkling-2-small", "deepseek/deepseek-v4-flash:free"} { + if resting(at(m)) { + t.Fatalf("%s rests after the harness gate: %v", m, rests()) + } + } + if !retryable(http.StatusForbidden, []byte(openRouterHarness403)) { + t.Fatal("a group's next member isn't asked after the harness gate") + } + // the boundary: a 403 about the key rests it + s.restAfter(gated, http.StatusForbidden, http.Header{}, []byte(`{"error":{"message":"Key disabled","code":403}}`)) + if !resting(at("deepseek/deepseek-v4-flash:free")) { + t.Fatal("a disabled key's 403 no longer rests the key") + } +} diff --git a/internal/gateway/routing.go b/internal/gateway/routing.go index 7f2881568..d29759a33 100644 --- a/internal/gateway/routing.go +++ b/internal/gateway/routing.go @@ -1457,6 +1457,16 @@ func (s *Server) restAfterMarked(c candidate, status int, header http.Header, bo // connection (regionFresh) return Rest{Why: why, Status: status, By: "off", Until: now} } + if status == http.StatusForbidden && provider.HarnessOnly(wordsOf(body)) { + // OpenRouter serving a free model only to the agent apps it lists + // (provider.HarnessOnly): the app the request came from was + // turned away, not the key, whose other models answer as before, + // nor the model, which another agent's request may be served. Read + // as the key's 403 it set every OpenRouter model aside + // (Wade111999 on X); none is set aside and the failure counts + // nowhere + return Rest{Why: why, Status: status, By: "off", Until: now} + } if status == http.StatusBadRequest && signatureRefused.Match(wordsOf(body)) { // Google turned a thought signature away as one it didn't give // (signatureRefused): the history's doing, not the account's. A diff --git a/internal/provider/harness_only.go b/internal/provider/harness_only.go new file mode 100644 index 000000000..1c0887402 --- /dev/null +++ b/internal/provider/harness_only.go @@ -0,0 +1,31 @@ +package provider + +import ( + "bytes" + + "github.com/yetone/magpie/internal/lazyre" +) + +// OpenRouter serves some free endpoints only to the agent apps it lists +// (openrouter.ai/apps), as it attributes a request to an app (its +// HTTP-Referer). Any other request is answered 403 "thinkingmachines/ +// inkling-2-small:free is only available on agentic harnesses. Try +// plugging it into a coding agent or productivity app listed on +// https://openrouter.ai/apps" (Wade111999 on X), its routing step "Gate +// Free Endpoints by Agentic Harness". The key is fine, and so is the +// model: the app the request came from is what is turned away, so a +// magpie test, which is magpie's own request and names no app, is +// refused, and an agent's may be served. magpie never names an app it +// isn't. + +// harnessOnly matches that refusal's words. +var harnessOnly = lazyre.New(`(?i)only available (?:on|with|via|in|to|for use with) agentic harness`) + +// HarnessOnlyHint says what the refusal means and what to do. +const HarnessOnlyHint = "OpenRouter serves this free model only to requests from an agent app it lists at openrouter.ai/apps, which magpie's own requests (a model test) are not; the model without :free is served to any request" + +// HarnessOnly says whether an error body is OpenRouter's refusal of a +// request not from an agent app it lists. +func HarnessOnly(b []byte) bool { + return harnessOnly.Match(b) || bytes.Contains(b, []byte(HarnessOnlyHint)) +} diff --git a/internal/provider/harness_only_test.go b/internal/provider/harness_only_test.go new file mode 100644 index 000000000..21b51c7df --- /dev/null +++ b/internal/provider/harness_only_test.go @@ -0,0 +1,46 @@ +package provider + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +// A model test OpenRouter refuses as not from an agent app says why and +// what to do, not only the 403 (Wade111999 on X), whatever the words are +// wrapped in, and once. +func TestHarnessOnlyTestSaysWhy(t *testing.T) { + const said = "thinkingmachines/inkling-2-small:free is only available on agentic harnesses. Try plugging it into a coding agent or productivity app listed on https://openrouter.ai/apps" + for _, b := range []string{ + `{"error":{"message":"` + said + `","code":403}}`, + said, + } { + got := APIError([]byte(b), "403 Forbidden") + if !strings.Contains(got, said) || !strings.HasSuffix(got, " — "+HarnessOnlyHint) { + t.Fatalf("%s: %q", b, got) + } + if again := APIError([]byte(got), "403 Forbidden"); strings.Count(again, HarnessOnlyHint) > 1 { + t.Fatalf("hint said twice: %q", again) + } + if !HarnessOnly([]byte(b)) { + t.Fatalf("%s not read as the harness gate", b) + } + } + if HarnessOnly([]byte(`{"error":{"message":"Key disabled","code":403}}`)) || strings.Contains(APIError([]byte(`{"error":{"message":"Key disabled","code":403}}`), ""), HarnessOnlyHint) { + t.Fatal("another 403 read as the harness gate") + } + + // the test itself, as the editor's Test models runs it + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(http.StatusForbidden) + w.Write([]byte(`{"error":{"message":"` + said + `","code":403}}`)) + })) + defer srv.Close() + p := Provider{ID: "openrouter", Chat: srv.URL + "/api/v1", Key: "sk-or-v1-test"} + r := p.TestModels(t.Context(), []string{"thinkingmachines/inkling-2-small:free"})[0] + if r.OK || r.Status != http.StatusForbidden || !strings.Contains(r.Error, HarnessOnlyHint) { + t.Fatalf("test result %+v", r) + } +} diff --git a/internal/provider/test.go b/internal/provider/test.go index 76292e060..7792cfdd1 100644 --- a/internal/provider/test.go +++ b/internal/provider/test.go @@ -1167,6 +1167,9 @@ func APIError(b []byte, fallback string) string { if cmdGoNoAPI.Match(b) { return apiError(b, fallback) + " — " + CommandCodeGoHint } + if harnessOnly.Match(b) && !bytes.Contains(b, []byte(HarnessOnlyHint)) { + return apiError(b, fallback) + " — " + HarnessOnlyHint + } return apiError(b, fallback) }