usage: Volcengine Ark's Coding Plan and Agent Plan windows, read with the account's access key (#1427, yayoinoyume)

Ark tells a Coding Plan's or Agent Plan's 5-hour, weekly and monthly
windows only to the account's control plane (GetCodingPlanUsage,
GetAFPUsage on open.volcengineapi.com), signed with the account's
AccessKey ID and Secret, never to the plan's inference key. An Ark
provider's editor now takes that access key, and the Usage page shows the
plan's windows as a card.

From yayoinoyume's feat/volcengine-usage, reviewed and reworked:
- Signing is volc-sdk-golang's (base/sign.go GetSignRequest, 06f9ef66):
  signed headers sorted (content-type;host;x-content-sha256;x-date), only
  Action and Version in the query. The branch signed them unsorted and put
  Region in the query. TestVolcSignMatchesSDK pins two signatures the SDK
  made.
- The card is in PlanQuotas beside the Step Plan's (its cache, last
  reading, refresh and `magpie quota wait`), not in the subscription
  cards. One per access key and plan.
- The plan is the endpoint's: /api/coding asks GetCodingPlanUsage,
  /api/plan GetAFPUsage, pay-as-you-go none, in the host's region. The
  branch asked both and showed whichever answered.
- Dropped guessed reply fields; the Coding Plan reply is the one
  pi-ark-usage, dsh-ark-quota and ArkCodingPlanUsage read. AFP buckets are
  read in the forms dsh-ark-quota and arkcli read (Used of Quota or Total,
  or Percent), plus Tier; none was seen from a real account.
- An Ark provider is known by its host, not the preset id, so a copy or a
  custom provider takes the key too.
- The Secret is never sent to the page (accessKey {id, secretSet}); a
  blank Secret keeps it, a save without the ID keeps both, Remove
  (clearAccessKey) drops both, an ID with no Secret is refused.
- The pair goes where keys go: AddCopy, Restore, Mirror, backups and
  davsync carry it only with keys (withoutKeys), and a keyless restore or
  sync keeps this machine's. CLI: access.key, access.secret.
- A changed access key drops the cached cards (ForgetPlanQuotas).
- UI strings in zh, zh-TW, ja and de.

Nothing was tried against the real Volcengine API: there was no access
key. A local fake checked the real request PlanQuotas makes against
volc-sdk-golang's own GetSignRequest (both actions, two regions); it
lives outside the repo, so go.mod is unchanged.

Run: gofmt -l; go vet (darwin), GOOS=linux and GOOS=windows go vet
-tags nogui on provider, gui, backup, davsync and the root; go test
-tags nogui ./internal/provider ./internal/gui ./internal/backup
./internal/davsync . under a temp HOME; node --test
volc-access-key, zhipu-team, gui-ja, gui-de, i18n-keys in Chromium and
WebKit. Fail without the change: TestVolcSignMatchesSDK (unsorted
headers), TestAddCopy, TestBackupBalanceToken, TestNoKeys,
TestTakeBalanceToken, TestSyncBalanceToken (pair not carried),
TestProviderSaveKeepsVolcengineSecret (blank Secret dropped),
volc-access-key (Remove not posted).

