provider: Alibaba Cloud Token Plan quota read with the account's AccessKey; intl Token Plan preset (pppMathew on X, #2940)
Cause: a Token Plan sk-sp- key only authorizes inference. The plan's
usage sits on the Bailian console gateway, which wants a console token
(the key gets BailianGateway.Login.NotLogined) that Alibaba's own `bl` CLI
makes from the account's AccessKey through GenerateCLIAccessToken (ACS3
signed). magpie had no such path, so the usage card showed no quota.
Change:
- alibaba_usage.go: ACS3-HMAC-SHA256 signing, the console token (kept 20
minutes per AccessKey and region, made again once on NotLogined), the
personal plan's usage API, and per<N><Unit>Percentage/ResetTime read as
5 hours / Weekly / Month windows. Hooked in as AccessKeyVendor "alibaba"
(editor asks AccessKey ID and Secret, a keyless card says so),
accountPlanOf (routing), PlanQuotas and the key card tag.
- Hosts: token-plan.cn-beijing.maas.aliyuncs.com (bailian-token-plan) and
the new token-plan.ap-southeast-1.maas.aliyuncs.com preset
alibaba-token-plan (Alibaba Cloud international Token Plan, #2940), also
an OpenCode import target.
- Editor hint in zh, zh-TW, ja, de; docs (providers-accounts, reference).
Not covered: qwen-token-plan (Qwen AI platform) and qwencloud-token-plan
have no AccessKey route (browser-session console, #5829); team plans.
Run on mica at this tree: go test ./internal/gui ./internal/provider ok;
go vet darwin, linux nogui, windows on provider/gui clean; GUI files
i18n-keys, i18n-en-no-cjk, tencent-access-key, volc-access-key,
usage-access-key-card, tencent-cloud in chromium and webkit: 60 of 64 pass,
the 4 reds are tencent-cloud's "region clicked right after the strip
scrolled", red the same at origin/main 319753d89 (filed: #4321, #4399,
#4625). Broke it by hand: dropping the *100 on the percentage turns
TestAliReadWindows and TestAliPlanQuotas red.
Tests never reach the network (httptest behind a rewriting transport).
Not tried: no real Alibaba Cloud account, so neither the mint nor the
usage reply was seen live; the field names and the envelope come from the
official client's source. The international gateway host
(bailian-singapore-cs.alibabacloud.com) and the RAM-user case are the least
certain. The full suite was not run before the tag.
This commit is contained in:
+5
-1
@@ -1084,7 +1084,11 @@ at `/v2/models`.
|
||||
Alibaba's Token Plan is sold in two places, each with its own `sk-sp-` key
|
||||
that only its own host takes: on the Qwen AI platform as `qwen-token-plan`
|
||||
(`token-plan.maas.qianwenaiapi.com`), and on Alibaba Cloud Bailian as
|
||||
`bailian-token-plan` (`token-plan.cn-beijing.maas.aliyuncs.com`). Both serve
|
||||
`bailian-token-plan` (`token-plan.cn-beijing.maas.aliyuncs.com`). Alibaba Cloud's international
|
||||
plan is `alibaba-token-plan` (`token-plan.ap-southeast-1.maas.aliyuncs.com`),
|
||||
and the two at aliyuncs.com show the plan's windows on the Usage page once the
|
||||
provider's editor is given the Alibaba Cloud account's AccessKey ID and Secret
|
||||
(the `sk-sp-` key cannot read them). All serve
|
||||
Chat Completions at `/compatible-mode/v1` and Anthropic Messages at
|
||||
`/apps/anthropic`, and carry the plans' documented text models for when the
|
||||
host lists none. Bailian's also answers its decision model,
|
||||
|
||||
@@ -409,6 +409,7 @@ and `TestHistoricalWindowHoldsUsesEachWindowsOwnReading`.
|
||||
- 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 or sends it blank keeps both (an editor opened before the key was given sends `""`, #1821), and `clearAccessKey` drops both. The ID and Secret go together everywhere the keys go: a copy takes them, also when its form sends the source's ID without the Secret (`AddCopy`), a backup or sync without keys has neither (`withoutKeys`), and a restore, mirror or sync keeps this machine's (`KeepSecrets` in `Restore`, `Mirror`, davsync's `take`) when it came without keys, or with the same key and no access key at all, as a magpie before v0.1.1142 or one the access key was never given on sends it (#1821); another key is another account and brings its own. A copy without keys keeps this machine's secret headers (`SecretHeader`) the same way. A plan endpoint with no provider on it holding the access key is a card that says which to give (`accessKeyCard`, `needsAccessKey`), with a button to the provider's settings, not a card left out. A `providers.json` saved with a UTF-8 BOM is read through it, not taken for a broken file whose `.bak` stands in. 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`).
|
||||
- A Tencent Cloud provider's SecretId and SecretKey are kept, listed and saved the same way, in the same fields (`AccessKeyVendor` tells the editor whose: `accessKey.vendor`, the preset's `accessKeyVendor`). Only the Token Plan's endpoints are read with them (`TakesTencentAccessKey`: `/plan` on `tokenhub.tencentmaas.com`, region `ap-guangzhou`, or `tokenhub-intl.tencentmaas.com`, `ap-singapore`). Since 10-22 Tencent serves 个人版 and 企业版 in China at the same `/plan` endpoints with the same `sk-tp-` keys (product/1823/130060, 130659), so they are one region, `plan` (a key saved on `enterprise` is on it, `regionAliases`/`RegionID`); 个人版 has no usage API, so a Guangzhou provider without a SecretId gets no card asking for one (`tcSharedRegion`), while Singapore's does. A Tencent Cloud provider saved at the old personal host `api.lkeap.cloud.tencent.com/plan/...` is moved to TokenHub's at load (`movedEndpoints`, `moveEndpoints` in `normalize`), with Responses added; one of no preset keeps the address its user typed, and an app imported at the old host lands on the plan. TokenHub's pay as you go has no plan and no card. A custom provider (no preset) at a Token Plan's or Ark plan's address is the user's own: its editor and Usage page ask it for no access key (`AsksAccessKey`) until one is saved on it, and its key goes as typed, `Authorization: Bearer` on chat and Responses (ysm119). The preset lists its regions that take one (`accessKeyRegions`, `presetAccessKey`), and the editor shows SecretId and SecretKey at those alone. `DescribeTokenPlanList` gives the account's team plans (a sub-user sees the ones it made); each is asked `DescribeTokenPlan` for its `PackageInfo` and `TokenSummary`, the list's kept for what the reply leaves out. The card's one window is `TotalUsed` of `CycleQuota` (else `TotalQuota`), resetting at `TokenSummary.CycleEndTime`, else counted in months from `StartTime` and never past `ExpireTime`. A plan not `enable` says its status beside the plan's name. Errors come back as 200 with `Response.Error`; an `AuthFailure…` or `UnauthorizedOperation` one says to check the key. Built from the API docs (api/1823/132270 and siblings) and the signing doc's worked example; never seen from a real account here.
|
||||
- An Alibaba Cloud Token Plan provider's AccessKey ID and Secret are kept in the same fields (`AccessKeyVendor` "alibaba"). Only the plan's two hosts at `token-plan.<region>.maas.aliyuncs.com` take them (`TakesAlibabaAccessKey`, `aliPlanSite`: `cn-beijing` is `bailian-token-plan`, `ap-southeast-1` is `alibaba-token-plan`, #2940); the Qwen AI platform's (`qianwenaiapi.com`) and Qwen Cloud's plans have no read here (their console takes a browser sign-in, #5829). The plan key only authorizes inference. The usage is on the console's gateway behind a console token, which `POST modelstudio.<region>.aliyuncs.com/modelstudio/cli/generateAccessToken` (ACS3-HMAC-SHA256, `aliACSSign`; Action `GenerateCLIAccessToken`, version `2026-02-10`; reply `cliAccessToken`) makes from the AccessKey, as Alibaba's own `bl` CLI does. The token is kept 20 minutes per AccessKey and region and made again once when the gateway answers `BailianGateway.Login.NotLogined`. The gateway call is `POST <console>/cli/api.json?action=BroadScopeAspnGateway|IntlBroadScopeAspnGateway&product=sfm_bailian&api=zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage` with `Bearer` and a form `params`, `region`; the windows are the `per<N><Hour|Day|Week|Month>Percentage` (a share used, 0 to 1) and `ResetTime` (ms) fields of `data.DataV2.data.data`, so 5 hours, Weekly and Month show as the plan has them. A RAM user not in the Bailian workspace gets `BailianGateway.Team.NotAuthorised`, said in the card. Team plans (团队版) use other APIs and have no card. The gateway has no public doc: built from the official client's source; never seen from a real account here, and the international gateway host (`bailian-singapore-cs.alibabacloud.com`) is the least certain part.
|
||||
- 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 Vertex AI provider's credentials are read only when a request is signed (`Sign`), so adding, listing and showing one ask Google nothing. With no `credentials` given and no file where Application Default Credentials are looked for, the request fails with `no Google credentials at <file>`, naming `gcloud auth application-default login` and the provider's credentials file as the ways to give it some. A `credentials` file that isn't there fails with the same words, saying to correct it or clear it. When Google refuses a person's sign-in (revoked, or past the organization's session length), the error says how to sign in again for the file used (`signInAgain`): gcloud's Application Default Credentials with `gcloud auth application-default login`, adding `--impersonate-service-account=<account>` when the file impersonates one; a file under gcloud's `legacy_credentials/<account>/` with `gcloud auth login <account>`; any other file by writing it anew or giving the provider another. The new file is read at the next request, with no restart.
|
||||
- Not read for Vertex AI: the metadata server of Compute Engine, Cloud Run and GKE; workload identity federation (`external_account`, `external_account_authorized_user`, refused by name); credentials whose `universe_domain` isn't `googleapis.com`; Vertex AI's express-mode API keys (Save refuses a key). No quota project is sent: Vertex AI bills the project in the URL.
|
||||
@@ -478,7 +479,7 @@ node --test internal/gui/tests/key-spend-cap.test.cjs
|
||||
go test -tags nogui ./internal/provider -run 'TestRemoteMagpie'
|
||||
go test -tags nogui ./internal/provider -run 'TestVolc|TestQianfan|TestBedrock|TestMantleBase|TestAddCopy|TestBackupBalanceToken'
|
||||
go test -tags nogui ./internal/gui -run TestProviderSaveKeepsVolcengineSecret
|
||||
go test -tags nogui ./internal/provider -run 'TestTC3|TestTencent'
|
||||
go test -tags nogui ./internal/provider -run 'TestTC3|TestTencent|TestAli'
|
||||
go test -tags nogui ./internal/gui -run TestProviderListTellsTencentAccessKey
|
||||
go test -tags nogui ./internal/backup ./internal/davsync -run 'TestRoundTrip|TestNoKeys|BalanceToken'
|
||||
node --test internal/gui/tests/volc-access-key.test.cjs internal/gui/tests/tencent-access-key.test.cjs
|
||||
|
||||
@@ -9634,7 +9634,7 @@ func render(proto provider.Protocol, res Result, r *Request) []byte {
|
||||
// custom provider.
|
||||
func dashScope(p provider.Provider) bool {
|
||||
switch p.VendorPreset() {
|
||||
case "qwen", "qwen-cn", "qwen-token-plan", "bailian-token-plan", "qwencloud", "qwencloud-token-plan":
|
||||
case "qwen", "qwen-cn", "qwen-token-plan", "bailian-token-plan", "alibaba-token-plan", "qwencloud", "qwencloud-token-plan":
|
||||
return true
|
||||
}
|
||||
h := p.VendorHost()
|
||||
|
||||
@@ -10001,6 +10001,8 @@ function drawEditor(p, presetID) {
|
||||
...field(idName, ak, ""),
|
||||
...field(secretName, pair, tc
|
||||
? t("Token Plan Enterprise's usage is told only to the Tencent Cloud account's API key (console → Access management → API keys), not to the plan's API key. Give its SecretId and SecretKey here for the Usage page to show it; a sub-user's key that may read TokenHub is enough. It is used for nothing else.")
|
||||
: access.vendor === "alibaba"
|
||||
? t("The plan's usage is told only to the Alibaba Cloud account's AccessKey (console → AccessKey), not to the plan's API key. Give its AccessKey ID and Secret here for the Usage page to show it; a RAM user that may use Model Studio is enough. It is used for nothing else.")
|
||||
: 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.")),
|
||||
];
|
||||
ed.append(...rows);
|
||||
|
||||
@@ -3776,6 +3776,7 @@ const I18N = {
|
||||
"SecretId": "SecretId",
|
||||
"SecretKey": "SecretKey",
|
||||
"Token Plan Enterprise's usage is told only to the Tencent Cloud account's API key (console → Access management → API keys), not to the plan's API key. Give its SecretId and SecretKey here for the Usage page to show it; a sub-user's key that may read TokenHub is enough. It is used for nothing else.": "Token Plan 企业版的用量只对腾讯云账号的 API 密钥开放(控制台 → 访问管理 → API 密钥管理),套餐的 API Key 查不到。在这里填入它的 SecretId 和 SecretKey,用量页就会显示;有 TokenHub 读权限的子用户密钥即可。仅用于查询用量。",
|
||||
"The plan's usage is told only to the Alibaba Cloud account's AccessKey (console → AccessKey), not to the plan's API key. Give its AccessKey ID and Secret here for the Usage page to show it; a RAM user that may use Model Studio is enough. It is used for nothing else.": "套餐的用量只对阿里云账号的 AccessKey 开放(控制台 → AccessKey 管理),套餐的 API Key 查不到。在这里填入它的 AccessKey ID 和 Secret,用量页就会显示;有百炼使用权限的 RAM 子账号即可。仅用于查询用量。",
|
||||
"This plan's usage needs the account's AccessKey ID and Secret — give them in the provider's settings": "此套餐的用量需要账号的 AccessKey ID 和 Secret 才能读取,请在服务商设置里填写",
|
||||
"Open settings": "打开设置",
|
||||
"This plan's usage needs the account's SecretId and SecretKey — give them in the provider's settings": "此套餐的用量需要账号的 SecretId 和 SecretKey 才能读取,请在服务商设置里填写",
|
||||
@@ -8857,6 +8858,7 @@ const I18N = {
|
||||
"SecretId": "SecretId",
|
||||
"SecretKey": "SecretKey",
|
||||
"Token Plan Enterprise's usage is told only to the Tencent Cloud account's API key (console → Access management → API keys), not to the plan's API key. Give its SecretId and SecretKey here for the Usage page to show it; a sub-user's key that may read TokenHub is enough. It is used for nothing else.": "Token Plan 企業版的用量只對騰訊雲帳號的 API 金鑰開放(主控台 → 存取管理 → API 金鑰管理),套餐的 API Key 查不到。在這裡填入它的 SecretId 和 SecretKey,用量頁就會顯示;有 TokenHub 讀取權限的子使用者金鑰即可。僅用於查詢用量。",
|
||||
"The plan's usage is told only to the Alibaba Cloud account's AccessKey (console → AccessKey), not to the plan's API key. Give its AccessKey ID and Secret here for the Usage page to show it; a RAM user that may use Model Studio is enough. It is used for nothing else.": "套餐的用量只對阿里雲帳號的 AccessKey 開放(主控台 → AccessKey 管理),套餐的 API Key 查不到。在這裡填入它的 AccessKey ID 和 Secret,用量頁就會顯示;有百鍊使用權限的 RAM 子帳號即可。僅用於查詢用量。",
|
||||
"This plan's usage needs the account's AccessKey ID and Secret — give them in the provider's settings": "此方案的用量需要帳號的 AccessKey ID 和 Secret 才能讀取,請在服務商設定中填寫",
|
||||
"Open settings": "開啟設定",
|
||||
"This plan's usage needs the account's SecretId and SecretKey — give them in the provider's settings": "此方案的用量需要帳號的 SecretId 和 SecretKey 才能讀取,請在服務商設定中填寫",
|
||||
@@ -13946,6 +13948,7 @@ const I18N = {
|
||||
"SecretId": "SecretId",
|
||||
"SecretKey": "SecretKey",
|
||||
"Token Plan Enterprise's usage is told only to the Tencent Cloud account's API key (console → Access management → API keys), not to the plan's API key. Give its SecretId and SecretKey here for the Usage page to show it; a sub-user's key that may read TokenHub is enough. It is used for nothing else.": "Token Plan Enterprise の使用量は、Tencent Cloud アカウントの API キー(コンソール → アクセス管理 → API キー)にだけ返され、プランの API キーでは取得できません。ここに SecretId と SecretKey を入力すると使用量ページに表示されます。TokenHub を読み取れるサブユーザーのキーで十分です。それ以外には使いません。",
|
||||
"The plan's usage is told only to the Alibaba Cloud account's AccessKey (console → AccessKey), not to the plan's API key. Give its AccessKey ID and Secret here for the Usage page to show it; a RAM user that may use Model Studio is enough. It is used for nothing else.": "プランの使用量は、Alibaba Cloud アカウントの AccessKey(コンソール → AccessKey 管理)にだけ返され、プランの API キーでは取得できません。ここに AccessKey ID と Secret を入力すると使用量ページに表示されます。Model Studio を利用できる RAM ユーザーで十分です。それ以外には使いません。",
|
||||
"This plan's usage needs the account's AccessKey ID and Secret — give them in the provider's settings": "このプランの使用量を読むにはアカウントの AccessKey ID と Secret が必要です。プロバイダの設定で入力してください",
|
||||
"Open settings": "設定を開く",
|
||||
"This plan's usage needs the account's SecretId and SecretKey — give them in the provider's settings": "このプランの使用量を読むにはアカウントの SecretId と SecretKey が必要です。プロバイダの設定で入力してください",
|
||||
@@ -19044,6 +19047,7 @@ const I18N = {
|
||||
"SecretId": "SecretId",
|
||||
"SecretKey": "SecretKey",
|
||||
"Token Plan Enterprise's usage is told only to the Tencent Cloud account's API key (console → Access management → API keys), not to the plan's API key. Give its SecretId and SecretKey here for the Usage page to show it; a sub-user's key that may read TokenHub is enough. It is used for nothing else.": "Die Nutzung des Token Plan Enterprise gibt Tencent Cloud nur dem API-Schlüssel des Kontos (Konsole → Zugriffsverwaltung → API-Schlüssel), nicht dem API-Schlüssel des Plans. Geben Sie hier dessen SecretId und SecretKey an, damit die Seite „Nutzung“ sie zeigt; der Schlüssel eines Unterbenutzers, der TokenHub lesen darf, genügt. Er wird für nichts anderes verwendet.",
|
||||
"The plan's usage is told only to the Alibaba Cloud account's AccessKey (console → AccessKey), not to the plan's API key. Give its AccessKey ID and Secret here for the Usage page to show it; a RAM user that may use Model Studio is enough. It is used for nothing else.": "Die Nutzung des Plans gibt Alibaba Cloud nur dem AccessKey des Kontos (Konsole → AccessKey), nicht dem API-Schlüssel des Plans. Geben Sie hier dessen AccessKey ID und Secret an, damit die Seite „Nutzung“ sie zeigt; ein RAM-Benutzer, der Model Studio nutzen darf, genügt. Er wird für nichts anderes verwendet.",
|
||||
"This plan's usage needs the account's AccessKey ID and Secret — give them in the provider's settings": "Die Nutzung dieses Tarifs wird mit der AccessKey ID und dem Secret des Kontos gelesen – geben Sie sie in den Einstellungen des Anbieters an",
|
||||
"Open settings": "Einstellungen öffnen",
|
||||
"This plan's usage needs the account's SecretId and SecretKey — give them in the provider's settings": "Die Nutzung dieses Tarifs wird mit der SecretId und dem SecretKey des Kontos gelesen – geben Sie sie in den Einstellungen des Anbieters an",
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// Alibaba Cloud's two Token Plan presets at aliyuncs.com ask for the
|
||||
// account's AccessKey (#2940); the Qwen AI platform's and Qwen Cloud's
|
||||
// plans have no such read and ask for nothing.
|
||||
func TestPresetAccessKeyAlibaba(t *testing.T) {
|
||||
for id, want := range map[string]string{"bailian-token-plan": "alibaba", "alibaba-token-plan": "alibaba", "qwen-token-plan": "", "qwencloud-token-plan": "", "qwen": ""} {
|
||||
pr := provider.Preset(id)
|
||||
if pr == nil {
|
||||
t.Fatalf("no preset %s", id)
|
||||
}
|
||||
if v, ids := presetAccessKey(*pr); v != want || ids != nil {
|
||||
t.Errorf("%s: %q %v", id, v, ids)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,439 @@
|
||||
package provider
|
||||
|
||||
// Alibaba Cloud's Token Plan (Bailian's, at token-plan.<region>.maas.
|
||||
// aliyuncs.com, sk-sp- keys) has a monthly window and, on some plans, 5-hour
|
||||
// and weekly ones, which Alibaba tells only to its console's gateway, never
|
||||
// to the plan's inference key (the key gets BailianGateway.Login.NotLogined
|
||||
// there, and 400 "model missing" on every path of the model host). The
|
||||
// console takes a temporary token, which Alibaba's own client (modelstudioai
|
||||
// /cli, `bl usage token-plan`) makes from the account's AccessKey ID and
|
||||
// Secret:
|
||||
//
|
||||
// 1. POST modelstudio.<region>.aliyuncs.com/modelstudio/cli/
|
||||
// generateAccessToken, signed ACS3-HMAC-SHA256 (Action
|
||||
// GenerateCLIAccessToken, version 2026-02-10, no query, no body), gives
|
||||
// cliAccessToken;
|
||||
// 2. POST <console>/cli/api.json?action=BroadScopeAspnGateway&product=
|
||||
// sfm_bailian&api=zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage
|
||||
// with Bearer cliAccessToken and the form params={Api,V,Data}®ion,
|
||||
// gives data.DataV2.data.data with per5HourPercentage, per1WeekPercentage
|
||||
// and per1MonthPercentage (each a share used, 0 to 1) and their
|
||||
// ResetTime in milliseconds.
|
||||
//
|
||||
// The gateway has no public documentation: the fields are read as the
|
||||
// client does, from whichever per<N><Unit> pairs the reply has. Only the
|
||||
// personal plan's API is known; the Qwen AI platform's and Qwen Cloud's
|
||||
// plans sit behind a console of their own that takes a browser sign-in, so
|
||||
// they have no card (#5829).
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
aliACSAction = "GenerateCLIAccessToken"
|
||||
aliACSVersion = "2026-02-10"
|
||||
aliACSPath = "/modelstudio/cli/generateAccessToken"
|
||||
aliUsageAPI = "zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage"
|
||||
aliPlanName = "Token Plan"
|
||||
aliKeyHint = "check the AccessKey ID and Secret in the provider's editor (Alibaba Cloud console → AccessKey), and that the account may use Model Studio"
|
||||
// aliTokenTTL is how long a console token is kept before a new one is
|
||||
// made; one the console refuses is made again at once
|
||||
aliTokenTTL = 20 * time.Minute
|
||||
)
|
||||
|
||||
// aliSite is where a Token Plan's region is asked: the host that makes
|
||||
// the console token, the console gateway and its action.
|
||||
type aliSite struct {
|
||||
region, mint, gateway, action string
|
||||
}
|
||||
|
||||
var aliSites = map[string]aliSite{
|
||||
"cn-beijing": {"cn-beijing", "modelstudio.cn-beijing.aliyuncs.com", "bailian-cs.console.aliyun.com", "BroadScopeAspnGateway"},
|
||||
"ap-southeast-1": {"ap-southeast-1", "modelstudio.ap-southeast-1.aliyuncs.com", "bailian-singapore-cs.alibabacloud.com", "IntlBroadScopeAspnGateway"},
|
||||
}
|
||||
|
||||
// aliPlanSite is the region of the Alibaba Cloud Token Plan p's endpoint is
|
||||
// on (token-plan.cn-beijing.maas.aliyuncs.com, token-plan.ap-southeast-1.
|
||||
// maas.aliyuncs.com); ok false for another host, a plan of the Qwen AI
|
||||
// platform or Qwen Cloud, or an account.
|
||||
func aliPlanSite(p Provider) (aliSite, bool) {
|
||||
if p.Account != nil {
|
||||
return aliSite{}, false
|
||||
}
|
||||
for _, base := range []string{p.Chat, p.Anthropic, p.Responses} {
|
||||
if !strings.Contains(strings.ToLower(base), "maas.aliyuncs.com") {
|
||||
continue
|
||||
}
|
||||
h := hostOf(base)
|
||||
region, ok := strings.CutPrefix(h, "token-plan.")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
region, ok = strings.CutSuffix(region, ".maas.aliyuncs.com")
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if s, ok := aliSites[region]; ok {
|
||||
return s, true
|
||||
}
|
||||
}
|
||||
return aliSite{}, false
|
||||
}
|
||||
|
||||
// TakesAlibabaAccessKey says p is on Alibaba Cloud's Token Plan, whose
|
||||
// editor then asks for the account's AccessKey ID and Secret.
|
||||
func TakesAlibabaAccessKey(p Provider) bool {
|
||||
_, ok := aliPlanSite(p)
|
||||
return ok
|
||||
}
|
||||
|
||||
// aliPlanQuotas is a card for each Alibaba Cloud Token Plan region a
|
||||
// provider in use is on and has the account's access key for, one for each
|
||||
// access key and region, named for the first such provider; a region no
|
||||
// provider on it has the access key for is a card that says so
|
||||
// (accessKeyCard, #1821).
|
||||
func aliPlanQuotas(ctx context.Context) []SubscriptionQuota {
|
||||
type job struct {
|
||||
p Provider
|
||||
site aliSite
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
var jobs, keyless []job
|
||||
keyed := map[string]bool{}
|
||||
for _, p := range planViews(All()) {
|
||||
if p.Hidden || p.Off {
|
||||
continue
|
||||
}
|
||||
site, ok := aliPlanSite(p)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if p.AccessKeyID == "" || p.SecretAccessKey == "" {
|
||||
if AsksAccessKey(p) != "" {
|
||||
keyless = append(keyless, job{p, site})
|
||||
}
|
||||
continue
|
||||
}
|
||||
keyed[site.region] = true
|
||||
if seen[p.AccessKeyID+" "+site.region] || !wantsCard(ctx, p.ID, "") {
|
||||
continue
|
||||
}
|
||||
seen[p.AccessKeyID+" "+site.region] = true
|
||||
jobs = append(jobs, job{p, site})
|
||||
}
|
||||
out := make([]SubscriptionQuota, len(jobs))
|
||||
var wg sync.WaitGroup
|
||||
for i, j := range jobs {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
out[i] = aliPlanQuota(j.p.Via(ctx), j.p, j.site)
|
||||
if out[i].Error == "" {
|
||||
// what routing goes by, read just now (KeyAllowance)
|
||||
noteKeyAllowance(j.p, out[i].Windows, time.Now())
|
||||
}
|
||||
out[i] = keepReading(ctx, out[i], keyTag("alibaba "+j.site.region, j.p.AccessKeyID))
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
for _, j := range keyless {
|
||||
if keyed[j.site.region] || seen["none "+j.site.region] || !wantsCard(ctx, j.p.ID, "") {
|
||||
continue
|
||||
}
|
||||
seen["none "+j.site.region] = true
|
||||
out = append(out, accessKeyCard(j.p, aliPlanName))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// aliPlanQuota is p's plan as a card, read with its access key.
|
||||
func aliPlanQuota(ctx context.Context, p Provider, site aliSite) SubscriptionQuota {
|
||||
q := SubscriptionQuota{Provider: p.ID, Name: p.Name, Icon: p.Icon, Plan: aliPlanName, Windows: []QuotaWindow{}}
|
||||
ws, err := aliReadUsage(ctx, p.AccessKeyID, p.SecretAccessKey, site, time.Now)
|
||||
if err != nil {
|
||||
q.Error = err.Error()
|
||||
return q
|
||||
}
|
||||
q.Windows = ws
|
||||
return q
|
||||
}
|
||||
|
||||
type aliToken struct {
|
||||
token string
|
||||
at time.Time
|
||||
}
|
||||
|
||||
var (
|
||||
aliTokensMu sync.Mutex
|
||||
aliTokens = map[string]aliToken{}
|
||||
)
|
||||
|
||||
func aliTokenKey(ak string, site aliSite) string { return ak + " " + site.region }
|
||||
|
||||
// aliReadUsage reads the plan's windows: the console token kept for the
|
||||
// access key, made again once when the console says it isn't logged in.
|
||||
func aliReadUsage(ctx context.Context, ak, sk string, site aliSite, now func() time.Time) ([]QuotaWindow, error) {
|
||||
key := aliTokenKey(ak, site)
|
||||
for try := 0; ; try++ {
|
||||
aliTokensMu.Lock()
|
||||
t, ok := aliTokens[key]
|
||||
aliTokensMu.Unlock()
|
||||
if !ok || try > 0 || now().Sub(t.at) > aliTokenTTL {
|
||||
tok, err := aliMintToken(ctx, ak, sk, site, now())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t = aliToken{tok, now()}
|
||||
aliTokensMu.Lock()
|
||||
aliTokens[key] = t
|
||||
aliTokensMu.Unlock()
|
||||
}
|
||||
raw, err := aliGateway(ctx, t.token, site)
|
||||
if err != nil {
|
||||
if try == 0 && ok && err == errAliNotLogged {
|
||||
continue
|
||||
}
|
||||
if err == errAliNotLogged {
|
||||
return nil, fmt.Errorf("Alibaba Cloud's console answered BailianGateway.Login.NotLogined for this access key; %s", aliKeyHint)
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
ws := aliReadWindows(raw)
|
||||
if len(ws) == 0 {
|
||||
return nil, fmt.Errorf("Alibaba Cloud's console told no window for this plan (it may be unlimited, or not a personal Token Plan): %s", volcHead(raw))
|
||||
}
|
||||
return ws, nil
|
||||
}
|
||||
}
|
||||
|
||||
var errAliNotLogged = fmt.Errorf("not logged in")
|
||||
|
||||
// aliACSSign is the headers of an ACS3-HMAC-SHA256 request of the
|
||||
// control plane's RPC action to host at path, with no query and body, at
|
||||
// now with nonce: as Alibaba's own client (acs.ts signAcsRequest) signs it,
|
||||
// the signed headers sorted, content-type among them.
|
||||
func aliACSSign(ak, sk, host, path, action, version string, body []byte, now time.Time, nonce string) map[string]string {
|
||||
sum := sha256.Sum256(body)
|
||||
hashed := hex.EncodeToString(sum[:])
|
||||
h := map[string]string{
|
||||
"host": host,
|
||||
"x-acs-action": action,
|
||||
"x-acs-version": version,
|
||||
"x-acs-date": now.UTC().Format("2006-01-02T15:04:05Z"),
|
||||
"x-acs-signature-nonce": nonce,
|
||||
"x-acs-content-sha256": hashed,
|
||||
"content-type": "application/json",
|
||||
}
|
||||
keys := make([]string, 0, len(h))
|
||||
for k := range h {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
var ch strings.Builder
|
||||
for _, k := range keys {
|
||||
ch.WriteString(k + ":" + h[k] + "\n")
|
||||
}
|
||||
signed := strings.Join(keys, ";")
|
||||
canonical := strings.Join([]string{http.MethodPost, path, "", ch.String(), signed, hashed}, "\n")
|
||||
csum := sha256.Sum256([]byte(canonical))
|
||||
toSign := "ACS3-HMAC-SHA256\n" + hex.EncodeToString(csum[:])
|
||||
m := hmac.New(sha256.New, []byte(sk))
|
||||
m.Write([]byte(toSign))
|
||||
h["authorization"] = "ACS3-HMAC-SHA256 Credential=" + ak + ",SignedHeaders=" + signed + ",Signature=" + hex.EncodeToString(m.Sum(nil))
|
||||
return h
|
||||
}
|
||||
|
||||
func aliNonce() string {
|
||||
b := make([]byte, 16)
|
||||
_, _ = rand.Read(b)
|
||||
return hex.EncodeToString(b)
|
||||
}
|
||||
|
||||
// aliMintToken makes the console token from the access key. The access
|
||||
// key is sent nowhere but modelstudio.<region>.aliyuncs.com.
|
||||
func aliMintToken(ctx context.Context, ak, sk string, site aliSite, now time.Time) (string, error) {
|
||||
h := aliACSSign(ak, sk, site.mint, aliACSPath, aliACSAction, aliACSVersion, nil, now, aliNonce())
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://"+site.mint+aliACSPath, nil)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
for k, v := range h {
|
||||
if k != "host" {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
}
|
||||
req.Header.Set("Accept", "application/json")
|
||||
res, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
raw, err := io.ReadAll(io.LimitReader(res.Body, 1<<20))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var r struct {
|
||||
CliAccessToken string `json:"cliAccessToken"`
|
||||
Code string `json:"Code"`
|
||||
Message string `json:"Message"`
|
||||
}
|
||||
_ = json.Unmarshal(raw, &r)
|
||||
if tok := strings.TrimSpace(r.CliAccessToken); tok != "" && res.StatusCode < 300 {
|
||||
return tok, nil
|
||||
}
|
||||
switch {
|
||||
case r.Code != "" || r.Message != "":
|
||||
return "", fmt.Errorf("Alibaba Cloud %s: %s %s; %s", aliACSAction, r.Code, r.Message, aliKeyHint)
|
||||
case res.StatusCode == http.StatusUnauthorized || res.StatusCode == http.StatusForbidden:
|
||||
return "", fmt.Errorf("Alibaba Cloud %s: %s; %s", aliACSAction, res.Status, aliKeyHint)
|
||||
case res.StatusCode >= 300:
|
||||
return "", fmt.Errorf("Alibaba Cloud %s: %s: %s", aliACSAction, res.Status, volcHead(raw))
|
||||
}
|
||||
return "", fmt.Errorf("Alibaba Cloud %s gave no token: %s", aliACSAction, volcHead(raw))
|
||||
}
|
||||
|
||||
// aliGateway asks the console's usage API with token and gives the
|
||||
// business data of the reply (data.DataV2.data.data).
|
||||
func aliGateway(ctx context.Context, token string, site aliSite) ([]byte, error) {
|
||||
params, _ := json.Marshal(map[string]any{
|
||||
"Api": aliUsageAPI, "V": "1.0",
|
||||
"Data": map[string]any{"cornerstoneParam": map[string]any{
|
||||
"protocol": "V2", "console": "ONE_CONSOLE", "productCode": "p_efm", "switchUserType": 3, "consoleSite": "BAILIAN_ALIYUN"}},
|
||||
})
|
||||
form := url.Values{"params": {string(params)}, "region": {site.region}}
|
||||
u := "https://" + site.gateway + "/cli/api.json?action=" + site.action + "&product=sfm_bailian&api=" + url.QueryEscape(aliUsageAPI)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u, bytes.NewReader([]byte(form.Encode())))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
req.Header.Set("Accept", "*/*")
|
||||
res, err := Keyed(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
|
||||
}
|
||||
if res.StatusCode >= 300 {
|
||||
return nil, fmt.Errorf("Alibaba Cloud's console: %s: %s", res.Status, volcHead(raw))
|
||||
}
|
||||
var env struct {
|
||||
Data struct {
|
||||
Success *bool `json:"success"`
|
||||
ErrorCode json.RawMessage `json:"errorCode"`
|
||||
DataV2 json.RawMessage `json:"DataV2"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if json.Unmarshal(raw, &env) != nil {
|
||||
return nil, fmt.Errorf("Alibaba Cloud's console answered in a form magpie doesn't know: %s", volcHead(raw))
|
||||
}
|
||||
if env.Data.Success != nil && !*env.Data.Success && len(env.Data.ErrorCode) > 0 {
|
||||
code := strings.Trim(string(env.Data.ErrorCode), `"`)
|
||||
switch {
|
||||
case strings.Contains(code, "NotLogined"):
|
||||
return nil, errAliNotLogged
|
||||
case strings.Contains(code, "NotAuthorised"), strings.Contains(code, "NotAuthorized"):
|
||||
return nil, fmt.Errorf("Alibaba Cloud's console: %s: this RAM user isn't authorised in Model Studio's workspace; add it there in the Alibaba Cloud console, or use the account's own access key", code)
|
||||
}
|
||||
return nil, fmt.Errorf("Alibaba Cloud's console: %s", code)
|
||||
}
|
||||
// the reply holds it in two envelopes, one less in some replies
|
||||
var node json.RawMessage = env.Data.DataV2
|
||||
for i := 0; i < 2; i++ {
|
||||
var in struct {
|
||||
Data json.RawMessage `json:"data"`
|
||||
}
|
||||
if json.Unmarshal(node, &in) == nil && len(in.Data) > 0 && in.Data[0] == '{' {
|
||||
node = in.Data
|
||||
}
|
||||
}
|
||||
return node, nil
|
||||
}
|
||||
|
||||
var aliWindowField = regexp.MustCompile(`^per(\d+)(Hour|Day|Week|Month)(Percentage|ResetTime)$`)
|
||||
|
||||
// aliReadWindows reads the per<N><Unit>Percentage and ResetTime pairs of
|
||||
// the usage data as windows, the shortest first. Percentage is the share
|
||||
// used, 0 to 1; a window with no percentage is left out (it may be
|
||||
// unlimited).
|
||||
func aliReadWindows(raw []byte) []QuotaWindow {
|
||||
var m map[string]any
|
||||
if json.Unmarshal(raw, &m) != nil {
|
||||
return nil
|
||||
}
|
||||
type win struct {
|
||||
n int
|
||||
unit string
|
||||
used *float64
|
||||
at any
|
||||
}
|
||||
wins := map[string]*win{}
|
||||
for k, v := range m {
|
||||
g := aliWindowField.FindStringSubmatch(k)
|
||||
if g == nil {
|
||||
continue
|
||||
}
|
||||
n, _ := strconv.Atoi(g[1])
|
||||
key := g[1] + g[2]
|
||||
w := wins[key]
|
||||
if w == nil {
|
||||
w = &win{n: n, unit: g[2]}
|
||||
wins[key] = w
|
||||
}
|
||||
if g[3] == "ResetTime" {
|
||||
w.at = v
|
||||
} else if f, ok := volcNum(v); ok {
|
||||
w.used = &f
|
||||
}
|
||||
}
|
||||
hours := map[string]time.Duration{"Hour": time.Hour, "Day": 24 * time.Hour, "Week": 7 * 24 * time.Hour, "Month": 30 * 24 * time.Hour}
|
||||
var all []*win
|
||||
for _, w := range wins {
|
||||
if w.used != nil {
|
||||
all = append(all, w)
|
||||
}
|
||||
}
|
||||
sort.Slice(all, func(i, j int) bool {
|
||||
return time.Duration(all[i].n)*hours[all[i].unit] < time.Duration(all[j].n)*hours[all[j].unit]
|
||||
})
|
||||
var out []QuotaWindow
|
||||
for _, w := range all {
|
||||
q := QuotaWindow{Used: *w.used * 100, Span: time.Duration(w.n) * hours[w.unit], ResetsAt: volcTime(w.at)}
|
||||
switch {
|
||||
case w.n == 5 && w.unit == "Hour":
|
||||
q.Name = "5 hours"
|
||||
case w.n == 1 && w.unit == "Week":
|
||||
q.Name = "Weekly"
|
||||
case w.n == 1 && w.unit == "Month":
|
||||
q.Name = "Month"
|
||||
case w.n == 1:
|
||||
q.Name = map[string]string{"Hour": "Hour", "Day": "Daily"}[w.unit]
|
||||
}
|
||||
if q.Name == "" {
|
||||
q.Name = fmt.Sprintf("%d %ss", w.n, strings.ToLower(w.unit))
|
||||
}
|
||||
out = append(out, q)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/agentenv"
|
||||
)
|
||||
|
||||
// the signature is fixed by the algorithm: this one was made by hand with
|
||||
// openssl from the canonical request below
|
||||
func TestAliACSSignIsACS3(t *testing.T) {
|
||||
now := time.Date(2026, 11, 12, 1, 2, 3, 0, time.UTC)
|
||||
h := aliACSSign("AKID", "SECRET", "modelstudio.cn-beijing.aliyuncs.com", aliACSPath, aliACSAction, aliACSVersion, nil, now, "nonce1")
|
||||
const empty = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
|
||||
if h["x-acs-content-sha256"] != empty || h["x-acs-date"] != "2026-11-12T01:02:03Z" {
|
||||
t.Fatalf("%v", h)
|
||||
}
|
||||
signed := "content-type;host;x-acs-action;x-acs-content-sha256;x-acs-date;x-acs-signature-nonce;x-acs-version"
|
||||
pre := "ACS3-HMAC-SHA256 Credential=AKID,SignedHeaders=" + signed + ",Signature="
|
||||
auth := h["authorization"]
|
||||
if !strings.HasPrefix(auth, pre) || len(auth) != len(pre)+64 {
|
||||
t.Fatalf("Authorization %q", auth)
|
||||
}
|
||||
// another secret, another signature
|
||||
if aliACSSign("AKID", "OTHER", "modelstudio.cn-beijing.aliyuncs.com", aliACSPath, aliACSAction, aliACSVersion, nil, now, "nonce1")["authorization"] == auth {
|
||||
t.Fatal("the secret doesn't sign")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAliReadWindows(t *testing.T) {
|
||||
ws := aliReadWindows([]byte(`{"per1MonthPercentage":"0.25","per1MonthResetTime":1780000000000,"per5HourPercentage":0.1,"per5HourResetTime":1770000000000,"per1WeekPercentage":0.5,"planName":"x","per1DayPercentage":null}`))
|
||||
if len(ws) != 3 || ws[0].Name != "5 hours" || ws[1].Name != "Weekly" || ws[2].Name != "Month" {
|
||||
t.Fatalf("%+v", ws)
|
||||
}
|
||||
if ws[0].Used != 10 || ws[2].Used != 25 || ws[0].Span != 5*time.Hour || ws[2].ResetsAt.UnixMilli() != 1780000000000 {
|
||||
t.Fatalf("%+v", ws)
|
||||
}
|
||||
if len(aliReadWindows([]byte(`{"x":1}`))) != 0 {
|
||||
t.Fatal("windows from nothing")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAliPlanSite(t *testing.T) {
|
||||
for url, region := range map[string]string{
|
||||
"https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1": "cn-beijing",
|
||||
"https://token-plan.ap-southeast-1.maas.aliyuncs.com/apps/anthropic": "ap-southeast-1",
|
||||
"https://token-plan.maas.qianwenaiapi.com/compatible-mode/v1": "",
|
||||
"https://token-plan.maas.qwencloudapi.com/compatible-mode/v1": "",
|
||||
"https://dashscope-intl.aliyuncs.com/compatible-mode/v1": "",
|
||||
"https://ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1": "",
|
||||
} {
|
||||
s, ok := aliPlanSite(Provider{Chat: url})
|
||||
if ok != (region != "") || s.region != region {
|
||||
t.Errorf("%s: %v %q", url, ok, s.region)
|
||||
}
|
||||
}
|
||||
if _, ok := aliPlanSite(Provider{Chat: "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1", Account: &Account{}}); ok {
|
||||
t.Error("an account is a plan's")
|
||||
}
|
||||
for _, id := range []string{"bailian-token-plan", "alibaba-token-plan"} {
|
||||
p, err := FromPreset(id)
|
||||
if err != nil || AccessKeyVendor(p) != "alibaba" {
|
||||
t.Errorf("%s: %v", id, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAliPlanQuotas(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, "")
|
||||
}
|
||||
var mu sync.Mutex
|
||||
mints, reads := 0, 0
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
host := r.Header.Get("X-Host")
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
switch host {
|
||||
case "modelstudio.cn-beijing.aliyuncs.com":
|
||||
if r.Method != http.MethodPost || r.URL.Path != aliACSPath || r.URL.RawQuery != "" || len(body) != 0 ||
|
||||
r.Header.Get("x-acs-action") != aliACSAction || r.Header.Get("x-acs-version") != aliACSVersion {
|
||||
t.Errorf("mint %s %s with %q", r.Method, r.URL, body)
|
||||
}
|
||||
auth := r.Header.Get("Authorization")
|
||||
if strings.Contains(auth, "sk-sp-key") {
|
||||
t.Errorf("the plan's key was sent: %s", auth)
|
||||
}
|
||||
if !strings.Contains(auth, "Credential=AK1,") {
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
io.WriteString(w, `{"Code":"InvalidAccessKeyId.NotFound","Message":"Specified access key is not found."}`)
|
||||
return
|
||||
}
|
||||
date, _ := time.Parse("2006-01-02T15:04:05Z", r.Header.Get("x-acs-date"))
|
||||
want := aliACSSign("AK1", "SK1", host, aliACSPath, aliACSAction, aliACSVersion, nil, date, r.Header.Get("x-acs-signature-nonce"))["authorization"]
|
||||
if auth != want {
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
io.WriteString(w, `{"Code":"SignatureDoesNotMatch","Message":"bad"}`)
|
||||
return
|
||||
}
|
||||
mints++
|
||||
io.WriteString(w, `{"cliAccessToken":"tok2"}`)
|
||||
case "bailian-cs.console.aliyun.com":
|
||||
reads++
|
||||
q := r.URL.Query()
|
||||
f, _ := url.ParseQuery(string(body))
|
||||
if r.Method != http.MethodPost || r.URL.Path != "/cli/api.json" || q.Get("action") != "BroadScopeAspnGateway" || q.Get("product") != "sfm_bailian" ||
|
||||
q.Get("api") != aliUsageAPI || f.Get("region") != "cn-beijing" || !strings.Contains(f.Get("params"), aliUsageAPI) {
|
||||
t.Errorf("usage %s %s with %q", r.Method, r.URL, body)
|
||||
}
|
||||
// the first token is refused once: the reader makes another
|
||||
if r.Header.Get("Authorization") == "Bearer tok1" {
|
||||
io.WriteString(w, `{"code":"200","data":{"success":false,"errorCode":"BailianGateway.Login.NotLogined"}}`)
|
||||
return
|
||||
}
|
||||
if r.Header.Get("Authorization") != "Bearer tok2" {
|
||||
t.Errorf("Authorization %q", r.Header.Get("Authorization"))
|
||||
}
|
||||
io.WriteString(w, `{"code":"200","data":{"success":true,"DataV2":{"data":{"data":{"per5HourPercentage":0.1,"per5HourResetTime":1770000000000,"per1WeekPercentage":0.2,"per1MonthPercentage":0.3,"per1MonthResetTime":1780000000000}}}}}`)
|
||||
default:
|
||||
t.Errorf("asked %s %s", host, r.URL)
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
old := http.DefaultClient.Transport
|
||||
http.DefaultClient.Transport = rewrite{srv}
|
||||
t.Cleanup(func() { http.DefaultClient.Transport = old })
|
||||
aliTokensMu.Lock()
|
||||
// a token kept from before, which the console no longer takes
|
||||
aliTokens = map[string]aliToken{"AK1 cn-beijing": {"tok1", time.Now()}}
|
||||
aliTokensMu.Unlock()
|
||||
forgetPlanQuotas()
|
||||
t.Cleanup(forgetPlanQuotas)
|
||||
|
||||
const cn = "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"
|
||||
for _, p := range []Provider{
|
||||
{ID: "bailian-token-plan", Name: "Bailian Token Plan", Chat: cn, Key: "sk-sp-key", AccessKeyID: "AK1", SecretAccessKey: "SK1"},
|
||||
// the same access key: one card
|
||||
{ID: "bailian-copy", Name: "Bailian copy", Chat: cn, Key: "sk-sp-key", AccessKeyID: "AK1", SecretAccessKey: "SK1"},
|
||||
{ID: "bailian-bad", Name: "Bailian bad", Chat: cn, Key: "sk-sp-key", AccessKeyID: "AKbad", SecretAccessKey: "SKbad"},
|
||||
// no access key for the Singapore region: a card that asks for it
|
||||
{ID: "alibaba-token-plan", Name: "Alibaba Cloud Token Plan", Preset: "alibaba-token-plan", Chat: "https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1", Key: "sk-sp-key"},
|
||||
// not a plan's host
|
||||
{ID: "qwen", Name: "Qwen", Chat: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1", Key: "sk-x", AccessKeyID: "AK1", SecretAccessKey: "SK1"},
|
||||
} {
|
||||
if err := Save(p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
got := map[string]SubscriptionQuota{}
|
||||
for _, q := range PlanQuotas(context.Background()) {
|
||||
if q.Provider == "bailian-token-plan" || q.Provider == "bailian-copy" || q.Provider == "bailian-bad" || q.Provider == "alibaba-token-plan" || q.Provider == "qwen" {
|
||||
got[q.Provider] = q
|
||||
}
|
||||
}
|
||||
if len(got) != 3 {
|
||||
t.Fatalf("%+v", got)
|
||||
}
|
||||
q := got["bailian-token-plan"]
|
||||
if q.Error != "" || len(q.Windows) != 3 || q.Windows[0].Name != "5 hours" || q.Windows[0].Used != 10 || q.Windows[2].Name != "Month" || q.Windows[2].Used != 30 {
|
||||
t.Fatalf("%+v", q)
|
||||
}
|
||||
if mints != 1 || reads != 2 {
|
||||
// tok1 refused, tok2 made and read once; AKbad's mint is refused
|
||||
t.Errorf("mints %d, reads %d", mints, reads)
|
||||
}
|
||||
if b := got["bailian-bad"]; !strings.Contains(b.Error, "AccessKey") || strings.Contains(b.Error, "SKbad") {
|
||||
t.Errorf("bad key: %+v", b)
|
||||
}
|
||||
if a := got["alibaba-token-plan"]; a.Error == "" || !strings.Contains(a.Error, "AccessKey") {
|
||||
t.Errorf("keyless: %+v", a)
|
||||
}
|
||||
}
|
||||
@@ -25,7 +25,7 @@ func BillingOK(s string) bool { return s == "" || s == BillingPlan || s == Billi
|
||||
// you go endpoints of their own to tell them apart by.
|
||||
var planPresets = map[string]bool{
|
||||
"kimi-code": true, "kimi-code-cn": true,
|
||||
"qwen-token-plan": true, "bailian-token-plan": true, "qwencloud-token-plan": true,
|
||||
"qwen-token-plan": true, "bailian-token-plan": true, "alibaba-token-plan": true, "qwencloud-token-plan": true,
|
||||
"opencode-go": true, "clinepass": true,
|
||||
}
|
||||
|
||||
|
||||
@@ -49,7 +49,7 @@ var openCodePresets = map[string]string{
|
||||
"kimi-code-plan-cn": "kimi-code-cn", "kimi-code-plan-global": "kimi-code",
|
||||
"stepfun-step-plan": "stepfun-cn", "stepfun-ai-step-plan": "stepfun", "longcat": "longcat",
|
||||
"volcengine-coding-plan": "volcengine",
|
||||
"alibaba-token-plan-cn": "bailian-token-plan", "tencent-token-plan": "tencent-cloud",
|
||||
"alibaba-token-plan-cn": "bailian-token-plan", "alibaba-token-plan": "alibaba-token-plan", "tencent-token-plan": "tencent-cloud",
|
||||
}
|
||||
|
||||
func readOpenCodeAuth(path string) ([]AppImport, error) {
|
||||
|
||||
@@ -72,8 +72,9 @@ func readsKeyWindows(p Provider) bool {
|
||||
|
||||
// accountPlanOf is which plan p's key is on whose windows the key's
|
||||
// account tells, not the key: Volcengine Ark's Coding and Agent Plans and
|
||||
// Tencent Cloud's Token Plan Enterprise, read with the account's access
|
||||
// key (volcengine_usage.go, tencent_usage.go), and StepFun's Step Plan,
|
||||
// Tencent Cloud's Token Plan Enterprise and Alibaba Cloud's Token Plan, read
|
||||
// with the account's access key (volcengine_usage.go, tencent_usage.go,
|
||||
// alibaba_usage.go), and StepFun's Step Plan,
|
||||
// read with magpie's sign-in to its platform (stepfun_plan.go). The
|
||||
// Usage page had their windows while routing had none, and the Routing
|
||||
// page said "one key" of a plan with them (chen on Discord). "" for any
|
||||
@@ -90,6 +91,9 @@ func accountPlanOf(p Provider) string {
|
||||
if _, ok := tencentPlanRegion(p); ok && keyed {
|
||||
return "tencent"
|
||||
}
|
||||
if _, ok := aliPlanSite(p); ok && keyed {
|
||||
return "alibaba"
|
||||
}
|
||||
if StepFunSite(p) != "" {
|
||||
return "stepfun"
|
||||
}
|
||||
@@ -112,6 +116,9 @@ func accountPlanWindows(ctx context.Context, q Provider) (keyReading, error) {
|
||||
return keyReading{}, nil
|
||||
}
|
||||
c = cs[0]
|
||||
case "alibaba":
|
||||
site, _ := aliPlanSite(q)
|
||||
c = aliPlanQuota(q.Via(ctx), q, site)
|
||||
case "stepfun":
|
||||
if !StepFunSignedIn(q.ID) {
|
||||
return keyReading{}, nil
|
||||
@@ -279,6 +286,9 @@ func keyCardTag(p Provider) string {
|
||||
return keyTag("volc "+action, p.AccessKeyID)
|
||||
case "tencent":
|
||||
return keyTag("tencent", p.AccessKeyID)
|
||||
case "alibaba":
|
||||
site, _ := aliPlanSite(p)
|
||||
return keyTag("alibaba "+site.region, p.AccessKeyID)
|
||||
case "stepfun":
|
||||
return keyTag("stepfun", p.ID)
|
||||
}
|
||||
|
||||
@@ -886,6 +886,8 @@ func PlanQuotas(ctx context.Context) []SubscriptionQuota {
|
||||
go func() { volc <- volcPlanQuotas(ctx) }()
|
||||
tencent := make(chan []SubscriptionQuota, 1)
|
||||
go func() { tencent <- tencentPlanQuotas(ctx) }()
|
||||
ali := make(chan []SubscriptionQuota, 1)
|
||||
go func() { ali <- aliPlanQuotas(ctx) }()
|
||||
wg.Wait()
|
||||
out := []SubscriptionQuota{}
|
||||
for i, q := range got {
|
||||
@@ -895,8 +897,8 @@ func PlanQuotas(ctx context.Context) []SubscriptionQuota {
|
||||
out = append(out, *q)
|
||||
}
|
||||
}
|
||||
// StepFun's, Volcengine's and Tencent's, read just now too
|
||||
for _, qs := range [][]SubscriptionQuota{<-stepfun, <-volc, <-tencent} {
|
||||
// StepFun's, Volcengine's, Tencent's and Alibaba's, read just now too
|
||||
for _, qs := range [][]SubscriptionQuota{<-stepfun, <-volc, <-tencent, <-ali} {
|
||||
for _, q := range qs {
|
||||
out = append(out, readNow(q))
|
||||
}
|
||||
|
||||
@@ -412,8 +412,10 @@ var presets = []PresetDef{
|
||||
// token-plan.maas.qianwenaiapi.com, and on Alibaba Cloud Bailian
|
||||
// (bailian.console.aliyun.com) at token-plan.cn-beijing.maas.aliyuncs.com
|
||||
// (#1506). The models given are the plans' text models as their
|
||||
// overviews list them, for when the host gives no list. Neither has an
|
||||
// API for the plan's credits: its console's subscription page shows them.
|
||||
// overviews list them, for when the host gives no list. Only the
|
||||
// two at aliyuncs.com have a way to read the plan's credits, with the
|
||||
// account's AccessKey (alibaba_usage.go); the Qwen AI platform's console
|
||||
// takes a browser sign-in (#5829).
|
||||
{ID: "qwen-token-plan", Name: "Qwen Token Plan", Short: "Qwen Plan", Icon: "qwen-color", Kind: KindVendor,
|
||||
Chat: "https://token-plan.maas.qianwenaiapi.com/compatible-mode/v1", Anthropic: "https://token-plan.maas.qianwenaiapi.com/apps/anthropic",
|
||||
Note: "Qwen AI platform · subscription",
|
||||
@@ -429,6 +431,14 @@ var presets = []PresetDef{
|
||||
Note: "Alibaba Cloud Bailian · subscription",
|
||||
Website: "https://help.aliyun.com/zh/model-studio/token-plan-overview", KeysURL: "https://bailian.console.aliyun.com/cn-beijing/subscription/token-plan/personal",
|
||||
Models: alibabaPlanModels},
|
||||
// Alibaba Cloud's international Token Plan, the same plan at the
|
||||
// Singapore host (sk-sp- keys, #2940). Its quota is read like Bailian's,
|
||||
// with the account's AccessKey (alibaba_usage.go).
|
||||
{ID: "alibaba-token-plan", Name: "Alibaba Cloud Token Plan", Short: "Alibaba Plan", Icon: "bailian-color", Kind: KindVendor,
|
||||
Chat: "https://token-plan.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1", Anthropic: "https://token-plan.ap-southeast-1.maas.aliyuncs.com/apps/anthropic",
|
||||
Note: "Alibaba Cloud Model Studio · subscription",
|
||||
Website: "https://www.alibabacloud.com/help/en/model-studio/token-plan-personal-quick-start", KeysURL: "https://modelstudio.console.alibabacloud.com/ap-southeast-1/?tab=globalset#/efm/token_plan",
|
||||
Models: alibabaPlanModels},
|
||||
// Qwen Cloud (qwencloud.com) is Alibaba's international Qwen platform,
|
||||
// on keys of its own made at home.qwencloud.com, at
|
||||
// {region}.maas.qwencloudapi.com (docs.qwencloud.com, "Regions and
|
||||
|
||||
@@ -70,7 +70,9 @@ type Provider struct {
|
||||
// key (TakesVolcAccessKey), what Ark tells its Coding or Agent Plan's
|
||||
// windows to (volcengine_usage.go), or a Tencent Cloud account's API
|
||||
// key, its SecretId and SecretKey (TakesTencentAccessKey), what TokenHub
|
||||
// tells Token Plan 企业版's usage to (tencent_usage.go); not the plan's
|
||||
// tells Token Plan 企业版's usage to (tencent_usage.go), or an Alibaba
|
||||
// Cloud account's AccessKey ID and Secret (TakesAlibabaAccessKey), what
|
||||
// its console tells a Token Plan's usage to (alibaba_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"`
|
||||
|
||||
@@ -62,13 +62,15 @@ func TakesTencentAccessKey(p Provider) bool {
|
||||
|
||||
// AccessKeyVendor is whose account access key p's plan is read with:
|
||||
// "volcengine" (Ark's Coding and Agent Plans), "tencent" (Token Plan
|
||||
// 企业版), or "" for none.
|
||||
// 企业版), "alibaba" (Token Plan on aliyuncs.com), or "" for none.
|
||||
func AccessKeyVendor(p Provider) string {
|
||||
switch {
|
||||
case TakesVolcAccessKey(p):
|
||||
return "volcengine"
|
||||
case TakesTencentAccessKey(p):
|
||||
return "tencent"
|
||||
case TakesAlibabaAccessKey(p):
|
||||
return "alibaba"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user