A provider can have up to 8 rate windows: days, a span that may cross midnight (on this computer's clock), and a rate. Inside a window a call costs the base price times the rate. The base is the user's model price as set, or the list price times PriceRate with the vendor's own peak (DeepSeek, Command Code, OpenCode Go) already in it. The author gave this order as the spec: a 0.8 window on a shared DeepSeek key takes 0.8 off the peak price at peak. The editor's hint says not to set the official peak hours again as a window, in every language. Each call is priced at its own time on the Usage page and its CSV, in the Requests tab's rows, and against a gateway key's cost limit. The Sessions page, group templates and the model list written into an agent's own config use the base price. /v1/models prices at now. Ported from YangHonghang's 2c9d459ff (rate-windows-2463-v2). The Go pricing, its tests and the translations are theirs. Changed here: - No budget raised. Their commit raised appScriptBudget and coreScriptBudget; core_budget_test.go is main's again. The editor's window rows, time menus, validation and hint moved to ratewindows.js, which app.js imports when the field is drawn (as signsheets.js is). The sliding-thumb and modalDepth comments were cut down to make room. The core is 1,535,528 of 1,536,586 and app.js 1,312,242 of 1,315,316. Until the script has loaded, a save leaves rateWindows out, and the server keeps the saved ones. - Their unrelated TestAssetsHaveNoConflictMarkers is dropped (one commit, one goal). - The row badge shows only for a provider with windows. Before, every provider with a price rate alone got a new ×badge. Its title is shorter, and so are its translations. - AgentPricer (agent model files: Pi, omp, OpenCode cost) uses the base price. Nothing rewrites those files when a window opens or closes, so a price taken at Sync stayed on outside the window. - internal/budget gets a TestMain through testenv, so the new test runs in a home of its own. - old-webkit's list of lazily loaded scripts names ratewindows.js. - The draft keeps each window as a shallow copy, and a day chip replaces its days array, so the saved provider is never changed. - The GUI test waits for the lazy script's hint, not a fixed 300ms. It also checks the peak note in each language. Run first on2f5a3f1c0, then again after rebasing on70d9996c5,8acb0d3a7andd609729cf. The rebase onto70d9996c5met main's ruleedit.js in old-webkit's list, and both are listed. - gofmt -l internal: clean at8acb0d3a7(129578c3dgofmt'd main's pi_api_test.go). - mote, on8acb0d3a7: go vet on usage, provider and gui ok; GOOS=linux and GOOS=windows go vet -tags nogui ./... ok. go test -tags nogui for internal/usage, provider, gui, budget and sessions: ok. The five internal/agent tests that are red on WSL (below) pass on mote there. Ond609729cf(a one-line mover min in internal/provider), internal/provider again: ok. - On2f5a3f1c0: internal/provider, usage, budget and sessions, and the gui RateNow|PriceRate|CoreScript|Budget tests, each under TZ=UTC, Asia/Shanghai and America/Los_Angeles: all ok. - wsl-run (magpie-desktop, Playwright chromium and webkit) on70d9996c5: provider-rate-windows, old-webkit, i18n-keys, provider-price-rate, provider-advanced-fold, agent-hides-editor, key-box-once, provider-many-keys, nokey-editor and editor-short-window: 200/200. On2f5a3f1c0the first five and model-price-edit: 132/132. On mote the same files hit WebKit launch timeouts (180s) under another session's full GUI suite (load 30), and that run was stopped. - Full suite, wsl-run (mote was running another session's full suite), go test -tags nogui -count=1 -timeout 45m ./... at 6e534f546 (this change on70d9996c5): every package ok except internal/agent. internal/agent fails TestInstalledVersion, TestGrokInstalled, TestCursorFolderFromTheEditorIsNotTheCLI, TestOmpDetectedWithPiDir and TestZedAppPath. This change doesn't touch internal/agent. At origin/main8acb0d3a7on the same box, TestInstalledVersion, TestGrokInstalled and TestOmpDetectedWithPiDir fail too: a fake CLI in /tmp exec'd with "Invalid argument". That is #4033 and #3548 (WSL2 binfmt interop). - Broken by hand, red each time: - Pricer without the window: TestPricerRateWindows, TestBlockRowsTakeTheirRateWindow, TestCostLimitCountsTheRateWindow. - Block rows without atWindow: TestBlockRowsTakeTheirRateWindow. - AgentPricer at now: TestAgentPricerLeavesTheRateWindowOut. - Badge for a price rate alone: TestRateNowOf. - Peak note removed: provider-rate-windows, 10 of 10 chromium layouts. - ratewindows.js not in old-webkit's list: old-webkit. Not tried: - A real relay billed by the hour. - The real desktop app (WebKitGTK, WKWebView). - The full GUI suite (mote was running another session's). Known limits: - No rate is stored per record, so changing the windows reprices history, as a changed PriceRate does. - Windows follow this computer's zone, with no zone of their own. - The Sessions page uses the base price. Co-authored-by: YangHonghang <honghang.yang@qq.com>
160 lines
4.9 KiB
Go
160 lines
4.9 KiB
Go
package provider
|
||
|
||
import (
|
||
"fmt"
|
||
"math"
|
||
"slices"
|
||
"strconv"
|
||
"strings"
|
||
"time"
|
||
)
|
||
|
||
// RateWindow is a time-of-day window a provider bills at its own rate
|
||
// (#2463): a relay that charges 2× or 3× at peak and a discount off
|
||
// peak. Start and End are "HH:MM" on this computer's clock, End may be
|
||
// "24:00"; Start after End crosses midnight, and the window then belongs
|
||
// to the day it starts on, its Days among them. Days are time.Weekday's
|
||
// numbers (Sunday 0), empty for every day. Rate is what the provider
|
||
// bills against the official price inside the window, on top of
|
||
// PriceRate: from just over 0 to 1000, at most three decimals. The first
|
||
// window that holds a call's time wins; outside every window the price
|
||
// rate alone counts. The window's rate scales a price the user set for a
|
||
// model too, which the price rate alone leaves as set.
|
||
type RateWindow struct {
|
||
Days []int `json:"days,omitempty"`
|
||
Start string `json:"start"`
|
||
End string `json:"end"`
|
||
Rate float64 `json:"rate"`
|
||
}
|
||
|
||
// RateWindowsMax is how many windows one provider can have (#2463).
|
||
const RateWindowsMax = 8
|
||
|
||
// ParseClock reads "HH:MM" as minutes into the day: 0 for 00:00 through
|
||
// 1440 for 24:00, which only an end may be. ok is false for anything
|
||
// else.
|
||
func ParseClock(s string) (min int, ok bool) {
|
||
h, m, found := strings.Cut(strings.TrimSpace(s), ":")
|
||
if !found || len(h) == 0 || len(h) > 2 || !isDigits(h) || len(m) != 2 || !isDigits(m) {
|
||
return 0, false
|
||
}
|
||
hh, err := strconv.Atoi(h)
|
||
if err != nil || hh > 24 {
|
||
return 0, false
|
||
}
|
||
mm, err := strconv.Atoi(m)
|
||
if err != nil || mm > 59 {
|
||
return 0, false
|
||
}
|
||
if min = hh*60 + mm; min > 1440 {
|
||
return 0, false
|
||
}
|
||
return min, true
|
||
}
|
||
|
||
// isDigits says whether s is ASCII digits alone.
|
||
func isDigits(s string) bool {
|
||
for _, r := range s {
|
||
if r < '0' || r > '9' {
|
||
return false
|
||
}
|
||
}
|
||
return len(s) > 0
|
||
}
|
||
|
||
// CheckRateWindows says what is wrong with a set of a provider's rate
|
||
// windows, "" when nothing. A window's rate stands to the same rule as a
|
||
// price rate but is never 0: 0 would read as the price as listed, which
|
||
// is what being outside every window already means.
|
||
func CheckRateWindows(ws []RateWindow) string {
|
||
if len(ws) > RateWindowsMax {
|
||
return fmt.Sprintf("at most %d rate windows", RateWindowsMax)
|
||
}
|
||
for i, w := range ws {
|
||
start, ok := ParseClock(w.Start)
|
||
if !ok {
|
||
return fmt.Sprintf("rate window %d: the start is a time like 09:00, not %s", i+1, w.Start)
|
||
}
|
||
end, ok := ParseClock(w.End)
|
||
if !ok {
|
||
return fmt.Sprintf("rate window %d: the end is a time like 18:00, not %s", i+1, w.End)
|
||
}
|
||
if start == 1440 {
|
||
return fmt.Sprintf("rate window %d: the start is a time like 09:00, not %s", i+1, w.Start)
|
||
}
|
||
if start == end {
|
||
return fmt.Sprintf("rate window %d: the start and the end are both %s", i+1, w.Start)
|
||
}
|
||
for _, d := range w.Days {
|
||
if d < 0 || d > 6 {
|
||
return fmt.Sprintf("rate window %d: a day is 0 (Sunday) to 6 (Saturday), not %d", i+1, d)
|
||
}
|
||
}
|
||
if r := w.Rate; !(r > 0) || math.IsNaN(r) || r > 1000 {
|
||
return fmt.Sprintf("rate window %d: the rate is a number from 0 to 1000, not %v", i+1, r)
|
||
}
|
||
if math.Abs(w.Rate*1000-math.Round(w.Rate*1000)) > 1e-6 {
|
||
return fmt.Sprintf("rate window %d: the rate has at most three decimals, not %v", i+1, w.Rate)
|
||
}
|
||
}
|
||
return ""
|
||
}
|
||
|
||
// RateAt is the rate the windows bill at at t, on this computer's clock:
|
||
// 0 when no window holds t, which means the price rate alone, and for a
|
||
// zero t, a price asked for with no call's time (a memo of the price
|
||
// shared by many calls) being the base. The first window that holds t
|
||
// wins. A window's span is from its start in and to
|
||
// its end out; one that crosses midnight belongs to the day it starts
|
||
// on, so its early hours read as that day's.
|
||
func RateAt(ws []RateWindow, t time.Time) float64 {
|
||
if len(ws) == 0 || t.IsZero() {
|
||
return 0
|
||
}
|
||
// t's own zone is whatever wrote it: a call reported to
|
||
// /v1/magpie/usage as "…Z" parses in UTC, and its hour read there
|
||
// missed a window by the zone's offset
|
||
t = t.Local()
|
||
m := t.Hour()*60 + t.Minute()
|
||
day := int(t.Weekday())
|
||
for _, w := range ws {
|
||
start, ok1 := ParseClock(w.Start)
|
||
end, ok2 := ParseClock(w.End)
|
||
if !ok1 || !ok2 || start == end {
|
||
continue
|
||
}
|
||
var in bool
|
||
d := day
|
||
if start < end {
|
||
in = m >= start && m < end
|
||
} else {
|
||
in = m >= start || m < end
|
||
if m < end {
|
||
// past midnight: the window began yesterday
|
||
d = (d + 6) % 7
|
||
}
|
||
}
|
||
if !in || len(w.Days) > 0 && !slices.Contains(w.Days, d) {
|
||
continue
|
||
}
|
||
return w.Rate
|
||
}
|
||
return 0
|
||
}
|
||
|
||
// RateWindowsOf is the rate windows of the provider with id, or of the one
|
||
// renamed from it, none for a provider not known: for a caller holding
|
||
// a base price to read each call's time against (#2463).
|
||
func RateWindowsOf(id string) []RateWindow {
|
||
p, ok := byIDOrWas(id)
|
||
if !ok {
|
||
return nil
|
||
}
|
||
return p.RateWindows
|
||
}
|
||
|
||
// RateAt is the rate the provider's windows bill at at t, 0 for none.
|
||
func (p Provider) RateAt(t time.Time) float64 {
|
||
return RateAt(p.RateWindows, t)
|
||
}
|