Co-authored-by: YAYOI27 <111715843+yayoinoyume@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
YAYOI27
2026-10-09 23:25:04 +08:00
committed by yetone
co-authored by Claude
parent ea1c5d0457
commit aa82288fb6
19 changed files with 1135 additions and 33 deletions
+6 -2
View File
@@ -30,7 +30,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
| Allowance | `Quotas` asks every vendor at once: subscription windows (`SubscriptionUsage`), key-bought plans (`PlanQuotas`) and key balances (`KeyBalances`). The Usage page, `magpie quota --json` and `GET /v1/magpie/quotas` read it. A single card can be read again on its own (#840). A remote magpie's cards come from what it has kept (`CachedCards`, `GET /v1/magpie/quotas/cards`) and are never read there for this computer except by a card's refresh (`POST /v1/magpie/quotas/refresh`, throttled per card). What it has kept is the Usage page's cards with the readings made behind the requests since laid over them, a later one over an earlier by `readSeq` (`cards_kept.go`): each account's `LoginUsage` reading (the used-up switch, the Codex warm-up, routing's `Allowances`), and each key's `KeyAllowance` windows on its plan or balance card. An account or key read that way and never on the page gets a card from that reading, and after a restart, before either is read again, the cards come from `quotas.json`, dated (`AsOf`). A magpie serving only other magpies has nobody on its page (#1313). Cursor, Grok and a Kiro key keep the page's cards only. | [`cards_kept.go`](../../internal/provider/cards_kept.go), [`quotas.go`](../../internal/provider/quotas.go), [`subscription_usage.go`](../../internal/provider/subscription_usage.go), [`planquota.go`](../../internal/provider/planquota.go), [`balance.go`](../../internal/provider/balance.go), [`quota_refresh.go`](../../internal/provider/quota_refresh.go), [`remote_quotas.go`](../../internal/provider/remote_quotas.go) |
| A remote magpie's prices | A local magpie asks a remote magpie's `/v1/models` with `X-Magpie-Prices` (`PricesHeader`, sent by `listHeaders`). The remote answers each model's `magpie_price`: what its own Usage page counts the model at (`EntryPriceIn`: the price its user set, else its provider's list price at its price rate; a routing group only when every member costs the same). It tells it only to a request from its own computer or one let in with a gateway key (`local` or `sharedWith`); one let in without a key (`MAGPIE_ADDR` open, not shared) and a list that didn't ask get no prices. The local keeps the price with the fetched list (`catalog.Model.Price`; a value that isn't a price, or has a negative part, is dropped, the model kept) and uses it as that provider's list price (`ListPrice` → `remotePrice`). A price the local user set (`provider/model`, `provider/*`, `*/model`) still comes first, and the local provider's own price rate still applies on top. A remote from before this sends no field and the models stay priced as before; an older local sends no header and is sent nothing new. The model editor says the greyed price is the other magpie's (`remoteList`). | [`remote_magpie.go`](../../internal/provider/remote_magpie.go), [`models.go`](../../internal/provider/models.go), [`gateway.go`](../../internal/gateway/gateway.go) (`models`), [`live.go`](../../internal/catalog/live.go) |
| A membership's $0 catalog | models.dev lists every model of Kimi Code's plans (`kimi-code-plan-global`, `kimi-code-plan-cn`) at $0: what the membership charges per token, not what the model costs. `membershipCatalogs` are never read for a price (`priceCatalogs`, `makerPriceCatalogs`), so a Kimi Code provider's model is priced at the Kimi API model it is (`kimiCodeAPI`, from Kimi Code's docs: k3 and k3-256k are kimi-k3, kimi-for-coding-highspeed is kimi-k2.7-code-highspeed), and kimi-for-coding (K2.8 Preview, not on the API) is unpriced rather than free (#1370). The alias is Kimi Code's alone: a relay's own `k3` keeps its own price. The Requests list names the API model it was priced as (`PricedNameFor`). | [`models.go`](../../internal/provider/models.go) |
| A key's own windows | A sub2api key given a spending limit per 5 hours, day or 7 days answers its `/v1/usage` with `rate_limits` and no `remaining` (`readSub2APIKeyLimits`). With the Balance URL set to it, the key's card shows them as the windows *5 hours*, *1 day*, *7 days*, in USD, beside a balance field the user wrote; *Check balance* and `magpie provider show` give what its fullest window has left (`Balance`). `KeyAllowance` gives routing the same windows: never waited for, read in the background at most once a minute, a failed read keeping the last, and seeded from the card's last reading (`quotas.json`) after a restart. A key bought as a plan (Kimi Code, GLM Coding Plan and Z.ai, MiniMax Coding Plan, OpenCode Go, Command Code: `planQuotaSourceOf`) gives routing its card's windows the same way (`planKeyWindows`, Zhipu's team quota behind a key with none of its own); the Usage page's read of its card is taken at once (`noteKeyAllowance`), and a key there that turns out pay-as-you-go, with no windows, is asked again only every 30 minutes (`keyNoWindowsAge`). StepFun's Step Plan is read through a sign-in, not the key, and isn't one of them. | [`sub2api_usage.go`](../../internal/provider/sub2api_usage.go), [`key_allowance.go`](../../internal/provider/key_allowance.go) |
| A key's own windows | A sub2api key given a spending limit per 5 hours, day or 7 days answers its `/v1/usage` with `rate_limits` and no `remaining` (`readSub2APIKeyLimits`). With the Balance URL set to it, the key's card shows them as the windows *5 hours*, *1 day*, *7 days*, in USD, beside a balance field the user wrote; *Check balance* and `magpie provider show` give what its fullest window has left (`Balance`). `KeyAllowance` gives routing the same windows: never waited for, read in the background at most once a minute, a failed read keeping the last, and seeded from the card's last reading (`quotas.json`) after a restart. A key bought as a plan (Kimi Code, GLM Coding Plan and Z.ai, MiniMax Coding Plan, OpenCode Go, Command Code: `planQuotaSourceOf`) gives routing its card's windows the same way (`planKeyWindows`, Zhipu's team quota behind a key with none of its own); the Usage page's read of its card is taken at once (`noteKeyAllowance`), and a key there that turns out pay-as-you-go, with no windows, is asked again only every 30 minutes (`keyNoWindowsAge`). StepFun's Step Plan is read through a sign-in, not the key, and isn't one of them. Nor are Volcengine Ark's Coding Plan and Agent Plan (#1427): their 5-hour, weekly and monthly windows are told only to the account's access key (`AccessKeyID`, `SecretAccessKey`), asked of `open.volcengineapi.com` (`GetCodingPlanUsage`, `GetAFPUsage`) and signed as Volcengine's own SDK signs (`volcSign`), so they are cards on the Usage page (`volcPlanQuotas` in `PlanQuotas`), never routing's windows. | [`sub2api_usage.go`](../../internal/provider/sub2api_usage.go), [`key_allowance.go`](../../internal/provider/key_allowance.go), [`volcengine_usage.go`](../../internal/provider/volcengine_usage.go) |
| Last served | `served.json` records when each account, plan or key last answered, shown as `lastServedAt` (#570). | [`served.go`](../../internal/provider/served.go) |
| Partners | Services that pay to be listed first in the add sheet, under a heading of their own ("Partners · magpie's sponsors"). The list is `site/partners.js`, served at `usemagpie.ai/api/partners`: a change reaches users with a deploy, not a release. `Partners` never waits: it returns what was fetched last and fetches again behind the call every 6 hours (10 minutes after a failure), keeping the list in `partners.json` in the cache folder. Each entry is checked again on every read (`validPartners`): its own id, never a built-in preset's, a name, an endpoint, https only, at most 12; what only magpie's presets may set (a decision API, no key, a user endpoint) is cleared. Its logo is fetched through `FetchIcon` and kept as an uploaded icon. A partner is a preset to the rest of magpie (`Preset`, `FromPreset`, the editor), and one no longer listed still is to the providers added from it (`Seen`), without the sponsored mark. The window lists a partner in the languages it names (`langs`) only and shows its tagline in the page's language (`notes`, else `en`). `MAGPIE_PARTNERS` points it elsewhere, `off` lists none; tests list none unless they name a list. How often each listed partner was shown, opened (its row, its key page) and added is counted per UTC day (`CountPartner`, capped at 20 of each and 5 adds, kept in `partner-counts.json` in the cache folder) and sent with the next day's stats event as `magpie partner` events (`internal/stats`); nothing is counted with the stats or their usage part off. A listed partner the add sheet (or the TUI's, or `magpie providers presets`) hasn't shown yet is new (`NoticePartners` keeps those shown, as `noticed` in `partners.json`, whatever the stats); the window's add button carries a small dot for it, with its name in the title, until the sheet shows it. | [`partners.go`](../../internal/provider/partners.go), [`partner_events.go`](../../internal/provider/partner_events.go), [`site/partners.js`](../../site/partners.js) |
| Protocol detection | Works out which of Chat, Responses, Anthropic Messages and Gemini generateContent a base URL speaks when a provider is added. Each is asked at the URL as it takes it (`DetectBase`); Gemini's at the `…/v1beta` beside a typed `…/v1` or bare host, a Gemini model from the list picked for it, with the key in `x-goog-api-key` (#1346). Detection, endpoint tests and model tests share `probe`, which adds `anthropic-version` only for Anthropic Messages; OpenAI probes omit that default so a relay that refuses it can answer. User-supplied headers still apply through `Sign`. | [`detect.go`](../../internal/provider/detect.go), [`test.go`](../../internal/provider/test.go) |
@@ -58,6 +58,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
- A preset marked `NoList` uses its preset model list instead of requesting `/models`, and ignores previously fetched lists, including their protocol and key restrictions, unless the user sets `ModelsURL` or chooses a region marked `Lists`. Each region can carry a different list. Volcengine Ark's Coding Plan and Agent Plan use separate preset lists. Both plans include their embedding model separately from agents' chat-model lists; Agent Plan additionally exposes its image- and video-generation models to Settings → Images; Ark itself refuses video generation on Small and Medium Agent Plans, which include it only in the Large and Max tiers. Models magpie does not yet serve (Agent Plan's speech models) are not advertised. Ark's pay-as-you-go region still fetches its own list. Coding's `/api/coding/v3/models` returns a general Ark catalog instead of the plan's model ids, while Agent's `/api/plan/v3/models` returns 404. [`presets.go`](../../internal/provider/presets.go) defines these choices; `List`, `fetch`, `live`, `planModels`, `PlanEmbeddings`, `PlanDrawers` and `PlanVideos` in [`models.go`](../../internal/provider/models.go) apply them when adding, refreshing and reading cached models. `TestVolcengineModelLists` checks that the plans make no list requests, ignore old cached lists and return their own preset models; pay-as-you-go and an explicit list URL still make requests.
- A gateway key held to some accounts (#905) is held to those of the providers its list names: a provider it names no account of, the key uses as it always did. The list keeps an account by its stable id — `logins.json`'s `id`, set once written and kept through renames; the agents that keep no logins (and plugins) are known by a hash of the account's name, so an account renamed there drops out of a key's list, holding it closer, never wider. Storing an id for every agent is a larger change, not this one's.
- A sub2api key's windows are fixed: each starts at the key's first request after it was empty, aligned to the relay's day, and a window not started yet says `used 0` with no `reset_at`, so it is taken to renew a span from now. They count this key's spend only, not the relay's accounts behind it. `ForgetBalances` (a key or Balance URL changed) has every key's windows read again at its next ask, a read begun before dropped; until then the last reading stands, fresher than the card's, which routing's reads never write. A key changed is another key (`keyID`), with windows of its own.
- A Volcengine Ark provider's access key (`TakesVolcAccessKey`: any of its bases on `ark.<region>.volces.com`) is kept with its keys and never sent to the GUI: `/api/providers` tells the editor its ID and whether a Secret is saved (`accessKey`). A save that leaves the Secret blank keeps it, one that leaves the ID out keeps both, and `clearAccessKey` drops both. The ID and Secret go together everywhere the keys go: a copy takes them (`AddCopy`), a backup or sync without keys has neither (`withoutKeys`), and a restore, mirror or sync without keys keeps this machine's (`Restore`, `Mirror`, davsync's `take`). The plan read is the endpoint's: `/api/coding` asks `GetCodingPlanUsage`, `/api/plan` asks `GetAFPUsage`, pay-as-you-go (`/api/v3`) has no card; the region is the host's. One card is read for each access key and plan. `GetCodingPlanUsage`'s reply (`QuotaUsage[]` with `Level`, `Percent`, `ResetTimestamp` in seconds) is the one three tools built on it read; `GetAFPUsage`'s buckets are read in each form those tools read (`Used` of `Quota` or `Total`, or `Percent`; `ResetTime` or `ResetTimestamp`), none of them seen from a real account here. A reply none of that reads says so on the card with the reply's head. Changing the access key drops the cached cards (`ForgetPlanQuotas`).
- Whether a Codex account spends its credits (`CodexNoCredits` in settings, opt-out, by lower-cased email) is the gateway's routing only. It never changes which account Codex is signed in to: `NextLogin` moves off an account at its routing's spent share, 100% at most, credits or not.
- A usage cap is kept per account (`AccountCaps`, 1–99) and, beside it, per window (`AccountWindowCaps`, by the account and the window's `capId`, its name in lower case: `WindowCapID`). A window's own share wins over the account's; 100 is no cap on that window. `CapsOf` gives both (`WindowCaps`), `CapHeld` and `capReached` judge each window by its own, and `SetWindowCap` (GUI `provider/windowcap`, `magpie provider account-cap <id> <account> --window <name>`) sets one. A config without window caps reads as before.
- A window whose reset time has passed has started again, whatever share it was read at (`resetPassed`). That holds for a reading kept from before (`AsOf`) and for a fresh one: Claude Code's `/usage` gives a reset to the minute and can lag it, so a run just after a reset can still say 100% with that reset. `claudeWindows` hands such a window back empty on every path, and `usedPast`, `usedUp`, `BackAt` and `capReached` leave it out when they judge an account spent, for Codex, Claude Code and `magpie quota wait` alike. A card can still show a kept reading as it was read (`reported`, for a Claude card while `/usage` is unavailable); that changes what it shows, never which account is used. A reset `/usage` gives as a time alone ("resets 3pm") can be read as its next one, a day on (`claudeResetTime`), and is then not seen as passed here.
@@ -69,7 +70,10 @@ go test -tags nogui ./internal/provider -run 'TestAccount|TestCodex|TestGroup|Te
go test -tags nogui ./internal/provider -run 'TestCapHeld|TestCapReached|TestWindowCapHeld|TestSetWindowCap'
go test -tags nogui . -run TestAccountCapCmd
node --test internal/gui/tests/account-cap.test.cjs internal/gui/tests/window-cap.test.cjs
go test -tags nogui ./internal/provider -run 'TestVolcengine|TestQianfan|TestBedrock'
go test -tags nogui ./internal/provider -run 'TestVolc|TestQianfan|TestBedrock|TestAddCopy|TestBackupBalanceToken'
go test -tags nogui ./internal/gui -run TestProviderSaveKeepsVolcengineSecret
go test -tags nogui ./internal/backup ./internal/davsync -run 'TestRoundTrip|TestNoKeys|BalanceToken'
node --test internal/gui/tests/volc-access-key.test.cjs
go test -tags nogui ./internal/provider -run '^TestProviderProbesUseProtocolHeaders$'
go test -tags nogui ./internal/provider -run '^Test(Partners|CountPartner|NoticePartners)'
go test -tags nogui ./internal/provider -run 'TestGeminiBase|TestCustomGeminiProvider|TestFactoryGeminiUnchanged'
+1
View File
@@ -237,6 +237,7 @@ func Secret(name string) bool { return secretHeader.MatchString(name) }
func withoutKeys(p provider.Provider) provider.Provider {
p.Key, p.KeyName, p.Keys, p.KeyProtocol, p.KeyWeight = "", "", nil, "", 0
p.BalanceToken = ""
p.AccessKeyID, p.SecretAccessKey = "", ""
if len(p.Headers) > 0 {
h := map[string]string{}
for k, v := range p.Headers {
+10 -8
View File
@@ -68,9 +68,9 @@ func setUp(t *testing.T) {
}
for _, p := range []provider.Provider{
{ID: "acme", Name: "Acme", Chat: "https://acme.example.com/v1", Key: "sk-acme", Icon: icon,
BalanceToken: "balance-acme",
Keys: []provider.KeyAccount{{Name: "second", Key: "sk-acme-2"}},
Headers: map[string]string{"X-Team": "a", "X-Api-Key": "hdr-secret"}},
BalanceToken: "balance-acme", AccessKeyID: "AK-acme", SecretAccessKey: "SK-acme",
Keys: []provider.KeyAccount{{Name: "second", Key: "sk-acme-2"}},
Headers: map[string]string{"X-Team": "a", "X-Api-Key": "hdr-secret"}},
{ID: "beta", Name: "Beta", Chat: "https://beta.example.com/v1", Key: "sk-beta", BalanceToken: "balance-beta"},
} {
if err := provider.Save(p); err != nil {
@@ -96,7 +96,7 @@ func TestRoundTrip(t *testing.T) {
if err != nil {
t.Fatal(err)
}
for _, secret := range []string{"sk-acme", "balance-acme", "hdr-secret", "acme.example.com", "work"} {
for _, secret := range []string{"sk-acme", "balance-acme", "SK-acme", "hdr-secret", "acme.example.com", "work"} {
if strings.Contains(string(data), secret) {
t.Fatalf("%q readable in the file", secret)
}
@@ -118,7 +118,8 @@ func TestRoundTrip(t *testing.T) {
t.Fatalf("result: %+v", r)
}
p, err := provider.Find("acme")
if err != nil || p.Key != "sk-acme" || len(p.Keys) != 1 || p.BalanceToken != "balance-acme" || p.Headers["X-Api-Key"] != "hdr-secret" {
if err != nil || p.Key != "sk-acme" || len(p.Keys) != 1 || p.BalanceToken != "balance-acme" || p.Headers["X-Api-Key"] != "hdr-secret" ||
p.AccessKeyID != "AK-acme" || p.SecretAccessKey != "SK-acme" {
t.Fatalf("acme: %+v %v", p, err)
}
name, _ := strings.CutPrefix(p.Icon, "file:")
@@ -143,7 +144,7 @@ func TestNoKeys(t *testing.T) {
t.Fatal(err)
}
for _, p := range b.Providers {
if p.Key != "" || len(p.Keys) != 0 || p.BalanceToken != "" {
if p.Key != "" || len(p.Keys) != 0 || p.BalanceToken != "" || p.AccessKeyID != "" || p.SecretAccessKey != "" {
t.Fatalf("key in a keyless backup: %+v", p)
}
if _, ok := p.Headers["X-Api-Key"]; ok {
@@ -159,7 +160,8 @@ func TestNoKeys(t *testing.T) {
}
home(t)
if err := provider.Save(provider.Provider{ID: "acme", Name: "Acme old", Chat: "https://old.example.com/v1", Key: "sk-here", BalanceToken: "balance-here"}); err != nil {
if err := provider.Save(provider.Provider{ID: "acme", Name: "Acme old", Chat: "https://old.example.com/v1", Key: "sk-here", BalanceToken: "balance-here",
AccessKeyID: "AK-here", SecretAccessKey: "SK-here"}); err != nil {
t.Fatal(err)
}
got, err := Open(data, "pw")
@@ -173,7 +175,7 @@ func TestNoKeys(t *testing.T) {
if r.Added != 1 || r.Replaced != 1 || !slices.Equal(r.NeedKey, []string{"Beta"}) || r.Settings || r.Profiles != 0 {
t.Fatalf("result: %+v", r)
}
if p, _ := provider.Find("acme"); p.Key != "sk-here" || p.BalanceToken != "balance-here" || p.Chat != "https://acme.example.com/v1" || p.Headers["X-Team"] != "a" {
if p, _ := provider.Find("acme"); p.Key != "sk-here" || p.BalanceToken != "balance-here" || p.AccessKeyID != "AK-here" || p.SecretAccessKey != "SK-here" || p.Chat != "https://acme.example.com/v1" || p.Headers["X-Team"] != "a" {
t.Fatalf("acme: %+v", p)
}
if p, _ := provider.Find("beta"); p.BalanceToken != "" {
+19 -13
View File
@@ -11,7 +11,8 @@ import (
)
// A computer sending no keys leaves the server's balance token in place,
// just as it leaves its API keys. Sending keys replaces the token too.
// just as it leaves its API keys. Sending keys replaces the token too. A
// Volcengine access key (#1427) goes the same way, ID and Secret together.
func TestTakeBalanceToken(t *testing.T) {
for _, c := range []struct {
name string
@@ -29,10 +30,12 @@ func TestTakeBalanceToken(t *testing.T) {
server := provider.Provider{ID: "relay", Name: "Old", Chat: "https://old.example.com/v1"}
if c.serverKeys {
server.Key, server.BalanceToken = "sk-server", "balance-server"
server.AccessKeyID, server.SecretAccessKey = "AK-server", "SK-server"
}
incoming := provider.Provider{ID: "relay", Name: "New", Chat: "https://new.example.com/v1", BalanceToken: c.token}
if c.incomingKeys {
incoming.Key = "sk-new"
incoming.AccessKeyID, incoming.SecretAccessKey = "AK-new", "SK-new"
}
to := backup.Bundle{Keys: c.serverKeys, Providers: []provider.Provider{server}}
from := backup.Bundle{Keys: c.incomingKeys, Providers: []provider.Provider{incoming}}
@@ -44,9 +47,12 @@ func TestTakeBalanceToken(t *testing.T) {
if got.BalanceToken != c.want || got.Name != incoming.Name || got.Chat != incoming.Chat {
t.Fatalf("merged: %+v, want balance token %q and the incoming name and URL", got, c.want)
}
wantKey := incoming.Key
wantKey, wantAK, wantSK := incoming.Key, incoming.AccessKeyID, incoming.SecretAccessKey
if c.serverKeys && !c.incomingKeys {
wantKey = server.Key
wantKey, wantAK, wantSK = server.Key, server.AccessKeyID, server.SecretAccessKey
}
if got.AccessKeyID != wantAK || got.SecretAccessKey != wantSK {
t.Fatalf("access key: %q %q, want %q %q", got.AccessKeyID, got.SecretAccessKey, wantAK, wantSK)
}
if got.Key != wantKey || to.Keys != (c.serverKeys || c.incomingKeys) || (to.Keys || (to.ProvidersKeys != nil && *to.ProvidersKeys)) != (c.serverKeys || c.incomingKeys) {
t.Fatalf("keys after merge: %+v", to)
@@ -87,24 +93,24 @@ func TestSyncBalanceToken(t *testing.T) {
}
use(a)
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Chat: "https://relay.example.com/v1",
Key: "sk-a", BalanceToken: "balance-a"}); err != nil {
Key: "sk-a", BalanceToken: "balance-a", AccessKeyID: "AK-a", SecretAccessKey: "SK-a"}); err != nil {
t.Fatal(err)
}
if err := Configure(cfg); err != nil {
t.Fatal(err)
}
now()
wantKey, wantToken := "", ""
wantKey, wantToken, wantSecret := "", "", ""
if serverKeys {
wantKey, wantToken = "sk-a", "balance-a"
wantKey, wantToken, wantSecret = "sk-a", "balance-a", "SK-a"
}
if got := remote(); got.Keys != serverKeys || len(got.Providers) != 1 || got.Providers[0].Key != wantKey || got.Providers[0].BalanceToken != wantToken {
if got := remote(); got.Keys != serverKeys || len(got.Providers) != 1 || got.Providers[0].Key != wantKey || got.Providers[0].BalanceToken != wantToken || got.Providers[0].SecretAccessKey != wantSecret {
t.Fatalf("first upload: %+v", got)
}
use(b)
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay b", Chat: "https://relay.example.com/v1",
Key: "sk-b", BalanceToken: "balance-b"}); err != nil {
Key: "sk-b", BalanceToken: "balance-b", AccessKeyID: "AK-b", SecretAccessKey: "SK-b"}); err != nil {
t.Fatal(err)
}
keyless := cfg
@@ -113,12 +119,12 @@ func TestSyncBalanceToken(t *testing.T) {
t.Fatal(err)
}
now()
localKey, localToken := "sk-b", "balance-b"
localKey, localToken, localSecret := "sk-b", "balance-b", "SK-b"
if serverKeys {
localKey, localToken = "sk-a", "balance-a"
localKey, localToken, localSecret = "sk-a", "balance-a", "SK-a"
}
ps, _ := provider.Stored()
if len(ps) != 1 || ps[0].Key != localKey || ps[0].BalanceToken != localToken {
if len(ps) != 1 || ps[0].Key != localKey || ps[0].BalanceToken != localToken || ps[0].SecretAccessKey != localSecret {
t.Fatalf("b after download: %+v", ps)
}
p := ps[0]
@@ -127,7 +133,7 @@ func TestSyncBalanceToken(t *testing.T) {
t.Fatal(err)
}
now()
if got := remote(); got.Keys != serverKeys || len(got.Providers) != 1 || got.Providers[0].Name != "Renamed" || got.Providers[0].Key != wantKey || got.Providers[0].BalanceToken != wantToken {
if got := remote(); got.Keys != serverKeys || len(got.Providers) != 1 || got.Providers[0].Name != "Renamed" || got.Providers[0].Key != wantKey || got.Providers[0].BalanceToken != wantToken || got.Providers[0].SecretAccessKey != wantSecret {
t.Fatalf("after b's keyless upload: %+v", got)
}
if ps, _ := provider.Stored(); len(ps) != 1 || ps[0].BalanceToken != "balance-b-new" {
@@ -135,7 +141,7 @@ func TestSyncBalanceToken(t *testing.T) {
}
use(a)
now()
if ps, _ := provider.Stored(); len(ps) != 1 || ps[0].Name != "Renamed" || ps[0].Key != "sk-a" || ps[0].BalanceToken != "balance-a" {
if ps, _ := provider.Stored(); len(ps) != 1 || ps[0].Name != "Renamed" || ps[0].Key != "sk-a" || ps[0].BalanceToken != "balance-a" || ps[0].AccessKeyID != "AK-a" || ps[0].SecretAccessKey != "SK-a" {
t.Fatalf("a after download: %+v", ps)
}
})
+3
View File
@@ -739,6 +739,9 @@ func take(to *backup.Bundle, from backup.Bundle, part string) {
if p.BalanceToken == "" {
ps[i].BalanceToken = k.BalanceToken
}
if p.AccessKeyID == "" && p.SecretAccessKey == "" {
ps[i].AccessKeyID, ps[i].SecretAccessKey = k.AccessKeyID, k.SecretAccessKey
}
}
}
}
+35
View File
@@ -8265,6 +8265,33 @@ function drawEditor(p, presetID) {
ed.append(...field(t("Team project ID"), proj, t("Only for a key on a team's GLM Coding Plan: both are in {p}'s console, under the team's organization and project. With them the Usage page shows the team's 5-hour and weekly windows.", { p: pr?.name || p.name })));
}
// Volcengine Ark tells a Coding or Agent Plan's windows only to the
// account's access key, never to the plan's key (#1427); the saved
// Secret is never sent back here, only that one is saved
const access = p ? p.accessKey : pr?.accessKey ? { id: "", secretSet: false } : null;
if (access) {
if (draft.accessKeyID === undefined) draft.accessKeyID = access.id || "";
const ak = input(draft.accessKeyID, t("AccessKey ID"));
ak.classList.add("volc-ak");
ak.oninput = () => { draft.accessKeyID = ak.value.trim(); };
const saved = access.secretSet && !draft.clearAccessKey;
const sk = input(draft.secretAccessKey || "", saved ? t("saved · paste a new one to replace it") : t("Secret Access Key"), "password");
sk.classList.add("volc-sk");
sk.oninput = () => { draft.secretAccessKey = sk.value.trim(); };
sk.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Escape") cancelEdit(); };
const pair = el("div", "pair");
pair.append(sk);
if (saved) {
const side = el("div", "side");
const drop = el("button", "text", t("Remove"));
drop.onclick = () => { draft.clearAccessKey = true; draft.accessKeyID = ""; draft.secretAccessKey = ""; ak.value = ""; sk.value = ""; sk.placeholder = t("Secret Access Key"); drop.remove(); };
side.append(drop);
pair.append(side);
}
ed.append(...field(t("AccessKey ID"), ak, ""));
ed.append(...field(t("Secret Access Key"), pair, t("The plan's 5-hour, weekly and monthly windows are told only to the account's access key (Volcengine console → API Access Keys), not to the plan's API key. Give it here for the Usage page to show them; it is used for nothing else.")));
}
// a relay that offers several regional endpoints, or a vendor whose plans
// are served at their own: one selector, and the provider's base URLs follow it
let refreshEndpoints = () => {}, onRegion = () => {};
@@ -8502,6 +8529,14 @@ function drawEditor(p, presetID) {
if (!org !== !project) { ed.querySelector(org ? ".team-project" : ".team-org")?.focus({ preventScroll: true }); return editorError(t("Team plan: give both the organization ID and the project ID"), "warn"); }
body.zhipuTeam = org ? { org, project } : {};
}
if (access) {
// the Secret is sent only when a new one is typed: blank keeps the
// saved one, unless it was removed
body.accessKeyID = draft.accessKeyID || "";
if (draft.secretAccessKey) body.secretAccessKey = draft.secretAccessKey;
else if (draft.clearAccessKey) body.clearAccessKey = true;
if (body.accessKeyID && !body.secretAccessKey && !(access.secretSet && !draft.clearAccessKey)) { ed.querySelector(".volc-sk")?.focus({ preventScroll: true }); return editorError(t("Give the access key's Secret too"), "warn"); }
}
if (isNew && custom && !body.name) { name.focus(); return editorError(t("Give it a name"), "warn"); }
if (isNew && custom && !body.chat && !body.anthropic && !body.responses && !body.decide) { url.focus(); return editorError(t("A base URL is needed"), "warn"); }
if (endpoint && !body.chat && !body.responses) { endpoint.focus(); return editorError(t(pr.endpointNeeded || "Your resource's endpoint is needed"), "warn"); }
+16
View File
@@ -2402,6 +2402,10 @@ const I18N = {
"optional · only for a team plan": "可选 · 仅团队套餐需要",
"Only for a key on a team's GLM Coding Plan: both are in {p}'s console, under the team's organization and project. With them the Usage page shows the team's 5-hour and weekly windows.": "仅团队 GLM Coding Plan 的 Key 需要:两者见 {p} 控制台的团队组织与项目。填写后用量页显示团队的 5 小时与每周额度。",
"Team plan: give both the organization ID and the project ID": "团队套餐:请同时填写组织 ID 和项目 ID",
"AccessKey ID": "AccessKey ID",
"Secret Access Key": "Secret Access Key",
"The plan's 5-hour, weekly and monthly windows are told only to the account's access key (Volcengine console → API Access Keys), not to the plan's API key. Give it here for the Usage page to show them; it is used for nothing else.": "套餐的 5 小时、每周和每月额度只对账号的访问密钥开放(火山引擎控制台 → API 访问密钥),套餐的 API Key 查不到。填在这里,用量页就会显示它们;仅用于查询额度。",
"Give the access key's Secret too": "请同时填写访问密钥的 Secret",
"A key tells only the balance. The Step Plan's 5-hour, weekly and credit windows are told only to a StepFun sign-in: bring yours here once and magpie keeps it (for 30 days), used for nothing else.": "API Key 只能查余额。Step Plan 的 5 小时、每周和积分额度仅对 StepFun 网页登录开放:导入一次登录,magpie 保存 30 天,仅用于查询额度。",
"Signed in · the Usage page shows the Step Plan": "已登录 · 用量页会显示 Step Plan 额度",
"Sign out": "退出登录",
@@ -6263,6 +6267,10 @@ const I18N = {
"optional · only for a team plan": "可選 · 僅團隊套餐需要",
"Only for a key on a team's GLM Coding Plan: both are in {p}'s console, under the team's organization and project. With them the Usage page shows the team's 5-hour and weekly windows.": "僅團隊 GLM Coding Plan 的 Key 需要:兩者見 {p} 控制台的團隊組織與專案。填寫後用量頁顯示團隊的 5 小時與每週額度。",
"Team plan: give both the organization ID and the project ID": "團隊套餐:請同時填寫組織 ID 和專案 ID",
"AccessKey ID": "AccessKey ID",
"Secret Access Key": "Secret Access Key",
"The plan's 5-hour, weekly and monthly windows are told only to the account's access key (Volcengine console → API Access Keys), not to the plan's API key. Give it here for the Usage page to show them; it is used for nothing else.": "套餐的 5 小時、每週和每月額度只對帳號的存取金鑰開放(火山引擎控制台 → API 存取金鑰),套餐的 API Key 查不到。填在這裡,用量頁就會顯示它們;僅用於查詢額度。",
"Give the access key's Secret too": "請同時填寫存取金鑰的 Secret",
"A key tells only the balance. The Step Plan's 5-hour, weekly and credit windows are told only to a StepFun sign-in: bring yours here once and magpie keeps it (for 30 days), used for nothing else.": "API Key 只能查餘額。Step Plan 的 5 小時、每週和積分額度僅對 StepFun 網頁登入開放:匯入一次登入,magpie 儲存 30 天,僅用於查詢額度。",
"Signed in · the Usage page shows the Step Plan": "已登入 · 用量頁會顯示 Step Plan 額度",
"Sign out": "退出登入",
@@ -10088,6 +10096,10 @@ const I18N = {
"optional · only for a team plan": "任意 · チームプランのみ",
"Only for a key on a team's GLM Coding Plan: both are in {p}'s console, under the team's organization and project. With them the Usage page shows the team's 5-hour and weekly windows.": "チームの GLM Coding Plan のキーの場合のみ必要です。どちらも {p} のコンソールで、チームの組織とプロジェクトの下にあります。入力すると、使用量ページにチームの 5 時間と週の利用枠が表示されます。",
"Team plan: give both the organization ID and the project ID": "チームプラン:組織 ID とプロジェクト ID の両方を入力してください",
"AccessKey ID": "AccessKey ID",
"Secret Access Key": "シークレットアクセスキー",
"The plan's 5-hour, weekly and monthly windows are told only to the account's access key (Volcengine console → API Access Keys), not to the plan's API key. Give it here for the Usage page to show them; it is used for nothing else.": "プランの 5 時間・週・月の利用枠は、アカウントのアクセスキー(Volcengine コンソール → API アクセスキー)にだけ返され、プランの API キーでは取得できません。ここに入力すると使用量ページに表示されます。それ以外には使いません。",
"Give the access key's Secret too": "アクセスキーのシークレットも入力してください",
"A key tells only the balance. The Step Plan's 5-hour, weekly and credit windows are told only to a StepFun sign-in: bring yours here once and magpie keeps it (for 30 days), used for nothing else.": "キーでわかるのは残高だけです。Step Plan の 5 時間・週・クレジットの利用枠は StepFun のサインインでのみ取得できます。一度ここに持ち込めば magpie が保存し(30 日間)、それ以外には使いません。",
"Signed in · the Usage page shows the Step Plan": "サインイン済み · 使用量ページに Step Plan が表示されます",
"Sign out": "サインアウト",
@@ -13932,6 +13944,10 @@ const I18N = {
"optional · only for a team plan": "optional · nur für einen Team-Plan",
"Only for a key on a team's GLM Coding Plan: both are in {p}'s console, under the team's organization and project. With them the Usage page shows the team's 5-hour and weekly windows.": "Nur für einen Schlüssel eines Team-GLM-Coding-Plans: Beide finden Sie in der Konsole von {p} unter Organisation und Projekt des Teams. Damit zeigt die Seite „Nutzung“ die 5-Stunden- und Wochen-Zeitfenster des Teams.",
"Team plan: give both the organization ID and the project ID": "Team-Plan: Geben Sie sowohl die Organisations-ID als auch die Projekt-ID an",
"AccessKey ID": "AccessKey ID",
"Secret Access Key": "Secret Access Key",
"The plan's 5-hour, weekly and monthly windows are told only to the account's access key (Volcengine console → API Access Keys), not to the plan's API key. Give it here for the Usage page to show them; it is used for nothing else.": "Die 5-Stunden-, Wochen- und Monats-Zeitfenster des Plans gibt Volcengine nur dem Zugriffsschlüssel des Kontos (Volcengine-Konsole → API-Zugriffsschlüssel), nicht dem API-Schlüssel des Plans. Geben Sie ihn hier an, damit die Seite „Nutzung“ sie zeigt; er wird für nichts anderes verwendet.",
"Give the access key's Secret too": "Geben Sie auch das Secret des Zugriffsschlüssels an",
"A key tells only the balance. The Step Plan's 5-hour, weekly and credit windows are told only to a StepFun sign-in: bring yours here once and magpie keeps it (for 30 days), used for nothing else.": "Ein Schlüssel liefert nur das Guthaben. Die 5-Stunden-, Wochen- und Credit-Zeitfenster des Step Plans gibt es nur mit einer StepFun-Anmeldung: Bringen Sie Ihre einmal hierher, magpie bewahrt sie (30 Tage) auf und nutzt sie für nichts anderes.",
"Signed in · the Usage page shows the Step Plan": "Angemeldet · die Seite „Nutzung“ zeigt den Step Plan",
"Sign out": "Abmelden",
@@ -0,0 +1,146 @@
package gui
// A Volcengine Ark provider's editor shows the account's control-plane
// AccessKey ID and whether a Secret is saved, never the Secret itself (#1427).
// A Save that leaves the Secret blank keeps the saved one, as a key's own
// Save does; one that doesn't name the access key keeps it; Remove
// (clearAccessKey) drops both.
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"github.com/yetone/magpie/internal/provider"
)
func TestProviderSaveKeepsVolcengineSecret(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)
post := func(body string) {
t.Helper()
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/provider/save", strings.NewReader(body)))
if w.Code != 200 {
t.Fatalf("%d %s", w.Code, w.Body)
}
}
v, err := provider.FromPreset("volcengine")
if err != nil {
t.Fatal(err)
}
v.Key = "ark-key"
v.AccessKeyID, v.SecretAccessKey = "AK-1", "SK-1"
if err := provider.Save(v); err != nil {
t.Fatal(err)
}
// the editor's own save: its form's fields, and the AccessKey ID it
// typed, with the Secret field left blank
base := `"id":"volcengine","from":"volcengine","name":"Volcengine Ark","preset":"volcengine","key":"","chat":"` +
v.Chat + `","responses":"` + v.Responses + `","anthropic":"` + v.Anthropic +
`","catalog":"volcengine","models":[],"headers":{},"searches":false,"pinUpstream":false,"unredacted":false,"contexts":{},"outputs":{},"compacts":{},"proxy":"","maxConcurrency":null,"queueLimit":0,"queueWait":0,"priceRate":null`
post(`{` + base + `,"accessKeyID":"AK-2"}`)
p, err := provider.Find("volcengine")
if err != nil {
t.Fatal(err)
}
if p.AccessKeyID != "AK-2" || p.SecretAccessKey != "SK-1" {
t.Errorf("blank Secret: ak=%q sk=%q, want AK-2/SK-1", p.AccessKeyID, p.SecretAccessKey)
}
// a typed Secret replaces the saved one
post(`{` + base + `,"accessKeyID":"AK-2","secretAccessKey":"SK-2"}`)
if p, _ = provider.Find("volcengine"); p.SecretAccessKey != "SK-2" {
t.Errorf("typed Secret: %q", p.SecretAccessKey)
}
// a save from elsewhere that doesn't name the access key keeps it
post(`{` + base + `}`)
if p, _ = provider.Find("volcengine"); p.AccessKeyID != "AK-2" || p.SecretAccessKey != "SK-2" {
t.Errorf("not named: ak=%q sk=%q", p.AccessKeyID, p.SecretAccessKey)
}
// the listing tells the editor the AccessKey ID and that a Secret is
// saved, and never the Secret
list := func() (string, map[string]*struct {
ID string `json:"id"`
SecretSet bool `json:"secretSet"`
}, map[string]bool) {
t.Helper()
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequest("GET", "/api/providers", nil))
if w.Code != 200 {
t.Fatalf("%d %s", w.Code, w.Body)
}
var got struct {
Providers []struct {
ID string `json:"id"`
AccessKey *struct {
ID string `json:"id"`
SecretSet bool `json:"secretSet"`
} `json:"accessKey"`
} `json:"providers"`
Presets []struct {
ID string `json:"id"`
AccessKey bool `json:"accessKey"`
} `json:"presets"`
}
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
t.Fatal(err)
}
ps := map[string]*struct {
ID string `json:"id"`
SecretSet bool `json:"secretSet"`
}{}
for _, x := range got.Providers {
ps[x.ID] = x.AccessKey
}
pre := map[string]bool{}
for _, x := range got.Presets {
pre[x.ID] = x.AccessKey
}
return w.Body.String(), ps, pre
}
body, ps, pre := list()
if strings.Contains(body, "SK-2") || strings.Contains(body, "secretAccessKey") {
t.Error("the listing told the Secret")
}
if a := ps["volcengine"]; a == nil || a.ID != "AK-2" || !a.SecretSet {
t.Errorf("provider json: %+v", a)
}
if !pre["volcengine"] || pre["deepseek"] {
t.Errorf("presets: %v", pre)
}
// Remove clears both, and the editor still asks for them
post(`{` + base + `,"accessKeyID":"","clearAccessKey":true}`)
if p, _ = provider.Find("volcengine"); p.AccessKeyID != "" || p.SecretAccessKey != "" || p.Key != "ark-key" {
t.Errorf("removed: %+v", p)
}
if _, ps, _ = list(); ps["volcengine"] == nil || ps["volcengine"].ID != "" || ps["volcengine"].SecretSet {
t.Errorf("removed, listed: %+v", ps["volcengine"])
}
// another vendor is asked for none
if err := provider.Save(provider.Provider{ID: "relay", Name: "Relay", Chat: "https://relay.example.com/v1", Key: "k"}); err != nil {
t.Fatal(err)
}
if _, ps, _ = list(); ps["relay"] != nil {
t.Errorf("relay: %+v", ps["relay"])
}
// an Ark provider added with its access key keeps it
post(`{"new":true,"preset":"volcengine","id":"volc-2","name":"Ark 2","key":"ark-2","chat":"` + v.Chat + `","accessKeyID":" AK-9 ","secretAccessKey":" SK-9 "}`)
if p, err = provider.Find("volc-2"); err != nil || p.AccessKeyID != "AK-9" || p.SecretAccessKey != "SK-9" {
t.Errorf("added: %+v %v", p, err)
}
}
+42 -2
View File
@@ -114,6 +114,10 @@ type providerJSON struct {
// a Zhipu or Z.ai key's team, for a team's GLM Coding Plan (#236):
// set, if empty, for those providers alone, which the editor asks it of
ZhipuTeam *provider.ZhipuTeam `json:"zhipuTeam,omitempty"`
// a Volcengine account's access key, which its plan's windows are
// read with (provider.TakesVolcAccessKey): whether the provider takes
// one, its ID, and whether a Secret is saved; never the Secret itself
AccessKey *accessKeyJSON `json:"accessKey,omitempty"`
// ModelTest is why its models can't each be sent a test request, ""
// when they can (provider.ModelTest): the editor says so on a chip's
// right-click rather than offer no menu
@@ -199,6 +203,13 @@ type moveJSON struct {
// stepPlanJSON: whether a StepFun provider's platform sign-in is kept, and
// where and how the user gets one
// accessKeyJSON is a provider's Volcengine access key as the editor sees
// it: the ID, and whether a Secret is saved, never the Secret.
type accessKeyJSON struct {
ID string `json:"id"`
SecretSet bool `json:"secretSet"`
}
type stepPlanJSON struct {
Site string `json:"site"`
SignedIn bool `json:"signedIn"`
@@ -293,6 +304,9 @@ type presetJSON struct {
// ZhipuTeam: a key of it may be on a team's GLM Coding Plan, whose
// organization and project the editor offers to take
ZhipuTeam bool `json:"zhipuTeam,omitempty"`
// AccessKey: a Volcengine Ark plan, whose windows are read with the
// account's access key, which the editor offers to take
AccessKey bool `json:"accessKey,omitempty"`
// a partner's tagline by language, and the languages it is listed in
Notes map[string]string `json:"notes,omitempty"`
Langs []string `json:"langs,omitempty"`
@@ -448,6 +462,9 @@ func providerInfo(p provider.Provider, agents []agentUse) providerJSON {
*out.ZhipuTeam = *p.ZhipuTeam
}
}
if provider.TakesVolcAccessKey(p) || p.AccessKeyID != "" || p.SecretAccessKey != "" {
out.AccessKey = &accessKeyJSON{ID: p.AccessKeyID, SecretSet: p.SecretAccessKey != ""}
}
if site := provider.StepFunSite(p); site != "" {
out.StepPlan = &stepPlanJSON{site, provider.StepFunSignedIn(site), provider.StepFunSignInURL(site), provider.StepFunBookmarklet()}
}
@@ -658,8 +675,9 @@ func providersState() providersJSON {
s.Presets = append(s.Presets, presetJSON{PresetDef: pa.PresetDef, Added: have[pa.ID], Notes: pa.Notes, Langs: pa.Langs, New: !have[pa.ID] && !provider.PartnerNoticed(pa.ID)})
}
for _, pr := range provider.Presets() {
team := provider.TakesZhipuTeam(provider.Provider{Chat: pr.Chat, Responses: pr.Responses, Anthropic: pr.Anthropic})
s.Presets = append(s.Presets, presetJSON{PresetDef: pr, Added: have[pr.ID], ZhipuTeam: team})
bases := provider.Provider{Chat: pr.Chat, Responses: pr.Responses, Anthropic: pr.Anthropic}
team := provider.TakesZhipuTeam(bases)
s.Presets = append(s.Presets, presetJSON{PresetDef: pr, Added: have[pr.ID], ZhipuTeam: team, AccessKey: provider.TakesVolcAccessKey(bases)})
}
cat := provider.Catalog()
s.Gateway = gatewayJSON{URL: gateway.URL(), Open: gateway.OpenToAnyone(), Models: len(cat), Calls: []gateway.Call{}, Groups: []gwGroupJSON{}}
@@ -864,6 +882,11 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
// ClearBalanceToken drops the saved balance token, which a
// blank one in the form otherwise keeps
ClearBalanceToken bool `json:"clearBalanceToken"`
// AccessKeyID is a Volcengine access key's ID, "" for none; a
// save that leaves it out keeps it. Its Secret (SecretAccessKey)
// is kept when sent blank, unless ClearAccessKey drops it.
AccessKeyID *string `json:"accessKeyID"`
ClearAccessKey bool `json:"clearAccessKey"`
// From is the id the provider had: another is a rename
From string `json:"from"`
// CopyOf, with New, is the provider the new one is a copy of
@@ -1013,6 +1036,7 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
if pr, err := provider.FromPreset(in.Preset); err == nil && in.Chat == "" && in.Responses == "" && in.Anthropic == "" && in.Gemini == "" {
pr.Key, pr.Models, pr.Fallback, pr.Headers, pr.BalanceToken, pr.Contexts = in.Key, in.Models, in.Fallback, in.Headers, in.BalanceToken, in.Contexts
pr.ZhipuTeam = in.ZhipuTeam
pr.SecretAccessKey = in.SecretAccessKey
pr.Searches = in.Searches
pr.PinUpstream = in.PinUpstream
pr.Unredacted = in.Unredacted
@@ -1079,6 +1103,10 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
in.Key, moreKeys = ks[0], ks[1:]
}
}
if req.AccessKeyID != nil {
in.AccessKeyID = strings.TrimSpace(*req.AccessKeyID)
}
in.SecretAccessKey = strings.TrimSpace(in.SecretAccessKey)
var old *provider.Provider
if req.New {
// a second one of a preset, or a name already in use, is
@@ -1147,6 +1175,14 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
if in.ZhipuTeam == nil && old != nil {
in.ZhipuTeam = old.ZhipuTeam
}
// a Volcengine access key likewise: its ID kept when left
// out, its Secret when sent blank, unless the form dropped it
if req.AccessKeyID == nil && old != nil {
in.AccessKeyID = old.AccessKeyID
}
if in.SecretAccessKey == "" && old != nil && !req.ClearAccessKey {
in.SecretAccessKey = old.SecretAccessKey
}
if in.Key == "" && old != nil {
in.Key = old.Key
}
@@ -1222,6 +1258,10 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
}
}
provider.ForgetBalances()
if old == nil || old.AccessKeyID != in.AccessKeyID || old.SecretAccessKey != in.SecretAccessKey {
// the plan's windows are read afresh with the new access key
provider.ForgetPlanQuotas()
}
// a new key means a new vendor list is worth a try; keep it short
if p, err := provider.Find(in.ID); err == nil && p.Ready() && (old == nil || old.Key != p.Key) {
ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second)
+17
View File
@@ -2180,3 +2180,20 @@ keys it matches, the routing header in the other language after
`setLocale`, the plugins listings arriving while the reader types. In
English, Chinese, Japanese and German, at 1100px and 440px. `MAGPIE_FILTER_ASSETS` points it
at another assets folder, to see it fail on the old code.
## Volcengine Ark access key
`volc-access-key.test.cjs` covers #1427: an Ark provider's editor (saved or
being added) asks for the account's AccessKey ID and Secret Access Key, which
the Usage page reads the Coding or Agent Plan's windows with. The saved Secret
is never in the page: only that one is saved, as the placeholder. Save posts
the ID and a Secret only when a new one was typed; Remove posts
`clearAccessKey`; an ID with no Secret is refused before anything is posted.
A relay and DeepSeek have neither field and post none. Every string is in
zh, zh-TW, ja and de. English and Chinese, Chromium and WebKit.
`TestProviderSaveKeepsVolcengineSecret` checks the server side.
```sh
node --test internal/gui/tests/volc-access-key.test.cjs
go test -tags nogui ./internal/gui -run TestProviderSaveKeepsVolcengineSecret
```
+182
View File
@@ -0,0 +1,182 @@
// Run with Node's test runner and Playwright on the module path; see README.md.
// A Volcengine Ark plan's windows are told only to the account's access key
// (#1427): the editor of an Ark provider, saved or being added, has
// AccessKey ID and Secret Access Key. The saved Secret is never shown, only
// that one is saved; Save posts the ID as typed and a Secret only when a new
// one was typed, Remove posts clearAccessKey, and an ID with no Secret is
// refused before anything is posted. Other providers have neither and post
// none. In English and Chinese, and every string in every language.
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 ark = {
id: "volcengine", name: "Volcengine Ark", icon: "volcengine-color", preset: "volcengine", chat: "https://ark.cn-beijing.volces.com/api/coding/v3", responses: "https://ark.cn-beijing.volces.com/api/coding/v3", anthropic: "https://ark.cn-beijing.volces.com/api/coding", catalog: "",
models: [{ id: "ark-code-latest", name: "ark-code-latest", on: true }], agents: [], fallback: [], headers: {},
key: { set: true, masked: "…ab12" }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "",
accessKey: { id: "AKLTsaved", secretSet: true },
};
const relay = {
id: "relay", name: "Relay", icon: "generic", chat: "https://relay.example.com/v1", responses: "", anthropic: "", catalog: "",
models: [{ id: "model-a", name: "Model A", on: true }], agents: [], fallback: [], headers: {},
key: { set: true, masked: "sk-…one" }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "",
};
const presets = [
{ id: "volcengine", name: "Volcengine Ark", icon: "volcengine-color", kind: "vendor", chat: "https://ark.cn-beijing.volces.com/api/coding/v3", added: true, accessKey: true,
regionLabel: "Plan", regions: [{ id: "coding", name: "Coding Plan", chat: "https://ark.cn-beijing.volces.com/api/coding/v3" }, { id: "agent", name: "Agent Plan", chat: "https://ark.cn-beijing.volces.com/api/plan/v3" }] },
{ id: "deepseek", name: "DeepSeek", icon: "deepseek", kind: "vendor", chat: "https://api.deepseek.com/v1", added: false },
];
function serve(lang, posts, fresh) {
// fresh: Ark not added yet, so its tile adds a new one
const providers = fresh
? { providers: [relay], presets: presets.map((x) => ({ ...x, added: false })), excluded: [], gateway: { running: true, window: true } }
: { providers: [ark, relay], 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)];
try { await route.fulfill({ body: await fs.readFile(file), contentType }); } catch { await route.fulfill({ status: 404, body: "" }); }
};
}
const strings = [
"AccessKey ID", "Secret Access Key", "saved · paste a new one to replace it", "Remove",
"The plan's 5-hour, weekly and monthly windows are told only to the account's access key (Volcengine console → API Access Keys), not to the plan's API key. Give it here for the Usage page to show them; it is used for nothing else.",
"Give the access key's Secret too",
];
const words = {
en: { id: "AccessKey ID", secret: "Secret Access Key", saved: "saved · paste a new one to replace it", remove: "Remove", save: "Save", add: "Add", cancel: "Cancel", one: "Give the access key's Secret too" },
zh: { id: "AccessKey ID", secret: "Secret Access Key", saved: "已保存 · 粘贴新的即可替换", remove: "移除", save: "保存", add: "添加", cancel: "取消", one: "请同时填写访问密钥的 Secret" },
};
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
for (const lang of ["en", "zh"]) {
const w = words[lang];
const start = async (t, name, fresh = false) => {
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
t.after(async () => {
if (process.env.ARTIFACT_DIR) {
await fs.mkdir(process.env.ARTIFACT_DIR, { recursive: true });
await page.screenshot({ path: path.join(process.env.ARTIFACT_DIR, `${engine}-${lang}-${name}-volc-access-key.png`) });
}
await browser.close();
});
const page = await (await browser.newContext({ viewport: { width: 900, height: 560 }, reducedMotion: "reduce" })).newPage();
page.setDefaultTimeout(5000);
const errors = [];
page.on("pageerror", (e) => errors.push(e.message));
const posts = [];
await page.route("**/*", serve(lang, posts, fresh));
await page.goto("http://magpie.test/?view=providers");
return { page, errors, posts };
};
const edit = async (page, name) => {
await page.locator(".row.provider", { hasText: name }).click();
await page.locator(".editor .proxy-mode").waitFor();
};
const ak = (page) => page.locator(".editor .volc-ak");
const sk = (page) => page.locator(".editor .volc-sk");
const press = async (page, posts, label) => {
const n = posts.length;
const b = page.locator(".editor .bar").getByRole("button", { name: label, exact: true });
await b.scrollIntoViewIfNeeded();
await b.click();
for (let i = 0; i < 50 && posts.length === n; i++) await page.waitForTimeout(50);
return posts.length > n ? posts.at(-1) : null;
};
test(`${engine} ${lang}: an Ark provider's access key is shown, kept, replaced and removed`, async (t) => {
const { page, errors, posts } = await start(t, "saved");
await edit(page, "Volcengine Ark");
const labels = await page.locator(".editor label").allTextContents();
assert(labels.includes(w.id) && labels.includes(w.secret), labels.join(" | "));
assert.equal(await ak(page).inputValue(), "AKLTsaved", "the ID is shown");
assert.equal(await sk(page).inputValue(), "", "the saved Secret is not");
assert.equal(await sk(page).getAttribute("type"), "password");
assert.equal(await sk(page).getAttribute("placeholder"), w.saved);
// left as it is: the ID posted, no Secret, nothing cleared
let saved = await press(page, posts, w.save);
assert.equal(saved.action, "save");
assert.equal(saved.body.accessKeyID, "AKLTsaved");
assert(!("secretAccessKey" in saved.body) && !("clearAccessKey" in saved.body), JSON.stringify(saved.body));
// a new Secret, trimmed
await edit(page, "Volcengine Ark");
await sk(page).fill(" new-secret ");
saved = await press(page, posts, w.save);
assert.equal(saved.body.secretAccessKey, "new-secret");
assert(!("clearAccessKey" in saved.body));
// Remove clears both
await edit(page, "Volcengine Ark");
await page.locator(".editor").getByRole("button", { name: w.remove, exact: true }).first().click();
assert.equal(await ak(page).inputValue(), "");
assert.notEqual(await sk(page).getAttribute("placeholder"), w.saved);
saved = await press(page, posts, w.save);
assert.equal(saved.body.accessKeyID, "");
assert.equal(saved.body.clearAccessKey, true);
assert(!("secretAccessKey" in saved.body));
const missing = await page.evaluate((keys) => Object.fromEntries(["zh", "zh-TW", "ja", "de"].map((l) => [l, keys.filter((k) => !I18N[l][k])])), strings);
assert.deepEqual(missing, { zh: [], "zh-TW": [], ja: [], de: [] }, "every string in every language");
const border = await page.evaluate(() => [...document.querySelectorAll(".editor, .editor *")].map((e) => getComputedStyle(e).borderLeftWidth).filter((b) => parseFloat(b) > 1));
assert.deepEqual(border, [], "no border stripes");
assert.deepEqual(errors, []);
});
test(`${engine} ${lang}: another provider has no access key fields and posts none`, async (t) => {
const { page, errors, posts } = await start(t, "relay");
await edit(page, "Relay");
assert.equal(await ak(page).count(), 0);
assert.equal(await sk(page).count(), 0);
const saved = await press(page, posts, w.save);
assert.equal(saved.body.id, "relay");
assert(!("accessKeyID" in saved.body) && !("secretAccessKey" in saved.body) && !("clearAccessKey" in saved.body));
assert.deepEqual(errors, []);
});
test(`${engine} ${lang}: Ark being added takes an access key, DeepSeek doesn't, an ID alone is refused`, async (t) => {
const { page, errors, posts } = await start(t, "add", true);
await page.locator("#addProvider").click();
const sheet = page.locator("#addSheet");
await sheet.locator('.tile[data-pick="DeepSeek"]').click();
await page.locator(".editor.new").waitFor();
assert.equal(await ak(page).count(), 0, "DeepSeek has none");
await page.locator(".editor .bar").getByRole("button", { name: w.cancel, exact: true }).click();
await page.locator(".editor").waitFor({ state: "detached" });
await sheet.locator('.tile[data-pick="Volcengine Ark"]').click();
await ak(page).waitFor();
assert.equal(await sk(page).inputValue(), "");
assert.notEqual(await sk(page).getAttribute("placeholder"), w.saved, "nothing is saved yet");
await page.locator(".editor.new input[type=password]").first().fill("ark-key");
await ak(page).fill(" AKLTnew ");
assert.equal(await press(page, posts, w.add), null, "an ID with no Secret posts nothing");
assert.equal(await page.locator(".editor .editor-error").textContent(), w.one);
await sk(page).fill("sk-new");
const saved = await press(page, posts, w.add);
assert.equal(saved.body.new, true);
assert.equal(saved.body.preset, "volcengine");
assert.equal(saved.body.accessKeyID, "AKLTnew");
assert.equal(saved.body.secretAccessKey, "sk-new");
assert.deepEqual(errors, []);
});
}
}
+6
View File
@@ -44,6 +44,9 @@ func Restore(ps []Provider) (added, replaced int, err error) {
if p.BalanceToken == "" {
p.BalanceToken = f.Providers[i].BalanceToken
}
if p.AccessKeyID == "" && p.SecretAccessKey == "" {
p.AccessKeyID, p.SecretAccessKey = f.Providers[i].AccessKeyID, f.Providers[i].SecretAccessKey
}
}
f.Providers[i] = p
replaced++
@@ -108,6 +111,9 @@ func Mirror(ps []Provider, gs []Group) error {
if p.BalanceToken == "" {
p.BalanceToken = h.BalanceToken
}
if p.AccessKeyID == "" && p.SecretAccessKey == "" {
p.AccessKeyID, p.SecretAccessKey = h.AccessKeyID, h.SecretAccessKey
}
}
out = append(out, p)
}
+7 -1
View File
@@ -8,6 +8,8 @@ import (
// Restoring and syncing a keyless provider keep this machine's balance
// token. A token supplied explicitly, or keys supplied with none, replaces it.
// A Volcengine access key (#1427) is kept the same way, the ID and Secret
// together.
func TestBackupBalanceToken(t *testing.T) {
for _, op := range []struct {
name string
@@ -39,7 +41,8 @@ func TestBackupBalanceToken(t *testing.T) {
t.Setenv("PATH", h)
here := Provider{ID: "relay", Name: "Relay old", Chat: "https://old.example.com/v1",
Key: "sk-here", KeyName: "main", KeyProtocol: Chat,
Keys: []KeyAccount{{Name: "spare", Key: "sk-spare", Protocol: Anthropic}}, BalanceToken: "balance-here"}
Keys: []KeyAccount{{Name: "spare", Key: "sk-spare", Protocol: Anthropic}}, BalanceToken: "balance-here",
AccessKeyID: "AK-here", SecretAccessKey: "SK-here"}
if err := Save(here); err != nil {
t.Fatal(err)
}
@@ -60,6 +63,9 @@ func TestBackupBalanceToken(t *testing.T) {
if p.Key == "" && len(p.Keys) == 0 {
wantKeys = here
}
if got.AccessKeyID != wantKeys.AccessKeyID || got.SecretAccessKey != wantKeys.SecretAccessKey {
t.Fatalf("access key: %q %q, want %q %q", got.AccessKeyID, got.SecretAccessKey, wantKeys.AccessKeyID, wantKeys.SecretAccessKey)
}
if got.Key != wantKeys.Key || got.KeyName != wantKeys.KeyName || got.KeyProtocol != wantKeys.KeyProtocol || !slices.Equal(got.Keys, wantKeys.Keys) {
t.Fatalf("keys: %+v, want %+v", got, wantKeys)
}
+3 -3
View File
@@ -7,7 +7,7 @@ import (
)
// A copy of a provider (#268) is added beside it with its keys, balance
// token and routing, the same key on the same host being what was asked
// token, Volcengine access key (#1427) and routing, the same key on the same host being what was asked
// for; a key pasted in the form is the copy's own, and a signed-in
// account has no copy.
func TestAddCopy(t *testing.T) {
@@ -18,7 +18,7 @@ func TestAddCopy(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
src := Provider{ID: "relay", Name: "Relay", Chat: "https://api.relay.example/v1", Key: "sk-1", KeyName: "main",
Keys: []KeyAccount{{Name: "spare", Key: "sk-2"}}, Routing: "rotate", BalanceToken: "tok",
Keys: []KeyAccount{{Name: "spare", Key: "sk-2"}}, Routing: "rotate", BalanceToken: "tok", AccessKeyID: "AK-1", SecretAccessKey: "SK-1",
Headers: map[string]string{"X-Org": "acme"}, Fallback: []string{"other/m"},
BalanceURL: "https://api.relay.example/q?key={key}", BalancePath: "balance"}
if err := Save(src); err != nil {
@@ -43,7 +43,7 @@ func TestAddCopy(t *testing.T) {
t.Fatal(err)
}
if id != "relay-copy" || c.Name != "Relay copy" || c.Key != "sk-1" || c.KeyName != "main" || len(c.Keys) != 1 || c.Keys[0].Key != "sk-2" ||
c.Routing != "rotate" || c.BalanceToken != "tok" || !slices.Equal(c.Fallback, src.Fallback) || c.BalanceURL != src.BalanceURL {
c.Routing != "rotate" || c.BalanceToken != "tok" || c.AccessKeyID != "AK-1" || c.SecretAccessKey != "SK-1" || !slices.Equal(c.Fallback, src.Fallback) || c.BalanceURL != src.BalanceURL {
t.Fatalf("copy: %+v", c)
}
// again, under the next free id and name, with a key of its own
+11 -3
View File
@@ -2,10 +2,11 @@ package provider
// A plan bought with an API key — Zhipu's GLM Coding Plan (and Z.ai's),
// Kimi Code, OpenCode Go, a Command Code plan, MiniMax's Coding (Token)
// Plan and StepFun's Step Plan —
// Plan, StepFun's Step Plan and Volcengine Ark's Coding and Agent Plans —
// has windows of allowance like a subscription's, which the vendor tells
// to the key (StepFun only to a sign-in, stepfun_plan.go): the Usage page
// shows them beside the subscriptions'.
// to the key (StepFun only to a sign-in, stepfun_plan.go; Volcengine only
// to the account's access key, volcengine_usage.go): the Usage page shows
// them beside the subscriptions'.
import (
"context"
@@ -489,6 +490,10 @@ var planQuotaCache struct {
data []SubscriptionQuota
}
// ForgetPlanQuotas has the next PlanQuotas ask again, after what a plan's
// windows are read with changed (a Volcengine access key).
func ForgetPlanQuotas() { forgetPlanQuotas() }
// PlanQuotas is the windows of every plan magpie has a key for, each key
// on a card of its own when a provider has several. What was asked less
// than a minute ago is not asked again.
@@ -581,6 +586,8 @@ func PlanQuotas(ctx context.Context) []SubscriptionQuota {
}
stepfun := make(chan []SubscriptionQuota, 1)
go func() { stepfun <- stepPlanQuotas(ctx) }()
volc := make(chan []SubscriptionQuota, 1)
go func() { volc <- volcPlanQuotas(ctx) }()
wg.Wait()
out := []SubscriptionQuota{}
for i, q := range got {
@@ -591,6 +598,7 @@ func PlanQuotas(ctx context.Context) []SubscriptionQuota {
}
}
out = append(out, <-stepfun...)
out = append(out, <-volc...)
if ctx.Err() == nil {
noteQuotaHistory(out, time.Now())
c.Lock()
+11
View File
@@ -51,6 +51,14 @@ type Provider struct {
Preset string `json:"preset,omitempty"` // preset this was created from, if any
Key string `json:"key"` // API key, as typed by the user
// AccessKeyID and SecretAccessKey are a Volcengine account's access
// key (TakesVolcAccessKey), what Ark tells its Coding or Agent Plan's
// windows to (volcengine_usage.go); not the plan's inference key in
// Key. They are kept, backed up and synced as the keys are: the Secret
// is never sent to the GUI, and a backup without keys has neither.
AccessKeyID string `json:"accessKeyID,omitempty"`
SecretAccessKey string `json:"secretAccessKey,omitempty"`
// KeyName names the key in use, and Keys are the provider's other
// accounts: keys saved to switch to (see keys.go).
KeyName string `json:"keyName,omitempty"`
@@ -677,6 +685,9 @@ func AddCopy(p Provider, from string) (string, error) {
if p.BalanceToken == "" {
p.BalanceToken = src.BalanceToken
}
if p.AccessKeyID == "" && p.SecretAccessKey == "" {
p.AccessKeyID, p.SecretAccessKey = src.AccessKeyID, src.SecretAccessKey
}
if p.ZhipuTeam == nil {
p.ZhipuTeam = src.ZhipuTeam
}
+402
View File
@@ -0,0 +1,402 @@
package provider
// Volcengine Ark's Coding Plan and Agent Plan (#1427, yayoinoyume) have
// 5-hour, weekly and monthly windows, which Ark tells only to the
// account's control plane: GetCodingPlanUsage and GetAFPUsage on
// open.volcengineapi.com, signed with the account's AccessKey ID and
// Secret (AccessKeyID, SecretAccessKey), never to the plan's inference
// key. The plan a provider is on is its endpoint's: /api/coding is the
// Coding Plan's, /api/plan the Agent Plan's; pay-as-you-go (/api/v3) has
// no windows and no card.
//
// The request is signed as Volcengine's own SDK signs it
// (volc-sdk-golang base/sign.go GetSignRequest, the signer of
// volcengine-go-sdk's volcenginequery): HMAC-SHA256 over the canonical
// request with the signed headers sorted, the scope
// date/region/ark/request, and a key derived from the bare Secret.
// TestVolcSignMatchesSDK pins a signature that SDK made.
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
)
const (
volcOpenAPIHost = "open.volcengineapi.com"
volcAPIVersion = "2024-01-01"
volcDefaultRegion = "cn-beijing"
volcService = "ark"
volcContentType = "application/json"
volcAKSKHint = "check the AccessKey ID and Secret in the provider's editor, and that the access key may query Ark (IAM)"
)
// TakesVolcAccessKey says p is on Volcengine Ark (ark.<region>.volces.com),
// whose editor then asks for the account's AccessKey ID and Secret.
func TakesVolcAccessKey(p Provider) bool {
if p.Account != nil {
return false
}
for _, base := range []string{p.Chat, p.Responses, p.Anthropic} {
if h := hostOf(base); strings.HasPrefix(h, "ark.") && strings.HasSuffix(h, ".volces.com") {
return true
}
}
return false
}
// volcPlanOf is the plan p's endpoint is on: the action that tells its
// windows, the plan's name and the region it is in; ok false for
// pay-as-you-go or another vendor.
func volcPlanOf(p Provider) (action, plan, region string, ok bool) {
if !TakesVolcAccessKey(p) {
return "", "", "", false
}
for _, base := range []string{p.Chat, p.Anthropic, p.Responses} {
u, err := url.Parse(base)
if err != nil || !strings.HasSuffix(strings.ToLower(u.Host), ".volces.com") {
continue
}
switch path := strings.TrimSuffix(u.Path, "/") + "/"; {
case strings.HasPrefix(path, "/api/coding/"):
return "GetCodingPlanUsage", "Coding Plan", volcRegion(u.Host), true
case strings.HasPrefix(path, "/api/plan/"):
return "GetAFPUsage", "Agent Plan", volcRegion(u.Host), true
}
}
return "", "", "", false
}
// volcRegion is the region of an Ark host: ark.cn-beijing.volces.com is
// cn-beijing; cn-beijing when it names none.
func volcRegion(host string) string {
labels := strings.Split(strings.ToLower(host), ".")
if len(labels) == 4 && labels[0] == "ark" && labels[1] != "" {
return labels[1]
}
return volcDefaultRegion
}
// volcPlanQuotas is a card for each Volcengine Ark plan a provider in use
// is on and has the account's AccessKey ID and Secret for: one for each
// access key and plan, named for the first such provider.
func volcPlanQuotas(ctx context.Context) []SubscriptionQuota {
type job struct {
p Provider
action, plan, region string
}
seen := map[string]bool{}
var jobs []job
for _, p := range All() {
if p.Hidden || p.Off || p.AccessKeyID == "" || p.SecretAccessKey == "" {
continue
}
action, plan, region, ok := volcPlanOf(p)
if !ok || seen[p.AccessKeyID+" "+action] || !wantsCard(ctx, p.ID, "") {
continue
}
seen[p.AccessKeyID+" "+action] = true
jobs = append(jobs, job{p, action, plan, region})
}
out := make([]SubscriptionQuota, len(jobs))
var wg sync.WaitGroup
for i, j := range jobs {
wg.Add(1)
go func() {
defer wg.Done()
out[i] = volcPlanQuota(j.p.Via(ctx), j.p, j.action, j.plan, j.region)
// a failed read shows what was last read, as a key's plan does
out[i] = keepReading(ctx, out[i], keyTag("volc "+j.action, j.p.AccessKeyID))
}()
}
wg.Wait()
return out
}
// volcPlanQuota is p's plan as a card, read with its access key.
func volcPlanQuota(ctx context.Context, p Provider, action, plan, region string) SubscriptionQuota {
q := SubscriptionQuota{Provider: p.ID, Name: p.Name, Icon: p.Icon, Plan: plan, Windows: []QuotaWindow{}}
raw, err := volcOpenAPICall(ctx, p.AccessKeyID, p.SecretAccessKey, region, action, time.Now())
if err != nil {
q.Error = err.Error()
return q
}
var env struct {
Result json.RawMessage `json:"Result"`
}
_ = json.Unmarshal(raw, &env)
var ws []QuotaWindow
if action == "GetAFPUsage" {
var tier string
ws, tier = volcReadAFP(env.Result)
if tier != "" {
q.Plan = plan + " " + tier
}
} else {
ws = volcReadCodingPlan(env.Result)
}
if len(ws) == 0 {
q.Error = fmt.Sprintf("this Volcengine account has no %s, or Ark answered %s in a form magpie doesn't know: %s", plan, action, volcHead(raw))
return q
}
q.Windows = ws
return q
}
// volcHead is the head of a reply, for a card to say what was answered.
func volcHead(raw []byte) string {
s := strings.TrimSpace(string(raw))
if len(s) > 300 {
s = s[:300] + "…"
}
return s
}
// volcSign is the Authorization header of a POST to the control plane's
// "/" with query and body, at now, as volc-sdk-golang's GetSignRequest
// makes it for the headers volcOpenAPICall sends: Content-Type, Host,
// X-Content-Sha256 and X-Date, signed in that (sorted) order.
func volcSign(ak, sk, region string, query url.Values, body []byte, now time.Time) (auth, xDate, contentSHA string) {
xDate = now.UTC().Format("20060102T150405Z")
date := xDate[:8]
contentSHA = volcHex(body)
const signed = "content-type;host;x-content-sha256;x-date"
canonical := strings.Join([]string{
http.MethodPost,
"/",
volcQuery(query),
"content-type:" + volcContentType + "\n" +
"host:" + volcOpenAPIHost + "\n" +
"x-content-sha256:" + contentSHA + "\n" +
"x-date:" + xDate + "\n",
signed,
contentSHA,
}, "\n")
scope := date + "/" + region + "/" + volcService + "/request"
toSign := strings.Join([]string{"HMAC-SHA256", xDate, scope, volcHex([]byte(canonical))}, "\n")
key := volcMAC([]byte(sk), date)
for _, s := range []string{region, volcService, "request"} {
key = volcMAC(key, s)
}
sig := hex.EncodeToString(volcMAC(key, toSign))
return "HMAC-SHA256 Credential=" + ak + "/" + scope + ", SignedHeaders=" + signed + ", Signature=" + sig, xDate, contentSHA
}
// volcQuery is a query as the SDK signs and sends it: sorted by key,
// percent-encoded, a space as %20 (its normquery).
func volcQuery(v url.Values) string {
return strings.ReplaceAll(v.Encode(), "+", "%20")
}
func volcMAC(key []byte, s string) []byte {
m := hmac.New(sha256.New, key)
m.Write([]byte(s))
return m.Sum(nil)
}
func volcHex(b []byte) string {
sum := sha256.Sum256(b)
return hex.EncodeToString(sum[:])
}
// volcOpenAPICall asks the control plane's action, signed with the access
// key ak and its Secret sk, and gives the reply's body. The access key is
// sent nowhere but open.volcengineapi.com.
func volcOpenAPICall(ctx context.Context, ak, sk, region, action string, now time.Time) ([]byte, error) {
query := url.Values{"Action": {action}, "Version": {volcAPIVersion}}
body := []byte("{}")
auth, xDate, contentSHA := volcSign(ak, sk, region, query, body, now)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://"+volcOpenAPIHost+"/?"+volcQuery(query), strings.NewReader(string(body)))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", volcContentType)
req.Header.Set("X-Date", xDate)
req.Header.Set("X-Content-Sha256", contentSHA)
req.Header.Set("Authorization", auth)
req.Header.Set("Accept", "application/json")
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
raw, err := io.ReadAll(io.LimitReader(res.Body, 1<<20))
if err != nil {
return nil, err
}
var env struct {
ResponseMetadata struct {
Error *struct{ Code, Message string } `json:"Error"`
} `json:"ResponseMetadata"`
}
_ = json.Unmarshal(raw, &env)
if e := env.ResponseMetadata.Error; e != nil && (e.Code != "" || e.Message != "") {
msg := fmt.Sprintf("Volcengine %s: %s %s", action, e.Code, e.Message)
if volcRefusesKey(e.Code) || res.StatusCode == http.StatusUnauthorized || res.StatusCode == http.StatusForbidden {
msg += "; " + volcAKSKHint
}
return nil, fmt.Errorf("%s", msg)
}
switch {
case res.StatusCode == http.StatusUnauthorized || res.StatusCode == http.StatusForbidden:
return nil, fmt.Errorf("Volcengine %s: %s; %s", action, res.Status, volcAKSKHint)
case res.StatusCode >= 300:
return nil, fmt.Errorf("Volcengine %s: %s: %s", action, res.Status, volcHead(raw))
}
return raw, nil
}
// volcRefusesKey says a control-plane error code is about the access key
// or its rights (InvalidAccessKey, SignatureDoesNotMatch, AccessDenied…),
// not the plan.
func volcRefusesKey(code string) bool {
c := strings.ToLower(code)
for _, w := range []string{"accesskey", "signature", "accessdenied", "unauthorized", "forbidden", "credential", "authfailure"} {
if strings.Contains(c, w) {
return true
}
}
return false
}
// volcReadCodingPlan reads GetCodingPlanUsage's Result:
//
// {"QuotaUsage":[{"Level":"session","Percent":10.5,"ResetTimestamp":1758100000},
// {"Level":"weekly",…},{"Level":"monthly",…}]}
//
// Percent is the share used; ResetTimestamp is in seconds.
func volcReadCodingPlan(result json.RawMessage) []QuotaWindow {
var r struct {
QuotaUsage []struct {
Level string `json:"Level"`
Percent any `json:"Percent"`
ResetTimestamp any `json:"ResetTimestamp"`
} `json:"QuotaUsage"`
}
if json.Unmarshal(result, &r) != nil {
return nil
}
var out []QuotaWindow
for _, u := range r.QuotaUsage {
w, ok := volcWindow(u.Level)
if !ok {
continue
}
used, ok := volcNum(u.Percent)
if !ok {
continue
}
w.Used, w.ResetsAt = used, volcTime(u.ResetTimestamp)
out = append(out, w)
}
return out
}
// volcReadAFP reads GetAFPUsage's Result: AFPFiveHour, AFPWeekly and
// AFPMonthly (AFPDaily isn't shown by Ark's own console either), each
// with what was used of its quota and when it resets, and the plan's
// Tier. What each bucket carries is from tools built on it, not from a
// reply seen here: Used of Quota (lordqyxz/dsh-ark-quota), Used of Total
// or Percent (arkcli's struct tags, HaydenSmith1121/dsh-ark-plans), and a
// reset in ResetTime or ResetTimestamp, seconds or milliseconds.
func volcReadAFP(result json.RawMessage) ([]QuotaWindow, string) {
type bucket struct {
Used, Quota, Total, Percent, ResetTime, ResetTimestamp any
}
var r struct {
Tier string `json:"Tier"`
AFPFiveHour *bucket `json:"AFPFiveHour"`
AFPWeekly *bucket `json:"AFPWeekly"`
AFPMonthly *bucket `json:"AFPMonthly"`
}
if json.Unmarshal(result, &r) != nil {
return nil, ""
}
var out []QuotaWindow
for _, b := range []struct {
level string
b *bucket
}{{"session", r.AFPFiveHour}, {"weekly", r.AFPWeekly}, {"monthly", r.AFPMonthly}} {
if b.b == nil {
continue
}
w, _ := volcWindow(b.level)
used, ok := volcNum(b.b.Percent)
if !ok {
n, nok := volcNum(b.b.Used)
of, ook := volcNum(b.b.Quota)
if !ook {
of, ook = volcNum(b.b.Total)
}
if !nok || !ook || of <= 0 {
continue // no quota: not on this plan
}
used = n / of * 100
w.Amount, w.Limit = n, of
}
w.Used = used
if w.ResetsAt = volcTime(b.b.ResetTime); w.ResetsAt == nil {
w.ResetsAt = volcTime(b.b.ResetTimestamp)
}
out = append(out, w)
}
return out, strings.TrimSpace(r.Tier)
}
// volcWindow is the window a level names, as other plans' are named.
func volcWindow(level string) (QuotaWindow, bool) {
switch strings.ToLower(strings.TrimSpace(level)) {
case "session":
return QuotaWindow{Name: "5 hours", Span: 5 * time.Hour}, true
case "weekly":
return QuotaWindow{Name: "Weekly", Span: 7 * 24 * time.Hour}, true
case "monthly":
return QuotaWindow{Name: "Month", Span: 30 * 24 * time.Hour}, true
}
return QuotaWindow{}, false
}
// volcNum is a JSON number, or a string of one.
func volcNum(v any) (float64, bool) {
switch x := v.(type) {
case float64:
return x, true
case string:
f, err := strconv.ParseFloat(strings.TrimSpace(x), 64)
return f, err == nil
}
return 0, false
}
// volcTime is a reset as Ark gives it: epoch seconds (Coding Plan),
// milliseconds (Agent Plan) or RFC 3339; nil for none.
func volcTime(v any) *time.Time {
if s, ok := v.(string); ok {
if t, err := time.Parse(time.RFC3339, strings.TrimSpace(s)); err == nil {
return &t
}
}
n, ok := volcNum(v)
if !ok || n <= 0 {
return nil
}
// 1e11 seconds is the year 5138, 1e11 ms 1973: no reset is on the
// wrong side of it
var t time.Time
if n > 1e11 {
t = time.UnixMilli(int64(n))
} else {
t = time.Unix(int64(n), 0)
}
return &t
}
+210
View File
@@ -0,0 +1,210 @@
package provider
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"net/url"
"path/filepath"
"strings"
"sync"
"testing"
"time"
"github.com/yetone/magpie/internal/agentenv"
)
// The signature is the one Volcengine's own SDK makes: these were made by
// volc-sdk-golang (06f9ef66) base.GetSignRequest for a POST to
// open.volcengineapi.com/ with Action and Version in the query, body {},
// Content-Type application/json, service ark, at 2026-10-09T08:30:15Z.
func TestVolcSignMatchesSDK(t *testing.T) {
now := time.Date(2026, 10, 9, 8, 30, 15, 0, time.UTC)
for _, c := range []struct{ region, action, sig string }{
{"cn-beijing", "GetCodingPlanUsage", "deb80c0cd8bd77768ca40f6d47c7204621c0994428f6ab77e23b76e15dc4c047"},
{"cn-shanghai", "GetAFPUsage", "8a241be0996c93de4dfcd9e8b1db37494bf63170804fcaebe8380ff7dca2bb23"},
} {
auth, xDate, sha := volcSign("AKLTexample", "c2VjcmV0LWV4YW1wbGU=", c.region,
url.Values{"Action": {c.action}, "Version": {"2024-01-01"}}, []byte("{}"), now)
want := "HMAC-SHA256 Credential=AKLTexample/20261009/" + c.region + "/ark/request, SignedHeaders=content-type;host;x-content-sha256;x-date, Signature=" + c.sig
if auth != want {
t.Errorf("%s:\n got %s\nwant %s", c.action, auth, want)
}
if xDate != "20261009T083015Z" || sha != "44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a" {
t.Errorf("%s: X-Date %s, X-Content-Sha256 %s", c.action, xDate, sha)
}
}
// a time in another zone signs as the same instant in UTC
cst := time.Date(2026, 10, 9, 16, 30, 15, 0, time.FixedZone("CST", 8*3600))
if _, xDate, _ := volcSign("a", "b", "cn-beijing", url.Values{}, nil, cst); xDate != "20261009T083015Z" {
t.Errorf("X-Date in CST: %s", xDate)
}
}
// The plan is the endpoint's: /api/coding the Coding Plan's, /api/plan the
// Agent Plan's, in the host's region; pay-as-you-go, another vendor and an
// account have none.
func TestVolcPlanOf(t *testing.T) {
for _, c := range []struct {
p Provider
action, plan, region string
}{
{Provider{Chat: "https://ark.cn-beijing.volces.com/api/coding/v3"}, "GetCodingPlanUsage", "Coding Plan", "cn-beijing"},
{Provider{Anthropic: "https://ark.cn-beijing.volces.com/api/coding"}, "GetCodingPlanUsage", "Coding Plan", "cn-beijing"},
{Provider{Chat: "https://ark.cn-shanghai.volces.com/api/plan/v3"}, "GetAFPUsage", "Agent Plan", "cn-shanghai"},
{Provider{Chat: "https://ark.ap-southeast.volces.com/api/plan"}, "GetAFPUsage", "Agent Plan", "ap-southeast"},
{Provider{Chat: "https://ark.cn-beijing.volces.com/api/v3"}, "", "", ""},
{Provider{Chat: "https://relay.example.com/api/coding/v3"}, "", "", ""},
{Provider{Chat: "https://ark.cn-beijing.volces.com/api/coding/v3", Account: &Account{}}, "", "", ""},
} {
action, plan, region, ok := volcPlanOf(c.p)
if action != c.action || plan != c.plan || region != c.region || ok != (c.action != "") {
t.Errorf("%+v: %s %s %s %v", c.p, action, plan, region, ok)
}
}
if !TakesVolcAccessKey(Provider{Chat: "https://ark.cn-beijing.volces.com/api/v3"}) || TakesVolcAccessKey(Provider{Chat: "https://api.deepseek.com/v1"}) {
t.Error("TakesVolcAccessKey")
}
}
// GetCodingPlanUsage as pi-ark-usage's fixture has it: Percent used,
// ResetTimestamp in seconds; an unknown level is left out.
func TestVolcReadCodingPlan(t *testing.T) {
ws := volcReadCodingPlan(json.RawMessage(`{"Status":"ok","UpdateTimestamp":1758000000,"QuotaUsage":[
{"Level":"session","Percent":10.5,"ResetTimestamp":1758100000},
{"Level":"weekly","Percent":20.25,"ResetTimestamp":1758200000},
{"Level":"monthly","Percent":"30.75","ResetTimestamp":1758300000},
{"Level":"daily","Percent":1}]}`))
if len(ws) != 3 || ws[0].Name != "5 hours" || ws[0].Used != 10.5 || ws[0].Span != 5*time.Hour || ws[0].ResetsAt == nil || ws[0].ResetsAt.Unix() != 1758100000 ||
ws[1].Name != "Weekly" || ws[1].Used != 20.25 || ws[2].Name != "Month" || ws[2].Used != 30.75 || ws[2].ResetsAt.Unix() != 1758300000 {
t.Fatalf("%+v", ws)
}
if ws := volcReadCodingPlan(json.RawMessage(`{"QuotaUsage":[]}`)); len(ws) != 0 {
t.Fatalf("none: %+v", ws)
}
}
// GetAFPUsage in both forms the tools built on it read: Used of Quota with
// a reset in ms (dsh-ark-quota), and Percent or Used of Total with
// ResetTimestamp (arkcli); a bucket with no quota is not on the plan.
func TestVolcReadAFP(t *testing.T) {
ws, tier := volcReadAFP(json.RawMessage(`{"AFPFiveHour":{"Quota":100,"Used":42,"ResetTime":1790000000000},
"AFPDaily":{"Quota":500,"Used":400},"AFPWeekly":{"Quota":0,"Used":5},"AFPMonthly":{"Quota":200,"Used":50}}`))
if tier != "" || len(ws) != 2 || ws[0].Name != "5 hours" || ws[0].Used != 42 || ws[0].Amount != 42 || ws[0].Limit != 100 ||
ws[0].ResetsAt == nil || ws[0].ResetsAt.Unix() != 1790000000 || ws[1].Name != "Month" || ws[1].Used != 25 || ws[1].ResetsAt != nil {
t.Fatalf("Quota form: %+v", ws)
}
ws, tier = volcReadAFP(json.RawMessage(`{"Tier":"Pro","AFPFiveHour":{"Percent":12.5,"ResetTimestamp":1790000000},
"AFPWeekly":{"Used":"30","Total":"120","ResetTime":"2026-10-12T00:00:00Z"}}`))
if tier != "Pro" || len(ws) != 2 || ws[0].Used != 12.5 || ws[0].ResetsAt.Unix() != 1790000000 ||
ws[1].Name != "Weekly" || ws[1].Used != 25 || ws[1].ResetsAt.Format(time.RFC3339) != "2026-10-12T00:00:00Z" {
t.Fatalf("Total form: %+v %q", ws, tier)
}
}
// The Usage page shows a card for each access key and plan, asked of
// open.volcengineapi.com only, signed with the access key and never with
// the plan's key; pay-as-you-go, a provider with no Secret and one
// switched off have none, and a refused access key says what to check.
func TestVolcPlanQuotas(t *testing.T) {
isolate(t)
h := t.TempDir()
t.Setenv("HOME", h)
t.Setenv("USERPROFILE", h)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(h, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(h, ".cache"))
t.Setenv("PATH", h)
for _, v := range agentenv.Vars {
t.Setenv(v, "")
}
secrets := map[string]string{"AK1": "SK1", "AKbad": "SKwrong"}
var mu sync.Mutex
asked := map[string]int{}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
if r.Header.Get("X-Host") != "open.volcengineapi.com" || r.Method != http.MethodPost || r.URL.Path != "/" || string(body) != "{}" {
t.Errorf("asked %s %s%s with %q", r.Method, r.Header.Get("X-Host"), r.URL, body)
w.WriteHeader(http.StatusNotFound)
return
}
auth := r.Header.Get("Authorization")
if strings.Contains(auth, "ark-k") {
t.Errorf("the plan's key was sent: %s", auth)
}
// Credential=<ak>/<date>/<region>/ark/request
cred, _, _ := strings.Cut(strings.TrimPrefix(auth, "HMAC-SHA256 Credential="), ",")
parts := strings.Split(cred, "/")
if len(parts) != 5 {
t.Errorf("Authorization %q", auth)
return
}
ak, region, action := parts[0], parts[2], r.URL.Query().Get("Action")
xDate, _ := time.Parse("20060102T150405Z", r.Header.Get("X-Date"))
want, _, _ := volcSign(ak, secrets[ak], region, r.URL.Query(), body, xDate)
if ak == "AKbad" || auth != want || r.Header.Get("Content-Type") != "application/json" {
w.WriteHeader(http.StatusUnauthorized)
io.WriteString(w, `{"ResponseMetadata":{"Action":"`+action+`","Error":{"Code":"SignatureDoesNotMatch","Message":"The request signature we calculated does not match"}}}`)
return
}
mu.Lock()
asked[ak+" "+region+" "+action]++
mu.Unlock()
switch action {
case "GetCodingPlanUsage":
io.WriteString(w, `{"ResponseMetadata":{"RequestId":"r1"},"Result":{"Status":"ok","QuotaUsage":[{"Level":"session","Percent":10.5,"ResetTimestamp":1758100000},{"Level":"weekly","Percent":20.25,"ResetTimestamp":1758200000},{"Level":"monthly","Percent":30.75,"ResetTimestamp":1758300000}]}}`)
case "GetAFPUsage":
io.WriteString(w, `{"ResponseMetadata":{"RequestId":"r2"},"Result":{"Tier":"Lite","AFPFiveHour":{"Quota":100,"Used":42},"AFPWeekly":{"Quota":400,"Used":100},"AFPMonthly":{"Quota":0,"Used":0}}}`)
default:
t.Errorf("action %q", action)
}
}))
defer srv.Close()
old := http.DefaultClient.Transport
http.DefaultClient.Transport = rewrite{srv}
t.Cleanup(func() { http.DefaultClient.Transport = old })
forgetPlanQuotas()
t.Cleanup(forgetPlanQuotas)
for _, p := range []Provider{
{ID: "volcengine", Name: "Volcengine Ark", Chat: "https://ark.cn-beijing.volces.com/api/coding/v3", Key: "ark-k", AccessKeyID: "AK1", SecretAccessKey: "SK1"},
// the same access key's Coding Plan again: one card
{ID: "volc-copy", Name: "Ark copy", Anthropic: "https://ark.cn-beijing.volces.com/api/coding", Key: "ark-k", AccessKeyID: "AK1", SecretAccessKey: "SK1"},
{ID: "volc-agent", Name: "Ark Agent", Chat: "https://ark.cn-shanghai.volces.com/api/plan/v3", Key: "ark-k", AccessKeyID: "AK1", SecretAccessKey: "SK1"},
{ID: "volc-payg", Name: "Ark API", Chat: "https://ark.cn-beijing.volces.com/api/v3", Key: "ark-k", AccessKeyID: "AK1", SecretAccessKey: "SK1"},
{ID: "volc-nosecret", Name: "Ark half", Chat: "https://ark.cn-beijing.volces.com/api/plan/v3", Key: "ark-k", AccessKeyID: "AK2"},
{ID: "volc-off", Name: "Ark off", Chat: "https://ark.cn-beijing.volces.com/api/plan/v3", Key: "ark-k", AccessKeyID: "AK3", SecretAccessKey: "SK3", Off: true},
{ID: "volc-bad", Name: "Ark bad", Chat: "https://ark.cn-beijing.volces.com/api/coding/v3", Key: "ark-k", AccessKeyID: "AKbad", SecretAccessKey: "SKwrong"},
} {
if err := Save(p); err != nil {
t.Fatal(err)
}
}
got := map[string]SubscriptionQuota{}
for _, q := range PlanQuotas(context.Background()) {
if q.Plan != "" && strings.HasPrefix(q.Provider, "volc") {
got[q.Provider] = q
}
}
if len(got) != 3 {
t.Fatalf("cards: %+v", got)
}
coding, ok := got["volcengine"]
if !ok {
coding = got["volc-copy"]
}
if coding.Plan != "Coding Plan" || coding.Error != "" || len(coding.Windows) != 3 || coding.Windows[0].Name != "5 hours" || coding.Windows[0].Used != 10.5 ||
coding.Windows[2].Name != "Month" || coding.Windows[2].ResetsAt.Unix() != 1758300000 {
t.Errorf("Coding Plan: %+v", coding)
}
if q := got["volc-agent"]; q.Plan != "Agent Plan Lite" || q.Error != "" || len(q.Windows) != 2 || q.Windows[0].Used != 42 || q.Windows[1].Name != "Weekly" || q.Windows[1].Used != 25 {
t.Errorf("Agent Plan: %+v", q)
}
if q := got["volc-bad"]; len(q.Windows) != 0 || !strings.Contains(q.Error, "SignatureDoesNotMatch") || !strings.Contains(q.Error, "AccessKey ID and Secret") {
t.Errorf("refused: %+v", q)
}
if asked["AK1 cn-beijing GetCodingPlanUsage"] != 1 || asked["AK1 cn-shanghai GetAFPUsage"] != 1 || len(asked) != 2 {
t.Errorf("asked: %v", asked)
}
}
+8 -1
View File
@@ -29,7 +29,8 @@ const providerUsage = `usage:
magpie provider <id> show one provider and its models
magpie provider add <preset> <key> add a preset vendor e.g. magpie provider add deepseek sk-…
again, it adds another (deepseek-2); k=v pairs too: id, name, header.X-Foo
magpie provider add <name> k=v… add a custom vendor k: url, anthropic, responses, gemini, decide, key, models, catalog, icon, header.X-Foo, balance, balance.path, balance.token, models.url, search
magpie provider add <name> k=v… add a custom vendor k: url, anthropic, responses, gemini, decide, key, models, catalog, icon, header.X-Foo, balance, balance.path, balance.token, models.url, search,
access.key, access.secret (a Volcengine account's access key, for its plan's windows)
magpie provider set <id> k=v… change a provider's settings, with the same k=v pairs as add
magpie provider key <id> <key> change the API key
magpie provider icon <id> <file|name> give a custom provider a picture (PNG, JPEG, SVG…) or a built-in icon
@@ -823,6 +824,12 @@ func applyPairs(p *provider.Provider, pairs []string) error {
p.BalancePath = v
case "balance.token":
p.BalanceToken = v
case "access.key":
// a Volcengine account's access key, which Ark tells its
// Coding or Agent Plan's windows to (#1427)
p.AccessKeyID = v
case "access.secret":
p.SecretAccessKey = v
case "models.url":
p.ModelsURL = v
case "search":