diff --git a/docs/reference.md b/docs/reference.md index 1d551cf6e..fcafa516b 100644 --- a/docs/reference.md +++ b/docs/reference.md @@ -1955,6 +1955,7 @@ magpie model api relay/claude-opus-5-5 relay/claude-sonnet-5 anthropic # sever magpie model api relay/gpt-5.5 --reset # auto again: the vendor's list and every URL magpie model apis # the models you set an API for magpie model apis relay # each of relay's models and its API +magpie model tier relay/gpt-5.5 ultrafast # fast, ultrafast or usual: the speed every request for it is sent at ``` It is saved as the editor's Save saves it (`provider.SetModelPrefs`, into diff --git a/docs/subsystems/gateway-routing.md b/docs/subsystems/gateway-routing.md index 84f98d412..348734b83 100644 --- a/docs/subsystems/gateway-routing.md +++ b/docs/subsystems/gateway-routing.md @@ -227,6 +227,7 @@ recorded as a prediction failure (`noPrediction`). - A failed call is in `app.log` too, not only the Routing page and the usage ledger (wjh66 on Discord: Codex's "error decoding response body" after "reconnecting 5/5", and the log had nothing of the turn). `record` writes each call whose status is 400 or more, or that carries an error, as one line (`failedCallLine`: agent, model, provider, status, time, the error to 300 characters); the same failure again within a minute is counted into the next line, not written (`failedLogEvery`), so a client asking in a loop can't fill the log. A Codex reply relayed from the ChatGPT backend that ends before its last event also says which side ended it (`codexEndedEarly` in [`codex_backend.go`](../../internal/gateway/codex_backend.go)): the read of OpenAI's stream that failed, with its error, or a clean end; and the client gone, a write to it that failed, or the failure passed on as `response.failed`, with the bytes passed on. reqwest, Codex's HTTP client, says "error decoding response body" for any read of a body whose connection broke, so only this line tells the legs apart. A gateway that ends with requests still in flight logs that they were cut (`srv.Shutdown`'s error; on Windows there is no handover, so an update or quit cuts a stream after `shortDrain`) (`TestCodexReplyBrokenOffLogged`, `TestCodexClientGoneLogged`, `TestFailedCallLineOncePerMinute`). - Each record keeps the service tier three ways (#1784): `tier_asked` is what the client's body asked (`bodyTier`; Claude's speed fast reads `fast`), `tier_sent` is what that try's last request went out with, noted in `forwardOnce` after every rewrite (fast picks, Ultrafast to priority on a plan without it) onto the per-attempt `wireAt`, and `tier_served` is only what the reply said it ran at (`upstreamTier`, read by the sniffer and the translated readers), empty when it says nothing; from the ChatGPT backend (CodexBase's host) its `auto` and `default` are empty too, since it says them whether priority ran or not (`servedTierAt`, applied in `attempt` and `codexUpstreamOn`). The route's tries carry `tier` and `tier_served` the same way. A bridge that doesn't go through `forwardOnce` (the Claude subscription, Cursor's built-in) leaves `tier_sent` empty. Code: [`tier_record.go`](../../internal/gateway/tier_record.go). - An agent's fast pick (`settings.FastPicks`, the bolt in its picker, #954) may also be in `settings.UltraPicks` (#1954), offered by the GUI only where one of Codex's accounts lists Ultrafast on the model (`provider.CanUltra`, `UltraModels`). `fastPick` marks its candidates `ultra`; a try of one goes with `service_tier: "ultrafast"` on Chat and Responses, and an agent on Messages carries it in the context (`withUltra`) to `forwardTranslated`, which sets `Request.Ultrafast` for the ChatGPT backend. Either way the same check as a client's own Ultrafast ask applies, now on Chat as well as Responses: an account whose list doesn't offer it is put after a mate that does (`tierMate`), or, with none left, sent `priority`. A Chat body's own `service_tier: "ultrafast"` is parsed as Ultrafast too (`chat.go`). `TestUltraPickSentUltrafast`. +- A group's member may be Ultrafast as well as fast (`Group.Ultra`, a subset of `Fast`, `Group.SetMemberTier`; the member's button steps Standard speed, Fast, Ultrafast where `ultraOK`; `ultra=` in `magpie group`), and a model has its own speed (`settings.ModelTiers`, "/" to `priority` or `ultrafast`, `provider.SetModelTier`, Model settings and `magpie model tier`; kdajenks on X). The gateway sends it on a direct pick for an agent with no fast pick of its own (`provider.ModelTier`, the branch after `IsFastPick`), through the same `fastPick`, so an account without Ultrafast is sent `priority`. A group member goes as the group says. `TestModelTierSentToEveryAgent`, `TestGroupMemberUltrafast`, `model-speed.test.cjs`. - Codex's service tier (`settings.CodexServiceTier`, a row in Codex's settings, JackyFill on X) sets the `service_tier` of every request of Codex's, whatever Codex's own `/fast` asked: empty is as Codex asks (the default, nothing changed), `default` sends none (standard), `priority` is Codex's Fast and `ultrafast` its Ultra Fast (the request values in Codex's `ServiceTier`; Flex is not offered, since the ChatGPT backend's requests drop it in `codex_request.go`). `codexTiered` ([`codex_tier.go`](../../internal/gateway/codex_tier.go)) rewrites the body as it comes in, on both of Codex's ways in: `codexBackend` (Codex signed in, `/backend-api/codex`) and the main handler's Codex-on-Responses block, which a websocket turn reaches too. Everything after treats it as Codex's own ask: an account whose list lacks Ultrafast is put after a mate that offers it (`tierMate`) or sent `priority`, and a provider that refuses a tier drops it. A model with no provider (`gpt-…`, Codex's own sign-in, whose plan magpie doesn't know) is sent `ultrafast` only where one of magpie's Codex accounts lists it on the model (`UltraModels`), else `priority`. Another agent's request is never touched, and fast picks still apply after. `TestCodexServiceTierSet`, `codex-service-tier.test.cjs`. - A usage record carries its prompt's cache beside `in` and `out` (#1839): `cache_read` (tokens read from the vendor's cache) and `cache_write` (cache creation, Anthropic's `cache_creation_input_tokens`; `cache_write_1h` the part written for an hour). `in` holds neither. Both are written on every record, 0 too, so a prompt that missed the cache reads as that. A record from before then has neither and reads as 0. Every route fills them: Anthropic's messages, Chat (OpenAI's `prompt_tokens_details.cached_tokens`, DeepSeek's `prompt_cache_hit_tokens`), Responses (`input_tokens_details.cached_tokens`) and Gemini (`cachedContentTokenCount`), passed through or translated, whole or streamed, a plugin's fetch, and the Claude subscription bridge. System One's decision calls report no cache. `TestUsageRecordsCacheTokensOnEveryRoute`, `TestPluginUsageRecordsCacheTokens`, `TestClaudeSubscriptionUsageKeepsCacheTokens`, `TestRecordAlwaysCarriesCacheTokens`. - What the vendor read from its cache reaches the agent in the names its SDK reads, not only the record. A relayed Chat reply whose usage tells the cache in another vendor's names (a relay's Anthropic `cache_read_input_tokens` and `cache_creation_input_tokens`, DeepSeek's `prompt_cache_hit_tokens` or Moonshot's top-level `cached_tokens` beside a 0 in `prompt_tokens_details`) is told in OpenAI's too, streamed (`chatTidy`) and whole (`chatWhole`), by `openAIUsage` in [`chattidy.go`](../../internal/gateway/chattidy.go): `prompt_tokens_details.cached_tokens` (and `cache_write_tokens`), with `prompt_tokens` and `total_tokens` made to hold the cached part where the vendor left it out. Every other field stays, and a usage already in OpenAI's names, or with no cache, goes byte for byte; one in OpenAI's names alone isn't even decoded (`mayMendUsage`). pi-ai, which DeepSeek Harness and Pi use, reads `prompt_tokens_details.cached_tokens` first, a 0 there too, and maps no Anthropic names at all, so such a relay showed DSH 缓存命中 0% while magpie had counted the hit (B3TT3R on Discord asked; DeepSeek's own API sends both names and was already read right). Relayed Responses and Messages replies, translated replies and a plugin's need nothing: their usage is written in the agent's own names. `TestAgentReadsCacheTokensOnEveryRoute`, `TestPluginAgentReadsCacheTokens`, `TestOpenAIUsageLeavesOpenAIsAlone`, `TestMayMendUsageOnlyOtherNames` in [`usage_cache_agent_test.go`](../../internal/gateway/usage_cache_agent_test.go). diff --git a/docs/subsystems/providers-accounts.md b/docs/subsystems/providers-accounts.md index dec946c5b..f1924769f 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 | 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) | | A model's own headers | `ModelHeaders` in [settings](../../internal/settings/settings.go) (`"pid/model"`, `SetModelHeaders`, at most 32, names checked as `Headers`' are; the editor's *Model settings*, `+ Add header`; axelburks on Discord: Volcengine Ark routes an endpoint by a header) go on a key's provider's requests for that model alone, after the provider's `Headers`: a name both have is sent once, as the model's, over the provider's and over the key's `Authorization` or `x-api-key` (`headersFor`, in `SentHeaders(ctx)` and `AsksThread(ctx)`). The gateway names the model in the request's context (`WithModel`) on every API, streamed or not, `count_tokens`, images, video, embeddings and System One's decision model; `modelOf` reads it only for the provider it was set for, so a fallback serving the same id is sent its own headers alone. A native route (Gemini's, Copilot's) names the model by the body's vendor id. Headers the agent passes (`PassHeaders`) still stand over both. A signed-in account and a plugin get none (`takesModelHeaders`). `TestModelHeadersReachTheirModelOnEveryRoute`, `TestModelHeadersStayWithTheirProvider`, `TestModelHeadersReachSystemOne`, `model-headers.test.cjs`. | | A model's own system prompt | `ModelSystemPrompts` in [settings](../../internal/settings/settings.go) (`"pid/model"`, `SetModelSystemPrompt` in [`modelsystem.go`](../../internal/provider/modelsystem.go): trimmed, at most 64KB, no NUL, a model the provider serves; empty takes it away; the editor's *Model settings*, *System prompt*, staged as `modelPrefs[id].system` by [`modellimits.js`](../../internal/gui/assets/modellimits.js); liucl on X) is added after the agent's own system prompt on every request for that model, whatever agent sends it: see [gateway routing](gateway-routing.md#a-models-own-system-prompt). Any provider takes one, a signed-in account and a plugin too. Renaming the provider or the model carries it (`perModelFields`). `TestProviderSaveModelPrefs`, `model-system-prompt.test.cjs`. | +| A model's own speed | `ModelTiers` in [settings](../../internal/settings/settings.go) (`"pid/model"` to `priority` or `ultrafast`; `CleanModelTier`, `SetModelTier` in [`modeltier.go`](../../internal/provider/modeltier.go), refused where `CanFast` / `CanUltra` say the model or account has no such mode). It rides `ModelPref.Tier` with the other Model settings, `magpie model tier` sets it, and the gateway sends it on a direct pick for an agent with no fast pick of its own (kdajenks on X). | [`modeltier.go`](../../internal/provider/modeltier.go), [`modelprefs.go`](../../internal/provider/modelprefs.go), [`gateway.go`](../../internal/gateway/gateway.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) | diff --git a/internal/cli/groups_cli.go b/internal/cli/groups_cli.go index d103098a8..c023e29e1 100644 --- a/internal/cli/groups_cli.go +++ b/internal/cli/groups_cli.go @@ -41,6 +41,8 @@ const groupUsage = `usage: counting; empty is the 0.4 groups have always asked), pick= (routing=manual, every request to that one of its models), fast=[,m2…] (the models sent in their vendor's fast mode; empty for none), + ultra=[,m2…] (those of them sent in the faster Ultrafast mode of a ChatGPT + account that offers it, priority otherwise; each is made fast too; empty for none), weight==[,m2=…] (each model's share under routing=weight, 1 to 1000; a model not named keeps its own, 1 by default; empty for all 1), listed=no (its models leave the lists agents see, offered through the @@ -446,7 +448,7 @@ func applyGroupPairs(g *provider.Group, pairs []string, resolve func(string) (st // the whole list, patterns too: what the old ones matched goes g.Members, err = members(v) g.Match, g.Matched = patterns, nil - g.Fast = nil // the list as typed: :fast on those sent fast + g.Fast, g.Ultra = nil, nil // the list as typed: :fast on those sent fast case "models+", "members+", "model+": var add []string if add, err = members(v); err == nil { @@ -574,6 +576,18 @@ func applyGroupPairs(g *provider.Group, pairs []string, resolve func(string) (st } g.Fast = append(g.Fast, id) } + case "ultra": + // the fast members sent in the faster mode: each named is fast + // too, the rest are not ultra + g.Ultra = nil + for _, m := range splitIDs(v, inGroup(g.Members)) { + m, _ = provider.MemberFast(m) + id, perr := pickMember(g.Members, m) + if perr != nil { + return perr + } + g.SetMemberTier(id, "ultrafast") + } case "weight", "weights": // each member's share when the group routes by weight (#1910): // those named, the rest kept; empty for every one 1 again @@ -1231,7 +1245,9 @@ func showGroup(g provider.Group) error { line = green.Render(fmt.Sprintf("%d %s ●", i+1, typedMember(g, id))) } if l, ok := memberLabel(id, names); ok { - if g.IsFast(id) { + if g.IsUltra(id) { + l += " · ultrafast" + } else if g.IsFast(id) { l += " · fast" } if g.Routing == provider.Weighted { diff --git a/internal/cli/model_cli.go b/internal/cli/model_cli.go index 36ac225a7..696b279f7 100644 --- a/internal/cli/model_cli.go +++ b/internal/cli/model_cli.go @@ -74,6 +74,9 @@ const modelUsage = `usage: magpie model api ... ask the model(s) on one API of the provider's: chat, responses, anthropic, gemini, or auto (--reset) for the vendor's list and every URL it has (magpie model api --help) + magpie model tier [fast|ultrafast|usual] + the speed it is sent at: Codex's Fast or Ultrafast, for every + agent with no fast pick of its own (magpie model tier --help) magpie model apis [] the models you set an API for, or each of a provider's magpie model names the models you named or narrowed magpie model alias count the model's usage under another model id in Usage, @@ -171,6 +174,8 @@ func modelCmd(args []string) error { return modelID(args[1:]) case "api", "protocol": return modelAPICmd(args[1:]) + case "tier", "speed", "fast": + return modelTierCmd(args[1:]) case "apis", "protocols": return modelAPIs(args[1:]) case "ids": diff --git a/internal/cli/model_tier_cli.go b/internal/cli/model_tier_cli.go new file mode 100644 index 000000000..c86635c3f --- /dev/null +++ b/internal/cli/model_tier_cli.go @@ -0,0 +1,59 @@ +package cli + +import ( + "fmt" + "slices" + "strings" + + "github.com/yetone/magpie/internal/provider" + "github.com/yetone/magpie/internal/settings" +) + +// magpie model tier: a model's own speed (kdajenks on X). + +const tierUsage = `usage: + magpie model tier the speed it is sent at + magpie model tier fast send every request for it in its vendor's fast mode + magpie model tier ultrafast send it in the faster Ultrafast mode where an account offers it + (priority where not) + magpie model tier usual the usual speed again (also --reset) + +An agent's own fast pick (the bolt in its model list) goes first, and a routing group +sends its members as it says.` + +func modelTierCmd(args []string) error { + if len(args) == 0 { + return fmt.Errorf("%s", tierUsage) + } + if slices.ContainsFunc(args, isHelp) { + fmt.Println(tierUsage) + return nil + } + p, model, err := modelRef(args[0]) + if err != nil { + return err + } + if len(args) == 1 { + fmt.Printf("%s/%s: %s\n", p.ID, model, tierWord(provider.ModelTier(p.ID, model))) + return nil + } + val := strings.TrimSpace(args[1]) + if isReset([]string{val}) { + val = "" + } + if err := provider.SetModelTier(p.ID+"/"+model, val); err != nil { + return err + } + fmt.Printf("%s/%s: %s\n", p.ID, model, tierWord(settings.Load().ModelTiers[p.ID+"/"+model])) + return nil +} + +func tierWord(t string) string { + switch t { + case "priority": + return "fast" + case "ultrafast": + return "ultrafast" + } + return "usual" +} diff --git a/internal/gateway/fallback.go b/internal/gateway/fallback.go index b6715560d..3f693cf78 100644 --- a/internal/gateway/fallback.go +++ b/internal/gateway/fallback.go @@ -786,7 +786,7 @@ func planLevel(g provider.Group, ms []provider.Member, depth int, from provider. // the same model at another effort is another member's for _, l := range [][]candidate{cs, aside, left, barred} { for i := range l { - l[i].effort, l[i].levels, l[i].effortMap, l[i].fast = m.Effort, m.Levels, m.EffortMap, m.Fast + l[i].effort, l[i].levels, l[i].effortMap, l[i].fast, l[i].ultra = m.Effort, m.Levels, m.EffortMap, m.Fast, m.Ultra l[i].firstToken = innerFirstToken(m) l[i].redact = m.Masking() l[i].patience = innerPatience(m) diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 18ce5108d..a6ab60891 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -3028,6 +3028,10 @@ func (s *Server) serve(w http.ResponseWriter, r *http.Request, from provider.Pro // (#954), as a group's member may be; its fallbacks, other // models, go as they are fastPick(cands, pl, p.ID, model, provider.IsUltraPick(agent, p.ID+"/"+model)) + } else if tier := provider.ModelTier(p.ID, model); tier != "" { + // the speed the user gave the model in its Model settings, for + // every agent that has no pick of its own for it + fastPick(cands, pl, p.ID, model, tier == "ultrafast") } } agentPick := provider.AgentEffort(agent) diff --git a/internal/gateway/model_tier_test.go b/internal/gateway/model_tier_test.go new file mode 100644 index 000000000..510547cf4 --- /dev/null +++ b/internal/gateway/model_tier_test.go @@ -0,0 +1,95 @@ +package gateway + +import ( + "net/http" + "net/url" + "strings" + "testing" + + "github.com/yetone/magpie/internal/provider" +) + +// kdajenks on X: the speed given to a model in its Model settings is sent +// on every agent's requests for it that have no fast pick of their own, +// Ultrafast first to the account that offers it and priority to one that +// doesn't; a group's member is sent as the group says. +func TestModelTierSentToEveryAgent(t *testing.T) { + proOut := false + tried := tierAccounts(t, &proOut, nil) + to, _ := url.Parse(provider.CodexBase) + provider.CodexBase = "https://chatgpt.com/backend-api/codex" + s := New() + s.client = &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) { + r.URL.Scheme, r.URL.Host = to.Scheme, to.Host + return http.DefaultTransport.RoundTrip(r) + })} + send := func(agent string) string { + t.Helper() + postFrom(t, s, agent, "/v1/responses", `{"model":"codex/gpt-6-luna","input":"ping"}`) + return strings.Join(tried(), ",") + } + if got := send("omp"); got != "acct-plus:" { + t.Fatalf("no tier set: tried %s", got) + } + if err := provider.SetModelTier("codex/gpt-6-luna", "ultrafast"); err != nil { + t.Fatal(err) + } + for _, agent := range []string{"omp", "opencode"} { + if got := send(agent); got != "acct-pro:ultrafast" { + t.Errorf("%s: ultrafast tried %s", agent, got) + } + } + proOut = true + if got := send("omp"); got != "acct-pro:ultrafast,acct-plus:priority" { + t.Errorf("pro out: tried %s", got) + } + proOut = false + if err := provider.SetModelTier("codex/gpt-6-luna", "fast"); err != nil { + t.Fatal(err) + } + if got := send("omp"); got != "acct-plus:priority" { + t.Errorf("fast tried %s", got) + } + if err := provider.SetModelTier("codex/gpt-6-luna", "usual"); err != nil { + t.Fatal(err) + } + if got := send("omp"); got != "acct-plus:" { + t.Errorf("usual again tried %s", got) + } +} + +// A group's member is sent as the group says: Ultrafast to the account that +// offers it, whatever tier the model's own settings give it. +func TestGroupMemberUltrafast(t *testing.T) { + proOut := false + tried := tierAccounts(t, &proOut, nil) + to, _ := url.Parse(provider.CodexBase) + provider.CodexBase = "https://chatgpt.com/backend-api/codex" + s := New() + s.client = &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) { + r.URL.Scheme, r.URL.Host = to.Scheme, to.Host + return http.DefaultTransport.RoundTrip(r) + })} + if err := provider.SaveGroup(provider.Group{ID: "u", Name: "U", Members: []string{"codex/gpt-6-luna"}, Fast: []string{"codex/gpt-6-luna"}, Ultra: []string{"codex/gpt-6-luna"}, Routing: provider.Ordered}); err != nil { + t.Fatal(err) + } + send := func() string { + t.Helper() + postFrom(t, s, "omp", "/v1/responses", `{"model":"group/u","input":"ping"}`) + return strings.Join(tried(), ",") + } + if got := send(); got != "acct-pro:ultrafast" { + t.Errorf("ultra member tried %s", got) + } + proOut = true + if got := send(); got != "acct-pro:ultrafast,acct-plus:priority" { + t.Errorf("pro out: tried %s", got) + } + proOut = false + if err := provider.SaveGroup(provider.Group{ID: "u", Name: "U", Members: []string{"codex/gpt-6-luna"}, Fast: []string{"codex/gpt-6-luna"}, Routing: provider.Ordered}); err != nil { + t.Fatal(err) + } + if got := send(); got != "acct-plus:priority" { + t.Errorf("fast member tried %s", got) + } +} diff --git a/internal/gateway/rules.go b/internal/gateway/rules.go index 6ae839d70..3bd68bd7a 100644 --- a/internal/gateway/rules.go +++ b/internal/gateway/rules.go @@ -859,7 +859,7 @@ func ruleEffort(c candidate, hit *RuleHit, nested []NestedRule, ms []provider.Me func homeCands(cs []candidate, ms []provider.Member) { for i := range cs { if j := slices.IndexFunc(ms, func(m provider.Member) bool { return ofMember(cs[i], m) }); j >= 0 { - cs[i].fast, cs[i].firstToken = ms[j].Fast, innerFirstToken(ms[j]) + cs[i].fast, cs[i].ultra, cs[i].firstToken = ms[j].Fast, ms[j].Ultra, innerFirstToken(ms[j]) } } } diff --git a/internal/gui/assets/app.css b/internal/gui/assets/app.css index 7af5ada53..3056239d6 100644 --- a/internal/gui/assets/app.css +++ b/internal/gui/assets/app.css @@ -3842,6 +3842,7 @@ body.window .ag-sk-icon { width: 22px; height: 22px; border-radius: 6px; } but for unsaved and Restore default; drawn with the limits, at once, so the row's height is whole when its editor holds the scroll */ .mname > .munsaved, .mname > .action { order: 2; } +.mname .mspeed { display: flex; align-items: center; flex: none; } .mname .msys { order: 1; display: flex; align-items: flex-start; gap: 6px; flex: 1 1 100%; min-width: 0; font-size: 11.5px; color: var(--muted); } .mname .msys span { flex: none; padding-top: 5px; } .editor .mname .msys textarea { flex: 1; min-width: 0; min-height: 25px; box-sizing: border-box; padding: 4px 8px; border-radius: 7px; border: 1px solid var(--line); background: var(--card); color: var(--fg); font: inherit; font-size: 11.5px; line-height: 1.45; resize: vertical; outline: none; transition: border-color .12s ease, box-shadow .12s ease; } diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 46a1e1b0f..85653f6c8 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -4166,6 +4166,8 @@ const I18N = { "whatever the agent asks": "无论 Agent 要求什么", "fast": "快速", "Fast": "快速", + "Standard speed": "标准速度", + "Sent at this speed with every request for {id} from an agent with no fast pick of its own; where an account has no Ultrafast it goes fast": "{id} 的每个请求(没有自己快速选择的 Agent 发出的)都按这个速度发;账号没有极速时按快速发", "standard": "标准", "deep": "深度", "visual": "视觉", @@ -9238,6 +9240,8 @@ const I18N = { "whatever the agent asks": "無論 Agent 要求什麼", "fast": "快速", "Fast": "快速", + "Standard speed": "標準速度", + "Sent at this speed with every request for {id} from an agent with no fast pick of its own; where an account has no Ultrafast it goes fast": "{id} 的每個請求(沒有自己快速選擇的 Agent 發出的)都按這個速度發;帳號沒有極速時按快速發", "standard": "標準", "deep": "深度", "visual": "視覺", @@ -14329,6 +14333,8 @@ const I18N = { "whatever the agent asks": "エージェントの指定にかかわらず", "fast": "高速", "Fast": "高速", + "Standard speed": "通常速度", + "Sent at this speed with every request for {id} from an agent with no fast pick of its own; where an account has no Ultrafast it goes fast": "{id} へのリクエストのうち、独自の高速指定を持たないエージェントのものは、すべてこの速度で送ります。アカウントに超高速がなければ高速で送ります", "standard": "標準", "deep": "ディープ", "visual": "ビジュアル", @@ -19428,6 +19434,8 @@ const I18N = { "whatever the agent asks": "egal was der Agent verlangt", "fast": "schnell", "Fast": "Schnell", + "Standard speed": "Standardgeschwindigkeit", + "Sent at this speed with every request for {id} from an agent with no fast pick of its own; where an account has no Ultrafast it goes fast": "Jede Anfrage an {id} von einem Agenten ohne eigene Schnell-Auswahl wird so gesendet; hat ein Konto kein Ultrafast, geht sie schnell", "standard": "Standard", "deep": "Tief", "visual": "Visuell", diff --git a/internal/gui/assets/modellimits.js b/internal/gui/assets/modellimits.js index b2ecc4b62..861f43aec 100644 --- a/internal/gui/assets/modellimits.js +++ b/internal/gui/assets/modellimits.js @@ -41,9 +41,33 @@ window.modelLimitsFill = function (at, m, p, changed) { at.append(box); const again = () => { if (document.activeElement !== i) i.value = shownOf(); i.placeholder = placeholder(); }; return { i, own, again, saved: () => saved?.[id] || 0 }; - }), modelSystemFill(at, m, changed)]; + }), modelSystemFill(at, m, changed), ...modelSpeedFill(at, m, changed)]; }; +// Its speed (kdajenks on X): the standard one, Codex's Fast, or Ultrafast +// where an account offers it, staged as modelPrefs[id].tier. Fast is +// "priority" on the wire; an agent's own fast pick still goes first. +function modelSpeedFill(at, m, changed) { + if (!m.canFast) return []; + const id = m.id, prefs = draft.modelPrefs = draft.modelPrefs || {}; + const own = () => (prefs[id]?.tier ?? m.tier) || ""; + const items = [["", t("Standard speed")], ["priority", t("Fast")]]; + if (m.canUltra || own() === "ultrafast") items.push(["ultrafast", t("Ultrafast")]); + const box = el("div", "mspeed"); + box.title = t("Sent at this speed with every request for {id} from an agent with no fast pick of its own; where an account has no Ultrafast it goes fast", { id }); + const draw = () => { box.replaceChildren(segs(items, own(), (v) => stage(v))); }; + const stage = (v) => { + const x = prefs[id] = prefs[id] || {}; + if (v === (m.tier || "")) delete x.tier; else x.tier = v; + changed(); + }; + draw(); + at.append(box); + // the reset's call: empty is the standard speed + const i = { value: "", onchange: () => { stage(""); draw(); } }; + return [{ i, own, again: () => draw(), saved: () => m.tier || 0 }]; +} + function modelSystemFill(at, m, changed) { const id = m.id, prefs = draft.modelPrefs = draft.modelPrefs || {}; const own = () => (prefs[id]?.system ?? m.system) || 0; diff --git a/internal/gui/assets/plugins/routing/client.js b/internal/gui/assets/plugins/routing/client.js index 974d364ca..31ba42a6a 100644 --- a/internal/gui/assets/plugins/routing/client.js +++ b/internal/gui/assets/plugins/routing/client.js @@ -6077,7 +6077,7 @@ function routingPage(part) { .map(([id, m]) => [id, Object.fromEntries(Object.entries(m).filter(([a, b]) => words.includes(a) && words.includes(b)))])); const group = (g) => ({ ...g, id: String(g.id ?? ""), name: typeof g.name === "string" && g.name ? g.name : String(g.id ?? ""), members: ids(g.members), memberInfo: objs(g.memberInfo), holds: ids(g.holds), offers: ids(g.offers), shared: ids(g.shared), patterns: objs(g.patterns), - match: opt(g.match, ids), matched: opt(g.matched, ids), off: opt(g.off, ids), fast: opt(g.fast, ids), levels: opt(g.levels, ids), weights: opt(g.weights, weightsOf), effortMaps: opt(g.effortMaps, effortMapsOf), keys: opt(g.keys, ids), + match: opt(g.match, ids), matched: opt(g.matched, ids), off: opt(g.off, ids), fast: opt(g.fast, ids), ultra: opt(g.ultra, ids), levels: opt(g.levels, ids), weights: opt(g.weights, weightsOf), effortMaps: opt(g.effortMaps, effortMapsOf), keys: opt(g.keys, ids), rules: opt(g.rules, (rs) => objs(rs).map((r) => ({ ...r, agents: opt(r.agents, ids), folders: opt(r.folders, ids), exceptFolders: opt(r.exceptFolders, ids), where: opt(r.where, objs) }))) }); const refs = (v) => objs(v).filter((m) => typeof m.id === "string"); return { ...x, groups: objs(x.groups).filter((g) => typeof g.id === "string" && g.id).map(group), @@ -6224,7 +6224,7 @@ function routingPage(part) { // there, rather than leaving the slot empty. const openGroupEditor = async (g) => { if (groupDirty() && !(await confirmDiscard())) return false; - gEdit = { id: g.id, draft: { name: g.name, note: g.note || "", members: [...g.members], match: [...(g.match || [])], matched: [...(g.matched || [])], fast: [...(g.fast || [])], off: [...(g.off || [])], weights: { ...(g.weights || {}) }, effortMaps: Object.fromEntries(Object.entries(g.effortMaps || {}).map(([id, m]) => [id, { ...m }])), accounts: [...(g.accounts || [])], keys: [...(g.keys || [])], redact: g.redact || "", routing: g.routing || "", pick: g.pick || "", affinity: g.affinity || "", sink: sinkModeOf(g), unlists: !!g.unlists, firstToken: g.firstToken || 0, patience: g.patience || 0, context: g.context || 0, classifier: g.classifier || "", intentSure: g.intentSure ?? null, effort: g.effort || "", levels: [...(g.levels || [])], rules: (g.rules || []).map((r) => ({ ...r, ...(r.more?.length ? { more: [...r.more] } : {}), intent: r.intent || "", agents: [...(r.agents || [])], folders: [...(r.folders || [])], exceptFolders: [...(r.exceptFolders || [])], where: (r.where || []).map((c) => ({ ...c })), time: r.time ? { ...r.time, days: [...(r.time.days || [])] } : null })) } }; + gEdit = { id: g.id, draft: { name: g.name, note: g.note || "", members: [...g.members], match: [...(g.match || [])], matched: [...(g.matched || [])], fast: [...(g.fast || [])], ultra: [...(g.ultra || [])], off: [...(g.off || [])], weights: { ...(g.weights || {}) }, effortMaps: Object.fromEntries(Object.entries(g.effortMaps || {}).map(([id, m]) => [id, { ...m }])), accounts: [...(g.accounts || [])], keys: [...(g.keys || [])], redact: g.redact || "", routing: g.routing || "", pick: g.pick || "", affinity: g.affinity || "", sink: sinkModeOf(g), unlists: !!g.unlists, firstToken: g.firstToken || 0, patience: g.patience || 0, context: g.context || 0, classifier: g.classifier || "", intentSure: g.intentSure ?? null, effort: g.effort || "", levels: [...(g.levels || [])], rules: (g.rules || []).map((r) => ({ ...r, ...(r.more?.length ? { more: [...r.more] } : {}), intent: r.intent || "", agents: [...(r.agents || [])], folders: [...(r.folders || [])], exceptFolders: [...(r.exceptFolders || [])], where: (r.where || []).map((c) => ({ ...c })), time: r.time ? { ...r.time, days: [...(r.time.days || [])] } : null })) } }; renderGroups(); return true; }; @@ -6668,7 +6668,7 @@ function routingPage(part) { if (groupDirty() && !(await confirmDiscard())) return; const g = tp.group; gSel = null; - gEdit = { id: "", draft: { name: tplName(tp), slug: g.id, members: [...g.members], match: [], matched: [], fast: [], off: [], routing: g.routing || "", affinity: "", rules: (g.rules || []).map((r) => ({ ...r, ...(r.more?.length ? { more: [...r.more] } : {}), intent: r.intent || "", agents: [...(r.agents || [])], folders: [], exceptFolders: [], where: (r.where || []).map((c) => ({ ...c })), time: null })), classifier: g.classifier || "", effort: "", levels: [] } }; + gEdit = { id: "", draft: { name: tplName(tp), slug: g.id, members: [...g.members], match: [], matched: [], fast: [], ultra: [], off: [], routing: g.routing || "", affinity: "", rules: (g.rules || []).map((r) => ({ ...r, ...(r.more?.length ? { more: [...r.more] } : {}), intent: r.intent || "", agents: [...(r.agents || [])], folders: [], exceptFolders: [], where: (r.where || []).map((c) => ({ ...c })), time: null })), classifier: g.classifier || "", effort: "", levels: [] } }; renderGroups(); const ed = gList.querySelector(".rt-gedit"); if (ed && window.scrollOnPurpose?.(ev)) ed.scrollIntoView({ block: "start", behavior: "smooth" }); @@ -7051,7 +7051,7 @@ function routingPage(part) { closeProtoMenu(); if (v === cur || (groupDirty() && !(await confirmDiscard()))) return b.focus({ preventScroll: true }); const n = opts.find(([id]) => id === v)?.[1] || v; - await groupAction("save", { id: g.id, name: g.name, note: g.note || "", members: namedOf(g), match: g.match || [], routing: v, pick: g.pick || "", affinity: g.affinity || "", sink: !!g.sink && sinkable(v), noSink: !!g.noSink, firstToken: g.firstToken || 0, patience: g.patience || 0, rules: g.rules || [], effort: g.effort || "", classifier: g.classifier || "", intentSure: g.intentSure ?? null, context: g.context || 0, levels: g.levels || [], family: g.family || "", fast: g.fast || [], off: g.off || [], weights: g.weights || {}, effortMaps: g.effortMaps || {}, accounts: g.accounts || [], unlists: !!g.unlists }, + await groupAction("save", { id: g.id, name: g.name, note: g.note || "", members: namedOf(g), match: g.match || [], routing: v, pick: g.pick || "", affinity: g.affinity || "", sink: !!g.sink && sinkable(v), noSink: !!g.noSink, firstToken: g.firstToken || 0, patience: g.patience || 0, rules: g.rules || [], effort: g.effort || "", classifier: g.classifier || "", intentSure: g.intentSure ?? null, context: g.context || 0, levels: g.levels || [], family: g.family || "", fast: g.fast || [], ultra: g.ultra || [], off: g.off || [], weights: g.weights || {}, effortMaps: g.effortMaps || {}, accounts: g.accounts || [], unlists: !!g.unlists }, t("{name}: {routing}", { name: g.name, routing: t(n) })); // the rows were drawn anew: the keyboard stays on this one's routing gList.querySelector(`.rt-group[data-id="${CSS.escape(g.id)}"] .rt-groute`)?.focus({ preventScroll: true }); @@ -7184,7 +7184,7 @@ function routingPage(part) { b.onclick = (e) => { e.stopPropagation(); // the card opens the editor; this picks if (on) return; - groupAction("save", { id: g.id, name: g.name, note: g.note || "", members: namedOf(g), match: g.match || [], routing: "manual", pick: id, affinity: g.affinity || "", sink: !!g.sink, noSink: !!g.noSink, firstToken: g.firstToken || 0, patience: g.patience || 0, rules: g.rules || [], effort: g.effort || "", classifier: g.classifier || "", intentSure: g.intentSure ?? null, context: g.context || 0, levels: g.levels || [], family: g.family || "", fast: g.fast || [], off: g.off || [], weights: g.weights || {}, effortMaps: g.effortMaps || {}, accounts: g.accounts || [], unlists: !!g.unlists }, + groupAction("save", { id: g.id, name: g.name, note: g.note || "", members: namedOf(g), match: g.match || [], routing: "manual", pick: id, affinity: g.affinity || "", sink: !!g.sink, noSink: !!g.noSink, firstToken: g.firstToken || 0, patience: g.patience || 0, rules: g.rules || [], effort: g.effort || "", classifier: g.classifier || "", intentSure: g.intentSure ?? null, context: g.context || 0, levels: g.levels || [], family: g.family || "", fast: g.fast || [], ultra: g.ultra || [], off: g.off || [], weights: g.weights || {}, effortMaps: g.effortMaps || {}, accounts: g.accounts || [], unlists: !!g.unlists }, t("{name}: every request to {model}", { name: g.name, model: memberName(id) })); }; box.append(b); @@ -7196,7 +7196,7 @@ function routingPage(part) { // whoever opened it, a draft has what the editor and Add read: a group // made from a model (newGroupWith) had no fast, and Add threw on it // and did nothing (悠悠哥 on Discord) - for (const k of ["members", "match", "matched", "fast", "off", "rules", "accounts", "keys"]) if (!Array.isArray(d[k])) d[k] = []; + for (const k of ["members", "match", "matched", "fast", "ultra", "off", "rules", "accounts", "keys"]) if (!Array.isArray(d[k])) d[k] = []; if (!d.weights || typeof d.weights !== "object") d.weights = {}; if (!d.effortMaps || typeof d.effortMaps !== "object") d.effortMaps = {}; const ed = el("div", "editor rt-gedit"); @@ -7450,6 +7450,7 @@ function routingPage(part) { d.matched = d.matched.filter((x) => x !== from); // named now, at its own reasoning for (const r of d.rules) setUses(r, rUses(r).map((x) => x === from ? to : x)); d.fast = d.fast.map((x) => x === from ? to : x); + d.ultra = d.ultra.map((x) => x === from ? to : x); d.off = d.off.map((x) => x === from ? to : x); if (d.weights[from]) { d.weights[to] = d.weights[from]; delete d.weights[from]; } // a map goes with it while it follows the group; one fixed at @@ -7502,16 +7503,26 @@ function routingPage(part) { // its vendor's fast mode, where the model has one: priority // processing, Claude's fast mode (provider.CanFast) if (m?.canFast) { + // usual -> fast -> Ultrafast, where an account offers it -> usual const on = d.fast.includes(id); - const fb = el("button", "rt-cond rt-fixed rt-fast" + (on ? " on" : ""), t(on ? "Fast" : "Standard speed")); + const ultra = on && !!m.ultraOK && d.ultra.includes(id); + const fb = el("button", "rt-cond rt-fixed rt-fast" + (on ? " on" : ""), t(ultra ? "Ultrafast" : on ? "Fast" : "Standard speed")); fb.type = "button"; fb.setAttribute("aria-pressed", String(on)); // on a provider the user added (provider.OwnFast, #1615) it is // only asked for: magpie can't know the provider serves it - fb.title = m.ownFast + fb.title = ultra ? t("Sent Ultrafast where the account offers it, and fast where it doesn't, whatever the agent asks. Click to send it at the usual speed") + : m.ownFast ? (on ? t("Asked for OpenAI's fast mode (service_tier \"priority\") whatever the agent asks: quicker, at a higher price, where your provider serves it. One that turns it away is asked without it") : t("Sent as the agent asks; click to ask your provider for OpenAI's fast mode (service_tier \"priority\")")) - : (on ? t("Sent in its vendor's fast mode whatever the agent asks: quicker, at a higher price") : t("Sent at its vendor's usual speed; click to send it in fast mode")); - fb.onclick = () => { d.fast = on ? d.fast.filter((x) => x !== id) : [...d.fast, id]; draw(); }; + : (on ? t(m.ultraOK ? "Sent in its vendor's fast mode whatever the agent asks: quicker, at a higher price. Click to send it Ultrafast, where the account offers it" : "Sent in its vendor's fast mode whatever the agent asks: quicker, at a higher price") : t("Sent at its vendor's usual speed; click to send it in fast mode")); + fb.onclick = () => { + const next = ultra || (on && !m.ultraOK) ? "" : on ? "ultra" : "fast"; + d.fast = d.fast.filter((x) => x !== id); + d.ultra = d.ultra.filter((x) => x !== id); + if (next) d.fast = [...d.fast, id]; + if (next === "ultra") d.ultra = [...d.ultra, id]; + draw(); + }; row.append(fb); } // the one account or key it is sent on (EastonXvii on X: account @@ -7750,6 +7761,7 @@ function routingPage(part) { // a rule keeps the models still here; it goes with its last d.rules = d.rules.filter((r) => { setUses(r, rUses(r).filter((x) => d.members.includes(x))); return !!r.use; }); d.fast = d.fast.filter((x) => d.members.includes(x)); + d.ultra = d.ultra.filter((x) => d.fast.includes(x)); d.off = d.off.filter((x) => d.members.includes(x)); } const pbox = el("div", "fallback rt-pats"); @@ -8799,7 +8811,7 @@ function routingPage(part) { if (own && !d.levels.length) return status(t("Pick a level to offer, or leave them to its models"), "warn"); saveBtn.classList.add("busy"); // refused, Add can be pressed again (busy, it takes no clicks) - groupAction("save", { id: idOf(), from: g?.id, name: d.name.trim() || idOf(), note: (d.note || "").trim(), members: namedOf(d), placed: d.members, match: d.match, routing: d.routing, pick: d.pick || "", affinity: d.affinity, sink: d.sink === "sink" && sinkable(d.routing), noSink: d.sink === "", firstToken: d.firstToken || 0, patience: d.patience || 0, rules: d.rules, effort: d.effort, classifier: d.rules.some((r) => r.intent) || d.effort === "auto" ? d.classifier : "", intentSure: d.intentSure ?? null, context: d.context || 0, levels: own ? d.levels : [], family: g?.family || "", fast: d.fast.filter((x) => d.members.includes(x)), off: d.off.filter((x) => d.members.includes(x)), weights: Object.fromEntries(Object.entries(d.weights).filter(([x, n]) => d.members.includes(x) && n > 1)), effortMaps: Object.fromEntries(Object.entries(d.effortMaps).filter(([x, m]) => d.members.includes(x) && Object.keys(m).length)), accounts: d.accounts.filter((a) => accountPids().includes(a.slice(0, a.indexOf("/")))), keys: d.keys, redact: d.redact || "follow", unlists: !!d.unlists }, t(g ? "{name} saved" : "{name} added", { name: d.name.trim() || idOf() })) + groupAction("save", { id: idOf(), from: g?.id, name: d.name.trim() || idOf(), note: (d.note || "").trim(), members: namedOf(d), placed: d.members, match: d.match, routing: d.routing, pick: d.pick || "", affinity: d.affinity, sink: d.sink === "sink" && sinkable(d.routing), noSink: d.sink === "", firstToken: d.firstToken || 0, patience: d.patience || 0, rules: d.rules, effort: d.effort, classifier: d.rules.some((r) => r.intent) || d.effort === "auto" ? d.classifier : "", intentSure: d.intentSure ?? null, context: d.context || 0, levels: own ? d.levels : [], family: g?.family || "", fast: d.fast.filter((x) => d.members.includes(x)), ultra: d.ultra.filter((x) => d.fast.includes(x) && d.members.includes(x)), off: d.off.filter((x) => d.members.includes(x)), weights: Object.fromEntries(Object.entries(d.weights).filter(([x, n]) => d.members.includes(x) && n > 1)), effortMaps: Object.fromEntries(Object.entries(d.effortMaps).filter(([x, m]) => d.members.includes(x) && Object.keys(m).length)), accounts: d.accounts.filter((a) => accountPids().includes(a.slice(0, a.indexOf("/")))), keys: d.keys, redact: d.redact || "follow", unlists: !!d.unlists }, t(g ? "{name} saved" : "{name} added", { name: d.name.trim() || idOf() })) .then(() => saveBtn.classList.remove("busy")); }; // what goes wrong is said where it is seen, never a click that does nothing @@ -8873,7 +8885,7 @@ function routingPage(part) { if (!groups) await loadGroups(); if (!groups) return; if (groupDirty() && !(await confirmDiscard())) return; - gEdit = { id: "", draft: { name: name || modelOf(id)?.name || id.split("/").pop(), members: [id], fast: [], routing: "", affinity: "", rules: [] } }; + gEdit = { id: "", draft: { name: name || modelOf(id)?.name || id.split("/").pop(), members: [id], fast: [], ultra: [], routing: "", affinity: "", rules: [] } }; renderGroups(); const ed = gList.querySelector(".rt-gedit"); if (ed && window.scrollOnPurpose?.(ev)) ed.scrollIntoView({ block: "center", behavior: "smooth" }); @@ -8883,7 +8895,7 @@ function routingPage(part) { async function newGroup(ev) { if (groupDirty() && !(await confirmDiscard())) return; gSel = null; - gEdit = { id: "", draft: { name: "", members: [], match: [], matched: [], fast: [], off: [], routing: "", affinity: "", rules: [] } }; + gEdit = { id: "", draft: { name: "", members: [], match: [], matched: [], fast: [], ultra: [], off: [], routing: "", affinity: "", rules: [] } }; renderGroups(); if (!ev) return; const ed = gList.querySelector(".rt-gedit"); diff --git a/internal/gui/assets/plugins/routing/i18n.js b/internal/gui/assets/plugins/routing/i18n.js index 49b9f99f6..a51c1d0c6 100644 --- a/internal/gui/assets/plugins/routing/i18n.js +++ b/internal/gui/assets/plugins/routing/i18n.js @@ -361,6 +361,8 @@ magpie.strings({ "{name} at that reasoning is in the group already": "{name} 以这个推理强度已经在分组里了", "Standard speed": "标准速度", "Sent in its vendor's fast mode whatever the agent asks: quicker, at a higher price": "无论 Agent 要求什么,都以服务商的快速模式发送:更快,价格更高", + "Sent Ultrafast where the account offers it, and fast where it doesn't, whatever the agent asks. Click to send it at the usual speed": "无论 Agent 要求什么,账号支持极速就走极速,不支持则走快速模式。点一下改回标准速度", + "Sent in its vendor's fast mode whatever the agent asks: quicker, at a higher price. Click to send it Ultrafast, where the account offers it": "无论 Agent 要求什么,都以服务商的快速模式发送:更快,价格更高。点一下改为极速(账号支持时)", "Sent at its vendor's usual speed; click to send it in fast mode": "以服务商的常规速度发送;点击改为快速模式", "Asked for OpenAI's fast mode (service_tier \"priority\") whatever the agent asks: quicker, at a higher price, where your provider serves it. One that turns it away is asked without it": "无论代理怎么请求,都向服务商请求 OpenAI 的快速模式(service_tier \"priority\"):服务商支持时更快,价格更高。服务商拒绝这个字段时,会去掉它再请求一次", "Sent as the agent asks; click to ask your provider for OpenAI's fast mode (service_tier \"priority\")": "按代理的请求发送;点击向你的服务商请求 OpenAI 的快速模式(service_tier \"priority\")", @@ -1104,6 +1106,8 @@ magpie.strings({ "{name} at that reasoning is in the group already": "{name} 以這個推理強度已經在分組裡了", "Standard speed": "標準速度", "Sent in its vendor's fast mode whatever the agent asks: quicker, at a higher price": "無論 Agent 要求什麼,都以服務商的快速模式傳送:更快,價格更高", + "Sent Ultrafast where the account offers it, and fast where it doesn't, whatever the agent asks. Click to send it at the usual speed": "無論 Agent 要求什麼,帳號支援極速就走極速,不支援則走快速模式。點一下改回標準速度", + "Sent in its vendor's fast mode whatever the agent asks: quicker, at a higher price. Click to send it Ultrafast, where the account offers it": "無論 Agent 要求什麼,都以服務商的快速模式傳送:更快,價格更高。點一下改為極速(帳號支援時)", "Sent at its vendor's usual speed; click to send it in fast mode": "以服務商的常規速度傳送;點選改為快速模式", "Asked for OpenAI's fast mode (service_tier \"priority\") whatever the agent asks: quicker, at a higher price, where your provider serves it. One that turns it away is asked without it": "無論代理怎麼請求,都向服務商請求 OpenAI 的快速模式(service_tier \"priority\"):服務商支援時更快,價格更高。服務商拒絕這個欄位時,會拿掉它再請求一次", "Sent as the agent asks; click to ask your provider for OpenAI's fast mode (service_tier \"priority\")": "依代理的請求傳送;點選向你的服務商請求 OpenAI 的快速模式(service_tier \"priority\")", @@ -1845,6 +1849,8 @@ magpie.strings({ "{name} at that reasoning is in the group already": "この推論レベルの {name} はすでにグループにあります", "Standard speed": "標準速度", "Sent in its vendor's fast mode whatever the agent asks: quicker, at a higher price": "エージェントの指定にかかわらず、ベンダーの高速モードで送ります。速くなりますが、料金は高くなります", + "Sent Ultrafast where the account offers it, and fast where it doesn't, whatever the agent asks. Click to send it at the usual speed": "エージェントの指定にかかわらず、アカウントが対応していれば超高速で、対応していなければ高速モードで送ります。クリックで通常の速度に戻します", + "Sent in its vendor's fast mode whatever the agent asks: quicker, at a higher price. Click to send it Ultrafast, where the account offers it": "エージェントの指定にかかわらず、ベンダーの高速モードで送ります。速くなりますが、料金は高くなります。クリックで、アカウントが対応していれば超高速にします", "Sent at its vendor's usual speed; click to send it in fast mode": "ベンダーの通常速度で送ります。クリックすると高速モードで送ります", "Asked for OpenAI's fast mode (service_tier \"priority\") whatever the agent asks: quicker, at a higher price, where your provider serves it. One that turns it away is asked without it": "エージェントの指定に関わらず、OpenAI の高速モード(service_tier \"priority\")を求めます。プロバイダーが対応していれば速く、料金は高めです。このフィールドを拒否するプロバイダーには、外して送り直します", "Sent as the agent asks; click to ask your provider for OpenAI's fast mode (service_tier \"priority\")": "エージェントの指定どおりに送ります。クリックすると、プロバイダーに OpenAI の高速モード(service_tier \"priority\")を求めます", @@ -2588,6 +2594,8 @@ magpie.strings({ "{name} at that reasoning is in the group already": "{name} mit diesem Reasoning ist bereits in der Gruppe", "Standard speed": "Standardgeschwindigkeit", "Sent in its vendor's fast mode whatever the agent asks: quicker, at a higher price": "Im Schnellmodus des Anbieters gesendet, egal was der Agent verlangt: schneller, zu höherem Preis", + "Sent Ultrafast where the account offers it, and fast where it doesn't, whatever the agent asks. Click to send it at the usual speed": "Egal was der Agent verlangt: Ultrafast, wo das Konto es bietet, sonst im Schnellmodus. Klicken für die normale Geschwindigkeit", + "Sent in its vendor's fast mode whatever the agent asks: quicker, at a higher price. Click to send it Ultrafast, where the account offers it": "Im Schnellmodus des Anbieters gesendet, egal was der Agent verlangt: schneller, zu höherem Preis. Klicken für Ultrafast, wo das Konto es bietet", "Sent at its vendor's usual speed; click to send it in fast mode": "Mit der üblichen Geschwindigkeit des Anbieters gesendet; klicken, um im Schnellmodus zu senden", "Asked for OpenAI's fast mode (service_tier \"priority\") whatever the agent asks: quicker, at a higher price, where your provider serves it. One that turns it away is asked without it": "Fragt unabhängig vom Agenten nach OpenAIs Schnellmodus (service_tier \"priority\"): schneller, zu einem höheren Preis, wo dein Anbieter ihn anbietet. Lehnt er das Feld ab, wird ohne es erneut gefragt", "Sent as the agent asks; click to ask your provider for OpenAI's fast mode (service_tier \"priority\")": "Gesendet, wie der Agent fragt; klicken, um deinen Anbieter nach OpenAIs Schnellmodus (service_tier \"priority\") zu fragen", diff --git a/internal/gui/groups.go b/internal/gui/groups.go index 999afb501..2dc6c0176 100644 --- a/internal/gui/groups.go +++ b/internal/gui/groups.go @@ -7,6 +7,7 @@ import ( "net/http" "slices" "strings" + "sync" "time" "github.com/yetone/magpie/internal/access" @@ -168,6 +169,10 @@ type memberJSON struct { // model has one (provider.CanFast) Fast bool `json:"fast,omitempty"` CanFast bool `json:"canFast,omitempty"` + // Ultra: it is sent in the faster mode still; UltraOK: an account + // offers one (provider.UltraOn, kdajenks on X) + Ultra bool `json:"ultra,omitempty"` + UltraOK bool `json:"ultraOK,omitempty"` // OwnFast: that fast mode is asked of a provider the user added by its // address, which may or may not serve it (provider.OwnFast, #1615) OwnFast bool `json:"ownFast,omitempty"` @@ -205,6 +210,9 @@ type modelRef struct { // CanFast: a group's member of it may be sent in its vendor's fast // mode (provider.CanFast) CanFast bool `json:"canFast,omitempty"` + // UltraOK: an account serves it Ultrafast (provider.UltraOn), so a + // member of it may be sent so + UltraOK bool `json:"ultraOK,omitempty"` // OwnFast: asked of a provider the user added by its address, which may // or may not serve it (provider.OwnFast, #1615) OwnFast bool `json:"ownFast,omitempty"` @@ -373,10 +381,13 @@ func groupsState() groupsJSON { served := provider.Served() chat := map[string]bool{} set := settings.Shared() // the prices the user set, for each model's free tag + ultra := sync.OnceValue(provider.UltraModels) for _, e := range served { if e.Group == "" { chat[e.ID] = true - out.Models = append(out.Models, servedRef(e, set)) + ref := servedRef(e, set) + ref.UltraOK = ref.CanFast && provider.UltraOn(e.Provider, e.Model, ultra()) + out.Models = append(out.Models, ref) } } // the image models, as Settings › Models › Images lists them: each provider's @@ -431,6 +442,7 @@ func groupsState() groupsJSON { } } } + ultraModels := sync.OnceValue(provider.UltraModels) for _, id := range g.Members { m := memberJSON{ID: id} if gid, ok := strings.CutPrefix(id, provider.GroupPrefix); ok { @@ -470,6 +482,8 @@ func groupsState() groupsJSON { m.CanFast = provider.CanFast(p, model) m.OwnFast = m.CanFast && provider.OwnFast(p, model) m.Fast = m.CanFast && g.IsFast(id) + m.UltraOK = m.CanFast && provider.UltraOn(p, model, ultraModels()) + m.Ultra = m.Fast && m.UltraOK && g.IsUltra(id) m.Free = p.FreeModel(model) m.Billing = p.BillingKind() for _, e := range served { diff --git a/internal/gui/providers.go b/internal/gui/providers.go index bd754c427..6bcd74245 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -74,6 +74,12 @@ type modelJSON struct { // System is the system prompt the user gave the model, added after the // agent's own (provider.SetModelSystemPrompt) System string `json:"system,omitempty"` + // Tier is the speed the user gave the model, "priority" or "ultrafast" + // (provider.SetModelTier); CanFast says it has a fast mode to give, + // CanUltra that an account offers the faster one (kdajenks on X) + Tier string `json:"tier,omitempty"` + CanFast bool `json:"canFast,omitempty"` + CanUltra bool `json:"canUltra,omitempty"` // Vendor is the provider's own id of a model the user lists by // another (provider.SetModelID), "" for one listed by its own; IDs // says the provider's models can be given ids at all (a key's) @@ -1061,6 +1067,7 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs // Discord, Windows) set := held noAPI := p.NoAPI() + ultraModels := sync.OnceValue(provider.UltraModels) // the provider's catalogs worked out once, and each model priced once // for its list price and whether it is free pricer := p.Pricer() @@ -1120,6 +1127,10 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs j.Headers = held.ModelHeaders[ref] } j.System = held.ModelSystemPrompts[ref] + if j.CanFast = provider.CanFast(p, m.ID); j.CanFast { + j.Tier = held.ModelTiers[ref] + j.CanUltra = provider.UltraOn(p, m.ID, ultraModels()) + } j.Merge = provider.MergeName(m.ID) j.Desktop = desktop[ref] if mp, ok := held.ModelPrices[ref]; ok { diff --git a/internal/gui/settings_keep_test.go b/internal/gui/settings_keep_test.go index fde17f2ed..92ec7420d 100644 --- a/internal/gui/settings_keep_test.go +++ b/internal/gui/settings_keep_test.go @@ -141,6 +141,7 @@ func TestSettingsSaveKeepsWhatItDoesNotSend(t *testing.T) { ModelKinds: map[string]string{"p/m": "video"}, ModelHeaders: map[string]map[string]string{"p/m": {"X-Endpoint": "ep-1"}}, ModelSystemPrompts: map[string]string{"p/m": "Answer in Chinese."}, + ModelTiers: map[string]string{"p/m": "ultrafast"}, RedactRules: []redact.Rule{{Kind: "prefix", Prefix: "oc_sk_"}}, RedactActions: map[string]string{"API_KEY": "block", "EMAIL": "warn"}, RedactAllow: []string{"team@kelvarn.io"}, diff --git a/internal/gui/tests/model-speed.test.cjs b/internal/gui/tests/model-speed.test.cjs new file mode 100644 index 000000000..e25e06943 --- /dev/null +++ b/internal/gui/tests/model-speed.test.cjs @@ -0,0 +1,173 @@ +// Run with Node's test runner and Playwright on the module path; see README.md. +// Codex's Fast and Ultrafast (kdajenks on X). Model settings gives a model +// that has a fast mode (canFast) a Standard speed / Fast / Ultrafast choice, +// Ultrafast only where an account offers it (canUltra) or the model is +// already set to it. A pick is staged as modelPrefs[id].tier, sent with the +// Save, put back by Escape-free reset (Restore default sends tier ""), and +// a model with no fast mode has none. In a group's editor the member's +// button goes Standard speed -> Fast -> Ultrafast -> Standard where the +// account offers Ultrafast, and saves its `ultra` list. Every language, +// 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(process.env.MAGPIE_ASSETS || path.resolve(__dirname, "../assets")); +const relay = { + id: "relay", name: "Relay", icon: "generic", chat: "https://relay.example/v1", responses: "", anthropic: "", catalog: "", + models: [ + { id: "gpt-6.1-sol", name: "gpt-6.1-sol", on: true, context: 400000, output: 128000, canFast: true, canUltra: true }, + { id: "gpt-6.1-mini", name: "gpt-6.1-mini", on: true, context: 400000, output: 128000, canFast: true, tier: "priority" }, + { id: "glm-5", name: "GLM-5", on: true, context: 200000, output: 128000 }, + ], + chosen: ["gpt-6.1-sol", "gpt-6.1-mini", "glm-5"], agents: [], fallback: [], headers: {}, + key: { set: true, masked: "sk-…aaa" }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "", ready: true, +}; +const gmodels = [ + { id: "oa/gpt-6.1-sol", name: "gpt-6.1-sol", providerName: "OpenAI", icon: "generic", canFast: true, ultraOK: true }, + { id: "oa/gpt-6.1-mini", name: "gpt-6.1-mini", providerName: "OpenAI", icon: "generic", canFast: true }, +]; +const gmembers = ["oa/gpt-6.1-sol", "oa/gpt-6.1-mini"]; +const groups = () => ({ + models: gmodels, pools: [], + groups: [{ id: "sol", name: "Sol", members: gmembers, fast: gmembers, routing: "order", ready: true, + memberInfo: gmembers.map((id) => ({ id, ready: true, fast: true, canFast: true, ultraOK: id.endsWith("sol") })) }], +}); + +function serve(lang, saves, posts) { + const state = { agents: [], profiles: [], settings: { lang, theme: "light" } }; + const list = { providers: [relay], presets: [], excluded: [], gateway: { running: true, window: true } }; + return async (route) => { + const req = route.request(), url = new URL(req.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/plugins") return json({ plugins: [] }); + if (url.pathname === "/api/providers") return json(list); + if (url.pathname === "/api/provider/save") { saves.push(req.postDataJSON()); return json(list); } + if (url.pathname === "/api/gateway/trace") { + if (url.searchParams.get("wait")) return new Promise(() => {}); + return json({ mine: true, now: new Date().toISOString(), seq: 1, totals: { requests: 0, rerouted: 0, errors: 0 }, routes: [] }); + } + if (url.pathname === "/api/gateway/history") return json({ cut: false, days: [], routes: [] }); + if (url.pathname === "/api/groups") return json(groups()); + if (url.pathname.startsWith("/api/groups/")) { posts.push({ path: url.pathname, body: JSON.parse(req.postData() || "{}") }); return json(groups()); } + 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 say = (page, lang, s) => page.evaluate(([l, s]) => (l === "en" ? s : I18N[l][s]), [lang, s]); +const launch = (engine) => (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" })); + +for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + for (const width of [1200, 420]) { + test(`${engine} ${lang} ${width}px: a model's speed is set in Model settings`, async (t) => { + const browser = await launch(engine); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width, height: 900 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + const errors = [], saves = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, saves, [])); + await page.goto("http://magpie.test/?view=providers"); + const L = {}; + for (const k of ["Model settings", "Standard speed", "Fast", "Ultrafast", "Restore default"]) { + L[k] = await say(page, lang, k); + assert.ok(L[k], `${k} has its ${lang}`); + } + const tip = "Sent at this speed with every request for {id} from an agent with no fast pick of its own; where an account has no Ultrafast it goes fast"; + assert.ok(await say(page, lang, tip), `the tooltip has its ${lang}`); + await page.locator(".row.provider", { hasText: "Relay" }).click(); + const editor = page.locator("#modal:not([hidden]) .editor"); + await editor.getByRole("button", { name: L["Model settings"], exact: true }).click(); + const names = editor.locator(".mnames:not([hidden])"); + const row = (id) => names.locator(".mname", { has: page.locator("code", { hasText: new RegExp(`^${id.replace(/\./g, "\\.")}$`) }) }); + const opt = (id, v) => row(id).locator(`.mspeed [data-seg="${v}"]`); + const on = async (id) => row(id).locator(".mspeed .opt.on").getAttribute("data-seg"); + + assert.equal(await row("glm-5").locator(".mspeed").count(), 0, "no fast mode, no choice"); + assert.equal(await opt("gpt-6.1-sol", "ultrafast").textContent(), L["Ultrafast"]); + assert.equal(await opt("gpt-6.1-sol", "").textContent(), L["Standard speed"]); + assert.equal(await opt("gpt-6.1-sol", "priority").textContent(), L["Fast"]); + assert.equal(await opt("gpt-6.1-mini", "ultrafast").count(), 0, "no Ultrafast where no account offers it"); + assert.equal(await on("gpt-6.1-sol"), ""); + assert.equal(await on("gpt-6.1-mini"), "priority", "a saved one shows"); + assert.equal(await row("gpt-6.1-sol").locator(".mspeed").getAttribute("title"), (await say(page, lang, tip)).replace("{id}", "gpt-6.1-sol")); + const [r, b] = [await row("gpt-6.1-sol").boundingBox(), await row("gpt-6.1-sol").locator(".mspeed").boundingBox()]; + assert.ok(b.x >= r.x - 0.5 && b.x + b.width <= r.x + r.width + 0.5, `the choice fits its row (${JSON.stringify([r, b])})`); + + await opt("gpt-6.1-sol", "ultrafast").click(); + assert.equal(await on("gpt-6.1-sol"), "ultrafast"); + assert.ok(await row("gpt-6.1-sol").locator(".munsaved").isVisible(), "the row says unsaved"); + assert.deepEqual(saves, [], "nothing is sent before the Save"); + // back to what it had: nothing to save + await opt("gpt-6.1-mini", "").click(); + await opt("gpt-6.1-mini", "priority").click(); + if (process.env.ARTIFACT_DIR) { + await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true }); + await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-model-speed.png`) }); + } + await editor.locator(".bar button.primary").click(); + for (let i = 0; i < 100 && !saves.length; i++) await page.waitForTimeout(20); + assert.equal(saves.length, 1); + assert.deepEqual(saves[0].modelPrefs, { "gpt-6.1-sol": { tier: "ultrafast" } }); + + // Restore default sends the usual speed for the one that had its own + await page.locator(".row.provider", { hasText: "Relay" }).click(); + if (!(await editor.locator(".mnames:not([hidden])").count())) await editor.getByRole("button", { name: L["Model settings"], exact: true }).click(); + await row("gpt-6.1-mini").getByRole("button", { name: L["Restore default"], exact: true }).click(); + assert.equal(await on("gpt-6.1-mini"), ""); + await editor.locator(".bar button.primary").click(); + for (let i = 0; i < 100 && saves.length < 2; i++) await page.waitForTimeout(20); + assert.equal(saves.length, 2); + assert.deepEqual(saves[1].modelPrefs, { "gpt-6.1-mini": { tier: "" } }); + assert.deepEqual(errors, []); + }); + } + } + for (const lang of ["en", "zh", "zh-TW", "ja", "de"]) { + test(`${engine} ${lang}: a group member goes Standard speed, Fast, Ultrafast`, async (t) => { + const browser = await launch(engine); + t.after(() => browser.close()); + const page = await (await browser.newContext({ viewport: { width: 1100, height: 1400 }, reducedMotion: "reduce" })).newPage(); + page.setDefaultTimeout(5000); + const errors = [], posts = []; + page.on("pageerror", (e) => errors.push(e.message)); + await page.route("**/*", serve(lang, [], posts)); + await page.goto("http://magpie.test/?view=groups"); + const L = {}; + for (const k of ["Edit", "Save", "Fast", "Ultrafast", "Standard speed"]) { L[k] = await say(page, lang, k); assert.ok(L[k], `${k} has its ${lang}`); } + const card = page.locator(".rt-group", { hasText: "Sol" }); + await card.waitFor(); + await card.locator("button", { hasText: L["Edit"] }).click(); + const ed = page.locator(".rt-gedit"); + const fast = (name) => ed.locator(".fbrow", { has: page.locator(".n", { hasText: name }) }).locator("button.rt-fast"); + await fast("gpt-6.1-sol").waitFor(); + assert.equal(await fast("gpt-6.1-sol").textContent(), L["Fast"]); + await fast("gpt-6.1-sol").click(); + assert.equal(await fast("gpt-6.1-sol").textContent(), L["Ultrafast"]); + assert.equal(await fast("gpt-6.1-sol").getAttribute("aria-pressed"), "true"); + // a member whose account has no Ultrafast goes Fast -> Standard + await fast("gpt-6.1-mini").click(); + assert.equal(await fast("gpt-6.1-mini").textContent(), L["Standard speed"]); + await fast("gpt-6.1-mini").click(); + assert.equal(await fast("gpt-6.1-mini").textContent(), L["Fast"]); + const b = ed.locator("button.primary", { hasText: L["Save"] }); + for (let i = 0; i < 10 && (await b.boundingBox()).y > 1400 - 160; i++) { await page.mouse.wheel(0, 300); await page.waitForTimeout(150); } + const bb = await b.boundingBox(); + await page.mouse.click(bb.x + bb.width / 2, bb.y + bb.height / 2); + await page.waitForFunction(() => !document.querySelector(".rt-gedit")); + const sent = posts.find((p) => p.path === "/api/groups/save"); + assert.deepEqual(sent.body.fast, gmembers); + assert.deepEqual(sent.body.ultra, ["oa/gpt-6.1-sol"]); + assert.deepEqual(errors, []); + }); + } +} diff --git a/internal/provider/autoref.go b/internal/provider/autoref.go index a774c1907..9cd2951ff 100644 --- a/internal/provider/autoref.go +++ b/internal/provider/autoref.go @@ -102,7 +102,7 @@ func canonicalRef(ref string, enabled bool) string { // as group/auto-, so its members, off and fast lists, weights, rules // and classifier name it by one id. g's lists are its own (Group.own). func (g *Group) canonicalRefs() { - for _, l := range [][]string{g.Members, g.Off, g.Fast} { + for _, l := range [][]string{g.Members, g.Off, g.Fast, g.Ultra} { for i, v := range l { l[i] = CanonicalRef(v) } diff --git a/internal/provider/fold.go b/internal/provider/fold.go index d460cc559..3f04a80c4 100644 --- a/internal/provider/fold.go +++ b/internal/provider/fold.go @@ -149,6 +149,9 @@ func foldRefs(f file, s *settings.Settings) map[string][]string { for _, m := range g.Fast { note(at+"fast", m) } + for _, m := range g.Ultra { + note(at+"ultra", m) + } for _, m := range g.Off { note(at+"off", m) } @@ -350,6 +353,7 @@ func foldWhere(candidates func([]Provider) [][]int) (int, error) { g.Rules[k].MapUses(ref) } g.Fast = compact(mapEach(g.Fast, ref)) + g.Ultra = compact(mapEach(g.Ultra, ref)) g.Placed = compact(mapEach(g.Placed, ref)) g.Seen = compact(mapEach(g.Seen, ref)) g.Off = compact(mapEach(g.Off, ref)) diff --git a/internal/provider/group.go b/internal/provider/group.go index 7c5f0392c..2890c860b 100644 --- a/internal/provider/group.go +++ b/internal/provider/group.go @@ -296,6 +296,10 @@ type Group struct { // beside Members, not in their ids, so a version before it still // routes to them, only not fast. Fast []string `json:"fast,omitempty"` + // Ultra are the members of Fast sent in the vendor's faster mode + // still (Codex's Ultra Fast, kdajenks on X), where the account + // offers it and priority where not. Always a part of Fast. + Ultra []string `json:"ultra,omitempty"` // Weights are the members' shares (as Members spells them) when the // group routes by weight (Weighted, #1910): one weighing 3 takes three // requests for every one a member weighing 1 takes. One not in it @@ -402,6 +406,8 @@ type Member struct { // Fast is set on a member the group sends in its vendor's fast mode // (Group.Fast), where its model has one. Fast bool + // Ultra is set on a Fast member the group sends in the faster mode. + Ultra bool // Account is the one account or key of Provider the member is sent // on, "/", as Group.Accounts has them // ("provider/model#", groupaccount.go); "" for every one the @@ -473,7 +479,7 @@ func (m Member) Groups() []string { // Below is the member as the group at depth (0 the group itself, 1 the // group in it Path[0] names, …) has it. func (m Member) Below(depth int) Member { - out := Member{ID: m.Path[depth], Path: m.Path[depth:], Via: m.Via[depth:], Redact: m.Redact, Provider: m.Provider, Model: m.Model, Effort: m.Effort, Levels: m.Levels, EffortMap: m.EffortMap, Fast: m.Fast, Account: m.Account, At: m.At} + out := Member{ID: m.Path[depth], Path: m.Path[depth:], Via: m.Via[depth:], Redact: m.Redact, Provider: m.Provider, Model: m.Model, Effort: m.Effort, Levels: m.Levels, EffortMap: m.EffortMap, Fast: m.Fast, Ultra: m.Ultra, Account: m.Account, At: m.At} // its other places in the same group at depth for _, o := range m.Also { if len(o.Path) > depth && slices.Equal(o.Path[:depth], m.Path[:depth]) { @@ -539,7 +545,7 @@ func cloneGroups(gs []Group) []Group { out := make([]Group, len(gs)) for i, g := range gs { g.Members, g.Match, g.Matched, g.Placed = slices.Clone(g.Members), slices.Clone(g.Match), slices.Clone(g.Matched), slices.Clone(g.Placed) - g.Off, g.Levels, g.Fast = slices.Clone(g.Off), slices.Clone(g.Levels), slices.Clone(g.Fast) + g.Off, g.Levels, g.Fast, g.Ultra = slices.Clone(g.Off), slices.Clone(g.Levels), slices.Clone(g.Fast), slices.Clone(g.Ultra) g.Accounts, g.Seen, g.Keys = slices.Clone(g.Accounts), slices.Clone(g.Seen), slices.Clone(g.Keys) g.Former = slices.Clone(g.Former) g.Weights = maps.Clone(g.Weights) @@ -647,6 +653,7 @@ func withoutRemoved(g Group, have map[string]bool) Group { g.Members = kept g.Off = slices.DeleteFunc(slices.Clone(g.Off), gone) g.Fast = slices.DeleteFunc(slices.Clone(g.Fast), gone) + g.Ultra = slices.DeleteFunc(slices.Clone(g.Ultra), gone) g.Weights = renamedWeights(g.Weights, func(m string) string { if gone(m) { return "" @@ -735,6 +742,7 @@ func (g Group) own() Group { g.Off = slices.Clone(g.Off) g.Levels = slices.Clone(g.Levels) g.Fast = slices.Clone(g.Fast) + g.Ultra = slices.Clone(g.Ultra) g.Accounts = slices.Clone(g.Accounts) g.Keys = slices.Clone(g.Keys) g.Seen = slices.Clone(g.Seen) @@ -1353,7 +1361,7 @@ func membersFound(entries []Entry, find entryOf, all []Group, g Group, off func( key := WithMemberAccount(WithMemberEffort(p.ID+"/"+m, effort), acct) here := append(slices.Clone(path), id) fixed, levels := MemberLevels(effort) - mem := Member{ID: here[0], Path: here, Via: via, Redact: redact, Provider: p, Model: m, Effort: fixed, Levels: levels, Fast: g.IsFast(id), Account: acct, At: at} + mem := Member{ID: here[0], Path: here, Via: via, Redact: redact, Provider: p, Model: m, Effort: fixed, Levels: levels, Fast: g.IsFast(id), Ultra: g.IsUltra(id), Account: acct, At: at} if fixed == "" && levels == nil { mem.EffortMap = g.MemberEffortMap(id) } diff --git a/internal/provider/group_share.go b/internal/provider/group_share.go index 53735bc84..57888ad5b 100644 --- a/internal/provider/group_share.go +++ b/internal/provider/group_share.go @@ -213,6 +213,7 @@ func importGroup(text string, over bool) (Imported, error) { p, id, ok := resolveIn(entries, model) return ok && !CanFast(p, id) }) + g.Ultra = slices.DeleteFunc(kept(g.Ultra), func(f string) bool { return !slices.Contains(g.Fast, f) }) g.Weights = renamedWeights(g.Weights, func(m string) string { return here[strings.TrimSpace(m)] }) g.EffortMaps = renamedEffortMaps(g.EffortMaps, func(m string) string { return here[strings.TrimSpace(m)] }) if g.Routing != Manual && len(g.Off) == len(g.Members) { diff --git a/internal/provider/groupaccount.go b/internal/provider/groupaccount.go index e8c9dd700..410bae322 100644 --- a/internal/provider/groupaccount.go +++ b/internal/provider/groupaccount.go @@ -118,7 +118,7 @@ func withoutMemberAccounts(g *Group) { g.RenameMember(m, base) } } - g.Members, g.Fast, g.Off, g.Placed = cleanList(g.Members), cleanList(g.Fast), cleanList(g.Off), cleanList(g.Placed) + g.Members, g.Fast, g.Ultra, g.Off, g.Placed = cleanList(g.Members), cleanList(g.Fast), cleanList(g.Ultra), cleanList(g.Off), cleanList(g.Placed) } // wasMembers are the members the stored group id has, those its patterns diff --git a/internal/provider/groupfast.go b/internal/provider/groupfast.go index ede80eb1e..e3c946d5f 100644 --- a/internal/provider/groupfast.go +++ b/internal/provider/groupfast.go @@ -221,15 +221,37 @@ func cleanFast(entries []Entry, g *Group) error { out = append(out, f) } g.Fast = out + // Ultra is a part of Fast: a member kept out of it is kept out here + g.Ultra = slices.DeleteFunc(slices.Clone(g.Ultra), func(u string) bool { return !slices.Contains(out, key(u)) }) return nil } +// IsUltra reports whether the group sends member id in the faster mode. +func (g Group) IsUltra(id string) bool { + return slices.Contains(g.Ultra, id) && slices.Contains(g.Fast, id) +} + // SetMemberFast sends the group's member id fast, or not, where it is in // the group. func (g *Group) SetMemberFast(id string, fast bool) { + tier := "" + if fast { + tier = "priority" + } + g.SetMemberTier(id, tier) +} + +// SetMemberTier sends the group's member id at tier: "" the usual speed, +// "priority" fast, "ultrafast" the faster mode of an account that offers +// it. Only a member that is in the group is switched on. +func (g *Group) SetMemberTier(id, tier string) { g.Fast = slices.DeleteFunc(slices.Clone(g.Fast), func(x string) bool { return x == id }) - if fast && slices.Contains(g.Members, id) { + g.Ultra = slices.DeleteFunc(slices.Clone(g.Ultra), func(x string) bool { return x == id }) + if tier != "" && slices.Contains(g.Members, id) { g.Fast = append(g.Fast, id) + if tier == "ultrafast" { + g.Ultra = append(g.Ultra, id) + } } } @@ -258,6 +280,11 @@ func (g *Group) RenameMember(from, to string) { g.Fast[i] = to } } + for i, f := range g.Ultra { + if f == from { + g.Ultra[i] = to + } + } for i, p := range g.Placed { if p == from { g.Placed[i] = to diff --git a/internal/provider/modelprefs.go b/internal/provider/modelprefs.go index 37d49e938..b8441a213 100644 --- a/internal/provider/modelprefs.go +++ b/internal/provider/modelprefs.go @@ -605,6 +605,9 @@ type ModelPref struct { // System is the model's own system prompt, as SetModelSystemPrompt // takes it, in place of the one it had: "" takes it away System *string `json:"system,omitempty"` + // Tier is the model's own speed, as SetModelTier: "" usual, "priority" + // or "ultrafast". + Tier *string `json:"tier,omitempty"` } // SetModelPrefs makes the changes to a provider's models, by model id, as @@ -668,6 +671,12 @@ func SetModelPrefs(pid string, prefs map[string]ModelPref) error { return err } } + // nor is its speed, which the gateway reads for each request + if m.Tier != nil { + if _, err := setModelTier(ref, *m.Tier); err != nil { + return err + } + } // nor is what a model makes: its chat list stays as it was, // and the gateway reads it for each request (#1399) if m.Kind != nil { diff --git a/internal/provider/modeltier.go b/internal/provider/modeltier.go new file mode 100644 index 000000000..129a3d264 --- /dev/null +++ b/internal/provider/modeltier.go @@ -0,0 +1,83 @@ +package provider + +// A model's own speed (kdajenks on X): the service tier the user gave one +// model in its Model settings, kept in settings' ModelTiers by "/": "priority" (Codex's Fast) or "ultrafast" (its Ultra +// Fast, which a plan that doesn't offer it is sent priority in place of). The +// gateway sends every request for the model so, for each agent that has no +// pick of its own for it (an agent's fast pick, FastPicks, is that agent's +// and goes first). A routing group's member is sent as the group says. + +import ( + "fmt" + "strings" + + "github.com/yetone/magpie/internal/settings" +) + +// ModelTier is the tier the user gave provider pid's model, "" for none. It +// reads the held settings, as it is asked on every request. +func ModelTier(pid, model string) string { + if pid == "" || model == "" { + return "" + } + return heldSettings().ModelTiers[pid+"/"+model] +} + +// CleanModelTier reads the words people use for a tier: "" (also off, +// usual, standard) for none, "priority" (fast), "ultrafast" (ultra, +// ultra-fast). +func CleanModelTier(v string) (string, error) { + switch strings.ToLower(strings.TrimSpace(v)) { + case "", "off", "none", "usual", "standard", "default": + return "", nil + case "priority", "fast": + return "priority", nil + case "ultrafast", "ultra", "ultra-fast", "ultra_fast": + return "ultrafast", nil + } + return "", fmt.Errorf("a model's speed is one of usual, fast or ultrafast, not %q", v) +} + +// SetModelTier sends a provider's model, spelt "provider/model", at tier: +// "" the usual speed, "priority" or "ultrafast" (see CleanModelTier). Only +// a model with a fast mode magpie can ask for (CanFast) is switched on. +func SetModelTier(ref, tier string) error { + _, err := setModelTier(ref, tier) + return err +} + +func setModelTier(ref, tier string) (bool, error) { + p, model, err := splitRef(ref) + if err != nil { + return false, err + } + if tier, err = CleanModelTier(tier); err != nil { + return false, err + } + key := p.ID + "/" + model + if tier != "" { + if !CanFast(*p, model) { + return false, fmt.Errorf("%s has no fast mode magpie can ask for", key) + } + if tier == "ultrafast" && !CanUltra(*p, model) { + return false, fmt.Errorf("no account offers Ultrafast on %s", key) + } + } + s := settings.Load() + if s.ModelTiers[key] == tier { + return false, nil + } + if tier == "" { + delete(s.ModelTiers, key) + } else { + if s.ModelTiers == nil { + s.ModelTiers = map[string]string{} + } + s.ModelTiers[key] = tier + } + if err := settings.Save(s); err != nil { + return false, err + } + return true, nil +} diff --git a/internal/provider/modeltier_test.go b/internal/provider/modeltier_test.go new file mode 100644 index 000000000..06e353e86 --- /dev/null +++ b/internal/provider/modeltier_test.go @@ -0,0 +1,53 @@ +package provider + +import ( + "slices" + "testing" +) + +func TestCleanModelTier(t *testing.T) { + for in, want := range map[string]string{"": "", "usual": "", "Fast": "priority", "priority": "priority", "ultra": "ultrafast", " ultrafast ": "ultrafast"} { + if got, err := CleanModelTier(in); err != nil || got != want { + t.Errorf("%q: %q %v", in, got, err) + } + } + if _, err := CleanModelTier("turbo"); err == nil { + t.Error("turbo accepted") + } +} + +// A group's Ultra is a part of its Fast: saving, renaming and taking a +// member out keep them so (kdajenks on X). +func TestSaveGroupUltra(t *testing.T) { + fastHome(t) + if err := SaveGroup(Group{ID: "u", Members: []string{"oa/gpt-6.1-sol:high", "an/claude-opus-5-5"}, + Fast: []string{"oa/gpt-6.1-sol:high"}, Ultra: []string{"oa/gpt-6.1-sol:high", "an/claude-opus-5-5"}}); err != nil { + t.Fatal(err) + } + g, ms, _ := FindGroup("group/u") + if !slices.Equal(g.Ultra, []string{"oa/gpt-6.1-sol:high"}) { + t.Fatalf("ultra %v: a member that isn't fast kept it", g.Ultra) + } + if len(ms) != 2 || !ms[0].Ultra || !ms[0].Fast || ms[1].Ultra { + t.Fatalf("resolved %+v", ms) + } + g.RenameMember("oa/gpt-6.1-sol:high", "oa/gpt-6.1-sol:low") + if !g.IsUltra("oa/gpt-6.1-sol:low") || g.IsUltra("oa/gpt-6.1-sol:high") { + t.Fatalf("renamed %v", g.Ultra) + } + g.SetMemberTier("oa/gpt-6.1-sol:low", "priority") + if g.IsUltra("oa/gpt-6.1-sol:low") || !g.IsFast("oa/gpt-6.1-sol:low") { + t.Fatalf("back to fast: %v %v", g.Fast, g.Ultra) + } + g.SetMemberTier("oa/gpt-6.1-sol:low", "ultrafast") + g.SetMemberFast("oa/gpt-6.1-sol:low", false) + if g.IsFast("oa/gpt-6.1-sol:low") || len(g.Ultra) != 0 { + t.Fatalf("off: %v %v", g.Fast, g.Ultra) + } + if err := Rename("oa", "openai"); err != nil { + t.Fatal(err) + } + if g, _, _ = FindGroup("group/u"); !slices.Contains(g.Ultra, "openai/gpt-6.1-sol:high") { + t.Fatalf("after the provider's rename %v", g.Ultra) + } +} diff --git a/internal/provider/rename.go b/internal/provider/rename.go index f867c9d9e..f7ed28a5c 100644 --- a/internal/provider/rename.go +++ b/internal/provider/rename.go @@ -141,6 +141,9 @@ func mapModelRefs(f *file, to func(string) string) { for k, m := range g.Fast { g.Fast[k] = to(m) } + for k, m := range g.Ultra { + g.Ultra[k] = to(m) + } for k, m := range g.Placed { g.Placed[k] = to(m) } diff --git a/internal/settings/settings.go b/internal/settings/settings.go index 6a23b2da7..59cce98f2 100644 --- a/internal/settings/settings.go +++ b/internal/settings/settings.go @@ -1140,6 +1140,12 @@ type Settings struct { // agent sends it (liucl on X). Absent is the agent's prompt as sent // (provider.ModelSystemPrompt). ModelSystemPrompts map[string]string `json:"modelSystemPrompts,omitempty"` + // ModelTiers is the speed the user gave one model, by "/": "priority" (Codex's Fast) or "ultrafast", sent on + // every request for the model of an agent with no fast pick of its own + // for it (kdajenks on X). Absent is the usual speed + // (provider.ModelTier). + ModelTiers map[string]string `json:"modelTiers,omitempty"` // ModelKinds is what the user said a model makes, by "/": "image" or "video", for a provider set up with a // base URL whose own model list doesn't say so (shen-joe, #1399).