provider: a provider the user counts free goes first under Free first (jiabubu on Discord)
jiabubu asked on Discord #help for a way to mark a provider, model or key
as free, so that Free first routing spends it first. Their example is
ModelScope, which has a free daily quota. Until now routes.Seat.Free
came only from the vendor catalog's Free flag, and there was no way for
the user to set it.
Provider.CountFree ("Free for me" in the provider editor's Advanced fold,
`magpie provider set <id> free=yes|no` in the CLI) makes FreeModel true
for every model of that provider. Routing therefore treats it like a
vendor's free model: Free first uses it before paid ones, and Cheapest
first weighs it at nothing, because PriceAt, which only routing reads,
returns 0 for a free model. Prices shown (ListPrice and the model list)
and the costs Usage counts (EffectivePrice) are unchanged. The mark says
what to spend first, not what a call cost, and a quota that runs out
still bills at the listed price. Key and account (subscription)
providers both carry it, through withPicks, the account literal and the
copy merge.
Tests:
- internal/gateway TestFreeFirstSpendsTheProviderTheUserCountsFree:
- a Free first group [paidv/m, mine/m] sends its first call to mine
once mine is marked, and the trace row says Free;
- EffectivePrice is still the listed 3/15;
- Cheapest picks mine first;
- unmarked, paidv goes first again.
- internal/gui TestProviderSaveKeepsCountFree: the preset and typed-in
providers save the mark and clear it, and /api/providers reports it.
- internal/cli TestProviderSetFree: free=yes and free=no work; the value
shows in `provider <id>`; free=maybe, an empty value and --help are
refused and change nothing.
- GUI internal/gui/tests/provider-count-free.test.cjs covers the
ModelScope preset, a custom provider saved with the mark, and a Codex
account. It runs chromium and webkit, in en, zh, zh-TW, ja and de, at
widths 900 and 440. It checks the Advanced fold, the check and save
POST bodies, that the row fits with no sideways scroll, and that each
string has a translation in I18N.
Core script budget: rebased on fa5e86cf2, the core's scripts came to
1,538,236 bytes, 880 over coreScriptBudget, which TestCoreScriptBudget
caught. The budget is not raised. countFreeField's comment and five
long comments on the editor's helpers (proxyPicker, concurrencyField,
priceRateField, pluginOptionsField) are cut down, so app.js ends 212
bytes smaller than before this change.
Run (mote via mote-run, at this change's tree on base 8ee75adbf):
- go test of internal/gateway (-run FreeFirst|InOrder), internal/gui,
internal/cli and internal/provider: ok.
- GUI test: chromium 30/30 on mote. WebKit could not launch on mote at
all at the time (a bare webkit.launch probe timed out at 60s, and
other sessions' WebKit launches were stuck there too). WebKit was run
on Linux instead (wsl-run, magpie-desktop): 30/30.
- gofmt -l clean; go vet ./..., GOOS=linux go vet -tags nogui ./... and
GOOS=windows go vet ./... ok; go build for darwin, linux (nogui) and
windows ok.
- At the pushed head (rebased on fa5e86cf2, comments cut): go test of
internal/gui, internal/cli, internal/provider and internal/gateway
-run FreeFirst|CountFree ok (internal/gui was red only on
TestCoreScriptBudget before the cut); node --check app.js ok; the GUI
test in chromium 30/30.
- The full Go suite (go test -tags nogui -timeout 45m ./...) is still
running on mote at ship time, per the owner's ship-at-once rule. Any
red it finds gets a follow-up commit. The whole GUI suite was not run:
mote's WebKit cannot launch and the Linux box was running other
sessions' GUI suites.
Broken by hand:
- With the CountFree line taken out of FreeModel, all three Go tests
went red, e.g. 'Free first went to "paidv" (free false) first'.
- With `pr.CountFree = in.CountFree` taken out of the preset save
branch, TestProviderSaveKeepsCountFree went red ("the preset's mark
wasn't kept").
Not tried:
- A real ModelScope account; the tests use fake upstreams.
- A per-model mark (optional in the request); the mark is
provider-wide.
- The TUI editor (the CLI setter covers the terminal).
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -164,7 +164,7 @@ A 401 marks the account's sign-in by default (`notePluginSignIn` in [`plugins.go
|
||||
|
||||
## A model's free and rate
|
||||
|
||||
magpie never reads `free` from `rate`: `rate` 0 is none given (`plugin.Model.Rate` in [`providers.go`](../../internal/plugin/providers.go)), and a model is free only by its own `free: true` or a $0 list price (`FreeModel` in [`models.go`](../../internal/provider/models.go)). A plugin sets `free` from the vendor's word; the guide says so ([magpie-community/plugins#468](https://github.com/magpie-community/plugins/issues/468)).
|
||||
magpie never reads `free` from `rate`: `rate` 0 is none given (`plugin.Model.Rate` in [`providers.go`](../../internal/plugin/providers.go)), and a model is free only by its own `free: true`, a $0 list price or the user counting its whole provider free (`Provider.CountFree`) (`FreeModel` in [`models.go`](../../internal/provider/models.go)). A plugin sets `free` from the vendor's word; the guide says so ([magpie-community/plugins#468](https://github.com/magpie-community/plugins/issues/468)).
|
||||
|
||||
## A model that gives no text
|
||||
|
||||
|
||||
@@ -138,6 +138,9 @@ const providerUsage = `usage:
|
||||
(Settings' redaction leaves its requests as written, at any address: your call,
|
||||
so mind a relay that passes them on to a vendor; a subscription or a plugin's
|
||||
provider too, whose vendor gets them so; never another magpie)
|
||||
magpie provider set modelscope free=yes
|
||||
(every model of it counts as free, so a Free first routing spends it before
|
||||
paid ones, as a free daily quota; prices and Usage's costs stay as listed)
|
||||
magpie provider add "My Relay" url=https://relay.example.com/v1 key=sk-… balance=https://relay.example.com/api/usage/token balance.path='$data.total_available / 500000'
|
||||
magpie provider set my-relay balance.path='(1 - credits.monthlyCredits / 70) %'
|
||||
magpie provider set my-relay balance.method=POST
|
||||
@@ -847,6 +850,9 @@ func showProvider(p provider.Provider) error {
|
||||
}
|
||||
kv("unmasked", "yes"+muted.Render(why))
|
||||
}
|
||||
if p.CountFree {
|
||||
kv("free", "yes"+muted.Render(" counted free by Free first and Cheapest routing; prices and Usage's costs stay as listed"))
|
||||
}
|
||||
if p.NativeCompaction {
|
||||
kv("compaction", "native"+muted.Render(" Codex's own, sealed by the key or account that answers it"))
|
||||
}
|
||||
@@ -1191,6 +1197,19 @@ func applyPairs(p *provider.Provider, pairs []string) error {
|
||||
return fmt.Errorf("unmasked=yes|no, not %q", v)
|
||||
}
|
||||
p.Unredacted = v == "yes"
|
||||
case "free":
|
||||
// yes: every model of it counts as free for Free first and
|
||||
// Cheapest routing, by the user's word (jiabubu on Discord:
|
||||
// ModelScope's free daily quota); prices and Usage's costs
|
||||
// stay as listed (provider.CountFree)
|
||||
switch strings.ToLower(v) {
|
||||
case "yes", "on":
|
||||
p.CountFree = true
|
||||
case "no", "off":
|
||||
p.CountFree = false
|
||||
default:
|
||||
return fmt.Errorf("free=yes|no, not %q", v)
|
||||
}
|
||||
case "context":
|
||||
if err := setContext(p, "*", v); err != nil {
|
||||
return err
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
package cli
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// magpie provider set free=yes counts every model of a provider free for
|
||||
// Free first (jiabubu on Discord: ModelScope's free daily quota), show
|
||||
// says so, free=no takes it back, and any other value is refused and
|
||||
// leaves the saved one alone.
|
||||
func TestProviderSetFree(t *testing.T) {
|
||||
groupsHome(t)
|
||||
if _, err := printed(t, func() error { return providerCmd([]string{"provider", "set", "a", "free=yes"}) }); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if p := mustFind(t, "a"); !p.CountFree || !p.FreeModel("whatever") {
|
||||
t.Fatalf("free=yes: %+v", p)
|
||||
}
|
||||
out, err := printed(t, func() error { return providerCmd([]string{"provider", "a"}) })
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !strings.Contains(out, "counted free") {
|
||||
t.Fatalf("show doesn't say it is counted free:\n%s", out)
|
||||
}
|
||||
for _, v := range []string{"maybe", "", "--help"} {
|
||||
err := providerCmd([]string{"provider", "set", "a", "free=" + v})
|
||||
if err == nil || !strings.Contains(err.Error(), "free=yes|no") {
|
||||
t.Errorf("free=%q: %v", v, err)
|
||||
}
|
||||
if !mustFind(t, "a").CountFree {
|
||||
t.Errorf("a refused free=%q turned it off", v)
|
||||
}
|
||||
}
|
||||
if _, err := printed(t, func() error { return providerCmd([]string{"provider", "set", "a", "free=no"}) }); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if mustFind(t, "a").CountFree {
|
||||
t.Fatal("free=no left it on")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/catalog"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// A provider the user counts free (provider.CountFree; jiabubu on Discord:
|
||||
// ModelScope's free daily quota) is spent first by Free first, though its
|
||||
// vendor's list says nothing of it being free and it is listed second. Its
|
||||
// price stays as set: the mark orders the routing, it doesn't
|
||||
// reprice what Usage counts. Cheapest first weighs it at
|
||||
// nothing too. Turned off, the listed order is back.
|
||||
func TestFreeFirstSpendsTheProviderTheUserCountsFree(t *testing.T) {
|
||||
fresh(t)
|
||||
var paid, mine atomic.Int32
|
||||
answer := func(n *atomic.Int32) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
n.Add(1)
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Write([]byte(`{"id":"ok","choices":[{"message":{"role":"assistant","content":"hi"}}]}`))
|
||||
}
|
||||
}
|
||||
serveOn(t, "paidv", "sk-paid", []string{"m"}, answer(&paid))
|
||||
serveOn(t, "mine", "sk-mine", []string{"m"}, answer(&mine))
|
||||
// both priced, the marked one dearer: nothing but the user's word says
|
||||
// it costs them nothing
|
||||
for id, pr := range map[string]catalog.Price{"paidv/m": {Input: 1, Output: 2}, "mine/m": {Input: 3, Output: 15}} {
|
||||
if err := provider.SetModelPrice(id, &pr); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := provider.SaveGroup(provider.Group{
|
||||
Name: "G", Members: []string{"paidv/m", "mine/m"}, Routing: provider.FreeFirst,
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := provider.SetCountFree("mine", true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
s := New()
|
||||
first := func() Weighed {
|
||||
t.Helper()
|
||||
code, body := postAs(t, s, "", `{"model":"group/g","messages":[{"role":"user","content":"x"}]}`)
|
||||
if code != 200 {
|
||||
t.Fatalf("code %d: %s", code, body)
|
||||
}
|
||||
last := s.trace.routes[len(s.trace.routes)-1]
|
||||
if len(last.Order) != 2 {
|
||||
t.Fatalf("the trace should weigh both members: %+v", last.Order)
|
||||
}
|
||||
return last.Order[0]
|
||||
}
|
||||
if w := first(); w.Provider != "mine" || !w.Free {
|
||||
t.Fatalf("Free first went to %q (free %v) first, want the one counted free", w.Provider, w.Free)
|
||||
}
|
||||
if mine.Load() != 1 || paid.Load() != 0 {
|
||||
t.Fatalf("answered by mine %d, paid %d", mine.Load(), paid.Load())
|
||||
}
|
||||
// what Usage counts a call at
|
||||
if pr, ok := provider.EffectivePrice("mine", "m"); !ok || pr.Input != 3 || pr.Output != 15 {
|
||||
t.Fatalf("counting it free repriced it: %+v %v", pr, ok)
|
||||
}
|
||||
|
||||
// Cheapest first weighs it at nothing too, though its set price is
|
||||
// the dearer
|
||||
if err := provider.SaveGroup(provider.Group{
|
||||
Name: "G", Members: []string{"paidv/m", "mine/m"}, Routing: provider.Cheapest,
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w := first(); w.Provider != "mine" {
|
||||
t.Fatalf("Cheapest first went to %q first, want the one counted free", w.Provider)
|
||||
}
|
||||
if err := provider.SaveGroup(provider.Group{
|
||||
Name: "G", Members: []string{"paidv/m", "mine/m"}, Routing: provider.FreeFirst,
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := provider.SetCountFree("mine", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if w := first(); w.Provider != "paidv" || w.Free {
|
||||
t.Fatalf("turned off, Free first went to %q (free %v) first, want paidv as listed", w.Provider, w.Free)
|
||||
}
|
||||
}
|
||||
+21
-26
@@ -7838,11 +7838,8 @@ function modelPrefsOfDraft() {
|
||||
return x && Object.keys(x).length ? x : undefined;
|
||||
}
|
||||
|
||||
// proxyPicker: the proxy one provider's requests go through (#237) — the
|
||||
// one in Settings, none, or its own — so Codex can go through a proxy
|
||||
// while a vendor at home goes direct. The draft keeps the choice as
|
||||
// proxyMode ("" global, "direct", "custom") and the address as proxyURL;
|
||||
// proxyOfDraft is what is saved.
|
||||
// proxyPicker: one provider's proxy (#237): Settings', none or its own,
|
||||
// as proxyMode ("" global, "direct", "custom") and proxyURL
|
||||
const PROXY_HINT = {
|
||||
"": "Follows the proxy in Settings",
|
||||
direct: "Requests to it go direct, whatever the proxy in Settings",
|
||||
@@ -7870,12 +7867,8 @@ function proxyPicker() {
|
||||
return box;
|
||||
}
|
||||
|
||||
// concurrencyField: how many requests each of the provider's keys or
|
||||
// accounts may have out at the vendor at once (Discord, Lemon: a Codex
|
||||
// account is risk-controlled past five or six); more wait their turn and
|
||||
// go in order. The draft keeps what is typed as concurrency, "" for none
|
||||
// set — a plugin's provider then takes what its plugin says, shown as the
|
||||
// placeholder — and concurrencyOfDraft is what is saved.
|
||||
// concurrencyField: requests each key or account has out at once (Lemon:
|
||||
// Codex risk control past five); "" takes the plugin's, as its placeholder
|
||||
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");
|
||||
@@ -7910,10 +7903,8 @@ function concurrencyField(p) {
|
||||
...field(t("Queue wait"), wait, t("Seconds a request waits for a free slot before it is turned away. 0 or empty waits as long as it takes")),
|
||||
];
|
||||
}
|
||||
// priceRateField: what the provider charges against the official price
|
||||
// (ITea312, #819), as a relay bills 0.8× or 1.5× of it: the Usage page's
|
||||
// costs are its list price, else its maker's, times this. Empty is the
|
||||
// price as listed; steps of 0.001.
|
||||
// priceRateField: a relay's rate on the official price (#819), which
|
||||
// Usage's costs are multiplied by; empty is the price as listed
|
||||
function priceRateField() {
|
||||
const box = input(draft.priceRate ?? "", t("1, the official price"));
|
||||
box.classList.add("price-rate");
|
||||
@@ -7921,18 +7912,21 @@ function priceRateField() {
|
||||
box.oninput = () => { draft.priceRate = box.value; };
|
||||
return field(t("Price rate"), box, t("Costs are counted at the official price times this, as a relay bills, like 0.8 or 1.5; a price you set for a model stays as set"));
|
||||
}
|
||||
// countFreeField: provider.CountFree (jiabubu: a free daily quota)
|
||||
function countFreeField() {
|
||||
const [l, c] = tick(t("Count its models as free"), !!draft.countFree);
|
||||
l.classList.add("count-free");
|
||||
c.onchange = () => { draft.countFree = c.checked; };
|
||||
return field(t("Free for me"), l, t("For a free quota, like a daily allowance: Free first uses its models before paid ones, and Cheapest first counts them as costing nothing. Prices and the costs Usage counts stay as listed."));
|
||||
}
|
||||
// a provider's hours at its own rate (#2463), drawn by ratewindows.js
|
||||
function rateWindowsField() {
|
||||
const box = el("div", "stack rate-windows"), d = draft;
|
||||
import("./ratewindows.js").then(() => rateWindowsPaint(box, d), statusErr);
|
||||
return field(t("Rate windows"), box);
|
||||
}
|
||||
// pluginOptionsField: the switches a plugin declares for its provider
|
||||
// (auth.options, #2038, Vocllum), each an Off/On beside the plugin's own
|
||||
// words for it, put in as text. One the plugin asks to confirm is asked
|
||||
// before it is turned on. A change is kept in the draft as
|
||||
// pluginOptions[key] and saved with the provider; nothing runs when it is,
|
||||
// the plugin reads the value when it next wants it.
|
||||
// pluginOptionsField: a plugin's declared switches (auth.options, #2038),
|
||||
// confirmed first where it asks, kept as draft.pluginOptions[key]
|
||||
function pluginOptionsField(sub) {
|
||||
const opts = sub?.plugin?.options || [];
|
||||
if (!opts.length) return [];
|
||||
@@ -8059,7 +8053,7 @@ function advancedSet(d, p) {
|
||||
!!d.proxyMode || Object.values(d.accountProxies || {}).some((x) => x?.mode) ||
|
||||
[d.concurrency, d.queueLimit, d.queueWait, d.maxRPM, d.priceRate, d.contexts, d.outputs, d.compacts].some((v) => String(v ?? "").trim()) ||
|
||||
!!d.rateWindows?.length ||
|
||||
!!(d.searches || d.authHeader || d.passUserAgent || d.unredacted || d.pinUpstream || d.nativeCompaction || d.balanceToken || d.limitRestOff) ||
|
||||
!!(d.searches || d.authHeader || d.passUserAgent || d.unredacted || d.countFree || d.pinUpstream || d.nativeCompaction || d.balanceToken || d.limitRestOff) ||
|
||||
!!d.fallback?.length || !!p?.balanceToken?.set;
|
||||
}
|
||||
function priceRateError(ed) {
|
||||
@@ -9217,7 +9211,7 @@ function baseAPIOf(p) {
|
||||
|
||||
// draftOf is a saved provider as its editor's form holds it.
|
||||
function draftOf(p) {
|
||||
return { id: p.id, name: p.name, preset: p.preset, chat: p.chat, responses: p.responses, anthropic: p.anthropic, gemini: p.gemini || "", catalog: p.catalog, decide: p.decide || "", key: "", api: baseAPIOf(p), chosen: pickedOf(p), none: !!p.noModels, best: !!p.bestInFamily, extra: [], headers: headerRows(p.headers), extraBody: extraBodyText(p.extraBody), replyHeaders: (p.replyHeaders || []).join(", "), icon: p.icon || "", fallback: [...(p.fallback || [])], unlisted: !!p.unlisted, hiddenDrawers: [...(p.hiddenDrawers || [])], searches: !!p.searches, unredacted: !!p.unredacted, insecureTLS: !!p.insecureTLS, limitRestOff: !!p.limitRestOff, nativeCompaction: !!p.nativeCompaction, passUserAgent: !!p.passUserAgent, pinUpstream: !!p.pinUpstream, authHeader: p.authHeader || "", balanceURL: p.balanceURL || "", balancePath: p.balancePath || "", balanceMethod: p.balanceMethod || "", modelsURL: p.modelsURL || "", contexts: contextsText(p.contexts), outputs: contextsText(p.outputs), compacts: contextsText(p.compacts), keysUrl: p.keysUrl || "", ...proxyDraft(p), ...concurrencyDraft(p), rateWindows: (p.rateWindows || []).map((w) => ({ ...w })) };
|
||||
return { id: p.id, name: p.name, preset: p.preset, chat: p.chat, responses: p.responses, anthropic: p.anthropic, gemini: p.gemini || "", catalog: p.catalog, decide: p.decide || "", key: "", api: baseAPIOf(p), chosen: pickedOf(p), none: !!p.noModels, best: !!p.bestInFamily, extra: [], headers: headerRows(p.headers), extraBody: extraBodyText(p.extraBody), replyHeaders: (p.replyHeaders || []).join(", "), icon: p.icon || "", fallback: [...(p.fallback || [])], unlisted: !!p.unlisted, hiddenDrawers: [...(p.hiddenDrawers || [])], searches: !!p.searches, unredacted: !!p.unredacted, countFree: !!p.countFree, insecureTLS: !!p.insecureTLS, limitRestOff: !!p.limitRestOff, nativeCompaction: !!p.nativeCompaction, passUserAgent: !!p.passUserAgent, pinUpstream: !!p.pinUpstream, authHeader: p.authHeader || "", balanceURL: p.balanceURL || "", balancePath: p.balancePath || "", balanceMethod: p.balanceMethod || "", modelsURL: p.modelsURL || "", contexts: contextsText(p.contexts), outputs: contextsText(p.outputs), compacts: contextsText(p.compacts), keysUrl: p.keysUrl || "", ...proxyDraft(p), ...concurrencyDraft(p), rateWindows: (p.rateWindows || []).map((w) => ({ ...w })) };
|
||||
}
|
||||
|
||||
// duplicateProvider opens the Add form on a copy of p (#268): its URLs,
|
||||
@@ -9537,7 +9531,7 @@ function drawEditor(p, presetID) {
|
||||
if (perAccount) proxies.append(perAccount);
|
||||
advIn.append(...field(t("Proxy"), proxies));
|
||||
advIn.append(...concurrencyField(p));
|
||||
advIn.append(...priceRateField(), ...rateWindowsField());
|
||||
advIn.append(...priceRateField(), ...countFreeField(), ...rateWindowsField());
|
||||
if (p.cline) advIn.append(...upstreamField());
|
||||
advIn.append(...unmaskRow(""));
|
||||
ed.append(...pluginOptionsField(subOf(a.agent)));
|
||||
@@ -9581,7 +9575,7 @@ function drawEditor(p, presetID) {
|
||||
if (priceTypedError(ed)) return;
|
||||
const picked = accountModelsDraft(p);
|
||||
if (picked === false) return pickError();
|
||||
const body = { id: p.id, models: chosenIds(), noModels: noneChosen(), bestInFamily: bestChosen(), unlisted: draft.unlisted, hiddenDrawers: draft.hiddenDrawers, fallback: draft.fallback, contexts: cx.map, outputs: ox.map, compacts: cpx.map, proxy, accountProxies: own.map, maxConcurrency, ...queue, priceRate, rateWindows, modelPrefs: modelPrefsOfDraft(), pinUpstream: !!draft.pinUpstream, unredacted: !!draft.unredacted, ...(p.carriesCompaction ? { nativeCompaction: !!draft.nativeCompaction } : {}), ...routingOfDraft(p) };
|
||||
const body = { id: p.id, models: chosenIds(), noModels: noneChosen(), bestInFamily: bestChosen(), unlisted: draft.unlisted, hiddenDrawers: draft.hiddenDrawers, fallback: draft.fallback, contexts: cx.map, outputs: ox.map, compacts: cpx.map, proxy, accountProxies: own.map, maxConcurrency, ...queue, priceRate, rateWindows, modelPrefs: modelPrefsOfDraft(), pinUpstream: !!draft.pinUpstream, unredacted: !!draft.unredacted, countFree: !!draft.countFree, ...(p.carriesCompaction ? { nativeCompaction: !!draft.nativeCompaction } : {}), ...routingOfDraft(p) };
|
||||
saving(saveBtn, t("Saving…"));
|
||||
saveAccountModelsDraft(picked).then(() => savePluginOptions(subOf(a.agent))).then(() => providerAction("save", body, t("{name} saved", { name: p.name })), (e) => { doneSaving(saveBtn); editorError(e.message || String(e)); }); };
|
||||
bar.append(cancel, saveBtn);
|
||||
@@ -9764,7 +9758,7 @@ function drawEditor(p, presetID) {
|
||||
if (perKey) proxies.append(perKey);
|
||||
advIn.append(...field(t("Proxy"), proxies));
|
||||
advIn.append(...concurrencyField(p));
|
||||
advIn.append(...priceRateField(), ...rateWindowsField());
|
||||
advIn.append(...priceRateField(), ...countFreeField(), ...rateWindowsField());
|
||||
|
||||
if (p?.cline || (isNew && pr?.id === "clinepass")) advIn.append(...upstreamField());
|
||||
|
||||
@@ -10182,6 +10176,7 @@ function drawEditor(p, presetID) {
|
||||
body.pinUpstream = !!draft.pinUpstream;
|
||||
if (twoKeyHeaders()) body.authHeader = draft.authHeader || "";
|
||||
body.unredacted = !!draft.unredacted && unmaskable();
|
||||
body.countFree = !!draft.countFree;
|
||||
if (tlsTakes()) body.insecureTLS = !!draft.insecureTLS && onHTTPS();
|
||||
if (custom) body.limitRestOff = !!draft.limitRestOff;
|
||||
if (!decideOnly(p || pr)) body.nativeCompaction = !!draft.nativeCompaction && carriesCompaction();
|
||||
|
||||
@@ -2279,6 +2279,9 @@ const I18N = {
|
||||
"A number of your own, up to 1000": "自定义数字,最大 1000",
|
||||
"No limit": "不限制",
|
||||
"Price rate": "价格倍率",
|
||||
"Free for me": "对我免费",
|
||||
"Count its models as free": "把它的模型算作免费",
|
||||
"For a free quota, like a daily allowance: Free first uses its models before paid ones, and Cheapest first counts them as costing nothing. Prices and the costs Usage counts stay as listed.": "适用于免费额度,比如每日免费额度:「免费优先」会先用它的模型,再用付费的;「最便宜优先」把它们算作不花钱。价格和用量统计的费用保持原样。",
|
||||
"Plugin options": "插件选项",
|
||||
"{plugin} declares these and reads them as it works; nothing runs on its own when one changes.": "{plugin} 声明了这些选项,并在工作时读取;更改选项不会自行运行任何操作。",
|
||||
"Turn on {name}?": "开启「{name}」?",
|
||||
@@ -6491,6 +6494,9 @@ const I18N = {
|
||||
"A number of your own, up to 1000": "自定義數字,最大 1000",
|
||||
"No limit": "不限制",
|
||||
"Price rate": "價格倍率",
|
||||
"Free for me": "對我免費",
|
||||
"Count its models as free": "把它的模型算作免費",
|
||||
"For a free quota, like a daily allowance: Free first uses its models before paid ones, and Cheapest first counts them as costing nothing. Prices and the costs Usage counts stay as listed.": "適用於免費額度,例如每日免費額度:「免費優先」會先用它的模型,再用付費的;「最便宜優先」把它們算作不花錢。價格和用量統計的費用維持原樣。",
|
||||
"Plugin options": "外掛選項",
|
||||
"{plugin} declares these and reads them as it works; nothing runs on its own when one changes.": "{plugin} 宣告了這些選項,並在工作時讀取;變更選項不會自行執行任何動作。",
|
||||
"Turn on {name}?": "開啟「{name}」?",
|
||||
@@ -10682,6 +10688,9 @@ const I18N = {
|
||||
"A number of your own, up to 1000": "任意の数(最大 1000)",
|
||||
"No limit": "上限なし",
|
||||
"Price rate": "価格倍率",
|
||||
"Free for me": "自分には無料",
|
||||
"Count its models as free": "このモデルを無料として扱う",
|
||||
"For a free quota, like a daily allowance: Free first uses its models before paid ones, and Cheapest first counts them as costing nothing. Prices and the costs Usage counts stay as listed.": "毎日の無料枠のような無料分に。「無料優先」は有料のものより先にこのモデルを使い、「最安優先」はコストなしとして扱います。価格と使用量で数える費用はそのままです。",
|
||||
"Plugin options": "プラグインのオプション",
|
||||
"{plugin} declares these and reads them as it works; nothing runs on its own when one changes.": "{plugin} が宣言し、動作中に読み取ります。変更しても、それだけで何かが実行されることはありません。",
|
||||
"Turn on {name}?": "「{name}」をオンにしますか?",
|
||||
@@ -14903,6 +14912,9 @@ const I18N = {
|
||||
"A number of your own, up to 1000": "Eine eigene Zahl, bis 1000",
|
||||
"No limit": "Kein Limit",
|
||||
"Price rate": "Preisfaktor",
|
||||
"Free for me": "Für mich kostenlos",
|
||||
"Count its models as free": "Seine Modelle als kostenlos zählen",
|
||||
"For a free quota, like a daily allowance: Free first uses its models before paid ones, and Cheapest first counts them as costing nothing. Prices and the costs Usage counts stay as listed.": "Für ein Gratiskontingent, etwa ein tägliches: „Kostenlos zuerst“ nutzt seine Modelle vor bezahlten, und „Günstigste zuerst“ rechnet sie als kostenlos. Preise und die Kosten in der Nutzung bleiben wie gelistet.",
|
||||
"Plugin options": "Plugin-Optionen",
|
||||
"{plugin} declares these and reads them as it works; nothing runs on its own when one changes.": "{plugin} legt diese fest und liest sie bei der Arbeit; eine Änderung löst selbst nichts aus.",
|
||||
"Turn on {name}?": "{name} einschalten?",
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// jiabubu on Discord: the editor's "Count its models as free" is saved on
|
||||
// a preset (ModelScope, whose free daily quota is the case) and on a
|
||||
// provider the user typed in, given back by /api/providers for the editor
|
||||
// to open with, and turned off by a save that says so.
|
||||
func TestProviderSaveKeepsCountFree(t *testing.T) {
|
||||
t.Setenv("HOME", t.TempDir())
|
||||
t.Setenv("USERPROFILE", os.Getenv("HOME"))
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
t.Setenv("XDG_CACHE_HOME", t.TempDir())
|
||||
mux := http.NewServeMux()
|
||||
providerRoutes(mux, nil)
|
||||
do := func(method, path, body string) string {
|
||||
t.Helper()
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, httptest.NewRequest(method, path, strings.NewReader(body)))
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("%s: %d %s", path, w.Code, w.Body)
|
||||
}
|
||||
return w.Body.String()
|
||||
}
|
||||
do("POST", "/api/provider/save", `{"id":"modelscope","name":"ModelScope","preset":"modelscope","key":"ms-k","countFree":true,"new":true}`)
|
||||
if p, err := provider.Find("modelscope"); err != nil || !p.CountFree || !p.FreeModel("any-model-of-it") {
|
||||
t.Fatalf("the preset's mark wasn't kept: %+v %v", p, err)
|
||||
}
|
||||
if !strings.Contains(do("GET", "/api/providers", ""), `"countFree":true`) {
|
||||
t.Fatal("/api/providers doesn't give the mark back")
|
||||
}
|
||||
do("POST", "/api/provider/save", `{"id":"modelscope","from":"modelscope","name":"ModelScope","preset":"modelscope","key":"","countFree":false}`)
|
||||
if p, err := provider.Find("modelscope"); err != nil || p.CountFree {
|
||||
t.Fatalf("turned off, it stayed: %+v %v", p, err)
|
||||
}
|
||||
|
||||
do("POST", "/api/provider/save", `{"id":"box","name":"Box","chat":"http://127.0.0.1:9/v1","key":"k","countFree":true,"new":true}`)
|
||||
if p, err := provider.Find("box"); err != nil || !p.CountFree {
|
||||
t.Fatalf("a typed-in provider's mark wasn't kept: %+v %v", p, err)
|
||||
}
|
||||
}
|
||||
@@ -103,6 +103,9 @@ type providerJSON struct {
|
||||
// on this machine or the local network, set to go unmasked by
|
||||
// Settings' redaction (provider.Unredacted)
|
||||
Unredacted bool `json:"unredacted"`
|
||||
// every model of it counted free by the user's word, for Free first
|
||||
// and Cheapest (provider.CountFree)
|
||||
CountFree bool `json:"countFree,omitempty"`
|
||||
// a provider the user added whose own HTTPS host's certificate is
|
||||
// taken as it is (provider.InsecureTLS, #2383); TakesInsecureTLS: it
|
||||
// may be, being the user's own and not a preset's or a sign-in's
|
||||
@@ -640,7 +643,7 @@ func providerInfoWith(p provider.Provider, agents []agentUse, desktop map[string
|
||||
ID: p.ID, Name: p.Name, Icon: p.Icon, Preset: p.Preset, Host: p.Host(),
|
||||
Chat: p.Chat, Responses: p.Responses, Anthropic: p.Anthropic, Gemini: p.Gemini, Decide: p.Decide, BaseAPI: p.BaseAPI, ModelTest: p.ModelTest(), TestsAs: p.TestClients(), DecideTest: p.AsksDecideModels(), MarksKinds: p.MarksKinds(),
|
||||
Catalog: p.Catalog, Website: p.Website, KeysURL: p.KeysURL,
|
||||
Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, ReplyHeaders: p.ReplyHeaders, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, InsecureTLS: p.InsecureTLS, TakesInsecureTLS: p.TakesInsecureTLS(), LimitRestOff: p.LimitRestOff, NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: p.PassUserAgent, OwnClient: p.OwnClient(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, BalanceMethod: p.BalanceMethod, ModelsURL: p.ModelsURL,
|
||||
Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, AccountNames: p.AccountNames, Headers: p.Headers, ExtraBody: p.ExtraBody, ReplyHeaders: p.ReplyHeaders, Searches: p.Searches, Cline: p.ClinePinnable(), PinUpstream: p.PinUpstream, Unredacted: p.Unredacted, CountFree: p.CountFree, InsecureTLS: p.InsecureTLS, TakesInsecureTLS: p.TakesInsecureTLS(), LimitRestOff: p.LimitRestOff, NativeCompaction: p.NativeCompaction, CarriesCompaction: p.CarriesCompaction(), PassUserAgent: p.PassUserAgent, OwnClient: p.OwnClient(), AuthHeader: p.AuthHeader, BothAuth: p.BothAuth(), BalanceURL: p.BalanceURL, BalancePath: p.BalancePath, BalanceMethod: p.BalanceMethod, ModelsURL: p.ModelsURL,
|
||||
Ready: p.Ready(), Chosen: p.Picks(), Models: []modelJSON{}, Agents: []providerAgent{},
|
||||
Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, CapStop: p.CapStop, CapCareful: p.CapCareful, Unlisted: p.Unlisted, NoModels: p.ServesNone(), BestInFamily: p.BestInFamily && len(p.Models) == 0 && !p.NoModels, Off: p.Off, Contexts: p.Contexts,
|
||||
MaxConcurrency: p.MaxConcurrency, PluginConcurrency: p.PluginConcurrency(), PriceRate: p.PriceRate,
|
||||
@@ -1480,6 +1483,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
pr.Searches = in.Searches
|
||||
pr.PinUpstream = in.PinUpstream
|
||||
pr.Unredacted = in.Unredacted
|
||||
pr.CountFree = in.CountFree
|
||||
pr.NativeCompaction = in.NativeCompaction
|
||||
pr.PassUserAgent = in.PassUserAgent
|
||||
pr.AuthHeader = in.AuthHeader
|
||||
|
||||
@@ -0,0 +1,149 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// "Count its models as free" (jiabubu on Discord: ModelScope's free daily
|
||||
// quota) is the user's word that a provider costs them nothing, so Free
|
||||
// first spends it first. The editor's Free for me row, under Advanced
|
||||
// beside Price rate, opens as it was saved (and opens Advanced when on),
|
||||
// and Save posts it: for a provider of keys and for a signed-in account.
|
||||
// In every language, in both engines, wide and narrow.
|
||||
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(__dirname, "../assets");
|
||||
const base = {
|
||||
icon: "generic", chat: "", responses: "", anthropic: "", catalog: "",
|
||||
models: [{ id: "qwen3", name: "Qwen3", on: true }], agents: [], fallback: [], headers: {},
|
||||
key: { set: true, masked: "ms-…1234" }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "", searches: false, unredacted: false,
|
||||
};
|
||||
const scope = { ...base, id: "modelscope", name: "ModelScope", preset: "modelscope", chat: "https://api-inference.modelscope.cn/v1" };
|
||||
const counted = { ...base, id: "free-relay", name: "Free Relay", chat: "https://relay.example.com/v1", countFree: true };
|
||||
const codex = {
|
||||
id: "codex", name: "Codex", icon: "codex-color", chat: "", responses: "", anthropic: "", catalog: "",
|
||||
models: [{ id: "gpt-6", name: "GPT-6", on: true }], agents: [], fallback: [], headers: {}, keyList: [],
|
||||
account: { agent: "codex", agentName: "Codex", user: "me@example.com", plan: "PLUS", logins: [{ user: "me@example.com", plan: "PLUS", active: true, on: true }] },
|
||||
proxy: "",
|
||||
};
|
||||
|
||||
function serve(lang, posts) {
|
||||
const providers = { providers: [scope, counted, codex], presets: [], excluded: [], gateway: { running: true, window: true } };
|
||||
const state = { agents: [], profiles: [], settings: { lang, theme: "light" } };
|
||||
return async (route) => {
|
||||
const url = new URL(route.request().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/providers") return json(providers);
|
||||
if (url.pathname === "/api/groups") return json({ groups: [] });
|
||||
if (url.pathname.startsWith("/api/provider/") && route.request().method() === "POST") {
|
||||
posts.push({ action: url.pathname.slice("/api/provider/".length), body: route.request().postDataJSON() });
|
||||
return json(providers);
|
||||
}
|
||||
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)];
|
||||
await route.fulfill({ body: await fs.readFile(file), contentType });
|
||||
};
|
||||
}
|
||||
|
||||
const TICK = "Count its models as free";
|
||||
const STRINGS = [
|
||||
"Free for me", TICK,
|
||||
"For a free quota, like a daily allowance: Free first uses its models before paid ones, and Cheapest first counts them as costing nothing. Prices and the costs Usage counts stay as listed.",
|
||||
];
|
||||
|
||||
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 [900, 440]) {
|
||||
const open = async (t, name) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
let page;
|
||||
t.after(async () => {
|
||||
if (process.env.ARTIFACT_DIR && page) {
|
||||
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
|
||||
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${width}-${name.replace(/\W+/g, "-")}-count-free.png`), fullPage: true });
|
||||
}
|
||||
await browser.close();
|
||||
});
|
||||
page = await (await browser.newContext({ viewport: { width, height: 760 }, reducedMotion: "reduce" })).newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
const posts = [];
|
||||
await page.route("**/*", serve(lang, posts));
|
||||
await page.goto("http://magpie.test/?view=providers");
|
||||
await page.locator(".row.provider", { hasText: name }).click();
|
||||
await page.locator(".editor .bar").waitFor();
|
||||
const tick = await page.evaluate((k) => t(k), TICK);
|
||||
return { page, errors, posts, tick };
|
||||
};
|
||||
const adv = (page) => page.locator(".editor details.advanced");
|
||||
const unfold = async (page) => {
|
||||
await adv(page).waitFor({ state: "attached" });
|
||||
if (!(await adv(page).evaluate((d) => d.open))) await adv(page).locator(":scope > summary").click();
|
||||
};
|
||||
const box = (page, tick) => page.locator(".editor label.tick.count-free", { hasText: tick }).locator("input");
|
||||
const save = async (page, posts) => {
|
||||
const n = posts.length;
|
||||
const label = await page.evaluate(() => t("Save"));
|
||||
await page.locator(".editor .bar").getByRole("button", { name: label, exact: true }).click();
|
||||
for (let i = 0; i < 50 && posts.length === n; i++) await page.waitForTimeout(50);
|
||||
return posts.at(-1);
|
||||
};
|
||||
const fits = async (page, tick) => {
|
||||
const r = await page.locator(".editor label.tick.count-free").boundingBox();
|
||||
assert.ok(r && r.width > 60 && r.x >= 0 && r.x + r.width <= width, `the row fits: ${JSON.stringify(r)}`);
|
||||
assert.equal(await page.evaluate(() => document.documentElement.scrollWidth <= innerWidth), true, "no sideways scroll");
|
||||
assert.equal(await page.locator(".editor label.tick.count-free").textContent(), tick);
|
||||
};
|
||||
|
||||
test(`${engine} ${lang} ${width}: ModelScope is counted free and saved so`, async (t) => {
|
||||
const { page, errors, posts, tick } = await open(t, "ModelScope");
|
||||
assert.equal(await adv(page).evaluate((d) => d.open), false, "nothing set opens Advanced");
|
||||
await unfold(page);
|
||||
assert.equal(await box(page, tick).isChecked(), false, "opens off");
|
||||
await box(page, tick).scrollIntoViewIfNeeded();
|
||||
await fits(page, tick);
|
||||
await box(page, tick).check();
|
||||
const saved = await save(page, posts);
|
||||
assert.equal(saved.action, "save");
|
||||
assert.equal(saved.body.id, "modelscope");
|
||||
assert.equal(saved.body.countFree, true);
|
||||
if (lang !== "en") {
|
||||
const missing = await page.evaluate(([l, ks]) => ks.filter((k) => !I18N[l][k]), [lang, STRINGS]);
|
||||
assert.deepEqual(missing, [], `every string has its ${lang}`);
|
||||
}
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test(`${engine} ${lang} ${width}: one saved counted free opens Advanced ticked, and is saved off`, async (t) => {
|
||||
const { page, errors, posts, tick } = await open(t, "Free Relay");
|
||||
assert.equal(await adv(page).evaluate((d) => d.open), true, "set, it opens Advanced");
|
||||
assert.equal(await box(page, tick).isChecked(), true);
|
||||
await box(page, tick).scrollIntoViewIfNeeded();
|
||||
await box(page, tick).uncheck();
|
||||
const saved = await save(page, posts);
|
||||
assert.equal(saved.body.id, "free-relay");
|
||||
assert.equal(saved.body.countFree, false);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test(`${engine} ${lang} ${width}: a signed-in account is counted free too`, async (t) => {
|
||||
const { page, errors, posts, tick } = await open(t, "Codex");
|
||||
await unfold(page);
|
||||
assert.equal(await box(page, tick).isChecked(), false);
|
||||
await box(page, tick).scrollIntoViewIfNeeded();
|
||||
await fits(page, tick);
|
||||
await box(page, tick).check();
|
||||
const saved = await save(page, posts);
|
||||
assert.equal(saved.action, "save");
|
||||
assert.equal(saved.body.id, "codex");
|
||||
assert.equal(saved.body.countFree, true);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1741,8 +1741,12 @@ func (p Provider) PaidBesideFree(model string) bool {
|
||||
//
|
||||
// A model neither listed free nor priced is not free: nothing says it costs
|
||||
// nothing, and the routes that go by this put it with the paid ones, so a
|
||||
// pool without free models behaves as In order.
|
||||
// pool without free models behaves as In order. The user's word is
|
||||
// something: every model of a provider they count free is (CountFree).
|
||||
func (p Provider) FreeModel(model string) bool {
|
||||
if p.CountFree {
|
||||
return true
|
||||
}
|
||||
for _, m := range p.Available() {
|
||||
if strings.EqualFold(m.ID, model) {
|
||||
if m.Free {
|
||||
|
||||
@@ -212,6 +212,13 @@ type Provider struct {
|
||||
// a price the user set for one of its models stands as set. 0 is the
|
||||
// price as listed; at most three decimals (PriceRateOK).
|
||||
PriceRate float64 `json:"priceRate,omitempty"`
|
||||
// CountFree is the user's word that the provider costs them nothing
|
||||
// (jiabubu on Discord: ModelScope's free daily quota): every model of
|
||||
// it counts as free where routing weighs that, as a model its vendor
|
||||
// lists free does (FreeModel: Free first spends it first, Cheapest
|
||||
// weighs it at nothing). Prices and the costs Usage counts stay as
|
||||
// listed: it says what to spend first, not what a call cost.
|
||||
CountFree bool `json:"countFree,omitempty"`
|
||||
// RateWindows are the time-of-day windows it bills at its own rate
|
||||
// (#2463): a peak at 2× or 3×, a discount off peak. The first window
|
||||
// that holds a call's time multiplies the price again, on top of
|
||||
@@ -806,6 +813,8 @@ func withPicks(a, pk Provider) Provider {
|
||||
// what it bills against the official price (#819): an account's editor
|
||||
// sets it as a key provider's does (PaulT on Discord, Codex)
|
||||
a.PriceRate = pk.PriceRate
|
||||
// counted free by the user's word, every account alike
|
||||
a.CountFree = pk.CountFree
|
||||
// the hours the provider bills at its own rate (#2463), as the editor
|
||||
// keeps them for the account like the rest of these
|
||||
a.RateWindows = pk.RateWindows
|
||||
@@ -943,7 +952,7 @@ func Save(p Provider) error {
|
||||
if p.ID == "kiro" {
|
||||
key = p.Key
|
||||
}
|
||||
p = Provider{ID: p.ID, Key: key, Models: p.Models, NoModels: p.NoModels, BestInFamily: p.BestInFamily, RateWindows: p.RateWindows, PickedFrom: p.PickedFrom, Delisted: p.Delisted, Unlisted: p.Unlisted, HiddenDrawers: p.HiddenDrawers, Off: p.Off, Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, Contexts: p.Contexts, Family: p.Family, Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, CapStop: p.CapStop, CapCareful: p.CapCareful, AccountNames: p.AccountNames, MaxConcurrency: p.MaxConcurrency, AccountConcurrency: p.AccountConcurrency, QueueLimit: p.QueueLimit, QueueWait: p.QueueWait, MaxRPM: p.MaxRPM, PriceRate: p.PriceRate, QuotaRest: p.QuotaRest, QuotaResetAt: p.QuotaResetAt, RestCap: p.RestCap, PinUpstream: p.PinUpstream, NativeCompaction: p.NativeCompaction, PromptAsWritten: p.PromptAsWritten, Unredacted: p.Unredacted, Hidden: hiddenAccount(p.ID), Quiet: quietAccount(p.ID), Tucked: tuckedAccount(p.ID)}
|
||||
p = Provider{ID: p.ID, Key: key, Models: p.Models, NoModels: p.NoModels, BestInFamily: p.BestInFamily, RateWindows: p.RateWindows, PickedFrom: p.PickedFrom, Delisted: p.Delisted, Unlisted: p.Unlisted, HiddenDrawers: p.HiddenDrawers, Off: p.Off, Fallback: p.Fallback, Routing: p.Routing, Sink: p.Sink, Affinity: p.Affinity, KeepLogin: p.KeepLogin, KeepLoginAs: p.KeepLoginAs, SwitchOnly: p.SwitchOnly, Contexts: p.Contexts, Family: p.Family, Proxy: p.Proxy, AccountProxies: p.AccountProxies, AccountModels: p.AccountModels, AccountCaps: p.AccountCaps, AccountWindowCaps: p.AccountWindowCaps, CapStop: p.CapStop, CapCareful: p.CapCareful, AccountNames: p.AccountNames, MaxConcurrency: p.MaxConcurrency, AccountConcurrency: p.AccountConcurrency, QueueLimit: p.QueueLimit, QueueWait: p.QueueWait, MaxRPM: p.MaxRPM, PriceRate: p.PriceRate, CountFree: p.CountFree, QuotaRest: p.QuotaRest, QuotaResetAt: p.QuotaResetAt, RestCap: p.RestCap, PinUpstream: p.PinUpstream, NativeCompaction: p.NativeCompaction, PromptAsWritten: p.PromptAsWritten, Unredacted: p.Unredacted, Hidden: hiddenAccount(p.ID), Quiet: quietAccount(p.ID), Tucked: tuckedAccount(p.ID)}
|
||||
} else {
|
||||
p.AccountProxies = keyProxies(p) // a provider of keys proxies each key apart
|
||||
if subscriptionID(p.ID) && !stored(p.ID) {
|
||||
@@ -1157,6 +1166,7 @@ func AddCopy(p Provider, from string) (string, error) {
|
||||
}
|
||||
p.Searches = p.Searches || src.Searches
|
||||
p.Unredacted = p.Unredacted || src.Unredacted
|
||||
p.CountFree = p.CountFree || src.CountFree
|
||||
p.NativeCompaction = p.NativeCompaction || src.NativeCompaction
|
||||
p.PassUserAgent = p.PassUserAgent || src.PassUserAgent
|
||||
if p.Website == "" {
|
||||
|
||||
@@ -100,6 +100,18 @@ func SetCapCareful(id string, on bool) error {
|
||||
return Save(*p)
|
||||
}
|
||||
|
||||
// SetCountFree has every model of a provider count as free for the
|
||||
// routings that weigh it, or go by its vendor's word again
|
||||
// (Provider.CountFree).
|
||||
func SetCountFree(id string, on bool) error {
|
||||
p, err := Find(id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
p.CountFree = on
|
||||
return Save(*p)
|
||||
}
|
||||
|
||||
// SetKeepLogin keeps Codex or Claude Code signed in to the account the
|
||||
// user made first (Provider.KeepLogin), or lets magpie move it on again.
|
||||
// Either way it is no longer kept on one of the user's choosing
|
||||
|
||||
Reference in New Issue
Block a user