plugins: a provider plugin says which service tiers a model serves, and Codex offers them (#2514)

Lovest on Discord (#general, v0.1.1267): a provider plugin had no way to
say a model is served at Fast or Ultrafast, so Codex never offered them for
plugin models, and the host dropped the field anyway.

- host.js keeps m.serviceTiers (tiersOf: string ids or {id} objects,
  trimmed, de-duplicated, anything else dropped) as plugin.Model.ServiceTiers.
- pluginCatalog puts them on catalog.Model.Tiers; CodexTiers offers a
  plugin's tiers when it declares any, so codexcat writes service_tiers
  (priority named Fast) into Codex's catalog and /v1/models.
- forwardTranslated keeps service_tier (OwnTier) for a plugin provider only
  when the request is translated to its Chat or Responses and the tier is
  one the model declares (provider.PluginTiers). A request relayed in its
  own protocol was already sent as the client wrote it; unchanged. Cursor's
  fast flag and #1954's ChatGPT tiers are untouched (#1954 not on main yet).
- Docs: serviceTiers in site/public/docs plugins (en, zh, ja) and a
  "service tiers" section in docs/subsystems/provider-plugins.md.

Tests (internal/gateway/plugin_tiers_test.go, fake plugin FAKE_TIERS):
TestPluginModelServiceTiersListed (fake-1 priority=Fast + ultrafast,
fake-resp ultrafast, fake-claude none) and TestPluginServiceTierReachesFetch
(Responses→plugin Chat and Chat→plugin Responses send a declared tier,
drop an undeclared one; same-protocol relays as before).
Broken by hand: OwnTier branch forced false → 3 translated cases red;
CodexTiers without IsPlugin → listed test red; host.js serviceTiers: [] →
listed test red. Restored → green.

gofmt -l clean; go vet -tags nogui with GOOS=darwin, linux, windows clean.
Not tried with a real vendor plugin that serves ultrafast.
Full suite: go test -timeout 45m ./... at af9e0d6b2 (sandbox HOME, load
average ~408 from other sessions): every package ok except agent and
gateway, which timed out at 45m with no failed test (rerun whole: timed
out again, 0 failures), gui (TestMainWindowCorners killed, #1936),
TestVendorThatStopsMidAnswerIsSaid (filed #2535) and
TestSetAnswersWhileDevinAndProvidersHang (#1375). The reds and the tests
running at each timeout (TestCodexKeptOnChatGPT, TestReplyNamesMember)
pass rerun alone, except TestMainWindowCorners (#1936). CI is the gate.
This commit is contained in:
yetone
2026-10-16 18:13:15 +08:00
parent 63be47717a
commit e733b0722e
13 changed files with 209 additions and 6 deletions
+4
View File
@@ -64,6 +64,10 @@ The provider's editor lists them under *Plugin options* (`pluginOptionsField` in
A plugin in front of Anthropic's or OpenAI's own API (a CPA or sub2api relay, say) can say its upstream answers a web search tool by itself (#2027). Its `config` hook sets `searches: true` on the provider; the host passes it through (`plugin.Provider.Searches`), and [`pluginProvider`](../../internal/provider/plugins.go) sets the provider's `Searches`, as a custom provider's "Searches the web by itself" does (#359). [`searchesItself`](../../internal/gateway/search.go) honours it for a plugin's provider only, on Anthropic's or Responses' API, and only for one the plugin has a model on: a client's `web_search` then goes to the plugin's `fetch` as sent, not through magpie's search. Another sign-in's `Searches` is never read, and Codex's and Grok's stay as they were. As with a relay, `searchRank` leaves it out, so magpie never picks it to search for other models; Settings can name it by hand (`namedSearcherRank`).
## A plugin's service tiers
A plugin says which service tiers its vendor serves a model at with `serviceTiers` on the model (#2514): ids such as `"priority"` and `"ultrafast"`, or objects with an `id`. The host keeps the ids (`tiersOf` in `host.js`, into `plugin.Model.ServiceTiers`), `pluginCatalog` puts them on the catalog model's `Tiers`, and [`CodexTiers`](../../internal/provider/codex_models.go) offers them to Codex, as `codexcat` names them (`priority` is Fast). In [`forwardTranslated`](../../internal/gateway/gateway.go) a request translated to the plugin's Chat or Responses keeps its `service_tier` (`Request.OwnTier`) only when it is among the model's tiers (`provider.PluginTiers`); a request relayed in its own protocol was sent as the client wrote it before, and still is. Cursor's `fast` flag is separate and unchanged.
## A plugin's decision API
A plugin can serve TypeSafe's System One for its provider (#1514). Its `config` hook sets `decide: true` on the provider, and `decides: true` on a model that answers questions rather than a conversation, in the `config` hook or on the `models` hook's list. The host passes both through (`plugin.Provider.Decide`, `plugin.Model.Decides`). [`pluginProvider`](../../internal/provider/plugins.go) then sets the provider's `Decide` to `plugin://<id>/v1`, its own base: `pluginFetch` sends nowhere but the loader's host, so a decision address of the plugin's own couldn't be reached. `AskSystemOne` and the gateway's classifier post `/v1/systemone` with `Provider.Do`, which reaches the loader's `fetch` as `{baseURL}/systemone` with the account's sign-in.
+2 -1
View File
@@ -77,7 +77,8 @@ type Model struct {
// Tiers, in one ChatGPT account's own model list, are the service
// tiers its plan offers on the model ("priority", "ultrafast"); in
// another magpie's, the tiers it offers its Codex on the model
// (#1234).
// (#1234); in a provider plugin's, the tiers it says its vendor serves
// the model at (#2514).
Tiers []string `json:",omitempty"`
// OwnTier is set on a model of a provider the user added by its
// address, which the gateway sends the tier Codex asks for as it is
+7 -2
View File
@@ -4808,8 +4808,13 @@ func (s *Server) forwardTranslated(ctx context.Context, p provider.Provider, to
// the tier the client asked for goes to a provider the user added
// by its address as it was asked (Request.Tier), and to another
// magpie, which offered it and serves it as its own Codex would be
// (#1234)
if own := (p.Preset == "" && p.Account == nil || p.IsRemoteMagpie()) && s.fits(p.ID, tierField, to); own != req.OwnTier {
// (#1234), and to a provider plugin, on its Chat or Responses, when
// it is one the plugin says the model is served at (#2514)
own := p.Preset == "" && p.Account == nil || p.IsRemoteMagpie()
if p.IsPlugin() {
own = req.Tier != "" && (to == provider.Chat || to == provider.Responses) && slices.Contains(provider.PluginTiers(p, model), req.Tier)
}
if own := own && s.fits(p.ID, tierField, to); own != req.OwnTier {
r := *req
r.OwnTier, req = own, &r
}
+143
View File
@@ -0,0 +1,143 @@
package gateway
import (
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync"
"testing"
)
// tierUp is an upstream for the fake plugin that answers Chat and Responses
// and keeps the service_tier each request was sent with ("" for none).
type tierUp struct {
mu sync.Mutex
tiers []any
}
func (u *tierUp) ServeHTTP(w http.ResponseWriter, r *http.Request) {
var q map[string]any
b, _ := io.ReadAll(r.Body)
json.Unmarshal(b, &q)
u.mu.Lock()
u.tiers = append(u.tiers, q["service_tier"])
u.mu.Unlock()
w.Header().Set("Content-Type", "text/event-stream")
if strings.HasSuffix(r.URL.Path, "/responses") {
io.WriteString(w, sse(
`event: response.created`+"\n"+`data: {"type":"response.created","response":{"id":"r1","object":"response","status":"in_progress","output":[]}}`,
`event: response.output_item.done`+"\n"+`data: {"type":"response.output_item.done","output_index":0,"item":{"type":"message","id":"m1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"hi","annotations":[]}]}}`,
`event: response.completed`+"\n"+`data: {"type":"response.completed","response":{"id":"r1","object":"response","status":"completed","output":[{"type":"message","id":"m1","role":"assistant","status":"completed","content":[{"type":"output_text","text":"hi","annotations":[]}]}],"usage":{"input_tokens":3,"output_tokens":1,"total_tokens":4}}}`))
return
}
io.WriteString(w, sse(`data: {"id":"c1","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":"hi"},"finish_reason":"stop"}]}`, `data: [DONE]`))
}
func (u *tierUp) last(t *testing.T) any {
t.Helper()
u.mu.Lock()
defer u.mu.Unlock()
if len(u.tiers) == 0 {
t.Fatal("the plugin asked its upstream nothing")
}
return u.tiers[len(u.tiers)-1]
}
// A provider plugin says which service tiers its vendor serves a model at
// (serviceTiers), and the model list Codex reads offers them: priority as
// Fast, ultrafast by its id (Lovest on Discord, #2514). A model that says
// none is offered none.
func TestPluginModelServiceTiersListed(t *testing.T) {
t.Setenv("FAKE_TIERS", "1")
pid := besideFake(t, "tiered", &tierUp{})
rec := httptest.NewRecorder()
New().Handler().ServeHTTP(rec, httptest.NewRequest("GET", "/v1/models", nil))
var list struct {
Data []struct {
ID string `json:"id"`
Tiers []struct {
ID string `json:"id"`
Name string `json:"name"`
} `json:"service_tiers"`
} `json:"data"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &list); err != nil {
t.Fatalf("%v: %s", err, rec.Body)
}
got := map[string]string{}
for _, m := range list.Data {
s := ""
for _, x := range m.Tiers {
s += x.ID + "=" + x.Name + " "
}
got[m.ID] = s
}
for id, want := range map[string]string{pid + "/fake-1": "priority=Fast ultrafast= ", pid + "/fake-resp": "ultrafast= ", pid + "/fake-claude": ""} {
if s, ok := got[id]; !ok || !tiersLike(s, want) {
t.Errorf("%s tiers %q (listed %v), want %q", id, s, ok, want)
}
}
}
// tiersLike compares "id=name " lists by id, and by name where want names
// one: ultrafast's name comes from Codex's own catalog when it has one.
func tiersLike(got, want string) bool {
g, w := strings.Fields(got), strings.Fields(want)
if len(g) != len(w) {
return false
}
for i := range w {
gi, gn, _ := strings.Cut(g[i], "=")
wi, wn, _ := strings.Cut(w[i], "=")
if gi != wi || wn != "" && gn != wn {
return false
}
}
return true
}
// A request that asks a plugin's model for a tier the plugin says it is
// served at reaches the plugin's fetch with that service_tier, on Chat and
// on Responses (#2514), also where magpie translates the request to the
// plugin's protocol. There, one it doesn't say, or a model that says none, is
// sent without it, as before; a request relayed in the client's own protocol
// was already sent as the client wrote it.
func TestPluginServiceTierReachesFetch(t *testing.T) {
t.Setenv("FAKE_TIERS", "1")
t.Setenv("FAKE_RESPONSES", "1")
up := &tierUp{}
pid := besideFake(t, "tiered", up)
for _, c := range []struct {
path, model, tier string
want any
}{
// translated: Responses to the plugin's Chat model, Chat to its
// Responses one
{"/v1/responses", "fake-1", "ultrafast", "ultrafast"},
{"/v1/responses", "fake-1", "priority", "priority"},
{"/v1/responses", "fake-1", "flex", nil},
{"/v1/chat/completions", "fake-resp", "ultrafast", "ultrafast"},
{"/v1/chat/completions", "fake-resp", "priority", nil},
{"/v1/responses", "fake-claude", "priority", nil},
// relayed as the client sent it, as before
{"/v1/chat/completions", "fake-1", "ultrafast", "ultrafast"},
{"/v1/responses", "fake-resp", "ultrafast", "ultrafast"},
} {
body := `{"model":"` + pid + "/" + c.model + `","service_tier":"` + c.tier + `","stream":true,`
if c.path == "/v1/responses" {
body += `"input":"hi"}`
} else {
body += `"messages":[{"role":"user","content":"hi"}]}`
}
rec := httptest.NewRecorder()
New().Handler().ServeHTTP(rec, httptest.NewRequest("POST", c.path, strings.NewReader(body)))
if rec.Code != 200 {
t.Fatalf("%s %s: %d %s", c.path, c.model, rec.Code, rec.Body)
}
if got := up.last(t); got != c.want {
t.Errorf("%s %s asked %s: the plugin was sent service_tier %v, want %v", c.path, c.model, c.tier, got, c.want)
}
}
}
+16
View File
@@ -1655,6 +1655,19 @@ function rateOf(v) {
return typeof n === "number" && Number.isFinite(n) && n > 0 ? n : 0
}
// tiersOf reads the service tiers a plugin says a model serves
// (m.serviceTiers): ids ("priority", "ultrafast"), or objects with an id as
// Codex's catalog writes them; anything else is dropped
function tiersOf(v) {
if (!Array.isArray(v)) return []
const out = []
for (const t of v) {
const id = typeof t === "string" ? t.trim() : typeof t?.id === "string" ? t.id.trim() : ""
if (id && !out.includes(id)) out.push(id)
}
return out
}
// providers lists each provider and its accounts' models, each asked
// through its proxy (proxies[provider][key], "" the provider's own), as a
// built-in fetches each account's list through the account's.
@@ -1729,6 +1742,9 @@ async function providers({ proxies } = {}) {
rateWas: rateOf(m.rateWas),
// run fast when the request's service_tier is priority (Cursor's)
fast: m.fast === true,
// the service tiers the vendor serves it at (service_tier
// "priority", "ultrafast"), which Codex then offers (#2514)
serviceTiers: tiersOf(m.serviceTiers),
// a decision model (System One's), hidden from agents and
// offered as a routing group's classifier
decides: m.decides === true,
+5
View File
@@ -91,6 +91,11 @@ type Model struct {
// mode when the request says service_tier "priority" (m.fast: Cursor's
// plugin from 0.2.2, for a model Cursor has a fast variant of)
Fast bool `json:"fast"`
// ServiceTiers are the service tiers the plugin says its vendor serves
// the model at (m.serviceTiers: "priority", "ultrafast"): Codex is
// offered them, and a request asking for one reaches the plugin's
// fetch with its service_tier (#2514)
ServiceTiers []string `json:"serviceTiers,omitempty"`
// Decides is set by the plugin on a model that answers System One's
// questions rather than a conversation (m.decides: a decision model
// not named jev-…, Clef or a vendor's own). It counts only where the
+6
View File
@@ -274,6 +274,12 @@ export const FakePlugin = async ({ client }) => ({
p.models["fake-opus@300k"] = { ...sized("fake-opus@300k", "Fake Opus @ 300k"), fast: true }
p.models["fake-opus@1m"] = sized("fake-opus@1m", "Fake Opus @ 1m")
}
// $FAKE_TIERS: fake-1 and fake-resp say the service tiers their vendor
// serves them at (#2514), one as an object as Codex's catalog writes it
if (process.env.FAKE_TIERS) {
p.models["fake-1"] = { ...p.models["fake-1"], serviceTiers: ["priority", { id: "ultrafast" }, "", 7, "priority"] }
if (p.models["fake-resp"]) p.models["fake-resp"] = { ...p.models["fake-resp"], serviceTiers: ["ultrafast"] }
}
// $FAKE_MODELS: the vendor's list, whose answer names one more model
if (process.env.FAKE_MODELS && auth) {
const r = await fetch(process.env.FAKE_MODELS).then((r) => r.text()).catch((e) => {
+4 -2
View File
@@ -631,8 +631,10 @@ func CodexTiers(m *catalog.Model, e Entry, members func(id string) []Member) {
// asks for as it is (hsiangron on X)
m.OwnTier = e.Group == "" && e.Provider.Preset == "" && e.Provider.Account == nil && e.Provider.ID != ""
// another magpie offers the tiers its own Codex is offered on the
// model, and is sent the one Codex asks for as it is (#1234)
if e.Group == "" && e.Provider.IsRemoteMagpie() {
// model, and is sent the one Codex asks for as it is (#1234); a
// provider plugin, those it says its vendor serves the model at, and
// is sent the one Codex asks for when it is among them (#2514)
if e.Group == "" && (e.Provider.IsRemoteMagpie() || e.Provider.IsPlugin() && len(e.Tiers) > 0) {
m.Tiers = e.Tiers
}
if e.Group != "" {
+2 -1
View File
@@ -2290,7 +2290,8 @@ type Entry struct {
// tasks a magpie-served lead writes as text.
AgentsV2 bool `json:"-"`
// Tiers are the service tiers its list offers Codex on the model:
// another magpie's, those it offers its own Codex (#1234)
// another magpie's, those it offers its own Codex (#1234); a provider
// plugin's, those it says its vendor serves the model at (#2514)
Tiers []string `json:"-"`
// Released is the model's release day (YYYY-MM-DD) as its list or
// models.dev says it, "" when neither does: what a group's template
+17
View File
@@ -175,6 +175,21 @@ func pluginModel(pp plugin.Provider, id string) (plugin.Model, bool) {
return plugin.Model{}, false
}
// PluginTiers are the service tiers p's plugin says its vendor serves
// model at (m.serviceTiers, #2514): none for a provider not a plugin's, or
// a model it doesn't list.
func PluginTiers(p Provider, model string) []string {
if !p.IsPlugin() {
return nil
}
pp, ok := PluginOf(p.ID)
if !ok {
return nil
}
m, _ := pluginModel(pp, model)
return m.ServiceTiers
}
func pluginCatalog(pp plugin.Provider) []catalog.Model {
out := make([]catalog.Model, 0, len(pp.Models))
for _, m := range pp.Models {
@@ -186,6 +201,8 @@ func pluginCatalog(pp plugin.Provider) []catalog.Model {
// a decision model the plugin marked counts only where it
// serves a decision API (pp.Decide)
Decides: pp.Decide && m.Decides,
// the tiers it says its vendor serves the model at (#2514)
Tiers: m.ServiceTiers,
}
// a limit under catalog.LeastWindow (512, H20 on Discord) is none:
// the other one, or models.dev, answers (ListedWindow)
+1
View File
@@ -348,6 +348,7 @@ magpie quota <span class="c"># acme · Pro · 5h 37%
<li><code>rateWas</code>:現在実施中の割引の前の倍率。</li>
</ul>
モデル選択画面に表示されます。</li>
<li><code>serviceTiers</code>(<code>models</code> フックが返すモデルに):ベンダーがそのモデルを提供するサービス階層を id で、たとえば <code>["priority", "ultrafast"]</code>。Codex のモデル一覧に載り(<code>priority</code> は Fast)、そのどれかを指定した Chat または Responses のリクエストは <code>service_tier</code> 付きで <code>fetch</code> に届きます。magpie がプロトコルを変換するリクエストでは、モデルが挙げていない階層は送られません。</li>
<li>モデルが推論する場合、<code>variants</code> のキーがそのモデルの推論レベルになります。</li>
</ul>
<h3>ベンダーに接続できないとき</h3>
+1
View File
@@ -348,6 +348,7 @@ magpie quota <span class="c"># acme · Pro · 5h 37%
<li><code>rateWas</code>: the rate before a discount that is running now.</li>
</ul>
Model pickers show them.</li>
<li><code>serviceTiers</code>, on a model the <code>models</code> hook gives: the service tiers its vendor serves it at, as ids, such as <code>["priority", "ultrafast"]</code>. Codex is offered them in its model list (<code>priority</code> as Fast), and a Chat or Responses request that asks for one of them reaches your <code>fetch</code> with its <code>service_tier</code>. A tier the model doesn’t list isn’t sent where magpie translates the request.</li>
<li>The keys of <code>variants</code> become the model’s reasoning levels when it reasons.</li>
</ul>
<h3>When the vendor can’t be reached</h3>
+1
View File
@@ -348,6 +348,7 @@ magpie quota <span class="c"># acme · Pro · 5h 37%
<li><code>rateWas</code>:当前优惠之前的倍率。</li>
</ul>
模型选择器会显示它们。</li>
<li><code>serviceTiers</code>(在 <code>models</code> 钩子返回的模型上):厂商为该模型提供的服务档位,写成 id,例如 <code>["priority", "ultrafast"]</code>。magpie 会把它们写进 Codex 的模型列表(<code>priority</code> 显示为 Fast);Chat 或 Responses 请求选了其中一档时,会带着 <code>service_tier</code> 到达你的 <code>fetch</code>。在 magpie 转换协议的请求里,模型没列出的档位不会发出。</li>
<li>模型支持推理时,<code>variants</code> 的键会成为它的推理档位。</li>
</ul>
<h3>连不上厂商时</h3>