From ff9b0dc9362b80d95f9fc7e281c1108c6dd0a0a4 Mon Sep 17 00:00:00 2001 From: antior <131586786+aantior@users.noreply.github.com> Date: Fri, 20 Nov 2026 19:20:52 +0800 Subject: [PATCH] provider: support plugin account concurrency Let a plugin report an automatic request limit for each account. Account and provider manual limits keep priority, and the GUI and CLI show the automatic value without saving it as a manual override. Verification on origin/main f65fe92ef: targeted provider/plugin tests and race tests pass; go vet, Linux nogui vet, Windows vet, native build, Linux nogui build and Windows build pass; 57 Chromium/i18n plus 24 WebKit GUI tests pass. Without the change, the new automatic-limit GUI cases fail in English and Chinese on both engines. Earlier full Windows runs also exposed unrelated existing path, symlink, cleanup and timeout failures. --- docs/subsystems/provider-plugins.md | 6 ++ internal/cli/providers_cli.go | 9 ++- internal/gui/assets/app.js | 33 ++++++---- internal/gui/assets/i18n.js | 16 +++++ internal/gui/providers.go | 10 +++ .../gui/tests/provider-concurrency.test.cjs | 31 ++++++++- internal/plugin/account_concurrency_test.go | 66 +++++++++++++++++++ internal/plugin/host.js | 34 ++++++++-- internal/plugin/providers.go | 4 ++ .../testdata/accountconcurrency/index.js | 20 ++++++ .../testdata/accountconcurrency/package.json | 7 ++ .../account_plugin_concurrency_test.go | 53 +++++++++++++++ internal/provider/concurrency.go | 38 ++++++++++- internal/provider/provider.go | 3 +- 14 files changed, 308 insertions(+), 22 deletions(-) create mode 100644 internal/plugin/account_concurrency_test.go create mode 100644 internal/plugin/testdata/accountconcurrency/index.js create mode 100644 internal/plugin/testdata/accountconcurrency/package.json create mode 100644 internal/provider/account_plugin_concurrency_test.go diff --git a/docs/subsystems/provider-plugins.md b/docs/subsystems/provider-plugins.md index 309ecc231..1469f7529 100644 --- a/docs/subsystems/provider-plugins.md +++ b/docs/subsystems/provider-plugins.md @@ -349,6 +349,12 @@ A completed fetch still drains its queued response head before interpreting the The GUI's plugin integration includes `subOf`, `pluginSubs`, and `startPluginSignIn`. A change to sign-in or provider presentation must follow these paths as well as the built-in paths it affects. +## Per-account automatic concurrency + +A plugin may expose `auth.accountConcurrency(getAuth, { signal })`, returning a positive integer for the account passed to `getAuth`. During `providers`, [`host.js`](../../internal/plugin/host.js) runs the hook separately for every account, in that account's scope and through its proxy, after the normal credential refresh. The calls run beside model discovery and share the provider-list deadline. The returned value is listed as `plugin.Account.MaxConcurrency`; `Cached` retains the last listed value across cache rebuilds. + +[`Provider.LaneLimit`](../../internal/provider/concurrency.go) applies an account's manual `AccountConcurrency` first, then the provider's manual `MaxConcurrency`, then the plugin account value, and finally the plugin's static `magpie.maxConcurrency`/`auth.maxConcurrency`. An automatic value is never saved into either manual map. `/api/providers` exposes the automatic values separately as `accountPluginConcurrency`, keyed by lowercase account reference, so the editor can show an account-specific Automatic choice. A missing hook, timeout, failed read, or invalid result leaves that entry absent and preserves the old static-default behavior. The auxiliary read must not mark the account's sign-in expired. `TestProvidersListEachAccountsConcurrency`, `TestPluginAccountLaneLimits`, and `provider-concurrency.test.cjs` cover the host handoff, priority and restoration to automatic, and GUI presentation. + ## Verification Plugins may also declare a provider-independent `magpie.hooks` entry, including pure gateway packages and mixed provider/Pi packages. Its asynchronous request contract and verification are documented in [Gateway request hooks](gateway-request-hooks.md). Existing provider hooks still use their normal entry path. diff --git a/internal/cli/providers_cli.go b/internal/cli/providers_cli.go index a924ca4bc..fae9a7232 100644 --- a/internal/cli/providers_cli.go +++ b/internal/cli/providers_cli.go @@ -2111,18 +2111,25 @@ func accountConcurrencyCmd(rest []string) error { label[k.ID] = k.Masked + " " + muted.Render(k.ID) } } - base := p.Concurrency() for _, r := range refs { name := r if l, ok := label[r]; ok { name = l } n, own := p.AccountConcurrencyOf(r) + base, automatic := p.Concurrency(), false + if p.MaxConcurrency == nil { + if v, ok := p.PluginAccountConcurrency(r); ok { + base, automatic = v, true + } + } switch { case own && n > 0: fmt.Printf("%s · at most %d at once (its own)\n", name, n) case own: fmt.Println(name, "· no limit at once (its own)") + case automatic: + fmt.Printf("%s · at most %d at once (automatic)\n", name, base) case base > 0: fmt.Println(name, muted.Render(fmt.Sprintf("· at most %d at once (%s's)", base, p.Name))) default: diff --git a/internal/gui/assets/app.js b/internal/gui/assets/app.js index 83217eee2..50f16db8e 100644 --- a/internal/gui/assets/app.js +++ b/internal/gui/assets/app.js @@ -7922,10 +7922,11 @@ function proxyPicker() { } // concurrencyField: requests each key or account has out at once (Lemon: -// Codex risk control past five); "" takes the plugin's, as its placeholder +// Codex risk control past five); "" takes the automatic or plugin default function concurrencyField(p) { const plugin = p?.pluginConcurrency || 0; - const box = input(draft.concurrency ?? "", plugin ? t("{n}, as its plugin says", { n: plugin }) : t("No limit"), "number"); + const automatic = Object.keys(p?.accountPluginConcurrency || {}).length > 0; + const box = input(draft.concurrency ?? "", automatic ? t("Automatic for each account (plan or plugin default)") : plugin ? t("{n}, as its plugin says", { n: plugin }) : t("No limit"), "number"); box.classList.add("concurrency"); // the queue past it (#892): past either, a request is turned away (429) const queue = input(draft.queueLimit ?? "", t("No bound"), "number"); @@ -7949,7 +7950,7 @@ function concurrencyField(p) { }; } return [ - ...field(t("Requests at once"), box, (plugin ? t("Over it, requests queue and go out in order; empty takes the plugin's {n}, 0 is no limit", { n: plugin }) : t("Over it, requests queue and go out in order; 0 or empty is no limit"))), + ...field(t("Requests at once"), box, (automatic ? t("Over it, requests queue and go out in order; empty follows each account's plan or plugin default, 0 is no limit") : plugin ? t("Over it, requests queue and go out in order; empty takes the plugin's {n}, 0 is no limit", { n: plugin }) : t("Over it, requests queue and go out in order; 0 or empty is no limit"))), ...field(t("Accounts at once"), accounts, t("How many of its accounts or keys take requests at once, the first in the list; the next takes over when one runs out or fails. 0 is no limit")), ...field(t("Requests per minute"), rpm, t("How many requests each key or account sends in any minute, retries included; one more waits for room, up to 2 minutes. 0 or empty is no limit")), ...field(t("Queue size"), queue, t("How many requests may wait for each key or account; one more is turned away at once. 0 or empty is no bound")), @@ -14738,14 +14739,24 @@ function laneOwnOf(p, ref) { const k = String(ref).toLowerCase(); return Object.prototype.hasOwnProperty.call(m, k) ? m[k] : null; } -// laneBase: the provider's limit, as typed in its open editor before Save -function laneBase(p) { +// laneBase: a manual provider limit, as typed before Save, else this +// account's automatic value and then the plugin's static default +function laneManualBase(p) { const d = draft && editing === p?.id ? concurrencyOfDraft() : undefined; - return d != null ? d : d === null ? p?.pluginConcurrency || 0 : p?.maxConcurrency != null ? p.maxConcurrency : p?.pluginConcurrency || 0; + return d != null ? d : d === null ? null : p?.maxConcurrency; +} +function laneAutomatic(p, ref) { + return laneManualBase(p) == null && Object.prototype.hasOwnProperty.call(p?.accountPluginConcurrency || {}, String(ref).toLowerCase()); +} +function laneBase(p, ref) { + const manual = laneManualBase(p); + if (manual != null) return manual; + const automatic = p?.accountPluginConcurrency?.[String(ref).toLowerCase()]; + return automatic > 0 ? automatic : p?.pluginConcurrency || 0; } function laneLimitOf(p, ref) { const own = laneOwnOf(p, ref); - return own != null ? own : laneBase(p); + return own != null ? own : laneBase(p, ref); } function laneText(pill) { const p = providers?.providers?.find((x) => x.id === pill.dataset.provider); @@ -14761,7 +14772,7 @@ function laneText(pill) { if (tools && line && !pill.classList.contains("open") && pill !== document.activeElement && pill.parentElement === (on ? tools : line)) on ? line.querySelector(".grow").before(pill) : tools.insertBefore(pill, tools.querySelector(".text.quiet")); pill.classList.toggle("busy-lane", !!(limit && busy >= limit)); pill.classList.toggle("queued", !!waiting); - const whose = own != null ? t("its own") : t("the provider's"); + const whose = own != null ? t("its own") : laneAutomatic(p, pill.dataset.ref) ? t("its plan or plugin default") : t("the provider's"); pill.title = (limit ? t("At most {n} requests out at once on this one, {whose}; more wait in a queue and go in order. Counted across every model, routing group and agent", { n: limit, whose }) : t("No limit on requests at once on this one, {whose}", { whose })) + (busy || waiting ? "\n" + t("{n} running, {q} queued now", { n: busy, q: waiting }) : "") @@ -14777,13 +14788,13 @@ function laneLimitPill(p, ref, who, name) { laneText(pill); const own = laneOwnOf(p, ref); const set = (v) => accountAction("provider/accountconcurrency", { id: p.id, account: ref, limit: v }, - v == null ? t("{who} takes the provider's limit", { who: name }) : v ? t("{who}: at most {n} requests at once", { who: name, n: v }) : t("{who}: no limit on requests at once", { who: name })); + v == null ? t(laneAutomatic(p, ref) ? "{who} takes its automatic limit" : "{who} takes the provider's limit", { who: name }) : v ? t("{who}: at most {n} requests at once", { who: name, n: v }) : t("{who}: no limit on requests at once", { who: name })); const other = () => pillNumber(pill, own ? String(own) : "", "1–1000", "alane-in", t("Requests at once"), (v) => /^\d+$/.test(v) && +v <= 1000 ? +v : null, t("Requests at once: a whole number from 0 to 1000"), own, set); pill.onclick = (e) => { e.stopPropagation(); if (pill.classList.contains("open")) return closeProtoMenu(); - const base = laneBase(p); - const opts = [{ v: "default", name: "Provider's", note: base ? t("{n} at once", { n: base }) : t("No limit") }, { v: 0, name: "No limit", note: "Any number at once" }]; + const base = laneBase(p, ref), automatic = laneAutomatic(p, ref); + const opts = [{ v: "default", name: automatic ? t("Automatic") : "Provider's", note: base ? t("{n} at once", { n: base }) : t("No limit") }, { v: 0, name: "No limit", note: "Any number at once" }]; const nums = own == null || own === 0 || LANE_LIMITS.includes(own) ? LANE_LIMITS : [...LANE_LIMITS, own].sort((a, b) => a - b); for (const n of nums) opts.push({ v: n, name: String(n), note: "", literalName: true }); opts.push({ v: -1, name: "Other…", note: "A number of your own, up to 1000" }); diff --git a/internal/gui/assets/i18n.js b/internal/gui/assets/i18n.js index 7fbe9a03b..24d8b7ea1 100644 --- a/internal/gui/assets/i18n.js +++ b/internal/gui/assets/i18n.js @@ -3064,6 +3064,10 @@ const I18N = { "Price rate of {user}": "{user} 的价格倍率", "Price rate of {user}: a number above 0 up to 1000, at most three decimals": "{user} 的价格倍率:大于 0、不超过 1000 的数字,最多三位小数", "{n}, as its plugin says": "{n}(插件的默认值)", + "Automatic for each account (plan or plugin default)": "按账号自动(套餐或插件默认值)", + "Over it, requests queue and go out in order; empty follows each account's plan or plugin default, 0 is no limit": "超出时排队,按顺序发出;留空则按各账号套餐或插件默认值,0 为不限制", + "its plan or plugin default": "它的套餐或插件默认值", + "{who} takes its automatic limit": "{who}已恢复为自动并发", "Over it, requests queue and go out in order; 0 or empty is no limit": "超出时排队,按顺序发出;0 或留空为不限制", "Accounts at once": "同时使用的账号数", "How many of its accounts or keys take requests at once, the first in the list; the next takes over when one runs out or fails. 0 is no limit": "同时接请求的账号或 Key 数量,按列表顺序取前几个;其中一个额度用完或失败时,由下一个接替。0 为不限制", @@ -8582,6 +8586,10 @@ const I18N = { "Price rate of {user}": "{user} 的價格倍率", "Price rate of {user}: a number above 0 up to 1000, at most three decimals": "{user} 的價格倍率:大於 0、不超過 1000 的數字,最多三位小數", "{n}, as its plugin says": "{n}(外掛的預設值)", + "Automatic for each account (plan or plugin default)": "按帳號自動(方案或外掛預設值)", + "Over it, requests queue and go out in order; empty follows each account's plan or plugin default, 0 is no limit": "超出時排隊,按順序發出;留空則依各帳號方案或外掛預設值,0 為不限制", + "its plan or plugin default": "它的方案或外掛預設值", + "{who} takes its automatic limit": "{who}已恢復為自動並發", "Over it, requests queue and go out in order; 0 or empty is no limit": "超出時排隊,按順序發出;0 或留空為不限制", "Accounts at once": "同時使用的帳號數", "How many of its accounts or keys take requests at once, the first in the list; the next takes over when one runs out or fails. 0 is no limit": "同時接請求的帳號或 Key 數量,依清單順序取前幾個;其中一個額度用完或失敗時,由下一個接替。0 為不限制", @@ -14071,6 +14079,10 @@ const I18N = { "Price rate of {user}": "{user} の価格倍率", "Price rate of {user}: a number above 0 up to 1000, at most three decimals": "{user} の価格倍率: 0 より大きく 1000 以下の数値、小数点以下 3 桁まで", "{n}, as its plugin says": "{n}(プラグインの既定値)", + "Automatic for each account (plan or plugin default)": "アカウントごとに自動(プランまたはプラグインの既定値)", + "Over it, requests queue and go out in order; empty follows each account's plan or plugin default, 0 is no limit": "超えたリクエストはキューに入り、順番に送られます。空欄なら各アカウントのプランまたはプラグインの既定値、0 で上限なし", + "its plan or plugin default": "そのプランまたはプラグインの既定値", + "{who} takes its automatic limit": "{who}は自動同時リクエスト数に戻りました", "Over it, requests queue and go out in order; 0 or empty is no limit": "超えたリクエストはキューに入り、順番に送られます。0 または空欄で上限なし", "Accounts at once": "同時に使うアカウント数", "How many of its accounts or keys take requests at once, the first in the list; the next takes over when one runs out or fails. 0 is no limit": "同時にリクエストを受けるアカウントやキーの数で、一覧の先頭から選ばれます。どれかが使い切るか失敗すると次が引き継ぎます。0 で上限なし", @@ -19603,6 +19615,10 @@ const I18N = { "Price rate of {user}": "Preisfaktor von {user}", "Price rate of {user}: a number above 0 up to 1000, at most three decimals": "Preisfaktor von {user}: eine Zahl über 0 bis 1000, höchstens drei Nachkommastellen", "{n}, as its plugin says": "{n}, laut Erweiterung", + "Automatic for each account (plan or plugin default)": "Automatisch je Konto (Plan oder Standard der Erweiterung)", + "Over it, requests queue and go out in order; empty follows each account's plan or plugin default, 0 is no limit": "Darüber hinaus warten Anfragen in einer Warteschlange und gehen der Reihe nach raus; leer folgt dem Plan oder Erweiterungsstandard jedes Kontos, 0 heißt kein Limit", + "its plan or plugin default": "sein Plan oder Erweiterungsstandard", + "{who} takes its automatic limit": "{who} nutzt wieder das automatische Limit", "Over it, requests queue and go out in order; 0 or empty is no limit": "Darüber hinaus warten Anfragen in einer Warteschlange und gehen der Reihe nach raus; 0 oder leer heißt kein Limit", "Accounts at once": "Konten gleichzeitig", "How many of its accounts or keys take requests at once, the first in the list; the next takes over when one runs out or fails. 0 is no limit": "Wie viele seiner Konten oder Schlüssel gleichzeitig Anfragen annehmen, die ersten der Liste; ist eines aufgebraucht oder schlägt fehl, übernimmt das nächste. 0 heißt kein Limit", diff --git a/internal/gui/providers.go b/internal/gui/providers.go index c85383615..71e529ffb 100644 --- a/internal/gui/providers.go +++ b/internal/gui/providers.go @@ -449,6 +449,8 @@ type providerJSON struct { // each key's or account's own limit over it (#892), by its name in // lower case or its key id; 0 there is none AccountConcurrency map[string]int `json:"accountConcurrency,omitempty"` + // each plugin account's automatic limit, before either manual setting + AccountPluginConcurrency map[string]int `json:"accountPluginConcurrency,omitempty"` // each subscription account's weight under By weight routing, by its // name in lower case; one not in it weighs 1 (provider.AccountWeights) AccountWeights map[string]int `json:"accountWeights,omitempty"` @@ -1003,6 +1005,14 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs AccountConcurrency: p.AccountConcurrency, AccountWeights: p.AccountWeights, QueueLimit: p.QueueLimit, QueueWait: p.QueueWait, MaxRPM: p.MaxRPM, MaxImages: p.MaxImages, Outputs: provider.OutputsOf(p.ID), Compacts: provider.CompactsOf(p.ID), } + for _, r := range p.AccountRefs() { + if n, ok := p.PluginAccountConcurrency(r); ok { + if out.AccountPluginConcurrency == nil { + out.AccountPluginConcurrency = map[string]int{} + } + out.AccountPluginConcurrency[strings.ToLower(strings.TrimSpace(r))] = n + } + } if p.Account != nil && p.Account.Agent == p.ID { out.SignInMoves = provider.SignInMovesOf(p.ID) } diff --git a/internal/gui/tests/provider-concurrency.test.cjs b/internal/gui/tests/provider-concurrency.test.cjs index 546929607..cf90c7057 100644 --- a/internal/gui/tests/provider-concurrency.test.cjs +++ b/internal/gui/tests/provider-concurrency.test.cjs @@ -36,9 +36,19 @@ const lemon = { account: { agent: "plugin", agentName: "Lemon", user: "lemon@example.com", plan: "" }, proxy: "", maxConcurrency: null, pluginConcurrency: 4, }; +const kimi = { + id: "kimi-work", name: "Kimi Work", icon: "generic", chat: "plugin://kimi-work/v1", responses: "", anthropic: "", catalog: "", + models: [{ id: "k3-agent", name: "K3", on: true }], agents: [], fallback: [], headers: {}, keyList: [], + account: { agent: "kimi-work", agentName: "Kimi Work", user: "a@example.com", plan: "", logins: [ + { user: "a@example.com", plan: "", active: true, on: true }, + { user: "b@example.com", plan: "", on: true }, + ] }, + proxy: "", maxConcurrency: null, pluginConcurrency: 1, + accountPluginConcurrency: { "a@example.com": 2, "b@example.com": 4 }, +}; function serve(lang, posts) { - const providers = { providers: [relay, codex, lemon], presets: [], excluded: [], gateway: { running: true, window: true } }; + const providers = { providers: [relay, codex, lemon, kimi], presets: [], excluded: [], gateway: { running: true, window: true }, plugins: [{ id: "kimi-work", pid: "kimi-work", name: "Kimi Work", icon: "generic", spec: "@magpie-community/opencode-kimi-work-auth" }] }; const state = { agents: [], profiles: [], settings: { lang, theme: "light" } }; return async (route) => { const url = new URL(route.request().url()); @@ -60,8 +70,8 @@ function serve(lang, posts) { } const words = { - en: { label: "Requests at once", save: "Save", none: "No limit", plugin: "4, as its plugin says", hint: "Over it, requests queue and go out in order; 0 or empty is no limit", bad: "Requests at once: a whole number from 0 to 1000" }, - zh: { label: "同时请求数", save: "保存", none: "不限制", plugin: "4(插件的默认值)", hint: "超出时排队,按顺序发出;0 或留空为不限制", bad: "同时请求数:请填写 0 到 1000 之间的整数" }, + en: { label: "Requests at once", save: "Save", none: "No limit", plugin: "4, as its plugin says", automatic: "Automatic for each account (plan or plugin default)", automaticMenu: "Automatic", hint: "Over it, requests queue and go out in order; 0 or empty is no limit", bad: "Requests at once: a whole number from 0 to 1000" }, + zh: { label: "同时请求数", save: "保存", none: "不限制", plugin: "4(插件的默认值)", automatic: "按账号自动(套餐或插件默认值)", automaticMenu: "自动", hint: "超出时排队,按顺序发出;0 或留空为不限制", bad: "同时请求数:请填写 0 到 1000 之间的整数" }, }; for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) { @@ -183,6 +193,21 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", assert.deepEqual(errors, []); }); + test(`${engine} ${lang}: account plan limits are automatic unless a manual number is typed`, async (t) => { + const { page, errors } = await open(t, "Kimi Work"); + assert.equal(await box(page).inputValue(), ""); + assert.equal(await box(page).getAttribute("placeholder"), w.automatic); + const a = page.locator('.editor .accts .acc[data-account-id="a@example.com"] .alane'); + const b = page.locator('.editor .accts .acc[data-account-id="b@example.com"] .alane'); + assert.equal(await a.textContent(), lang === "zh" ? "并发 2" : "2 at once"); + assert.equal(await b.textContent(), lang === "zh" ? "并发 4" : "4 at once"); + await a.click(); + const option = page.locator(".proto-menu .pm-item", { has: page.locator(".pm-name", { hasText: w.automaticMenu }) }); + assert.equal(await option.count(), 1); + assert.equal(await option.locator(".pm-note").textContent(), lang === "zh" ? "并发 2" : "2 at once"); + assert.deepEqual(errors, []); + }); + test(`${engine} ${lang}: a plugin's provider shows what its plugin says`, async (t) => { const { page, errors, posts } = await open(t, "Lemon"); assert.equal(await box(page).inputValue(), ""); diff --git a/internal/plugin/account_concurrency_test.go b/internal/plugin/account_concurrency_test.go new file mode 100644 index 000000000..22dc99b1d --- /dev/null +++ b/internal/plugin/account_concurrency_test.go @@ -0,0 +1,66 @@ +package plugin + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "testing" + "time" +) + +func TestProvidersListEachAccountsConcurrency(t *testing.T) { + sandbox(t) + if err := os.MkdirAll(filepath.Dir(AuthPath()), 0o700); err != nil { + t.Fatal(err) + } + auth := `{ + "plan":{"type":"oauth","accountId":"a@example.com"}, + "plan#b":{"type":"oauth","accountId":"b@example.com"}, + "plan#bad":{"type":"oauth","accountId":"bad@example.com"}, + "legacy":{"type":"oauth","accountId":"old@example.com"} + }` + if err := os.WriteFile(AuthPath(), []byte(auth), 0o600); err != nil { + t.Fatal(err) + } + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + abs, _ := filepath.Abs("testdata/accountconcurrency") + if _, err := Add(ctx, abs); err != nil { + t.Fatal(err) + } + ps, err := Providers(ctx) + if err != nil { + t.Fatal(err) + } + check := func(list []Provider) { + t.Helper() + by := map[string]Provider{} + for _, p := range list { + by[p.ID] = p + } + b, err := json.Marshal(by["plan"].Accounts) + if err != nil { + t.Fatal(err) + } + var accounts []map[string]any + if err := json.Unmarshal(b, &accounts); err != nil { + t.Fatal(err) + } + got := map[string]any{} + for _, a := range accounts { + got[a["accountId"].(string)] = a["maxConcurrency"] + } + if got["a@example.com"] != float64(2) || got["b@example.com"] != float64(4) { + t.Errorf("per-account limits = %v, want A=2 and B=4; raw %s", got, b) + } + if got["bad@example.com"] != nil { + t.Errorf("a failed subscription read passed a limit instead of the static fallback: %v", got) + } + if by["plan"].MaxConcurrency != 1 || by["legacy"].MaxConcurrency != 3 { + t.Errorf("static plugin limits changed: plan=%d legacy=%d", by["plan"].MaxConcurrency, by["legacy"].MaxConcurrency) + } + } + check(ps) + check(Cached()) +} diff --git a/internal/plugin/host.js b/internal/plugin/host.js index f72330dd0..17fae33c2 100644 --- a/internal/plugin/host.js +++ b/internal/plugin/host.js @@ -2523,6 +2523,27 @@ function concurrencyOf(a) { return declared(a, "maxConcurrency") } +// accountConcurrency asks a plugin for one account's automatic limit. A +// missing hook, a failed read or an invalid answer leaves no account value, +// so the provider's static plugin default still applies. +async function accountConcurrency(id, a, key, through, signal) { + if (typeof a.auth.accountConcurrency !== "function") return 0 + const ctl = new AbortController(), stop = () => ctl.abort() + if (signal?.aborted) stop() + else signal?.addEventListener("abort", stop, { once: true }) + try { + return await inTime(() => via.run(through(key), () => inScope(id, key, async () => { + await fresh(id, key) + const n = await a.auth.accountConcurrency(async () => authCopy(key), { signal: ctl.signal }) + return Number.isInteger(n) && n > 0 ? Math.min(n, 1000) : 0 + })), listWait, "the plugin's account concurrency", ctl) + } catch { + return 0 + } finally { + signal?.removeEventListener("abort", stop) + } +} + // atOnceOf is how many of its accounts the plugin says may take requests // at the same time, magpie's own field: the auth hook's maxAccounts, else // package.json's magpie.maxAccounts, as concurrencyOf reads its own. The @@ -2582,28 +2603,30 @@ async function providers({ proxies, off } = {}, signal) { const gen = infoGen if (quiet.has(id)) { const p = await info(id, undefined, false, listWait, true) - return rowOf(id, a, keys, stored, p, []) + return rowOf(id, a, keys, stored, p, [], []) } // every account is listed side by side, each hook given listWait: a // second account no longer waits behind the first, where two // listWaits back to back took one provider past refreshDeadline twice // over (#4065) - const [p, own] = await Promise.all([ + const [p, own, limits] = await Promise.all([ via.run(through(), () => info(id, undefined, false, listWait, false, signal)).then((q) => (keepInfo(keys[0] ?? id, q, gen), q)), // each account's own models, as the built-ins read each account's: a // plan may serve fewer, or others, than the first account's. One that // can't be read is taken to have them all, or the ones it was last // told to have, as a built-in account whose fetch failed keeps its own. Promise.all(keys.slice(1).map((k) => via.run(through(k), () => info(id, k, true, listWait, false, signal)).then((q) => (keepInfo(k, q, gen), q)).catch((e) => ({ failed: true, listError: e?.message ?? String(e) })))), + Promise.all(keys.map((k) => accountConcurrency(id, a, k, through, signal))), ]) - return rowOf(id, a, keys, stored, p, own) + return rowOf(id, a, keys, stored, p, own, limits) } return Promise.all([...auths()].map(row)) } // rowOf is the providers row of id (registered as a), its accounts keys -// of stored, p its info and own the other accounts' infos. -function rowOf(id, a, keys, stored, p, own) { +// of stored, p its info and own the other accounts' infos. limits are the +// accounts' automatic request limits, in the same order as keys. +function rowOf(id, a, keys, stored, p, own, limits) { const models = { ...p.models } for (const q of own) for (const [k, m] of Object.entries(q?.models ?? {})) models[k] ??= m const ids = (q) => Object.values(q.models).filter((m) => m.status !== "deprecated").map((m) => m.id) @@ -2658,6 +2681,7 @@ function rowOf(id, a, keys, stored, p, own) { models: own.length === 0 ? undefined : i === 0 ? ids(p) : own[i - 1]?.models ? ids(own[i - 1]) : undefined, fellBack: i === 0 ? !!p.fellBack : !!(own[i - 1]?.fellBack || own[i - 1]?.failed), listError: (i === 0 ? p.fellBack && p.listError : own[i - 1]?.listError) || "", + maxConcurrency: limits[i] || undefined, })), models: Object.values(models) .filter((m) => m.status !== "deprecated") diff --git a/internal/plugin/providers.go b/internal/plugin/providers.go index 187c1ff38..847a37fa7 100644 --- a/internal/plugin/providers.go +++ b/internal/plugin/providers.go @@ -295,6 +295,9 @@ type Account struct { Models []string `json:"models,omitempty"` FellBack bool `json:"fellBack,omitempty"` ListError string `json:"listError,omitempty"` + // MaxConcurrency is this account's automatic limit from the plugin's + // accountConcurrency hook; 0 leaves the provider's static plugin default. + MaxConcurrency int `json:"maxConcurrency,omitempty"` } var ( @@ -748,6 +751,7 @@ func Cached() []Provider { for _, w := range was { if w.Key == a.Key { p.Accounts[i].Models, p.Accounts[i].FellBack, p.Accounts[i].ListError = w.Models, w.FellBack, w.ListError + p.Accounts[i].MaxConcurrency = w.MaxConcurrency } } } diff --git a/internal/plugin/testdata/accountconcurrency/index.js b/internal/plugin/testdata/accountconcurrency/index.js new file mode 100644 index 000000000..71d5ab30f --- /dev/null +++ b/internal/plugin/testdata/accountconcurrency/index.js @@ -0,0 +1,20 @@ +export const Plan = async () => ({ + auth: { + provider: "plan", + maxConcurrency: 1, + accountConcurrency: async (getAuth) => { + const auth = await getAuth() + if (auth.accountId === "bad@example.com") throw new Error("subscription unavailable") + return auth.accountId === "a@example.com" ? 2 : 4 + }, + methods: [{ type: "api", label: "API key" }], + }, +}) + +export const Legacy = async () => ({ + auth: { + provider: "legacy", + maxConcurrency: 3, + methods: [{ type: "api", label: "API key" }], + }, +}) diff --git a/internal/plugin/testdata/accountconcurrency/package.json b/internal/plugin/testdata/accountconcurrency/package.json new file mode 100644 index 000000000..1cc2124d6 --- /dev/null +++ b/internal/plugin/testdata/accountconcurrency/package.json @@ -0,0 +1,7 @@ +{ + "name": "opencode-account-concurrency-test", + "version": "1.0.0", + "type": "module", + "main": "index.js", + "magpie": { "maxConcurrency": 1 } +} diff --git a/internal/provider/account_plugin_concurrency_test.go b/internal/provider/account_plugin_concurrency_test.go new file mode 100644 index 000000000..fada172a9 --- /dev/null +++ b/internal/provider/account_plugin_concurrency_test.go @@ -0,0 +1,53 @@ +package provider + +import ( + "encoding/json" + "testing" + + "github.com/yetone/magpie/internal/plugin" +) + +func TestPluginAccountLaneLimits(t *testing.T) { + var pp plugin.Provider + if err := json.Unmarshal([]byte(`{ + "id":"kimi-work","maxConcurrency":1,"accounts":[ + {"key":"kimi-work","accountId":"a@example.com","maxConcurrency":2}, + {"key":"kimi-work#b","accountId":"b@example.com","maxConcurrency":4}, + {"key":"kimi-work#unknown","accountId":"unknown@example.com"} + ]}`), &pp); err != nil { + t.Fatal(err) + } + plugin.UseCached([]plugin.Provider{}) + t.Cleanup(func() { plugin.UseCached(nil) }) + account := func(user, key string) Provider { + return Provider{ID: "kimi-work", Account: &Account{Agent: "plugin", User: user, plugin: &pp, pluginKey: key}} + } + a, b := account("a@example.com", "kimi-work"), account("b@example.com", "kimi-work#b") + if got := a.LaneLimit(); got != 2 { + t.Errorf("Moderato account's lane limit = %d, want 2", got) + } + if got := b.LaneLimit(); got != 4 { + t.Errorf("Allegro account's lane limit = %d, want 4", got) + } + if got := account("unknown@example.com", "kimi-work#unknown").LaneLimit(); got != 1 { + t.Errorf("unknown plan's lane limit = %d, want the static fallback 1", got) + } + + three := 3 + a.MaxConcurrency = &three + if got := a.LaneLimit(); got != 3 { + t.Errorf("provider manual limit = %d, want 3 over the plan", got) + } + a.AccountConcurrency = map[string]int{"a@example.com": 1} + if got := a.LaneLimit(); got != 1 { + t.Errorf("account manual limit = %d, want 1 over provider and plan", got) + } + a.AccountConcurrency = map[string]int{"a@example.com": 0} + if got := a.LaneLimit(); got != 0 { + t.Errorf("account's explicit no limit = %d, want 0", got) + } + a.MaxConcurrency, a.AccountConcurrency = nil, nil + if got := a.LaneLimit(); got != 2 { + t.Errorf("restored automatic limit = %d, want 2", got) + } +} diff --git a/internal/provider/concurrency.go b/internal/provider/concurrency.go index 896be6fe5..384510cee 100644 --- a/internal/provider/concurrency.go +++ b/internal/provider/concurrency.go @@ -19,6 +19,36 @@ func (p Provider) Concurrency() int { return p.PluginConcurrency() } +// PluginAccountConcurrency is the automatic limit the plugin last listed +// for one account, and whether it listed one. It is not a user setting: a +// provider's or account's manual limit takes priority over it. +func (p Provider) PluginAccountConcurrency(ref string) (int, bool) { + if !p.IsPlugin() { + return 0, false + } + pp := *p.Account.plugin + if cur, ok := PluginOf(p.ID); ok { + pp = cur + } + key := "" + if accountKey(ref) == accountKey(p.Account.User) { + key = p.Account.pluginKey + } else { + for _, login := range pluginLogins(pp) { + if accountKey(login.User) == accountKey(ref) { + key = login.acct.Key + break + } + } + } + for _, account := range pp.Accounts { + if account.Key == key && account.MaxConcurrency > 0 { + return min(account.MaxConcurrency, MaxLimit), true + } + } + return 0, false +} + // PluginConcurrency is what the plugin giving the provider says it takes // at once, as it lists it now; 0 for none, or for a provider no plugin // gives. @@ -117,7 +147,13 @@ func (p Provider) LaneLimit() int { if n, ok := m[accountKey(ref)]; ok { return max(n, 0) } - return p.Concurrency() + if p.MaxConcurrency != nil { + return p.Concurrency() + } + if n, ok := p.PluginAccountConcurrency(ref); ok { + return n + } + return p.PluginConcurrency() } // AccountConcurrencyOf is the account's or key's own limit, and whether it diff --git a/internal/provider/provider.go b/internal/provider/provider.go index 1e863f209..8ccda5245 100644 --- a/internal/provider/provider.go +++ b/internal/provider/provider.go @@ -229,7 +229,8 @@ type Provider struct { // AccountConcurrency is, for one account or key, its own limit over // MaxConcurrency (#892): an account by its name in lower case, a key // by its KeyID; 0 there is no limit for it. One not in it takes the - // provider's (see LaneLimit). + // provider's manual limit, else its own plugin automatic value, else the + // provider's static plugin default (see LaneLimit). AccountConcurrency map[string]int `json:"accountConcurrency,omitempty"` // AccountWeights is, for a subscription, each account's weight under // Weighted routing, by its name in lower case (rubbzha on X: a Max