provider, gui: Token Plan 企业版 shows its usage on the Usage page, read with the account's SecretId and SecretKey (#1574, undirectlookable)
#1574 asks for Tencent Cloud Token Plan's usage on the Usage page through TokenHub's cloud API (api/1823/132270). That API covers the enterprise plan only (Token Plan 企业版; the previous commit added its regions). The personal plan (api.lkeap.cloud.tencent.com/plan) has no usage API, only the console, so it has no card. The API takes the account's API key, a SecretId and SecretKey signed TC3-HMAC-SHA256, never the plan's sk- key. provider (tencent_usage.go): - A provider at /plan on tokenhub.tencentmaas.com (ap-guangzhou) or tokenhub-intl.tencentmaas.com (ap-singapore) with a SecretId and SecretKey gets a card per team plan in PlanQuotas (tencentPlanQuotas), each key and region asked once. - It asks DescribeTokenPlanList, then DescribeTokenPlan per plan (version 2026-03-22), all at tokenhub.tencentcloudapi.com. Where a reply leaves a part out, the list's copy of it is kept. - The window is TotalUsed of CycleQuota (else TotalQuota), in credits (专业套餐) or tokens (轻享套餐, enterprise-auto). It resets at TokenSummary.CycleEndTime. Without that, it counts months from StartTime and stops at ExpireTime. - The docs don't say whether TotalUsed is the cycle's or the package's. This reads it as the cycle's. - A plan that isn't enable shows its status beside the plan's name. - An AuthFailure or UnauthorizedOperation reply says to check the key and its CAM rights. No plan visible to the key says so (a sub-user sees only the plans it made). - The SecretId and SecretKey sit in the AccessKeyID and SecretAccessKey fields Volcengine's access key uses (#1427). They are stored, kept out of key-less backups and dropped from cached cards the same way. AccessKeyVendor tells the two vendors apart. gui: - The listing tells whose access key a provider or preset takes. presetAccessKey lists the regions that take one: Tencent Cloud's two Enterprise regions. - The editor names the fields SecretId and SecretKey, with Tencent's hint, and shows them only at those regions (or at an endpoint none of the regions has). - A SecretId with no SecretKey is refused only where the fields are shown. The new strings are in zh, zh-TW, ja and de. - docs/subsystems/providers-accounts.md and the GUI tests README describe it. Run: - TestTC3SignMatchesDoc pins the signing doc's worked example (payload hash 35e9c5b0…, Signature 10b1a37a…). - TestTencentPlanRegion, TestTencentPlanWindow and TestTencentPlanQuotas use the API docs' own response examples. The last is an httptest fake that rechecks each TC3 signature and the X-TC-* headers, and fails if the plan's key is ever sent. - TestProviderListTellsTencentAccessKey covers the listing, alongside TestVolc* and TestPlanQuotas. - Breaking the action's lowercasing in the signature, or dropping TokenSummary, turns them red. - GUI: tencent-access-key.test.cjs (new) 12/12 in Chromium and WebKit at 420px, en and zh. It goes red with the region hook or the vendor labels taken out. volc-access-key, tencent-cloud, i18n-keys, gui-ja and gui-de pass. - gofmt; go vet on darwin, linux and windows; the full go test ./... Not tried against the real API: we have no Tencent Cloud account. What is read is what the docs show, and the reporter is asked to try it.
This commit is contained in:
@@ -35,7 +35,7 @@ keys and accounts per request is in [Gateway routing and fallback](gateway-routi
|
||||
| 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`); a list that didn't ask gets no prices (a remote request without a valid key never reaches the list: `lanGuard` refuses it). 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 remote magpie's service tiers | A remote magpie's `/v1/models`, asked with `X-Magpie-Drawers` (`DrawersHeader`), gives each model the `service_tiers` its own Codex is offered on it (`codexTiers` → `codexcat.ServiceTiers`, from the same `CodexCatalog` and `codexcat.Entries` as its `/v1/codex/models`: Fast on a ChatGPT account's GPT model, the tiers of Codex's own entry on a relay's, none on a model it offers none). The local keeps the ids (`catalog.Model.Tiers` → `Entry.Tiers`), `codexListed` hands them on for the remote's models, and `codexcat.Entries` offers them to the local Codex with Codex's own names (`namedTiers`). The gateway sends the tier Codex asks for to a remote magpie as it was asked (`Request.OwnTier`, as for a provider added by its address; dropped and not sent again if refused), and the remote serves it as its own Codex's turn (#1234). A remote from before this sends no tiers, and its models are offered none, as before. | [`codexcat.go`](../../internal/codexcat/codexcat.go), [`codex_models.go`](../../internal/provider/codex_models.go), [`codex_catalog.go`](../../internal/gateway/codex_catalog.go), [`gateway.go`](../../internal/gateway/gateway.go), [`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. 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) |
|
||||
| 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. Nor is Tencent Cloud's Token Plan 企业版 (#1574): what a team plan has used of its cycle's credits (专业套餐) or tokens (轻享套餐) is told only to the account's SecretId and SecretKey (kept as `AccessKeyID`, `SecretAccessKey`), asked of `tokenhub.tencentcloudapi.com` (`DescribeTokenPlanList`, `DescribeTokenPlan`, version 2026-03-22) and signed TC3-HMAC-SHA256 (`tc3Sign`), one card per team plan (`tencentPlanQuotas`). | [`sub2api_usage.go`](../../internal/provider/sub2api_usage.go), [`key_allowance.go`](../../internal/provider/key_allowance.go), [`volcengine_usage.go`](../../internal/provider/volcengine_usage.go), [`tencent_usage.go`](../../internal/provider/tencent_usage.go) |
|
||||
| Account names and seats | `AccountNames` (by the account, in lower case, like `AccountCaps`) are names the user gives accounts, set by `SetAccountName` (GUI `provider/accountname`, `magpie accounts alias`); they live in providers.json only, never in a vendor's or plugin's sign-in. A GLM Coding Plan read with a key (`glmPlan`) and a ZCode account (built-in or `zcode-plugin`) whose windows' resets agree are one seat (`seatMatch`, #90/#953), shown once, on the account's card (`seatCards`, used by `quotas`, `Allotted` and `CachedCards`). A match is remembered in `seats.json` beside `quotas.json`: a failed read or a window with no reset yet is unknown and keeps the key's card off while the account is signed in; windows that disagree forget it (#1515). Cards carry `Seat` (the key provider's name, and the key's when it has several) and `Alias` (the user's name, else `Seat`), as `/v1/magpie/quotas`, `magpie quota` and `magpie accounts` do. | [`account_names.go`](../../internal/provider/account_names.go), [`account_seats.go`](../../internal/provider/account_seats.go) |
|
||||
| Last served | `served.json` records when each account, plan or key last answered, shown as `lastServedAt` (#570) on `/v1/magpie/quotas` and on the Usage page's own cards (`Quotas` → `cardsServed`, this computer's cards only, the caches left alone). The Usage page and the tray panel show the last-answered account in full, and a menu bar card that follows the account in use (`codex|*`) takes the one that answered within the last hour, else `InUseLogin`'s guess, else the one that answered last at all (a plugin's accounts, #1516) (`trayInUseCard`; okingkee on X: A spent, B answering, the menu bar stayed on A). `NoteServed` calls `OnServedMoved` when a provider's answers move to another account or key, and `SwitchLogin` after a switch, so the menu bar reads its cards again at once. | [`served.go`](../../internal/provider/served.go), [`trayusage.go`](../../internal/gui/trayusage.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) |
|
||||
@@ -109,6 +109,7 @@ Account discovery can be turned off (#1535): Settings → Privacy → *Subscript
|
||||
- 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`).
|
||||
- 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`); the personal plan (`api.lkeap.cloud.tencent.com`) has no usage API and TokenHub's pay as you go no plan, so neither has a card. 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.
|
||||
- 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.
|
||||
@@ -130,8 +131,10 @@ node --test internal/gui/tests/account-cap.test.cjs internal/gui/tests/window-ca
|
||||
go test -tags nogui ./internal/provider -run 'TestRemoteMagpie'
|
||||
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/provider -run 'TestTC3|TestTencent'
|
||||
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
|
||||
node --test internal/gui/tests/volc-access-key.test.cjs internal/gui/tests/tencent-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'
|
||||
|
||||
@@ -8564,16 +8564,21 @@ function drawEditor(p, presetID) {
|
||||
}
|
||||
|
||||
// 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;
|
||||
// account's access key, never to the plan's key (#1427), and Tencent
|
||||
// Cloud a Token Plan 企业版's only to its SecretId and SecretKey (#1574),
|
||||
// asked only at the regions that are that plan; the saved Secret is
|
||||
// never sent back here, only that one is saved
|
||||
const access = p ? p.accessKey : pr?.accessKey ? { vendor: pr.accessKeyVendor || "volcengine", id: "", secretSet: false } : null;
|
||||
let accessAt = () => {}, accessShown = () => !!access;
|
||||
if (access) {
|
||||
const tc = access.vendor === "tencent";
|
||||
const idName = tc ? t("SecretId") : t("AccessKey ID"), secretName = tc ? t("SecretKey") : t("Secret Access Key");
|
||||
if (draft.accessKeyID === undefined) draft.accessKeyID = access.id || "";
|
||||
const ak = input(draft.accessKeyID, t("AccessKey ID"));
|
||||
const ak = input(draft.accessKeyID, idName);
|
||||
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");
|
||||
const sk = input(draft.secretAccessKey || "", saved ? t("saved · paste a new one to replace it") : secretName, "password");
|
||||
sk.classList.add("volc-sk");
|
||||
sk.oninput = () => { draft.secretAccessKey = sk.value.trim(); };
|
||||
sk.onkeydown = (e) => { e.stopPropagation(); if (e.key === "Escape") cancelEdit(); };
|
||||
@@ -8582,12 +8587,28 @@ function drawEditor(p, presetID) {
|
||||
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(); };
|
||||
drop.onclick = () => { draft.clearAccessKey = true; draft.accessKeyID = ""; draft.secretAccessKey = ""; ak.value = ""; sk.value = ""; sk.placeholder = secretName; 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.")));
|
||||
const rows = [
|
||||
...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.")
|
||||
: 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);
|
||||
// a preset with the plan at some of its regions only (Tencent Cloud's
|
||||
// 企业版 beside its personal plan) asks for it at those, and at an
|
||||
// endpoint none of its regions has, which may be one of them
|
||||
const at = pr?.accessKeyRegions;
|
||||
if (at?.length) {
|
||||
accessAt = (r) => {
|
||||
const on = !r || at.includes(r.id) || !regionAt(pr, draft);
|
||||
for (const x of rows) x.hidden = !on;
|
||||
};
|
||||
accessShown = () => !rows[0].hidden;
|
||||
}
|
||||
}
|
||||
|
||||
// a relay that offers several regional endpoints, or a vendor whose plans
|
||||
@@ -8608,12 +8629,14 @@ function drawEditor(p, presetID) {
|
||||
site.textContent = hostOf(site.dataset.url) + " ↗";
|
||||
}
|
||||
onRegion(r);
|
||||
accessAt(r);
|
||||
for (const x of seg.querySelectorAll(".opt")) x.classList.toggle("on", x === b);
|
||||
slide(seg, "regions");
|
||||
refreshEndpoints();
|
||||
};
|
||||
seg.append(b);
|
||||
}
|
||||
accessAt(cur);
|
||||
queueMicrotask(() => {
|
||||
slide(seg, "regions");
|
||||
// the region in use in view, where they scroll
|
||||
@@ -8841,7 +8864,7 @@ function drawEditor(p, presetID) {
|
||||
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 (accessShown() && 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 (vertex) body.vertex = vertexOfDraft();
|
||||
if (isNew && custom && !body.name) { name.focus(); return editorError(t("Give it a name"), "warn"); }
|
||||
|
||||
@@ -2665,6 +2665,9 @@ const I18N = {
|
||||
"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 查不到。填在这里,用量页就会显示它们;仅用于查询额度。",
|
||||
"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 读权限的子用户密钥即可。仅用于查询用量。",
|
||||
"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 额度",
|
||||
@@ -6927,6 +6930,9 @@ const I18N = {
|
||||
"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 查不到。填在這裡,用量頁就會顯示它們;僅用於查詢額度。",
|
||||
"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 讀取權限的子使用者金鑰即可。僅用於查詢用量。",
|
||||
"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 額度",
|
||||
@@ -11193,6 +11199,9 @@ const I18N = {
|
||||
"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 キーでは取得できません。ここに入力すると使用量ページに表示されます。それ以外には使いません。",
|
||||
"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 を読み取れるサブユーザーのキーで十分です。それ以外には使いません。",
|
||||
"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 が表示されます",
|
||||
@@ -15458,6 +15467,9 @@ const I18N = {
|
||||
"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.",
|
||||
"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.",
|
||||
"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",
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
package gui
|
||||
|
||||
// Tencent Cloud's Token Plan 企业版 is read with the account's SecretId and
|
||||
// SecretKey (#1574): the listing tells the editor the Tencent Cloud preset
|
||||
// takes one at its two Enterprise regions alone, and whose it is, and a
|
||||
// provider of it, at whatever region, its SecretId and whether a
|
||||
// SecretKey is saved, never the SecretKey. Volcengine Ark's take one at
|
||||
// all of theirs; another vendor's at none.
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
func TestProviderListTellsTencentAccessKey(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)
|
||||
|
||||
at := func(region string) provider.Provider {
|
||||
t.Helper()
|
||||
p, err := provider.FromPreset("tencent-cloud")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pr := provider.Preset("tencent-cloud")
|
||||
for _, r := range pr.Regions {
|
||||
if r.ID == region {
|
||||
p.Chat, p.Responses, p.Anthropic = r.Chat, r.Responses, r.Anthropic
|
||||
}
|
||||
}
|
||||
return p
|
||||
}
|
||||
team := at("enterprise")
|
||||
team.Key, team.AccessKeyID, team.SecretAccessKey = "sk-tp-1", "AKID-1", "SK-1"
|
||||
if err := provider.Save(team); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
personal := at("plan")
|
||||
personal.ID, personal.Name, personal.Key = "tc-personal", "Tencent personal", "sk-tp-2"
|
||||
if err := provider.Save(personal); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, httptest.NewRequest("GET", "/api/providers", nil))
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("%d %s", w.Code, w.Body)
|
||||
}
|
||||
if strings.Contains(w.Body.String(), "SK-1") {
|
||||
t.Error("the listing told the SecretKey")
|
||||
}
|
||||
var got struct {
|
||||
Providers []struct {
|
||||
ID string `json:"id"`
|
||||
AccessKey *accessKeyJSON `json:"accessKey"`
|
||||
} `json:"providers"`
|
||||
Presets []struct {
|
||||
ID string `json:"id"`
|
||||
AccessKey bool `json:"accessKey"`
|
||||
AccessKeyVendor string `json:"accessKeyVendor"`
|
||||
AccessKeyRegions []string `json:"accessKeyRegions"`
|
||||
} `json:"presets"`
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ps := map[string]*accessKeyJSON{}
|
||||
for _, x := range got.Providers {
|
||||
ps[x.ID] = x.AccessKey
|
||||
}
|
||||
if a := ps["tencent-cloud"]; a == nil || a.Vendor != "tencent" || a.ID != "AKID-1" || !a.SecretSet {
|
||||
t.Errorf("enterprise: %+v", a)
|
||||
}
|
||||
// at the personal plan it still takes one, for when it is moved
|
||||
if a := ps["tc-personal"]; a == nil || a.Vendor != "tencent" || a.ID != "" || a.SecretSet {
|
||||
t.Errorf("personal: %+v", a)
|
||||
}
|
||||
seen := 0
|
||||
for _, pr := range got.Presets {
|
||||
switch pr.ID {
|
||||
case "tencent-cloud":
|
||||
seen++
|
||||
if !pr.AccessKey || pr.AccessKeyVendor != "tencent" || !slices.Equal(pr.AccessKeyRegions, []string{"enterprise", "enterprise-intl"}) {
|
||||
t.Errorf("tencent-cloud preset: %+v", pr)
|
||||
}
|
||||
case "volcengine":
|
||||
seen++
|
||||
if !pr.AccessKey || pr.AccessKeyVendor != "volcengine" || pr.AccessKeyRegions != nil {
|
||||
t.Errorf("volcengine preset: %+v", pr)
|
||||
}
|
||||
case "deepseek":
|
||||
seen++
|
||||
if pr.AccessKey || pr.AccessKeyVendor != "" {
|
||||
t.Errorf("deepseek preset: %+v", pr)
|
||||
}
|
||||
}
|
||||
}
|
||||
if seen != 3 {
|
||||
t.Errorf("presets seen: %d", seen)
|
||||
}
|
||||
}
|
||||
+50
-14
@@ -122,9 +122,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
|
||||
// a Volcengine account's access key or a Tencent Cloud account's
|
||||
// SecretId and SecretKey, which its plan's windows are read with
|
||||
// (provider.AccessKeyVendor): whether the provider takes one, whose,
|
||||
// its ID, and whether a Secret is saved; never the Secret itself
|
||||
AccessKey *accessKeyJSON `json:"accessKey,omitempty"`
|
||||
// a Google Vertex AI provider's project, location and Google
|
||||
// credentials, which it is asked with in place of a key: set for it
|
||||
@@ -219,13 +220,36 @@ 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.
|
||||
// accessKeyJSON is a provider's account access key as the editor sees
|
||||
// it: whose ("volcengine", "tencent"), the ID, and whether a Secret is
|
||||
// saved, never the Secret.
|
||||
type accessKeyJSON struct {
|
||||
Vendor string `json:"vendor"`
|
||||
ID string `json:"id"`
|
||||
SecretSet bool `json:"secretSet"`
|
||||
}
|
||||
|
||||
// presetAccessKey is whose account access key a preset's plans are read
|
||||
// with ("volcengine", "tencent", "" for none) and, when only some of its
|
||||
// regions are such a plan (Tencent Cloud's Token Plan 企业版 beside its
|
||||
// personal plan and pay as you go, #1574), their ids; nil when all are.
|
||||
func presetAccessKey(pr provider.PresetDef) (string, []string) {
|
||||
vendor := provider.AccessKeyVendor(provider.Provider{Chat: pr.Chat, Responses: pr.Responses, Anthropic: pr.Anthropic})
|
||||
var ids []string
|
||||
for _, r := range pr.Regions {
|
||||
if v := provider.AccessKeyVendor(provider.Provider{Chat: r.Chat, Responses: r.Responses, Anthropic: r.Anthropic}); v != "" {
|
||||
ids = append(ids, r.ID)
|
||||
if vendor == "" {
|
||||
vendor = v
|
||||
}
|
||||
}
|
||||
}
|
||||
if vendor == "" || len(ids) == len(pr.Regions) {
|
||||
return vendor, nil
|
||||
}
|
||||
return vendor, ids
|
||||
}
|
||||
|
||||
type stepPlanJSON struct {
|
||||
Site string `json:"site"`
|
||||
SignedIn bool `json:"signedIn"`
|
||||
@@ -320,9 +344,13 @@ 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"`
|
||||
// AccessKey: a plan whose windows are read with the account's access
|
||||
// key (Volcengine Ark's, Tencent Cloud's Token Plan 企业版), which the
|
||||
// editor offers to take; AccessKeyVendor whose, and AccessKeyRegions
|
||||
// the regions it is asked at when not all of them (presetAccessKey)
|
||||
AccessKey bool `json:"accessKey,omitempty"`
|
||||
AccessKeyVendor string `json:"accessKeyVendor,omitempty"`
|
||||
AccessKeyRegions []string `json:"accessKeyRegions,omitempty"`
|
||||
// Vertex: it is Google Vertex AI, whose editor asks for a Google Cloud
|
||||
// project and the Google credentials to sign with, not a key
|
||||
Vertex bool `json:"vertex,omitempty"`
|
||||
@@ -501,8 +529,14 @@ 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 != ""}
|
||||
// a provider of a preset with such a plan among its regions takes one
|
||||
// wherever it is, the editor showing it at those regions
|
||||
vendor := provider.AccessKeyVendor(p)
|
||||
if pr := provider.Preset(p.Preset); vendor == "" && pr != nil {
|
||||
vendor, _ = presetAccessKey(*pr)
|
||||
}
|
||||
if vendor != "" || p.AccessKeyID != "" || p.SecretAccessKey != "" {
|
||||
out.AccessKey = &accessKeyJSON{Vendor: vendor, ID: p.AccessKeyID, SecretSet: p.SecretAccessKey != ""}
|
||||
}
|
||||
if p.IsVertex() {
|
||||
out.Vertex = &provider.Vertex{}
|
||||
@@ -732,7 +766,8 @@ func providersState() providersJSON {
|
||||
for _, pr := range provider.Presets() {
|
||||
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), Vertex: pr.ID == provider.VertexPreset})
|
||||
vendor, keyRegions := presetAccessKey(pr)
|
||||
s.Presets = append(s.Presets, presetJSON{PresetDef: pr, Added: have[pr.ID], ZhipuTeam: team, AccessKey: vendor != "", AccessKeyVendor: vendor, AccessKeyRegions: keyRegions, Vertex: pr.ID == provider.VertexPreset})
|
||||
}
|
||||
cat := provider.Catalog()
|
||||
s.Gateway = gatewayJSON{URL: gateway.URL(), OnNetwork: gateway.OnNetwork(), Models: len(cat), Calls: []gateway.Call{}, Groups: []gwGroupJSON{}}
|
||||
@@ -967,9 +1002,10 @@ 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 is a Volcengine access key's ID or a Tencent
|
||||
// Cloud SecretId, "" for none; a save that leaves it out keeps
|
||||
// it. Its Secret (SecretAccessKey, a Tencent SecretKey) 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
|
||||
|
||||
@@ -2241,3 +2241,22 @@ zh, zh-TW, ja and de. English and Chinese, Chromium and WebKit.
|
||||
node --test internal/gui/tests/volc-access-key.test.cjs
|
||||
go test -tags nogui ./internal/gui -run TestProviderSaveKeepsVolcengineSecret
|
||||
```
|
||||
|
||||
## Tencent Cloud SecretId and SecretKey
|
||||
|
||||
`tencent-access-key.test.cjs` covers #1574: Token Plan 企业版's usage is told
|
||||
only to the account's SecretId and SecretKey, so a Tencent Cloud provider's
|
||||
editor asks for them, named so, with Tencent's hint, at the two Enterprise
|
||||
plan regions alone (the preset's `accessKeyRegions`). At the personal plan
|
||||
or pay as you go they are hidden and come back when an Enterprise region is
|
||||
picked; a SecretId with no SecretKey is refused only where they are shown.
|
||||
The saved SecretKey is never in the page; Save, a new SecretKey and Remove
|
||||
post as Ark's do. Saved at Enterprise, saved at the personal plan, and being
|
||||
added; 420px wide with no sideways scroll; every string in zh, zh-TW, ja
|
||||
and de. English and Chinese, Chromium and WebKit.
|
||||
`TestProviderListTellsTencentAccessKey` checks what the listing tells.
|
||||
|
||||
```sh
|
||||
node --test internal/gui/tests/tencent-access-key.test.cjs
|
||||
go test -tags nogui ./internal/gui -run TestProviderListTellsTencentAccessKey
|
||||
```
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// Tencent Cloud's Token Plan 企业版 tells its usage only to the account's
|
||||
// API key, a SecretId and SecretKey (#1574): a Tencent Cloud provider's
|
||||
// editor asks for them, named so, at the Enterprise plan regions only. At
|
||||
// the personal plan or pay as you go they are hidden, and come back when
|
||||
// an Enterprise region is picked. The saved SecretKey is never shown, only
|
||||
// that one is saved; Save posts the SecretId and a SecretKey only when a new
|
||||
// one was typed, Remove posts clearAccessKey, and a SecretId with no
|
||||
// SecretKey is refused at an Enterprise region, never at one that hides
|
||||
// them. A 420px window; English and Chinese, 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 plan = { chat: "https://api.lkeap.cloud.tencent.com/plan/v3", anthropic: "https://api.lkeap.cloud.tencent.com/plan/anthropic" };
|
||||
const cn = { chat: "https://tokenhub.tencentmaas.com/v1", responses: "https://tokenhub.tencentmaas.com/v1", anthropic: "https://tokenhub.tencentmaas.com" };
|
||||
const intl = { chat: "https://tokenhub-intl.tencentmaas.com/v1", responses: "https://tokenhub-intl.tencentmaas.com/v1", anthropic: "https://tokenhub-intl.tencentmaas.com" };
|
||||
const ent = { chat: "https://tokenhub.tencentmaas.com/plan/v3", responses: "https://tokenhub.tencentmaas.com/plan/v3", anthropic: "https://tokenhub.tencentmaas.com/plan/anthropic" };
|
||||
const entIntl = { chat: "https://tokenhub-intl.tencentmaas.com/plan/v3", responses: "https://tokenhub-intl.tencentmaas.com/plan/v3", anthropic: "https://tokenhub-intl.tencentmaas.com/plan/anthropic" };
|
||||
// as /api/providers serves the preset: an access key at the two
|
||||
// Enterprise regions alone (presetAccessKey)
|
||||
const tencent = (added) => ({
|
||||
id: "tencent-cloud", name: "Tencent Cloud", icon: "tencentcloud-color", kind: "vendor", hosts: true, added, chat: plan.chat, anthropic: plan.anthropic,
|
||||
accessKey: true, accessKeyVendor: "tencent", accessKeyRegions: ["enterprise", "enterprise-intl"],
|
||||
regions: [{ id: "plan", name: "Plan · China", ...plan }, { id: "cn", name: "Pay as you go · China", ...cn }, { id: "intl", name: "Pay as you go · Global", ...intl },
|
||||
{ id: "enterprise", name: "Enterprise plan · China", ...ent }, { id: "enterprise-intl", name: "Enterprise plan · Global", ...entIntl }],
|
||||
});
|
||||
const saved = (id, name, at, accessKey) => ({
|
||||
id, name, icon: "tencentcloud-color", preset: "tencent-cloud", ...at, catalog: "",
|
||||
models: [{ id: "hy3", name: "hy3", on: true }], agents: [], fallback: [], headers: {},
|
||||
key: { set: true, masked: "sk-tp…ab12" }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "", accessKey,
|
||||
});
|
||||
const team = saved("tencent-cloud", "Tencent Cloud", ent, { vendor: "tencent", id: "AKIDsaved", secretSet: true });
|
||||
const relay = {
|
||||
id: "relay", name: "Relay", icon: "generic", chat: "https://relay.example.com/v1", responses: "", anthropic: "", catalog: "",
|
||||
models: [], agents: [], fallback: [], headers: {}, key: { set: true, masked: "sk-…one" }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "",
|
||||
};
|
||||
const personal = saved("tc-personal", "Tencent personal", plan, { vendor: "tencent", id: "", secretSet: false });
|
||||
|
||||
function serve(lang, list, posts) {
|
||||
const providers = { providers: list, presets: [tencent(list.some((x) => x.preset === "tencent-cloud"))], excluded: [], gateway: { running: true, window: true } };
|
||||
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({ agents: [], profiles: [], settings: { lang, theme: "light" } });
|
||||
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 hint = "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.";
|
||||
const strings = ["SecretId", "SecretKey", hint, "Enterprise plan · China", "Enterprise plan · Global"];
|
||||
const words = {
|
||||
en: { saved: "saved · paste a new one to replace it", remove: "Remove", save: "Save", add: "Add", one: "Give the access key's Secret too" },
|
||||
zh: { saved: "已保存 · 粘贴新的即可替换", remove: "移除", save: "保存", add: "添加", one: "请同时填写访问密钥的 Secret" },
|
||||
};
|
||||
// the region buttons in the preset's order
|
||||
const PLAN = 0, CN = 1, ENT = 3, ENT_INTL = 4;
|
||||
|
||||
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, list) => {
|
||||
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}-tencent-access-key.png`), fullPage: true });
|
||||
}
|
||||
await browser.close();
|
||||
});
|
||||
const page = await (await browser.newContext({ viewport: { width: 420, height: 760 }, reducedMotion: "reduce" })).newPage();
|
||||
page.setDefaultTimeout(5000);
|
||||
const errors = [];
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
const posts = [];
|
||||
await page.route("**/*", serve(lang, list, posts));
|
||||
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 region = async (page, i) => {
|
||||
const b = page.locator(".editor .segs.regions .opt").nth(i);
|
||||
await b.scrollIntoViewIfNeeded();
|
||||
await b.click();
|
||||
};
|
||||
const shown = async (page) => {
|
||||
const [a, s] = [await ak(page).isVisible(), await sk(page).isVisible()];
|
||||
assert.equal(a, s, "both or neither");
|
||||
return a;
|
||||
};
|
||||
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;
|
||||
};
|
||||
const fits = async (page) => {
|
||||
const over = await page.evaluate(() => document.documentElement.scrollWidth - document.documentElement.clientWidth);
|
||||
assert(over <= 0, `the page scrolls sideways by ${over}px`);
|
||||
};
|
||||
|
||||
test(`${engine} ${lang}: an Enterprise plan provider asks for its SecretId and SecretKey, kept, replaced and removed`, async (t) => {
|
||||
const { page, errors, posts } = await start(t, "team", [team, personal]);
|
||||
await edit(page, "Tencent Cloud");
|
||||
const labels = await page.locator(".editor label").allTextContents();
|
||||
assert(labels.includes("SecretId") && labels.includes("SecretKey"), labels.join(" | "));
|
||||
assert(!labels.includes("AccessKey ID"), "named as Tencent names them");
|
||||
assert(await shown(page));
|
||||
assert.equal(await ak(page).inputValue(), "AKIDsaved");
|
||||
assert.equal(await sk(page).inputValue(), "", "the saved SecretKey is not shown");
|
||||
assert.equal(await sk(page).getAttribute("type"), "password");
|
||||
assert.equal(await sk(page).getAttribute("placeholder"), w.saved);
|
||||
const tip = await page.locator(".editor .hint").allTextContents();
|
||||
assert(tip.some((x) => x.includes("TokenHub")), tip.join(" | "));
|
||||
assert(!tip.some((x) => x.includes("Volcengine") || x.includes("火山")), "not Volcengine's hint");
|
||||
await fits(page);
|
||||
|
||||
// the personal plan has no usage API: hidden; Enterprise · Global
|
||||
// brings them back
|
||||
await region(page, PLAN);
|
||||
assert.equal(await shown(page), false, "hidden at the personal plan");
|
||||
await region(page, CN);
|
||||
assert.equal(await shown(page), false, "hidden at pay as you go");
|
||||
await region(page, ENT_INTL);
|
||||
assert(await shown(page), "shown at Enterprise · Global");
|
||||
assert.equal(await ak(page).inputValue(), "AKIDsaved", "what was there is kept");
|
||||
|
||||
// left as it is: the SecretId posted, no SecretKey, nothing cleared
|
||||
let body = (await press(page, posts, w.save)).body;
|
||||
assert.equal(body.accessKeyID, "AKIDsaved");
|
||||
assert.equal(body.chat, entIntl.chat);
|
||||
assert(!("secretAccessKey" in body) && !("clearAccessKey" in body), JSON.stringify(body));
|
||||
|
||||
// a new SecretKey, trimmed
|
||||
await edit(page, "Tencent Cloud");
|
||||
await sk(page).fill(" new-secret ");
|
||||
body = (await press(page, posts, w.save)).body;
|
||||
assert.equal(body.secretAccessKey, "new-secret");
|
||||
|
||||
// Remove clears both; the placeholder names the SecretKey
|
||||
await edit(page, "Tencent Cloud");
|
||||
await page.locator(".editor").getByRole("button", { name: w.remove, exact: true }).first().click();
|
||||
assert.equal(await ak(page).inputValue(), "");
|
||||
assert.equal(await sk(page).getAttribute("placeholder"), "SecretKey");
|
||||
body = (await press(page, posts, w.save)).body;
|
||||
assert.equal(body.accessKeyID, "");
|
||||
assert.equal(body.clearAccessKey, true);
|
||||
|
||||
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}: a personal plan provider has them hidden, and Enterprise · China asks for both`, async (t) => {
|
||||
const { page, errors, posts } = await start(t, "personal", [team, personal]);
|
||||
await edit(page, "Tencent personal");
|
||||
assert.equal(await ak(page).count(), 1);
|
||||
assert.equal(await shown(page), false, "hidden at the personal plan");
|
||||
let body = (await press(page, posts, w.save)).body;
|
||||
assert.equal(body.id, "tc-personal");
|
||||
assert(!body.accessKeyID && !("secretAccessKey" in body), JSON.stringify(body));
|
||||
|
||||
await edit(page, "Tencent personal");
|
||||
await region(page, ENT);
|
||||
assert(await shown(page));
|
||||
assert.notEqual(await sk(page).getAttribute("placeholder"), w.saved, "nothing is saved yet");
|
||||
await ak(page).fill(" AKIDnew ");
|
||||
assert.equal(await press(page, posts, w.save), null, "a SecretId with no SecretKey posts nothing");
|
||||
assert.equal(await page.locator(".editor .editor-error").textContent(), w.one);
|
||||
await sk(page).fill("sk-new");
|
||||
body = (await press(page, posts, w.save)).body;
|
||||
assert.equal(body.chat, ent.chat);
|
||||
assert.equal(body.accessKeyID, "AKIDnew");
|
||||
assert.equal(body.secretAccessKey, "sk-new");
|
||||
await fits(page);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
|
||||
test(`${engine} ${lang}: Tencent Cloud being added asks for them at an Enterprise region only`, async (t) => {
|
||||
const { page, errors, posts } = await start(t, "add", [relay]);
|
||||
await page.locator("#addProvider").click();
|
||||
await page.locator('#addSheet .tile[data-pick="Tencent Cloud"]').click();
|
||||
await page.locator(".editor.new").waitFor();
|
||||
assert.equal(await shown(page), false, "hidden at the plan it opens at");
|
||||
await region(page, ENT);
|
||||
assert(await shown(page));
|
||||
const labels = await page.locator(".editor label").allTextContents();
|
||||
assert(labels.includes("SecretId") && labels.includes("SecretKey"), labels.join(" | "));
|
||||
await page.locator(".editor.new input[type=password]").first().fill("sk-tp-key");
|
||||
await ak(page).fill("AKIDadd");
|
||||
// moved back to the personal plan, a SecretId alone is no reason to refuse
|
||||
await region(page, PLAN);
|
||||
const body = (await press(page, posts, w.add)).body;
|
||||
assert.equal(body.new, true);
|
||||
assert.equal(body.preset, "tencent-cloud");
|
||||
assert.equal(body.chat, plan.chat);
|
||||
assert(!("secretAccessKey" in body));
|
||||
await fits(page);
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -2,11 +2,12 @@ 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, 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; Volcengine only
|
||||
// to the account's access key, volcengine_usage.go): the Usage page shows
|
||||
// them beside the subscriptions'.
|
||||
// Plan, StepFun's Step Plan, Volcengine Ark's Coding and Agent Plans and
|
||||
// Tencent Cloud's Token Plan 企业版 — has windows of allowance like a
|
||||
// subscription's, which the vendor tells to the key (StepFun only to a
|
||||
// sign-in, stepfun_plan.go; Volcengine and Tencent Cloud only to the
|
||||
// account's access key, volcengine_usage.go and tencent_usage.go): the
|
||||
// Usage page shows them beside the subscriptions'.
|
||||
|
||||
import (
|
||||
"context"
|
||||
@@ -560,7 +561,7 @@ var planQuotaCache struct {
|
||||
}
|
||||
|
||||
// ForgetPlanQuotas has the next PlanQuotas ask again, after what a plan's
|
||||
// windows are read with changed (a Volcengine access key).
|
||||
// windows are read with changed (a Volcengine or Tencent Cloud access key).
|
||||
func ForgetPlanQuotas() { forgetPlanQuotas() }
|
||||
|
||||
// PlanQuotas is the windows of every plan magpie has a key for, each key
|
||||
@@ -659,6 +660,8 @@ func PlanQuotas(ctx context.Context) []SubscriptionQuota {
|
||||
go func() { stepfun <- stepPlanQuotas(ctx) }()
|
||||
volc := make(chan []SubscriptionQuota, 1)
|
||||
go func() { volc <- volcPlanQuotas(ctx) }()
|
||||
tencent := make(chan []SubscriptionQuota, 1)
|
||||
go func() { tencent <- tencentPlanQuotas(ctx) }()
|
||||
wg.Wait()
|
||||
out := []SubscriptionQuota{}
|
||||
for i, q := range got {
|
||||
@@ -670,6 +673,7 @@ func PlanQuotas(ctx context.Context) []SubscriptionQuota {
|
||||
}
|
||||
out = append(out, <-stepfun...)
|
||||
out = append(out, <-volc...)
|
||||
out = append(out, <-tencent...)
|
||||
if ctx.Err() == nil {
|
||||
noteQuotaHistory(out, time.Now())
|
||||
c.Lock()
|
||||
|
||||
@@ -54,8 +54,10 @@ type Provider struct {
|
||||
|
||||
// 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
|
||||
// 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
|
||||
// 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"`
|
||||
|
||||
@@ -0,0 +1,388 @@
|
||||
package provider
|
||||
|
||||
// Tencent Cloud's Token Plan 企业版 (#1574, undirectlookable) tells what a
|
||||
// team's plan has used of its cycle's credits (专业套餐) or tokens (轻享套餐)
|
||||
// only to TokenHub's cloud API (api/1823/132270): DescribeTokenPlanList
|
||||
// and DescribeTokenPlan on tokenhub.tencentcloudapi.com, version
|
||||
// 2026-03-22, signed TC3-HMAC-SHA256 with the account's API key, a
|
||||
// SecretId and SecretKey (AccessKeyID, SecretAccessKey), never with the
|
||||
// plan's own sk- key. The plan a provider is on is its endpoint's: /plan
|
||||
// on tokenhub.tencentmaas.com is the enterprise plan in Guangzhou, on
|
||||
// tokenhub-intl.tencentmaas.com in Singapore. The personal plan
|
||||
// (api.lkeap.cloud.tencent.com) has no API for its usage, only the
|
||||
// console, and TokenHub's pay as you go no plan: neither has a card.
|
||||
//
|
||||
// The request is signed as Tencent's signing doc (api/213/30654) says:
|
||||
// the canonical request with content-type, host and x-tc-action signed,
|
||||
// the scope date/service/tc3_request, and a key derived from "TC3" and
|
||||
// the SecretKey. TestTC3SignMatchesDoc pins the doc's own example.
|
||||
//
|
||||
// Not tried against the real API: magpie has no Tencent Cloud account.
|
||||
// What is read is the docs' reply: TotalUsed of CycleQuota (else
|
||||
// TotalQuota), resetting at TokenSummary's CycleEndTime.
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
tcAPIHost = "tokenhub.tencentcloudapi.com"
|
||||
tcAPIVersion = "2026-03-22"
|
||||
tcAPIService = "tokenhub"
|
||||
tcContentType = "application/json; charset=utf-8"
|
||||
tcPlanName = "Token Plan Enterprise"
|
||||
tcKeyHint = "check the SecretId and SecretKey in the provider's editor (Tencent Cloud console → Access management → API keys), and that the key may read TokenHub (CAM)"
|
||||
)
|
||||
|
||||
// TakesTencentAccessKey says p is on Tencent Cloud's Token Plan 企业版 (at
|
||||
// /plan on TokenHub's hosts), whose editor then asks for the account's
|
||||
// SecretId and SecretKey.
|
||||
func TakesTencentAccessKey(p Provider) bool {
|
||||
_, ok := tencentPlanRegion(p)
|
||||
return ok
|
||||
}
|
||||
|
||||
// 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.
|
||||
func AccessKeyVendor(p Provider) string {
|
||||
switch {
|
||||
case TakesVolcAccessKey(p):
|
||||
return "volcengine"
|
||||
case TakesTencentAccessKey(p):
|
||||
return "tencent"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// tencentPlanRegion is the cloud API region of the enterprise plan p's
|
||||
// endpoint is on: ap-guangzhou for tokenhub.tencentmaas.com/plan,
|
||||
// ap-singapore for tokenhub-intl.tencentmaas.com/plan; ok false for
|
||||
// TokenHub's pay as you go, the personal plan or another vendor.
|
||||
func tencentPlanRegion(p Provider) (string, bool) {
|
||||
if p.Account != nil {
|
||||
return "", false
|
||||
}
|
||||
for _, base := range []string{p.Chat, p.Responses, p.Anthropic} {
|
||||
u, err := url.Parse(base)
|
||||
if err != nil || !strings.HasPrefix(strings.TrimSuffix(u.Path, "/")+"/", "/plan/") {
|
||||
continue
|
||||
}
|
||||
switch strings.ToLower(u.Hostname()) {
|
||||
case "tokenhub.tencentmaas.com":
|
||||
return "ap-guangzhou", true
|
||||
case "tokenhub-intl.tencentmaas.com":
|
||||
return "ap-singapore", true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// tencentPlanQuotas is a card for each Token Plan 企业版 team plan the
|
||||
// account of a provider in use has, read with its SecretId and SecretKey:
|
||||
// each account and region asked once, its cards named for the first such
|
||||
// provider.
|
||||
func tencentPlanQuotas(ctx context.Context) []SubscriptionQuota {
|
||||
type job struct {
|
||||
p Provider
|
||||
region string
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
var jobs []job
|
||||
for _, p := range All() {
|
||||
if p.Hidden || p.Off || p.AccessKeyID == "" || p.SecretAccessKey == "" {
|
||||
continue
|
||||
}
|
||||
region, ok := tencentPlanRegion(p)
|
||||
if !ok || seen[p.AccessKeyID+" "+region] || !wantsCard(ctx, p.ID, "") {
|
||||
continue
|
||||
}
|
||||
seen[p.AccessKeyID+" "+region] = true
|
||||
jobs = append(jobs, job{p, region})
|
||||
}
|
||||
got := make([][]SubscriptionQuota, len(jobs))
|
||||
var wg sync.WaitGroup
|
||||
for i, j := range jobs {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
got[i] = tencentPlanCards(ctx, j.p, j.region, time.Now)
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
out := []SubscriptionQuota{}
|
||||
for _, qs := range got {
|
||||
out = append(out, qs...)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// tencentPlanCards is the account's team plans in region as cards, each
|
||||
// showing what was last read when a read fails in passing.
|
||||
func tencentPlanCards(ctx context.Context, p Provider, region string, now func() time.Time) []SubscriptionQuota {
|
||||
via := p.Via(ctx)
|
||||
card := func(user string) SubscriptionQuota {
|
||||
return SubscriptionQuota{Provider: p.ID, Name: p.Name, Icon: p.Icon, Plan: tcPlanName, User: user, Windows: []QuotaWindow{}}
|
||||
}
|
||||
raw, err := tencentAPICall(via, p.AccessKeyID, p.SecretAccessKey, region, "DescribeTokenPlanList", map[string]any{"Offset": 0, "Limit": 100}, now())
|
||||
var list struct {
|
||||
Response *struct {
|
||||
TokenPlanSet []tencentPlan `json:"TokenPlanSet"`
|
||||
} `json:"Response"`
|
||||
}
|
||||
if err == nil && (json.Unmarshal(raw, &list) != nil || list.Response == nil) {
|
||||
err = fmt.Errorf("Tencent Cloud DescribeTokenPlanList: a reply magpie can't read: %s", shapeOf(raw))
|
||||
}
|
||||
tag := keyTag("tencent "+region, p.AccessKeyID)
|
||||
if err != nil {
|
||||
q := card("")
|
||||
q.Error = err.Error()
|
||||
return []SubscriptionQuota{keepReading(ctx, q, tag)}
|
||||
}
|
||||
var plans []tencentPlan
|
||||
for _, t := range list.Response.TokenPlanSet {
|
||||
if t.TeamID != "" {
|
||||
plans = append(plans, t)
|
||||
}
|
||||
}
|
||||
if len(plans) == 0 {
|
||||
q := card("")
|
||||
q.Error = "this Tencent Cloud account has no Token Plan Enterprise in " + region + " that its API key can see (a sub-user sees only the plans it made)"
|
||||
return []SubscriptionQuota{keepReading(ctx, q, tag)}
|
||||
}
|
||||
out := make([]SubscriptionQuota, len(plans))
|
||||
var wg sync.WaitGroup
|
||||
for i, t := range plans {
|
||||
user := ""
|
||||
if len(plans) > 1 {
|
||||
if user = strings.TrimSpace(t.Name); user == "" {
|
||||
user = t.TeamID
|
||||
}
|
||||
}
|
||||
if !wantsCard(ctx, p.ID, user) {
|
||||
continue
|
||||
}
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
// the plan's own reply has its cycle's end (TokenSummary); the
|
||||
// list's package is enough when it can't be read
|
||||
told := raw
|
||||
if detail, err := tencentAPICall(via, p.AccessKeyID, p.SecretAccessKey, region, "DescribeTokenPlan", map[string]any{"TeamId": t.TeamID}, now()); err == nil {
|
||||
var one struct {
|
||||
Response *tencentPlan `json:"Response"`
|
||||
}
|
||||
if json.Unmarshal(detail, &one) == nil && one.Response != nil {
|
||||
// what it tells over the list's, each part it has
|
||||
d := one.Response
|
||||
if d.PackageInfo != nil {
|
||||
t.PackageInfo, told = d.PackageInfo, detail
|
||||
}
|
||||
if d.TokenSummary != nil {
|
||||
t.TokenSummary = d.TokenSummary
|
||||
}
|
||||
if d.Status != "" {
|
||||
t.Status, t.StopReason = d.Status, d.StopReason
|
||||
}
|
||||
if d.ProductType != "" {
|
||||
t.ProductType = d.ProductType
|
||||
}
|
||||
}
|
||||
}
|
||||
q := card(user)
|
||||
if w, ok := t.window(now()); ok {
|
||||
q.Windows = []QuotaWindow{w}
|
||||
}
|
||||
// a stopped plan (used up, in arrears, frozen) says so beside
|
||||
// its name: it is what Tencent answered, not a read that failed
|
||||
if t.Status != "" && !strings.EqualFold(t.Status, "enable") {
|
||||
q.Plan += " · " + t.Status + tcReason(t.StopReason)
|
||||
}
|
||||
if len(q.Windows) == 0 {
|
||||
q.Error = "Tencent Cloud told no quota for this Token Plan Enterprise: " + shapeOf(told)
|
||||
}
|
||||
out[i] = keepReading(ctx, q, keyTag("tencent "+region+" "+t.TeamID, p.AccessKeyID))
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
var cards []SubscriptionQuota
|
||||
for _, q := range out {
|
||||
if q.Provider != "" {
|
||||
cards = append(cards, q)
|
||||
}
|
||||
}
|
||||
return cards
|
||||
}
|
||||
|
||||
func tcReason(r string) string {
|
||||
if r = strings.TrimSpace(r); r == "" || strings.EqualFold(r, "NORMAL") || strings.EqualFold(r, "none") {
|
||||
return ""
|
||||
}
|
||||
return ", " + r
|
||||
}
|
||||
|
||||
// tencentPlan is a team plan as DescribeTokenPlan and DescribeTokenPlanList
|
||||
// tell it (the docs' TokenPlanListItem and DescribeTokenPlan's output).
|
||||
type tencentPlan struct {
|
||||
TeamID string `json:"TeamId"`
|
||||
Name string `json:"Name"`
|
||||
Status string `json:"Status"`
|
||||
StopReason string `json:"StopReason"`
|
||||
ProductType string `json:"ProductType"`
|
||||
PackageInfo *struct {
|
||||
TotalQuota any `json:"TotalQuota"`
|
||||
TotalUsed any `json:"TotalUsed"`
|
||||
CycleQuota any `json:"CycleQuota"`
|
||||
CycleUnit string `json:"CycleUnit"`
|
||||
CurrentCycle any `json:"CurrentCycle"`
|
||||
StartTime string `json:"StartTime"`
|
||||
ExpireTime string `json:"ExpireTime"`
|
||||
} `json:"PackageInfo"`
|
||||
TokenSummary *struct {
|
||||
CycleStartTime string `json:"CycleStartTime"`
|
||||
CycleEndTime string `json:"CycleEndTime"`
|
||||
} `json:"TokenSummary"`
|
||||
}
|
||||
|
||||
// window is the plan's month: what it used of its cycle's quota, in
|
||||
// credits (专业套餐, ProductType enterprise) or tokens (轻享套餐,
|
||||
// enterprise-auto), and when the cycle ends; ok false when no quota is
|
||||
// told.
|
||||
func (t tencentPlan) window(now time.Time) (QuotaWindow, bool) {
|
||||
pk := t.PackageInfo
|
||||
if pk == nil {
|
||||
return QuotaWindow{}, false
|
||||
}
|
||||
limit, ok := volcNum(pk.CycleQuota)
|
||||
if !ok || limit <= 0 {
|
||||
limit, ok = volcNum(pk.TotalQuota)
|
||||
}
|
||||
used, uok := volcNum(pk.TotalUsed)
|
||||
if !ok || !uok || limit <= 0 {
|
||||
return QuotaWindow{}, false
|
||||
}
|
||||
w := QuotaWindow{Name: "Month", Span: 30 * 24 * time.Hour, Amount: used, Limit: limit, Unit: "credits",
|
||||
Used: max(0, min(100, used/limit*100))}
|
||||
if strings.EqualFold(t.ProductType, "enterprise-auto") {
|
||||
w.Unit = "tokens"
|
||||
}
|
||||
if t.TokenSummary != nil {
|
||||
if end, err := time.Parse(time.RFC3339, strings.TrimSpace(t.TokenSummary.CycleEndTime)); err == nil {
|
||||
w.ResetsAt = &end
|
||||
}
|
||||
if start, err := time.Parse(time.RFC3339, strings.TrimSpace(t.TokenSummary.CycleStartTime)); err == nil && w.ResetsAt != nil && w.ResetsAt.After(start) {
|
||||
w.Span = w.ResetsAt.Sub(start)
|
||||
}
|
||||
}
|
||||
if w.ResetsAt == nil {
|
||||
// the package's start and the cycle it is in: the cycle ends that
|
||||
// many months on, and never after the package does
|
||||
start, err := time.Parse(time.RFC3339, strings.TrimSpace(pk.StartTime))
|
||||
n, _ := volcNum(pk.CurrentCycle)
|
||||
if err == nil && (pk.CycleUnit == "" || strings.EqualFold(pk.CycleUnit, "month")) {
|
||||
end := start.AddDate(0, max(int(n), 1), 0)
|
||||
for !end.After(now) && n < 1200 {
|
||||
n++
|
||||
end = start.AddDate(0, int(n), 0)
|
||||
}
|
||||
if exp, err := time.Parse(time.RFC3339, strings.TrimSpace(pk.ExpireTime)); err == nil && exp.Before(end) {
|
||||
end = exp
|
||||
}
|
||||
w.ResetsAt = &end
|
||||
}
|
||||
}
|
||||
return w, true
|
||||
}
|
||||
|
||||
// tc3Sign is the Authorization header of a POST to host's "/" with payload
|
||||
// for action, at ts, as Tencent Cloud's TC3-HMAC-SHA256 makes it with the
|
||||
// headers tencentAPICall sends: Content-Type, Host and X-TC-Action signed.
|
||||
func tc3Sign(secretID, secretKey, service, host, action string, payload []byte, ts time.Time) string {
|
||||
date := ts.UTC().Format("2006-01-02")
|
||||
const signed = "content-type;host;x-tc-action"
|
||||
canonical := strings.Join([]string{
|
||||
http.MethodPost,
|
||||
"/",
|
||||
"",
|
||||
"content-type:" + tcContentType + "\n" +
|
||||
"host:" + host + "\n" +
|
||||
"x-tc-action:" + strings.ToLower(action) + "\n",
|
||||
signed,
|
||||
volcHex(payload),
|
||||
}, "\n")
|
||||
scope := date + "/" + service + "/tc3_request"
|
||||
toSign := strings.Join([]string{"TC3-HMAC-SHA256", strconv.FormatInt(ts.Unix(), 10), scope, volcHex([]byte(canonical))}, "\n")
|
||||
key := volcMAC([]byte("TC3"+secretKey), date)
|
||||
key = volcMAC(key, service)
|
||||
key = volcMAC(key, "tc3_request")
|
||||
sig := hex.EncodeToString(volcMAC(key, toSign))
|
||||
return "TC3-HMAC-SHA256 Credential=" + secretID + "/" + scope + ", SignedHeaders=" + signed + ", Signature=" + sig
|
||||
}
|
||||
|
||||
// tencentAPICall asks TokenHub's cloud API action in region with params,
|
||||
// signed with the SecretId and SecretKey, and gives the reply's body. The
|
||||
// key is sent nowhere but tokenhub.tencentcloudapi.com. Tencent answers an
|
||||
// error with 200 and Response.Error.
|
||||
func tencentAPICall(ctx context.Context, secretID, secretKey, region, action string, params map[string]any, now time.Time) ([]byte, error) {
|
||||
body, err := json.Marshal(params)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://"+tcAPIHost+"/", strings.NewReader(string(body)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", tcContentType)
|
||||
req.Header.Set("X-TC-Action", action)
|
||||
req.Header.Set("X-TC-Version", tcAPIVersion)
|
||||
req.Header.Set("X-TC-Region", region)
|
||||
req.Header.Set("X-TC-Timestamp", strconv.FormatInt(now.Unix(), 10))
|
||||
req.Header.Set("Authorization", tc3Sign(secretID, secretKey, tcAPIService, tcAPIHost, action, body, now))
|
||||
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 {
|
||||
Response struct {
|
||||
Error *struct{ Code, Message string } `json:"Error"`
|
||||
} `json:"Response"`
|
||||
}
|
||||
_ = json.Unmarshal(raw, &env)
|
||||
if e := env.Response.Error; e != nil && (e.Code != "" || e.Message != "") {
|
||||
msg := fmt.Sprintf("Tencent Cloud %s: %s %s", action, e.Code, e.Message)
|
||||
if tcRefusesKey(e.Code) {
|
||||
msg += "; " + tcKeyHint
|
||||
}
|
||||
return nil, fmt.Errorf("%s", msg)
|
||||
}
|
||||
switch {
|
||||
case res.StatusCode == http.StatusUnauthorized || res.StatusCode == http.StatusForbidden:
|
||||
return nil, fmt.Errorf("Tencent Cloud %s: %s; %s", action, res.Status, tcKeyHint)
|
||||
case res.StatusCode >= 300:
|
||||
return nil, fmt.Errorf("Tencent Cloud %s: %s: %s", action, res.Status, volcHead(raw))
|
||||
}
|
||||
return raw, nil
|
||||
}
|
||||
|
||||
// tcRefusesKey says a cloud API error code is about the API key or its
|
||||
// rights (AuthFailure.SignatureFailure, AuthFailure.SecretIdNotFound,
|
||||
// UnauthorizedOperation…), not the plan.
|
||||
func tcRefusesKey(code string) bool {
|
||||
c := strings.ToLower(code)
|
||||
return strings.HasPrefix(c, "authfailure") || strings.Contains(c, "unauthorized")
|
||||
}
|
||||
@@ -0,0 +1,269 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/agentenv"
|
||||
)
|
||||
|
||||
// The signature is the one Tencent Cloud's signing doc (api/213/30654)
|
||||
// works through: DescribeInstances on cvm.tencentcloudapi.com at
|
||||
// 1551113065, its payload byte for byte.
|
||||
func TestTC3SignMatchesDoc(t *testing.T) {
|
||||
// the doc sends the name as JSON escapes (a backslash and u672a…), not UTF-8
|
||||
esc := strings.ReplaceAll("#u672a#u547d#u540d", "#", `\`)
|
||||
payload := []byte(`{"Limit": 1, "Filters": [{"Values": ["` + esc + `"], "Name": "instance-name"}]}`)
|
||||
if got := volcHex(payload); got != "35e9c5b0e3ae67532d3c9f17ead6c90222632e5b1ff7f6e89887f1398934f064" {
|
||||
t.Fatalf("payload hash %s", got)
|
||||
}
|
||||
id, key := "AKID"+strings.Repeat("*", 32), strings.Repeat("*", 32)
|
||||
got := tc3Sign(id, key, "cvm", "cvm.tencentcloudapi.com", "DescribeInstances", payload, time.Unix(1551113065, 0))
|
||||
want := "TC3-HMAC-SHA256 Credential=" + id + "/2019-02-25/cvm/tc3_request, SignedHeaders=content-type;host;x-tc-action, Signature=10b1a37a7301a02ca19a647ad722d5e43b4b3cff309d421d85b46093f6ab6c4f"
|
||||
if got != want {
|
||||
t.Fatalf("\n got %s\nwant %s", got, want)
|
||||
}
|
||||
// a time in another zone signs with the UTC date
|
||||
cst := time.Unix(1551113065, 0).In(time.FixedZone("CST", 8*3600))
|
||||
if tc3Sign(id, key, "cvm", "cvm.tencentcloudapi.com", "DescribeInstances", payload, cst) != want {
|
||||
t.Error("CST time signed differently")
|
||||
}
|
||||
}
|
||||
|
||||
// Only the enterprise plan's endpoints take an access key: /plan on
|
||||
// TokenHub's hosts. Its pay as you go, the personal plan, another vendor
|
||||
// and an account don't; Volcengine's stay Volcengine's.
|
||||
func TestTencentPlanRegion(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
p Provider
|
||||
region string
|
||||
}{
|
||||
{Provider{Chat: "https://tokenhub.tencentmaas.com/plan/v3"}, "ap-guangzhou"},
|
||||
{Provider{Anthropic: "https://tokenhub.tencentmaas.com/plan/anthropic"}, "ap-guangzhou"},
|
||||
{Provider{Responses: "https://TokenHub-Intl.tencentmaas.com/plan/v3/"}, "ap-singapore"},
|
||||
{Provider{Chat: "https://tokenhub.tencentmaas.com/v1"}, ""},
|
||||
{Provider{Chat: "https://api.lkeap.cloud.tencent.com/plan/v3"}, ""},
|
||||
{Provider{Chat: "https://relay.example.com/plan/v3"}, ""},
|
||||
{Provider{Chat: "https://tokenhub.tencentmaas.com/planx/v3"}, ""},
|
||||
{Provider{Chat: "https://tokenhub.tencentmaas.com/plan/v3", Account: &Account{}}, ""},
|
||||
} {
|
||||
region, ok := tencentPlanRegion(c.p)
|
||||
if region != c.region || ok != (c.region != "") || TakesTencentAccessKey(c.p) != ok {
|
||||
t.Errorf("%+v: %q %v", c.p, region, ok)
|
||||
}
|
||||
}
|
||||
for _, c := range []struct {
|
||||
p Provider
|
||||
vendor string
|
||||
}{
|
||||
{Provider{Chat: "https://tokenhub.tencentmaas.com/plan/v3"}, "tencent"},
|
||||
{Provider{Chat: "https://ark.cn-beijing.volces.com/api/coding/v3"}, "volcengine"},
|
||||
{Provider{Chat: "https://api.lkeap.cloud.tencent.com/plan/v3"}, ""},
|
||||
} {
|
||||
if got := AccessKeyVendor(c.p); got != c.vendor {
|
||||
t.Errorf("AccessKeyVendor(%s) = %q", c.p.Chat, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The docs' PackageInfo (quotas as strings) and TokenSummary: used of the
|
||||
// cycle's quota, credits for 专业套餐 and tokens for 轻享套餐, resetting at
|
||||
// the cycle's end; with no TokenSummary the cycle is counted from the
|
||||
// package's start, never past its expiry; no quota is no window.
|
||||
func TestTencentPlanWindow(t *testing.T) {
|
||||
var p tencentPlan
|
||||
if err := json.Unmarshal([]byte(`{"TeamId":"team-a1b2c3d4","ProductType":"enterprise",
|
||||
"PackageInfo":{"TotalQuota":"1000000","TotalUsed":"100000","TotalCycles":1,"CycleUnit":"month","StartTime":"2026-04-01T00:00:00Z","ExpireTime":"2027-04-01T00:00:00Z",
|
||||
"ExclusiveAllocated":"500000","ExclusiveUsed":"100000","SharedPool":"500000","SharedUsed":"50000","CycleQuota":"1000000","CurrentCycle":1,"RemainCycles":0},
|
||||
"TokenSummary":{"CycleSeq":1,"CycleStartTime":"2026-04-01T00:00:00+08:00","CycleEndTime":"2026-05-01T00:00:00+08:00",
|
||||
"BillingItems":[{"BillingItem":"input","TotalQty":"60000"},{"BillingItem":"output","TotalQty":"40000"}]}}`), &p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
now := time.Date(2026, 4, 10, 0, 0, 0, 0, time.UTC)
|
||||
w, ok := p.window(now)
|
||||
if !ok || w.Name != "Month" || w.Used != 10 || w.Amount != 100000 || w.Limit != 1000000 || w.Unit != "credits" ||
|
||||
w.ResetsAt == nil || !w.ResetsAt.Equal(time.Date(2026, 4, 30, 16, 0, 0, 0, time.UTC)) || w.Span != 30*24*time.Hour {
|
||||
t.Fatalf("%+v %v", w, ok)
|
||||
}
|
||||
p.ProductType = "enterprise-auto"
|
||||
if w, _ := p.window(now); w.Unit != "tokens" {
|
||||
t.Errorf("轻享套餐 unit %q", w.Unit)
|
||||
}
|
||||
// no TokenSummary: month 1 from StartTime, and on past it as time goes
|
||||
p.TokenSummary = nil
|
||||
if w, _ := p.window(now); w.ResetsAt == nil || !w.ResetsAt.Equal(time.Date(2026, 5, 1, 0, 0, 0, 0, time.UTC)) {
|
||||
t.Errorf("from StartTime: %+v", w.ResetsAt)
|
||||
}
|
||||
if w, _ := p.window(time.Date(2026, 7, 15, 0, 0, 0, 0, time.UTC)); w.ResetsAt == nil || !w.ResetsAt.Equal(time.Date(2026, 8, 1, 0, 0, 0, 0, time.UTC)) {
|
||||
t.Errorf("July: %+v", w.ResetsAt)
|
||||
}
|
||||
p.PackageInfo.ExpireTime = "2026-07-20T00:00:00Z"
|
||||
if w, _ := p.window(time.Date(2026, 7, 15, 0, 0, 0, 0, time.UTC)); w.ResetsAt == nil || !w.ResetsAt.Equal(time.Date(2026, 7, 20, 0, 0, 0, 0, time.UTC)) {
|
||||
t.Errorf("capped at expiry: %+v", w.ResetsAt)
|
||||
}
|
||||
// no cycle quota: the total's; used past it shows full
|
||||
p.PackageInfo.CycleQuota, p.PackageInfo.TotalUsed = nil, 2000000.0
|
||||
if w, ok := p.window(now); !ok || w.Limit != 1000000 || w.Used != 100 {
|
||||
t.Errorf("TotalQuota: %+v", w)
|
||||
}
|
||||
for _, pk := range []string{`{}`, `{"TotalQuota":"0","TotalUsed":"1"}`, `{"TotalQuota":"10"}`} {
|
||||
var q tencentPlan
|
||||
json.Unmarshal([]byte(`{"PackageInfo":`+pk+`}`), &q)
|
||||
if _, ok := q.window(now); ok {
|
||||
t.Errorf("%s gave a window", pk)
|
||||
}
|
||||
}
|
||||
if _, ok := (tencentPlan{}).window(now); ok {
|
||||
t.Error("no PackageInfo gave a window")
|
||||
}
|
||||
}
|
||||
|
||||
// The Usage page has a card for each team plan the SecretId can see, read
|
||||
// from tokenhub.tencentcloudapi.com only, each request signed as TC3 with
|
||||
// the SecretKey and never with the plan's own key; a refused key says
|
||||
// what to check, an account with no plan says so, and the personal plan,
|
||||
// a provider with no SecretKey and one switched off have none.
|
||||
func TestTencentPlanQuotas(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{"AKIDone": "SK1", "AKIDtwo": "SK2", "AKIDnone": "SK4", "AKIDbad": "wrong"}
|
||||
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)
|
||||
action := r.Header.Get("X-TC-Action")
|
||||
if r.Header.Get("X-Host") != tcAPIHost || r.Method != http.MethodPost || r.URL.Path != "/" ||
|
||||
r.Header.Get("X-TC-Version") != "2026-03-22" || r.Header.Get("Content-Type") != tcContentType {
|
||||
t.Errorf("asked %s %s%s %s %v", r.Method, r.Header.Get("X-Host"), r.URL, action, r.Header)
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
auth := r.Header.Get("Authorization")
|
||||
if strings.Contains(auth, "sk-tp") || strings.Contains(string(body), "sk-tp") {
|
||||
t.Errorf("the plan's key was sent: %s %s", auth, body)
|
||||
}
|
||||
cred, _, _ := strings.Cut(strings.TrimPrefix(auth, "TC3-HMAC-SHA256 Credential="), "/")
|
||||
ts, _ := strconv.ParseInt(r.Header.Get("X-TC-Timestamp"), 10, 64)
|
||||
region := r.Header.Get("X-TC-Region")
|
||||
if want := tc3Sign(cred, secrets[cred], "tokenhub", tcAPIHost, action, body, time.Unix(ts, 0)); cred == "AKIDbad" || auth != want {
|
||||
io.WriteString(w, `{"Response":{"Error":{"Code":"AuthFailure.SignatureFailure","Message":"The provided credentials could not be validated."},"RequestId":"e1"}}`)
|
||||
return
|
||||
}
|
||||
mu.Lock()
|
||||
asked[cred+" "+region+" "+action]++
|
||||
mu.Unlock()
|
||||
var params map[string]any
|
||||
json.Unmarshal(body, ¶ms)
|
||||
switch {
|
||||
case action == "DescribeTokenPlanList" && cred == "AKIDnone":
|
||||
io.WriteString(w, `{"Response":{"RequestId":"r0","TokenPlanSet":[],"TotalCount":0}}`)
|
||||
case action == "DescribeTokenPlanList" && cred == "AKIDone":
|
||||
// the docs' example
|
||||
io.WriteString(w, `{"Response":{"RequestId":"be515245-e05f-4334-9f9d-6d55db1aa8b5","TokenPlanSet":[{"ApiKeyMax":10000,"AppId":"176623905","CreatedAt":"2026-04-05T21:06:09+08:00","Creator":"176623905","Name":"my-team-test-1","PrepayResourceID":"pre-123456","Status":"enable","StopReason":"","TeamId":"team-a1b2c3d4","Uin":"214508345","UpdatedAt":"2026-04-07T23:26:01+08:00","ProductType":"enterprise"}],"TotalCount":1}}`)
|
||||
case action == "DescribeTokenPlanList" && cred == "AKIDtwo":
|
||||
io.WriteString(w, `{"Response":{"RequestId":"r2","TokenPlanSet":[
|
||||
{"Name":"alpha","Status":"enable","TeamId":"team-a","ProductType":"enterprise-auto","PackageInfo":{"TotalQuota":"5000000","TotalUsed":"1250000","CycleQuota":"5000000","StartTime":"2026-04-01T00:00:00Z","ExpireTime":"2027-04-01T00:00:00Z","CurrentCycle":1}},
|
||||
{"Name":"beta","Status":"isolate","StopReason":"arrears","TeamId":"team-b","ProductType":"enterprise"}],"TotalCount":2}}`)
|
||||
case action == "DescribeTokenPlan" && params["TeamId"] == "team-a1b2c3d4":
|
||||
io.WriteString(w, `{"Response":{"ApiKeyCount":10,"ApiKeyMax":10000,"Name":"my-team-test-1","Status":"enable","TeamId":"team-a1b2c3d4","RequestId":"45b1f117",
|
||||
"PackageInfo":{"TotalQuota":"1000000","TotalUsed":"100000","CycleUnit":"month","StartTime":"2026-04-01T00:00:00Z","ExpireTime":"2027-04-01T00:00:00Z","CycleQuota":"1000000","CurrentCycle":1},
|
||||
"TokenSummary":{"CycleSeq":1,"CycleStartTime":"2026-04-01T00:00:00+08:00","CycleEndTime":"2026-05-01T00:00:00+08:00","BillingItems":[]}}}`)
|
||||
case action == "DescribeTokenPlan" && params["TeamId"] == "team-a":
|
||||
// the docs' own example: no PackageInfo, the list's is kept
|
||||
io.WriteString(w, `{"Response":{"ApiKeyCount":1,"Name":"alpha","Status":"enable","TeamId":"team-a","RequestId":"45b1f117"}}`)
|
||||
case action == "DescribeTokenPlan" && params["TeamId"] == "team-b":
|
||||
io.WriteString(w, `{"Response":{"Name":"beta","Status":"isolate","StopReason":"arrears","TeamId":"team-b","RequestId":"r3"}}`)
|
||||
default:
|
||||
t.Errorf("action %q %s by %s", action, body, cred)
|
||||
}
|
||||
}))
|
||||
defer srv.Close()
|
||||
old := http.DefaultClient.Transport
|
||||
http.DefaultClient.Transport = rewrite{srv}
|
||||
t.Cleanup(func() { http.DefaultClient.Transport = old })
|
||||
forgetPlanQuotas()
|
||||
t.Cleanup(forgetPlanQuotas)
|
||||
|
||||
ent, intl := "https://tokenhub.tencentmaas.com/plan/v3", "https://tokenhub-intl.tencentmaas.com/plan/v3"
|
||||
for _, p := range []Provider{
|
||||
{ID: "tencent-cloud", Name: "Tencent Cloud", Chat: ent, Anthropic: "https://tokenhub.tencentmaas.com/plan/anthropic", Key: "sk-tp-1", AccessKeyID: "AKIDone", SecretAccessKey: "SK1"},
|
||||
// the same key and region again: asked once
|
||||
{ID: "tc-copy", Name: "Tencent copy", Chat: ent, Key: "sk-tp-1", AccessKeyID: "AKIDone", SecretAccessKey: "SK1"},
|
||||
{ID: "tc-intl", Name: "Tencent intl", Chat: intl, Key: "sk-tp-2", AccessKeyID: "AKIDtwo", SecretAccessKey: "SK2"},
|
||||
{ID: "tc-none", Name: "Tencent none", Chat: ent, Key: "sk-tp-3", AccessKeyID: "AKIDnone", SecretAccessKey: "SK4"},
|
||||
{ID: "tc-bad", Name: "Tencent bad", Chat: ent, Key: "sk-tp-4", AccessKeyID: "AKIDbad", SecretAccessKey: "wrong"},
|
||||
{ID: "tc-personal", Name: "Tencent personal", Chat: "https://api.lkeap.cloud.tencent.com/plan/v3", Key: "sk-tp-5", AccessKeyID: "AKIDone", SecretAccessKey: "SK1"},
|
||||
{ID: "tc-nosecret", Name: "Tencent half", Chat: ent, Key: "sk-tp-6", AccessKeyID: "AKIDhalf"},
|
||||
{ID: "tc-off", Name: "Tencent off", Chat: ent, Key: "sk-tp-7", AccessKeyID: "AKIDoff", SecretAccessKey: "SKoff", Off: true},
|
||||
} {
|
||||
if err := Save(p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
var cards []SubscriptionQuota
|
||||
for _, q := range PlanQuotas(context.Background()) {
|
||||
if q.Plan != "" && (strings.HasPrefix(q.Provider, "tc-") || q.Provider == "tencent-cloud") {
|
||||
cards = append(cards, q)
|
||||
}
|
||||
}
|
||||
by := map[string]SubscriptionQuota{}
|
||||
for _, q := range cards {
|
||||
by[q.Provider+"|"+q.User] = q
|
||||
}
|
||||
if len(cards) != 5 || len(by) != 5 {
|
||||
t.Fatalf("cards: %+v", cards)
|
||||
}
|
||||
one, ok := by["tencent-cloud|"]
|
||||
if !ok {
|
||||
one = by["tc-copy|"]
|
||||
}
|
||||
if one.Plan != "Token Plan Enterprise" || one.Error != "" || len(one.Windows) != 1 || one.Windows[0].Used != 10 || one.Windows[0].Unit != "credits" ||
|
||||
one.Windows[0].ResetsAt == nil || !one.Windows[0].ResetsAt.Equal(time.Date(2026, 4, 30, 16, 0, 0, 0, time.UTC)) {
|
||||
t.Errorf("one plan: %+v", one)
|
||||
}
|
||||
alpha := by["tc-intl|alpha"]
|
||||
if alpha.Error != "" || len(alpha.Windows) != 1 || alpha.Windows[0].Used != 25 || alpha.Windows[0].Unit != "tokens" || alpha.Windows[0].ResetsAt == nil {
|
||||
t.Errorf("alpha: %+v", alpha)
|
||||
}
|
||||
beta := by["tc-intl|beta"]
|
||||
if beta.Plan != "Token Plan Enterprise · isolate, arrears" || !strings.Contains(beta.Error, "told no quota") {
|
||||
t.Errorf("beta: %+v", beta)
|
||||
}
|
||||
if q := by["tc-none|"]; !strings.Contains(q.Error, "no Token Plan Enterprise in ap-guangzhou") {
|
||||
t.Errorf("no plan: %+v", q)
|
||||
}
|
||||
if q := by["tc-bad|"]; !strings.Contains(q.Error, "AuthFailure.SignatureFailure") || !strings.Contains(q.Error, "SecretId and SecretKey") {
|
||||
t.Errorf("refused: %+v", q)
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
for k, want := range map[string]int{
|
||||
"AKIDone ap-guangzhou DescribeTokenPlanList": 1, "AKIDone ap-guangzhou DescribeTokenPlan": 1,
|
||||
"AKIDtwo ap-singapore DescribeTokenPlanList": 1, "AKIDtwo ap-singapore DescribeTokenPlan": 2,
|
||||
"AKIDnone ap-guangzhou DescribeTokenPlanList": 1,
|
||||
} {
|
||||
if asked[k] != want {
|
||||
t.Errorf("%s asked %d times, want %d (%v)", k, asked[k], want, asked)
|
||||
}
|
||||
}
|
||||
if len(asked) != 5 {
|
||||
t.Errorf("asked %v", asked)
|
||||
}
|
||||
}
|
||||
+3
-2
@@ -32,7 +32,7 @@ const providerUsage = `usage:
|
||||
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,
|
||||
access.key, access.secret (a Volcengine account's access key, for its plan's windows)
|
||||
access.key, access.secret (a Volcengine access key, or a Tencent Cloud SecretId and SecretKey, 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
|
||||
@@ -932,7 +932,8 @@ func applyPairs(p *provider.Provider, pairs []string) error {
|
||||
p.BalanceToken = v
|
||||
case "access.key":
|
||||
// a Volcengine account's access key, which Ark tells its
|
||||
// Coding or Agent Plan's windows to (#1427)
|
||||
// Coding or Agent Plan's windows to (#1427), or a Tencent Cloud
|
||||
// SecretId, which TokenHub tells Token Plan 企业版's usage to (#1574)
|
||||
p.AccessKeyID = v
|
||||
case "access.secret":
|
||||
p.SecretAccessKey = v
|
||||
|
||||
Reference in New Issue
Block a user