usage: a Qwen AI platform Token Plan is read through a sign-in to the platform (@imthe99galaxy on X, #5829)
On v0.1.4137 a provider on the Qwen AI platform's Token Plan
(qwen-token-plan, token-plan.maas.qianwenaiapi.com) had no quota card at
all. The plan key (sk-sp-) only authorizes inference; the platform tells
the plan's usage only to a sign-in on the platform, and magpie had none.
Now each such provider can sign in to the platform, as the QianWen CLI
1.10.0 does (qianwen_plan.go, UA qianwen-cli/1.10.0):
- a device sign-in with PKCE S256 at t.qianwenai.com/cli/device/code and
/cli/device/token, approved in the user's browser; the editor's
"Sign in to the Qwen AI platform" opens the page and waits for it;
- the session is the provider's own, kept by provider id in
qianwen-auth.json (0600), moved on Rename and dropped on Delete;
- cli.qianwenai.com/data/v2/api.json (GenerateCLIAccessToken) mints a
console token, kept and minted once more when the gateway answers
NotLogined; ConsoleNeedLogin or a fresh token refused signs it out;
- the usage is the Alibaba Token Plan's BroadScopeAspnGateway call at
cs-data.qianwenai.com with consoleSite QIANWENAI, region cn-beijing,
read by the shared aliAskUsage/aliReadWindows (alibaba_usage.go now
takes the console per call). The sk-sp- key is never sent there.
- Plan windows (planquota.go) and routing's key allowance
(key_allowance.go, keyTag "qianwen") read it; not signed in, the card
says so with Open settings (NeedsAccessKey).
- GUI routes /api/qianwen/{id}/signin (POST start, GET state),
/signin/cancel, /signout; the editor's field lives in qianwenplan.js,
imported when such a provider's editor opens. The core script budget
is raised by 326 for the import and one quotaError line (its reason in
core_budget_test.go). The routes are in the CLI parity's notYet, as
StepFun's are.
Run, on mote at the base df2b819c6 (= origin/main then):
- gofmt -l: clean. go vet (darwin), GOOS=linux go vet -tags nogui,
GOOS=windows go vet on internal/provider, internal/gui, internal/cli: ok.
- go test -count=1 -timeout 45m ./internal/provider ./internal/gui
./internal/cli: provider ok; gui and cli red on TestCoreScriptBudget
and TestEveryRouteHasACommandOrIsNamed, both mine; fixed (code moved to
qianwenplan.js, budget +326, routes named), then gui ok, cli ok.
- go test -race -run Qianwen ./internal/provider: ok.
- GUI (chromium + webkit, 900/420px, en zh zh-TW ja de where the file
has them): qianwen-plan 20/20, stepfun-per-provider,
usage-access-key-card, volc-access-key, quota-balance-error,
i18n-en-no-cjk all ok; earlier also opencode-zen-balance,
siliconflow-balance, usage-card-refresh, usage-remote-key-limits,
usage-remote-cards ok. Reds not mine: i18n-keys "a plugin's words are
its own" (#6619, fixed on main by ea6470cb7), old-webkit's
headerpresets.js (#6030) and app.css :has() (#5919).
- Rebased on origin/main 79a30eb9c and run again at that tree on mote:
go test -count=1 -timeout 45m ./internal/provider ./internal/gui
./internal/cli all ok; qianwen-plan + i18n-keys 24 pass, 0 fail. Rebased again onto
fc75d90af before the push; b507b5f69 and fc75d90af touch only
internal/sessions and third_party/yaml.v3, not run again.
Broken by hand, each red, then restored: the NotLogined retry, the
code_verifier, renameQianwen, the planquota channel, forgetQianwen on
Delete, the session expiry check, qianwenWatch not called, the sign-in
quotaError mapping.
Not tried: a real sign-in. No Qwen AI platform account is available here,
and approving the device sign-in grants an OAuth permission. Fixtures are
built from the QianWen CLI 1.10.0 source and the live device/code and
unauthenticated replies; the usage reply's shape is the Alibaba Token
Plan's, which the CLI reads with the same code.
This commit is contained in:
File diff suppressed because one or more lines are too long
@@ -484,6 +484,10 @@ var notYet = map[string]string{
|
||||
"POST /api/signin/export": P, // providers.go
|
||||
"POST /api/stepfun/{id}/session": P, // providers.go
|
||||
"POST /api/stepfun/{id}/signout": P, // providers.go
|
||||
"GET /api/qianwen/{id}/signin": P, // providers.go
|
||||
"POST /api/qianwen/{id}/signin": P, // providers.go
|
||||
"POST /api/qianwen/{id}/signin/cancel": P, // providers.go
|
||||
"POST /api/qianwen/{id}/signout": P, // providers.go
|
||||
"GET /api/speeds": U, // sessions_manage.go: the Sessions row's speed curve
|
||||
"GET /api/sessions/manage": U, // sessions_manage.go
|
||||
"GET /api/sessions/search": U, // sessions_manage.go
|
||||
|
||||
@@ -10037,6 +10037,8 @@ function drawEditor(p, presetID) {
|
||||
|
||||
// a Step Plan's windows are told only to a StepFun sign-in
|
||||
if (p?.stepPlan) ed.append(...field(t("Step Plan allowances"), renderStepPlan(p.stepPlan, p.id), t("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.")));
|
||||
// and a Qwen AI platform plan's to a sign-in there, in qianwenplan.js
|
||||
if (p?.qianwenPlan) { const at = el("span"); ed.append(at); import("./qianwenplan.js").then(() => at.replaceWith(...qianwenPlanField(p)), () => {}); }
|
||||
|
||||
// a team's GLM Coding Plan windows need its org and project (#236)
|
||||
const team = p ? !!p.zhipuTeam : !!pr?.zhipuTeam;
|
||||
@@ -14006,6 +14008,8 @@ function quotaError(err, q) {
|
||||
// a Volcengine or Tencent plan with no access key (#1821)
|
||||
if (/^this plan's usage is read with the account's access key: give its SecretId/.test(err)) return t("This plan's usage needs the account's SecretId and SecretKey — give them in the provider's settings");
|
||||
if (/^this plan's usage is read with the account's access key/.test(err)) return t("This plan's usage needs the account's AccessKey ID and Secret — give them in the provider's settings");
|
||||
// a Qwen AI platform plan (qianwen_plan.go)
|
||||
if (/^(this plan's usage is told only to a sign-in on|signed out of) the Qwen AI platform/.test(err)) return t("This plan's usage needs a sign-in to the Qwen AI platform — sign in in the provider's settings");
|
||||
// ZCode with no plan left, not a failed read (#1001)
|
||||
if (/^this account has no GLM Coding Plan, and ZCode's Start Plan has ended or was never started$/.test(err)) return t("ZCode: no GLM Coding Plan, and no free Start Plan — subscribe to a GLM Coding Plan to use this account");
|
||||
// an OpenCode Go key's windows (planquota.go)
|
||||
|
||||
@@ -3874,6 +3874,12 @@ const I18N = {
|
||||
"AiHubMix didn't take the access token — paste a new one in the provider's settings": "AiHubMix 不认这个访问令牌,请在供应商设置里重新填入",
|
||||
"Account balance": "账户余额",
|
||||
"Step Plan allowances": "Step Plan 额度",
|
||||
"Token Plan allowances": "Token Plan 额度",
|
||||
"The plan's usage is told only to a sign-in on the Qwen AI platform. magpie keeps it for this and nothing else.": "这个套餐的用量只告诉千问 AI 平台的登录。magpie 保存这次登录,只用于读取用量。",
|
||||
"Approve the sign-in in your browser…": "请在浏览器里批准登录…",
|
||||
"Sign in to the Qwen AI platform ↗": "登录千问 AI 平台 ↗",
|
||||
"Signed in to the Qwen AI platform": "已登录千问 AI 平台",
|
||||
"This plan's usage needs a sign-in to the Qwen AI platform — sign in in the provider's settings": "这个套餐的用量需要登录千问 AI 平台——在提供商设置里登录",
|
||||
"Team org ID": "团队组织 ID",
|
||||
"Team project ID": "团队项目 ID",
|
||||
"optional · only for a team plan": "可选 · 仅团队套餐需要",
|
||||
@@ -9115,6 +9121,12 @@ const I18N = {
|
||||
"AiHubMix didn't take the access token — paste a new one in the provider's settings": "AiHubMix 不認這個存取權杖,請在供應商設定裡重新填入",
|
||||
"Account balance": "帳戶餘額",
|
||||
"Step Plan allowances": "Step Plan 額度",
|
||||
"Token Plan allowances": "Token Plan 額度",
|
||||
"The plan's usage is told only to a sign-in on the Qwen AI platform. magpie keeps it for this and nothing else.": "這個方案的用量只告訴千問 AI 平台的登入。magpie 保存這次登入,只用於讀取用量。",
|
||||
"Approve the sign-in in your browser…": "請在瀏覽器裡核准登入…",
|
||||
"Sign in to the Qwen AI platform ↗": "登入千問 AI 平台 ↗",
|
||||
"Signed in to the Qwen AI platform": "已登入千問 AI 平台",
|
||||
"This plan's usage needs a sign-in to the Qwen AI platform — sign in in the provider's settings": "這個方案的用量需要登入千問 AI 平台——在供應商設定裡登入",
|
||||
"Team org ID": "團隊組織 ID",
|
||||
"Team project ID": "團隊專案 ID",
|
||||
"optional · only for a team plan": "可選 · 僅團隊套餐需要",
|
||||
@@ -14364,6 +14376,12 @@ const I18N = {
|
||||
"AiHubMix didn't take the access token — paste a new one in the provider's settings": "AiHubMix がアクセストークンを受け付けませんでした — プロバイダの設定で新しいものを貼り付けてください",
|
||||
"Account balance": "アカウント残高",
|
||||
"Step Plan allowances": "Step Plan の利用枠",
|
||||
"Token Plan allowances": "Token Plan の利用枠",
|
||||
"The plan's usage is told only to a sign-in on the Qwen AI platform. magpie keeps it for this and nothing else.": "このプランの利用量は Qwen AI プラットフォームへのサインインにしか伝えられません。magpie はそれを利用量の読み取りだけに使います。",
|
||||
"Approve the sign-in in your browser…": "ブラウザでサインインを承認してください…",
|
||||
"Sign in to the Qwen AI platform ↗": "Qwen AI プラットフォームにサインイン ↗",
|
||||
"Signed in to the Qwen AI platform": "Qwen AI プラットフォームにサインインしました",
|
||||
"This plan's usage needs a sign-in to the Qwen AI platform — sign in in the provider's settings": "このプランの利用量には Qwen AI プラットフォームへのサインインが必要です — プロバイダの設定でサインインしてください",
|
||||
"Team org ID": "チーム組織 ID",
|
||||
"Team project ID": "チームプロジェクト ID",
|
||||
"optional · only for a team plan": "任意 · チームプランのみ",
|
||||
@@ -19622,6 +19640,12 @@ const I18N = {
|
||||
"AiHubMix didn't take the access token — paste a new one in the provider's settings": "AiHubMix hat das Zugriffstoken nicht akzeptiert – fügen Sie in den Anbietereinstellungen ein neues ein",
|
||||
"Account balance": "Kontoguthaben",
|
||||
"Step Plan allowances": "Step-Plan-Kontingente",
|
||||
"Token Plan allowances": "Token-Plan-Kontingente",
|
||||
"The plan's usage is told only to a sign-in on the Qwen AI platform. magpie keeps it for this and nothing else.": "Die Nutzung des Plans erfährt nur eine Anmeldung bei der Qwen-AI-Plattform. magpie nutzt sie für nichts anderes.",
|
||||
"Approve the sign-in in your browser…": "Bestätige die Anmeldung im Browser …",
|
||||
"Sign in to the Qwen AI platform ↗": "Bei der Qwen-AI-Plattform anmelden ↗",
|
||||
"Signed in to the Qwen AI platform": "Bei der Qwen-AI-Plattform angemeldet",
|
||||
"This plan's usage needs a sign-in to the Qwen AI platform — sign in in the provider's settings": "Die Nutzung dieses Plans braucht eine Anmeldung bei der Qwen-AI-Plattform — melde dich in den Einstellungen des Anbieters an",
|
||||
"Team org ID": "Team-Organisations-ID",
|
||||
"Team project ID": "Team-Projekt-ID",
|
||||
"optional · only for a team plan": "optional · nur für einen Team-Plan",
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
// The Qwen AI platform's Token Plan: its usage is told only to a sign-in
|
||||
// on the platform, approved in the user's browser and kept per provider
|
||||
// id (qianwen_plan.go). app.js imports this when such a provider's
|
||||
// editor opens, so it weighs nothing on the core.
|
||||
window.qianwenPlanField = (p) => field(t("Token Plan allowances"), renderQianwenPlan(p.qianwenPlan, p.id), t("The plan's usage is told only to a sign-in on the Qwen AI platform. magpie keeps it for this and nothing else."));
|
||||
|
||||
// renderQianwenPlan: a sign-in to the Qwen AI platform, approved in the
|
||||
// user's browser, per provider id (qianwen_plan.go)
|
||||
const qianwenWaiting = new Set();
|
||||
function renderQianwenPlan(qp, id) {
|
||||
const box = el("div", "stepplan");
|
||||
const path = "qianwen/" + encodeURIComponent(id);
|
||||
const row = el("div", "pair");
|
||||
const side = el("div", "side");
|
||||
if (qp.signedIn) {
|
||||
const out = el("button", "text", t("Sign out"));
|
||||
out.onclick = async () => {
|
||||
try { providers = await api(path + "/signout", {}); renderProviders(); } catch (e) { statusErr(e); }
|
||||
};
|
||||
side.append(out);
|
||||
row.append(el("span", "state", qp.account ? t("Signed in as {user}", { user: qp.account }) : t("Signed in")), side);
|
||||
box.append(row);
|
||||
return box;
|
||||
}
|
||||
if (qianwenWaiting.has(id)) {
|
||||
const stop = el("button", "text", t("Cancel"));
|
||||
stop.onclick = () => {
|
||||
qianwenWaiting.delete(id);
|
||||
api(path + "/signin/cancel", {}).catch(() => {});
|
||||
renderProviders();
|
||||
};
|
||||
side.append(stop);
|
||||
row.append(el("span", "state", t("Approve the sign-in in your browser…")), side);
|
||||
box.append(row);
|
||||
return box;
|
||||
}
|
||||
const go = el("button", "link", t("Sign in to the Qwen AI platform ↗"));
|
||||
go.onclick = async () => {
|
||||
go.disabled = true;
|
||||
try {
|
||||
const r = await api(path + "/signin", {});
|
||||
qianwenWaiting.add(id);
|
||||
api("open", { url: r.url }).catch(() => {});
|
||||
renderProviders();
|
||||
qianwenWatch(id);
|
||||
} catch (e) {
|
||||
go.disabled = false;
|
||||
statusErr(e);
|
||||
}
|
||||
};
|
||||
box.append(go);
|
||||
return box;
|
||||
}
|
||||
|
||||
// qianwenWatch waits on the provider's sign-in, which magpie finishes
|
||||
// once the user approves it in their browser
|
||||
async function qianwenWatch(id) {
|
||||
const path = "qianwen/" + encodeURIComponent(id) + "/signin";
|
||||
while (qianwenWaiting.has(id)) {
|
||||
await new Promise((r) => setTimeout(r, 1500));
|
||||
if (!qianwenWaiting.has(id)) return;
|
||||
let s;
|
||||
try { s = await api(path); } catch (_) { continue; }
|
||||
if (s?.state === "pending") continue;
|
||||
qianwenWaiting.delete(id);
|
||||
if (s?.state === "done") {
|
||||
try { providers = await api("providers"); } catch (_) { /* keep the last known list */ }
|
||||
status(t("Signed in to the Qwen AI platform"), "ok");
|
||||
} else if (s?.error) {
|
||||
statusErr(new Error(s.error));
|
||||
}
|
||||
renderProviders();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ import (
|
||||
// `git log -L` of this file.
|
||||
const (
|
||||
appScriptBudget = 1_086_267 // app.js: 1,080,614 at 8016205e3, with the 5,653 of room it had
|
||||
coreScriptBudget = 1_269_531 // every core script at 8016205e3, the old measure 682 over its cap there (#5918); +367 for the model test on a chosen account (tmr11235), no page left to move it to; +151 for the provider menu's "Only on this device" item and its four translations; +458 for Settings › About's Report a problem row and its translations; +113 for withScheme, the one rule every typed address goes through (eachg0 on X), cut to the shortest form that keeps it whole; +10 for the kept whole's tooltip (Musikrv77852 on X), the past-cycle line reused for it, no page left to move it to; +1,112 for Codex's Open button and its Open Codex with menu (Yink88564391 on X), packed to the shortest form, no page left to move them to; +168 for Discover's long lists drawn in part (the owner, 11-13), after the rest of its hook moved into plugingrid.js, imported when Plugins first draws; +296 for the cap toggle and Smart sentences that say what they do and the Sign in on another computer row (Wing8Aqua on X), packed to the shortest form, no page left to move them to; +333 for In turn's figure in a provider's editor and its words naming the message that goes round (Wing8Aqua on X), the figure itself in rotfig.js, imported when In turn is first shown, the hook packed to the shortest form; +236 for a lone capped Codex account's row saying its turns go to the fallbacks when Codex is connected (not_4O4 on X), the two helpers inlined, no page left to move it to; +717 for omp's advisor (Awad_Yoo on X, #6408): its three rows moved into ompadvisor.js, imported when an omp's settings show, and what is left is the import, the role's " · off" and the Settings line's name, packed to the shortest form; +468 for a plugin's own file import (auth.import) in the import sheet, in the plugin's words (marchen_cc on X), packed to one statement; importSay is read as the Providers rows draw, so it has no lazy page to go to, and nothing else was moved out; +180 for Claude Magpie's own Claude Code folder (xMopf7RF on X, #6459): its Advanced fold in claudemagpie.js, imported when it first shows, and what is left is the import and the fold's place in the Separate app line, 216 bytes packed to the shortest form, less the 36 of room there was; +81 for the Use Claude Magpie button on Claude Desktop's row (xMopf7RF on X), drawn by claudemagpie.js too, what is left the one line that places it (#2710); +225 for the Hermes row's Other profiles lines (Norethcy on X), which 1d60b165c took out while each profile had a row and c96f33d65 left with no place at all, packed to the shortest form; the dead hermes# Default note went with it, and the Agents rows draw it, so there is no page to move it to; +397 for a key's own price rate (tnt12231 on X): its lines, check and placeholder in keyrates.js, imported when a provider with two or more keys opens, and what is left is the import, the draft's copy, Advanced opening for it, the save's one line and proxyLines drawing another kind of line; +316 for an image or video model's chip saying what it makes from its right-click (iceloon on X): the chat chip's Makes… now shared with it, and the media chip's Copy model ID left out, packed to the shortest form; the provider's editor draws it, so there is no page to move it to; +67 for the Claude Code · Claude Magpie row saying it is on magpie through Claude Magpie (xMopf7RF on X), one line in connectLine with the shortest words that say it; the Agents rows draw it, so there is no page to move it to; +12 for AIGoCode's logo in pngIcons (MindfulReturn on X), the list every drawn icon is looked up in; +491 for each cost in the tray panel's and Requests' chart and ranking in its own provider's currency (onkashiko on X): ledProv and the provider passed through, packed to the shortest form; drawLedColumns and drawLedRank are shared by the panel, so there is no page to move it to
|
||||
coreScriptBudget = 1_269_857 // every core script at 8016205e3, the old measure 682 over its cap there (#5918); +367 for the model test on a chosen account (tmr11235), no page left to move it to; +151 for the provider menu's "Only on this device" item and its four translations; +458 for Settings › About's Report a problem row and its translations; +113 for withScheme, the one rule every typed address goes through (eachg0 on X), cut to the shortest form that keeps it whole; +10 for the kept whole's tooltip (Musikrv77852 on X), the past-cycle line reused for it, no page left to move it to; +1,112 for Codex's Open button and its Open Codex with menu (Yink88564391 on X), packed to the shortest form, no page left to move them to; +168 for Discover's long lists drawn in part (the owner, 11-13), after the rest of its hook moved into plugingrid.js, imported when Plugins first draws; +296 for the cap toggle and Smart sentences that say what they do and the Sign in on another computer row (Wing8Aqua on X), packed to the shortest form, no page left to move them to; +333 for In turn's figure in a provider's editor and its words naming the message that goes round (Wing8Aqua on X), the figure itself in rotfig.js, imported when In turn is first shown, the hook packed to the shortest form; +236 for a lone capped Codex account's row saying its turns go to the fallbacks when Codex is connected (not_4O4 on X), the two helpers inlined, no page left to move it to; +717 for omp's advisor (Awad_Yoo on X, #6408): its three rows moved into ompadvisor.js, imported when an omp's settings show, and what is left is the import, the role's " · off" and the Settings line's name, packed to the shortest form; +468 for a plugin's own file import (auth.import) in the import sheet, in the plugin's words (marchen_cc on X), packed to one statement; importSay is read as the Providers rows draw, so it has no lazy page to go to, and nothing else was moved out; +180 for Claude Magpie's own Claude Code folder (xMopf7RF on X, #6459): its Advanced fold in claudemagpie.js, imported when it first shows, and what is left is the import and the fold's place in the Separate app line, 216 bytes packed to the shortest form, less the 36 of room there was; +81 for the Use Claude Magpie button on Claude Desktop's row (xMopf7RF on X), drawn by claudemagpie.js too, what is left the one line that places it (#2710); +225 for the Hermes row's Other profiles lines (Norethcy on X), which 1d60b165c took out while each profile had a row and c96f33d65 left with no place at all, packed to the shortest form; the dead hermes# Default note went with it, and the Agents rows draw it, so there is no page to move it to; +397 for a key's own price rate (tnt12231 on X): its lines, check and placeholder in keyrates.js, imported when a provider with two or more keys opens, and what is left is the import, the draft's copy, Advanced opening for it, the save's one line and proxyLines drawing another kind of line; +316 for an image or video model's chip saying what it makes from its right-click (iceloon on X): the chat chip's Makes… now shared with it, and the media chip's Copy model ID left out, packed to the shortest form; the provider's editor draws it, so there is no page to move it to; +67 for the Claude Code · Claude Magpie row saying it is on magpie through Claude Magpie (xMopf7RF on X), one line in connectLine with the shortest words that say it; the Agents rows draw it, so there is no page to move it to; +12 for AIGoCode's logo in pngIcons (MindfulReturn on X), the list every drawn icon is looked up in; +491 for each cost in the tray panel's and Requests' chart and ranking in its own provider's currency (onkashiko on X): ledProv and the provider passed through, packed to the shortest form; drawLedColumns and drawLedRank are shared by the panel, so there is no page to move it to; +326 for the Qwen AI platform's Token Plan sign-in (imthe99galaxy on X): its field, sign-in and wait in qianwenplan.js, imported when such a provider's editor opens, and what is left is the import and one quotaError line for its two refusals, packed to the shortest form; quotaError reads every card's error, so there is no page to move it to
|
||||
)
|
||||
|
||||
// codeBytes is how many bytes of b are code: its blank lines, its lines
|
||||
|
||||
@@ -319,6 +319,9 @@ type providerJSON struct {
|
||||
// a StepFun provider's Step Plan windows, told only to a platform
|
||||
// sign-in: which site's, and whether one is kept
|
||||
StepPlan *stepPlanJSON `json:"stepPlan,omitempty"`
|
||||
// a Qwen AI platform Token Plan's windows, told only to a sign-in on
|
||||
// the platform: whether magpie has one, and whose
|
||||
QianwenPlan *qianwenPlanJSON `json:"qianwenPlan,omitempty"`
|
||||
// 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"`
|
||||
@@ -570,6 +573,13 @@ type stepPlanJSON struct {
|
||||
Bookmarklet string `json:"bookmarklet"`
|
||||
}
|
||||
|
||||
// qianwenPlanJSON: whether magpie has a sign-in to the Qwen AI platform
|
||||
// for the provider, and its account
|
||||
type qianwenPlanJSON struct {
|
||||
SignedIn bool `json:"signedIn"`
|
||||
Account string `json:"account,omitempty"`
|
||||
}
|
||||
|
||||
type accountJSON struct {
|
||||
provider.Account
|
||||
Agent string `json:"agent"` // the agent's id
|
||||
@@ -1013,6 +1023,9 @@ func providerInfoWith(p provider.Provider, ls provider.Listing, agents []agentUs
|
||||
if site := provider.StepFunSite(p); site != "" {
|
||||
out.StepPlan = &stepPlanJSON{site, provider.StepFunSignedIn(p.ID), provider.StepFunSignInURL(site), provider.StepFunBookmarklet()}
|
||||
}
|
||||
if provider.QianwenPlan(p) {
|
||||
out.QianwenPlan = &qianwenPlanJSON{provider.QianwenSignedIn(p.ID), provider.QianwenAccount(p.ID)}
|
||||
}
|
||||
out.Key.Set = p.Key != ""
|
||||
out.Key.Masked = provider.Mask(p.Key)
|
||||
out.ProxyGone = provider.ProxyGone(p)
|
||||
@@ -3562,6 +3575,62 @@ func providerRoutes(mux *http.ServeMux, w Windows) {
|
||||
}
|
||||
writeProvidersJSON(rw, providersState())
|
||||
})
|
||||
// the Qwen AI platform's Token Plan windows: a sign-in to the
|
||||
// platform, approved in the user's browser, the provider's own
|
||||
qianwenOf := func(rw http.ResponseWriter, r *http.Request) (string, bool) {
|
||||
p, err := provider.Find(r.PathValue("id"))
|
||||
if err != nil || !provider.QianwenPlan(*p) {
|
||||
http.NotFound(rw, r)
|
||||
return "", false
|
||||
}
|
||||
return p.ID, true
|
||||
}
|
||||
mux.HandleFunc("POST /api/qianwen/{id}/signin", func(rw http.ResponseWriter, r *http.Request) {
|
||||
id, ok := qianwenOf(rw, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second)
|
||||
defer cancel()
|
||||
u, err := provider.StartQianwenSignIn(ctx, id)
|
||||
if err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
writeJSON(rw, struct {
|
||||
URL string `json:"url"`
|
||||
}{u})
|
||||
})
|
||||
mux.HandleFunc("GET /api/qianwen/{id}/signin", func(rw http.ResponseWriter, r *http.Request) {
|
||||
id, ok := qianwenOf(rw, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
state, why := provider.QianwenSignInState(id)
|
||||
writeJSON(rw, struct {
|
||||
State string `json:"state"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}{state, why})
|
||||
})
|
||||
mux.HandleFunc("POST /api/qianwen/{id}/signin/cancel", func(rw http.ResponseWriter, r *http.Request) {
|
||||
id, ok := qianwenOf(rw, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
provider.CancelQianwenSignIn(id)
|
||||
rw.WriteHeader(http.StatusNoContent)
|
||||
})
|
||||
mux.HandleFunc("POST /api/qianwen/{id}/signout", func(rw http.ResponseWriter, r *http.Request) {
|
||||
id, ok := qianwenOf(rw, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if err := provider.SignOutQianwen(id); err != nil {
|
||||
fail(rw, err)
|
||||
return
|
||||
}
|
||||
writeProvidersJSON(rw, providersState())
|
||||
})
|
||||
// the page copies through here first: in the app's window the
|
||||
// clipboard API is refused or missing, depending on the system
|
||||
mux.HandleFunc("POST /api/copy", func(rw http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -0,0 +1,97 @@
|
||||
package gui
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
)
|
||||
|
||||
// A Qwen AI platform Token Plan's sign-in (@imthe99galaxy on X: no quota
|
||||
// for the plan) is its provider's own: the editor is told each one's and
|
||||
// whose, and signing one out leaves the other signed in. A provider that
|
||||
// isn't on the plan has no sign-in to start, ask or end.
|
||||
func TestQianwenSignInRoutes(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())
|
||||
const base = "https://token-plan.maas.qianwenaiapi.com/compatible-mode/v1"
|
||||
for _, p := range []provider.Provider{
|
||||
{ID: "qwen-token-plan", Name: "Qwen Token Plan", Key: "sk-sp-1", Chat: base},
|
||||
{ID: "qwen-work", Name: "Qwen Work", Key: "sk-sp-2", Chat: base},
|
||||
{ID: "bailian", Name: "Bailian", Key: "sk-sp-3", Chat: "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1"},
|
||||
} {
|
||||
if err := provider.Save(p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
auth := filepath.Join(filepath.Dir(provider.Path()), "qianwen-auth.json")
|
||||
if err := os.WriteFile(auth, []byte(`{"qwen-token-plan":{"access":"a1","email":"a@example.com"},"qwen-work":{"access":"a2"}}`), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mux := http.NewServeMux()
|
||||
providerRoutes(mux, nil)
|
||||
plans := func() map[string]string {
|
||||
t.Helper()
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, httptest.NewRequest("GET", "/api/providers", nil))
|
||||
var got struct {
|
||||
Providers []struct {
|
||||
ID string
|
||||
QianwenPlan *struct {
|
||||
SignedIn bool
|
||||
Account string
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := json.Unmarshal(w.Body.Bytes(), &got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
out := map[string]string{}
|
||||
for _, p := range got.Providers {
|
||||
if q := p.QianwenPlan; q != nil {
|
||||
out[p.ID] = "out"
|
||||
if q.SignedIn {
|
||||
out[p.ID] = "in " + q.Account
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
if got := plans(); got["qwen-token-plan"] != "in a@example.com" || got["qwen-work"] != "in " || len(got) != 2 {
|
||||
t.Fatalf("before: %v", got)
|
||||
}
|
||||
for _, id := range []string{"bailian", "nobody"} {
|
||||
for _, c := range []struct{ method, path string }{{"POST", "/signin"}, {"GET", "/signin"}, {"POST", "/signin/cancel"}, {"POST", "/signout"}} {
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, httptest.NewRequest(c.method, "/api/qianwen/"+id+c.path, strings.NewReader("{}")))
|
||||
if w.Code != http.StatusNotFound {
|
||||
t.Errorf("%s %s for %s: %d, want 404", c.method, c.path, id, w.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
w := httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, httptest.NewRequest("GET", "/api/qianwen/qwen-work/signin", nil))
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), `"state":""`) {
|
||||
t.Errorf("no sign-in under way: %d %s", w.Code, w.Body)
|
||||
}
|
||||
w = httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/qianwen/qwen-work/signin/cancel", nil))
|
||||
if w.Code != http.StatusNoContent {
|
||||
t.Errorf("cancel: %d", w.Code)
|
||||
}
|
||||
w = httptest.NewRecorder()
|
||||
mux.ServeHTTP(w, httptest.NewRequest("POST", "/api/qianwen/qwen-token-plan/signout", strings.NewReader("{}")))
|
||||
if w.Code != 200 {
|
||||
t.Fatalf("signout: %d %s", w.Code, w.Body)
|
||||
}
|
||||
if got := plans(); got["qwen-token-plan"] != "out" || got["qwen-work"] != "in " {
|
||||
t.Fatalf("after signing one out: %v", got)
|
||||
}
|
||||
}
|
||||
@@ -185,7 +185,7 @@ test("compat.js is the first of the page's own scripts", async () => {
|
||||
// appearance.js when Settings draws General or the look changes;
|
||||
// the checks above
|
||||
// still read them
|
||||
for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quotatable.js", "quitask.js", "checkinnow.js", "proxies.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "agentwindow.js", "balfound.js", "passerrors.js", "tlscerts.js", "keybalance.js", "modellimits.js", "notices.js", "videogen.js", "provlinks.js", "setfeats.js", "pageshare.js", "panelfirst.js", "panelarrange.js", "modelfind.js", "agentsmanager.js", "agentsuffix.js", "phonetabs.js", "pluginmd.js", "bark.js", "acctexport.js", "plugincounts.js", "navicons.js", "autoswitchtip.js", "codexprojects.js", "pipecheck.js", "addfloat.js", "plugingrid.js", "plugininstalled.js", "rotfig.js", "ompadvisor.js", "claudemagpie.js", "keyrates.js", "updatetrust.js", "currencyprefs.js", "appearance.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html");
|
||||
for (const f of await scripts()) if (!["webfonts.js", "cfgblocked.js", "signsheets.js", "ruleedit.js", "ratewindows.js", "traywindows.js", "autoresetown.js", "registry.js", "navlamp.js", "whatsnew.js", "claudemode.js", "ctxtext.js", "resetask.js", "quotaall.js", "quotatable.js", "quitask.js", "checkinnow.js", "proxies.js", "autobackup.js", "scrollends.js", "profilerename.js", "settingshints.js", "keyspend.js", "syncfiles.js", "agentcompact.js", "agentwindow.js", "balfound.js", "passerrors.js", "tlscerts.js", "keybalance.js", "modellimits.js", "notices.js", "videogen.js", "provlinks.js", "setfeats.js", "pageshare.js", "panelfirst.js", "panelarrange.js", "modelfind.js", "agentsmanager.js", "agentsuffix.js", "phonetabs.js", "pluginmd.js", "bark.js", "acctexport.js", "plugincounts.js", "navicons.js", "autoswitchtip.js", "codexprojects.js", "pipecheck.js", "addfloat.js", "plugingrid.js", "plugininstalled.js", "rotfig.js", "ompadvisor.js", "claudemagpie.js", "keyrates.js", "qianwenplan.js", "updatetrust.js", "currencyprefs.js", "appearance.js"].includes(f)) assert(all.includes(f), f + " is not loaded by index.html");
|
||||
});
|
||||
|
||||
test("the styles hold up in Safari 15.0", async () => {
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
// Run with Node's test runner and Playwright on the module path; see README.md.
|
||||
// A Qwen AI platform Token Plan (qwen-token-plan) had no quota card at all
|
||||
// (@imthe99galaxy on X): its usage is told only to a sign-in on the
|
||||
// platform. The card now says so, also when the sign-in ended, in the user's
|
||||
// language, with the button to the provider's settings; there the user
|
||||
// signs in through their browser, magpie waits for the approval, and the
|
||||
// editor then says whose sign-in it is, with Sign out for that provider's
|
||||
// id. No backend, the API is faked here.
|
||||
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");
|
||||
// qianwen_plan.go's words
|
||||
const NONE = "this plan's usage is told only to a sign-in on the Qwen AI platform: sign in in Qwen Token Plan's settings";
|
||||
const ENDED = "signed out of the Qwen AI platform: sign in again in the provider's settings";
|
||||
|
||||
const quotas = [
|
||||
{ provider: "qwen-token-plan", name: "Qwen Token Plan", icon: "qwen-color", plan: "Token Plan", error: NONE, needsAccessKey: true, windows: [] },
|
||||
{ provider: "qwen-work", name: "Qwen Work", icon: "qwen-color", plan: "Token Plan", error: ENDED, needsAccessKey: true, windows: [] },
|
||||
];
|
||||
const qwen = (id, name, signedIn, account) => ({
|
||||
id, name, icon: "qwen-color", preset: "qwen-token-plan", chat: "https://token-plan.maas.qianwenaiapi.com/compatible-mode/v1", responses: "", anthropic: "https://token-plan.maas.qianwenaiapi.com/apps/anthropic", catalog: "",
|
||||
models: [{ id: "qwen3.6-plus", name: "Qwen3.6 Plus", on: true }], agents: [], fallback: [], headers: {},
|
||||
key: { set: true, masked: "sk-sp-…ab12" }, keyList: [], balanceToken: { takes: false, set: false }, proxy: "",
|
||||
qianwenPlan: { signedIn, ...(account ? { account } : {}) },
|
||||
});
|
||||
|
||||
function serve(lang, posts, flow) {
|
||||
const settings = { theme: "light", lang, tray: "panel", quotaLeft: false, currency: "usd" };
|
||||
const list = () => ({ providers: [qwen("qwen-token-plan", "Qwen Token Plan", flow.done, flow.done ? "a@example.com" : ""), qwen("qwen-work", "Qwen Work", false)], presets: [], excluded: [], gateway: { running: true, window: true } });
|
||||
return async (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
const json = (body) => route.fulfill({ json: body });
|
||||
// the platform's page, opened in a tab of its own: never the network
|
||||
if (url.host !== "magpie.test") {
|
||||
posts.push({ method: "TAB", path: url.href });
|
||||
return route.fulfill({ contentType: "text/html", body: "" });
|
||||
}
|
||||
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 });
|
||||
if (url.pathname === "/api/settings") return json(settings);
|
||||
if (url.pathname === "/api/providers") return json(list());
|
||||
if (url.pathname === "/api/usage/quotas") return json(quotas);
|
||||
if (url.pathname === "/api/usage/quotas/history") return json([]);
|
||||
if (url.pathname === "/api/groups") return json({ groups: [], models: [] });
|
||||
if (url.pathname === "/api/plugins") return json({ plugins: [] });
|
||||
if (url.pathname.startsWith("/api/qianwen/")) {
|
||||
const method = route.request().method();
|
||||
posts.push({ method, path: url.pathname, body: method === "POST" ? route.request().postDataJSON() : null });
|
||||
if (url.pathname.endsWith("/signin") && method === "POST") return json({ url: "https://account.qianwenai.com/sso/OIDCAuth?auth_token=t1" });
|
||||
if (url.pathname.endsWith("/signin")) {
|
||||
// pending once, then approved
|
||||
flow.asked++;
|
||||
if (flow.asked > 1) flow.done = true;
|
||||
return json({ state: flow.done ? "done" : "pending" });
|
||||
}
|
||||
if (url.pathname.endsWith("/signout")) return json(list());
|
||||
return json({});
|
||||
}
|
||||
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 words = {
|
||||
en: { none: "This plan's usage needs a sign-in to the Qwen AI platform — sign in in the provider's settings", open: "Open settings", signIn: "Sign in to the Qwen AI platform ↗", approve: "Approve the sign-in in your browser…", as: "Signed in as a@example.com", out: "Sign out" },
|
||||
zh: { none: "这个套餐的用量需要登录千问 AI 平台——在提供商设置里登录", open: "打开设置", signIn: "登录千问 AI 平台 ↗", approve: "请在浏览器里批准登录…", as: "已登录 a@example.com", out: "退出登录" },
|
||||
"zh-TW": { none: "這個方案的用量需要登入千問 AI 平台——在供應商設定裡登入", open: "開啟設定", signIn: "登入千問 AI 平台 ↗", approve: "請在瀏覽器裡核准登入…", as: "已登入 a@example.com", out: "退出登入" },
|
||||
ja: { none: "このプランの利用量には Qwen AI プラットフォームへのサインインが必要です — プロバイダの設定でサインインしてください", open: "設定を開く", signIn: "Qwen AI プラットフォームにサインイン ↗", approve: "ブラウザでサインインを承認してください…", as: "a@example.com としてサインインしました", out: "サインアウト" },
|
||||
de: { none: "Die Nutzung dieses Plans braucht eine Anmeldung bei der Qwen-AI-Plattform — melde dich in den Einstellungen des Anbieters an", open: "Einstellungen öffnen", signIn: "Bei der Qwen-AI-Plattform anmelden ↗", approve: "Bestätige die Anmeldung im Browser …", as: "Angemeldet als a@example.com", out: "Abmelden" },
|
||||
};
|
||||
|
||||
for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium", "webkit"])) {
|
||||
for (const [lang, w] of Object.entries(words)) {
|
||||
for (const width of [900, 420]) {
|
||||
test(`${engine} ${lang} ${width}px: a Qwen AI platform plan's card asks for the sign-in, which the editor makes`, async (t) => {
|
||||
const browser = await (engine === "webkit" ? webkit.launch() : chromium.launch({ channel: "chromium" }));
|
||||
t.after(() => browser.close());
|
||||
const errors = [];
|
||||
const ctx = await browser.newContext({ viewport: { width, height: 800 }, reducedMotion: "reduce" });
|
||||
const page = await ctx.newPage();
|
||||
page.setDefaultTimeout(8000);
|
||||
page.setDefaultNavigationTimeout(60000);
|
||||
page.on("pageerror", (e) => errors.push(e.message));
|
||||
const posts = [];
|
||||
const flow = { asked: 0, done: false };
|
||||
await ctx.route("**/*", serve(lang, posts, flow));
|
||||
await page.goto("http://magpie.test/?view=usage");
|
||||
|
||||
// the card says why it has no windows, the reason in its tooltip
|
||||
const err = page.locator('.subscription-card[data-provider="qwen-token-plan"] .subscription-error');
|
||||
await err.waitFor();
|
||||
assert.equal(await err.getAttribute("title"), NONE);
|
||||
assert.ok((await err.textContent()).includes(w.none), await err.textContent());
|
||||
const ended = page.locator('.subscription-card[data-provider="qwen-work"] .subscription-error');
|
||||
assert.ok((await ended.textContent()).includes(w.none), await ended.textContent());
|
||||
const go = err.locator(".quota-fix");
|
||||
assert.equal((await go.textContent()).trim(), w.open);
|
||||
const [e, b] = [await err.boundingBox(), await go.boundingBox()];
|
||||
assert.ok(e.x + e.width <= width && b.x + b.width <= width, "the error and its button fit the page");
|
||||
|
||||
// to the provider's own settings, where the sign-in starts
|
||||
await go.click();
|
||||
await page.waitForURL(/view=providers/);
|
||||
assert.equal(new URL(page.url()).searchParams.get("edit"), "qwen-token-plan");
|
||||
const box = page.locator(".editor .stepplan");
|
||||
const signIn = box.getByRole("button", { name: w.signIn, exact: true });
|
||||
await signIn.click();
|
||||
// the platform's page opens in the browser, and magpie waits
|
||||
await box.getByText(w.approve, { exact: true }).waitFor();
|
||||
for (let i = 0; i < 50 && !posts.some((p) => p.method === "TAB"); i++) await page.waitForTimeout(50);
|
||||
assert.deepEqual(posts.slice(0, 2).map((p) => p.method + " " + p.path), ["POST /api/qianwen/qwen-token-plan/signin", "TAB https://account.qianwenai.com/sso/OIDCAuth?auth_token=t1"]);
|
||||
// approved: whose sign-in it is, and Sign out for this provider
|
||||
await box.getByText(w.as, { exact: true }).waitFor({ timeout: 15000 });
|
||||
const sb = await box.boundingBox();
|
||||
assert.ok(sb.x + sb.width <= width, "the sign-in fits the editor");
|
||||
await box.getByRole("button", { name: w.out, exact: true }).click();
|
||||
for (let i = 0; i < 50 && !posts.some((p) => p.path.endsWith("/signout")); i++) await page.waitForTimeout(50);
|
||||
assert.ok(posts.some((p) => p.path === "/api/qianwen/qwen-token-plan/signout"), JSON.stringify(posts));
|
||||
assert.ok(!posts.some((p) => p.path.includes("qwen-work")), "nothing for the other provider");
|
||||
assert.deepEqual(errors, []);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -22,9 +22,10 @@ package provider
|
||||
//
|
||||
// The gateway has no public documentation: the fields are read as the
|
||||
// client does, from whichever per<N><Unit> pairs the reply has. Only the
|
||||
// personal plan's API is known; the Qwen AI platform's and Qwen Cloud's
|
||||
// plans sit behind a console of their own that takes a browser sign-in, so
|
||||
// they have no card (#5829).
|
||||
// personal plan's API is known. The Qwen AI platform's plan is read the
|
||||
// same way at its own console, with a sign-in to the platform instead of
|
||||
// an access key (qianwen_plan.go); Qwen Cloud's sits behind a console that
|
||||
// takes a browser sign-in, so it has no card (#5829).
|
||||
//
|
||||
// A RAM user's key is refused by the console (BailianGateway.Team.
|
||||
// NotAuthorised) until the main account grants what Alibaba's Token Plan
|
||||
@@ -324,20 +325,40 @@ func aliMintToken(ctx context.Context, ak, sk string, site aliSite, now time.Tim
|
||||
// aliGateway asks the console's usage API with token and gives the
|
||||
// business data of the reply (data.DataV2.data.data).
|
||||
func aliGateway(ctx context.Context, token string, site aliSite) ([]byte, error) {
|
||||
u := "https://" + site.gateway + "/cli/api.json?action=" + site.action + "&product=sfm_bailian&api=" + url.QueryEscape(aliUsageAPI)
|
||||
return aliAskUsage(ctx, token, aliConsole{url: u, region: site.region, site: "BAILIAN_ALIYUN", who: "Alibaba Cloud's console", denied: aliRAMHint})
|
||||
}
|
||||
|
||||
// aliConsole is a console gateway the Token Plan's usage API is asked
|
||||
// at: Alibaba Cloud's (aliGateway) or the Qwen AI platform's
|
||||
// (qianwen_plan.go), which answer alike.
|
||||
type aliConsole struct {
|
||||
url, region string
|
||||
site string // cornerstoneParam's consoleSite
|
||||
who string // the console, as an error names it
|
||||
denied string // what to do when the console says NotAuthorised
|
||||
ua string // the User-Agent its own client sends, if any
|
||||
}
|
||||
|
||||
// aliAskUsage posts the usage API's form to the console with token, and
|
||||
// gives the reply's business data.
|
||||
func aliAskUsage(ctx context.Context, token string, c aliConsole) ([]byte, error) {
|
||||
params, _ := json.Marshal(map[string]any{
|
||||
"Api": aliUsageAPI, "V": "1.0",
|
||||
"Data": map[string]any{"cornerstoneParam": map[string]any{
|
||||
"protocol": "V2", "console": "ONE_CONSOLE", "productCode": "p_efm", "switchUserType": 3, "consoleSite": "BAILIAN_ALIYUN"}},
|
||||
"protocol": "V2", "console": "ONE_CONSOLE", "productCode": "p_efm", "switchUserType": 3, "consoleSite": c.site}},
|
||||
})
|
||||
form := url.Values{"params": {string(params)}, "region": {site.region}}
|
||||
u := "https://" + site.gateway + "/cli/api.json?action=" + site.action + "&product=sfm_bailian&api=" + url.QueryEscape(aliUsageAPI)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u, bytes.NewReader([]byte(form.Encode())))
|
||||
form := url.Values{"params": {string(params)}, "region": {c.region}}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.url, bytes.NewReader([]byte(form.Encode())))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
req.Header.Set("Accept", "*/*")
|
||||
if c.ua != "" {
|
||||
req.Header.Set("User-Agent", c.ua)
|
||||
}
|
||||
res, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -348,7 +369,7 @@ func aliGateway(ctx context.Context, token string, site aliSite) ([]byte, error)
|
||||
return nil, err
|
||||
}
|
||||
if res.StatusCode >= 300 {
|
||||
return nil, fmt.Errorf("Alibaba Cloud's console: %s: %s", res.Status, volcHead(raw))
|
||||
return nil, fmt.Errorf("%s: %s: %s", c.who, res.Status, volcHead(raw))
|
||||
}
|
||||
var env struct {
|
||||
Data struct {
|
||||
@@ -359,20 +380,20 @@ func aliGateway(ctx context.Context, token string, site aliSite) ([]byte, error)
|
||||
} `json:"data"`
|
||||
}
|
||||
if json.Unmarshal(raw, &env) != nil {
|
||||
return nil, fmt.Errorf("Alibaba Cloud's console answered in a form magpie doesn't know: %s", volcHead(raw))
|
||||
return nil, fmt.Errorf("%s answered in a form magpie doesn't know: %s", c.who, volcHead(raw))
|
||||
}
|
||||
if env.Data.Success != nil && !*env.Data.Success && len(env.Data.ErrorCode) > 0 {
|
||||
code := strings.Trim(string(env.Data.ErrorCode), `"`)
|
||||
switch {
|
||||
case strings.Contains(code, "NotLogined"):
|
||||
return nil, errAliNotLogged
|
||||
case strings.Contains(code, "NotAuthorised"), strings.Contains(code, "NotAuthorized"):
|
||||
return nil, fmt.Errorf("Alibaba Cloud's console: %s: %s", code, aliRAMHint)
|
||||
case c.denied != "" && (strings.Contains(code, "NotAuthorised") || strings.Contains(code, "NotAuthorized")):
|
||||
return nil, fmt.Errorf("%s: %s: %s", c.who, code, c.denied)
|
||||
}
|
||||
if msg := strings.TrimSpace(strings.Trim(string(env.Data.ErrorMsg), `"`)); msg != "" && msg != "null" {
|
||||
return nil, fmt.Errorf("Alibaba Cloud's console: %s: %s", code, msg)
|
||||
return nil, fmt.Errorf("%s: %s: %s", c.who, code, msg)
|
||||
}
|
||||
return nil, fmt.Errorf("Alibaba Cloud's console: %s", code)
|
||||
return nil, fmt.Errorf("%s: %s", c.who, code)
|
||||
}
|
||||
// the reply holds it in two envelopes, one less in some replies
|
||||
var node json.RawMessage = env.Data.DataV2
|
||||
|
||||
@@ -74,8 +74,9 @@ func readsKeyWindows(p Provider) bool {
|
||||
// account tells, not the key: Volcengine Ark's Coding and Agent Plans and
|
||||
// Tencent Cloud's Token Plan Enterprise and Alibaba Cloud's Token Plan, read
|
||||
// with the account's access key (volcengine_usage.go, tencent_usage.go,
|
||||
// alibaba_usage.go), and StepFun's Step Plan,
|
||||
// read with magpie's sign-in to its platform (stepfun_plan.go). The
|
||||
// alibaba_usage.go), and StepFun's Step Plan and the Qwen AI platform's
|
||||
// Token Plan, read with magpie's sign-in to the platform (stepfun_plan.go,
|
||||
// qianwen_plan.go). The
|
||||
// Usage page had their windows while routing had none, and the Routing
|
||||
// page said "one key" of a plan with them (chen on Discord). "" for any
|
||||
// other key, or one whose access key magpie isn't given; said without
|
||||
@@ -97,6 +98,9 @@ func accountPlanOf(p Provider) string {
|
||||
if StepFunSite(p) != "" {
|
||||
return "stepfun"
|
||||
}
|
||||
if QianwenPlan(p) {
|
||||
return "qianwen"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
@@ -124,6 +128,11 @@ func accountPlanWindows(ctx context.Context, q Provider) (keyReading, error) {
|
||||
return keyReading{}, nil
|
||||
}
|
||||
c = stepPlanQuota(q.Via(ctx), q)
|
||||
case "qianwen":
|
||||
if !QianwenSignedIn(q.ID) {
|
||||
return keyReading{}, nil
|
||||
}
|
||||
c = qianwenPlanQuota(q.Via(ctx), q)
|
||||
}
|
||||
if c.Error != "" {
|
||||
return keyReading{}, errors.New(c.Error)
|
||||
@@ -291,6 +300,8 @@ func keyCardTag(p Provider) string {
|
||||
return keyTag("alibaba "+site.region, p.AccessKeyID)
|
||||
case "stepfun":
|
||||
return keyTag("stepfun", p.ID)
|
||||
case "qianwen":
|
||||
return keyTag("qianwen", p.ID)
|
||||
}
|
||||
}
|
||||
if _, ok := planQuotaSourceOf(p); ok && !sub2APIKeyLimits(p) {
|
||||
|
||||
@@ -6,7 +6,8 @@ package provider
|
||||
// Vibe, 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
|
||||
// sign-in, stepfun_plan.go, as is the Qwen AI platform's Token Plan,
|
||||
// qianwen_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'.
|
||||
|
||||
@@ -888,6 +889,8 @@ func PlanQuotas(ctx context.Context) []SubscriptionQuota {
|
||||
go func() { tencent <- tencentPlanQuotas(ctx) }()
|
||||
ali := make(chan []SubscriptionQuota, 1)
|
||||
go func() { ali <- aliPlanQuotas(ctx) }()
|
||||
qianwen := make(chan []SubscriptionQuota, 1)
|
||||
go func() { qianwen <- qianwenPlanQuotas(ctx) }()
|
||||
wg.Wait()
|
||||
out := []SubscriptionQuota{}
|
||||
for i, q := range got {
|
||||
@@ -897,8 +900,9 @@ func PlanQuotas(ctx context.Context) []SubscriptionQuota {
|
||||
out = append(out, *q)
|
||||
}
|
||||
}
|
||||
// StepFun's, Volcengine's, Tencent's and Alibaba's, read just now too
|
||||
for _, qs := range [][]SubscriptionQuota{<-stepfun, <-volc, <-tencent, <-ali} {
|
||||
// StepFun's, Volcengine's, Tencent's, Alibaba's and the Qwen AI
|
||||
// platform's, read just now too
|
||||
for _, qs := range [][]SubscriptionQuota{<-stepfun, <-volc, <-tencent, <-ali, <-qianwen} {
|
||||
for _, q := range qs {
|
||||
out = append(out, readNow(q))
|
||||
}
|
||||
|
||||
@@ -412,10 +412,10 @@ var presets = []PresetDef{
|
||||
// token-plan.maas.qianwenaiapi.com, and on Alibaba Cloud Bailian
|
||||
// (bailian.console.aliyun.com) at token-plan.cn-beijing.maas.aliyuncs.com
|
||||
// (#1506). The models given are the plans' text models as their
|
||||
// overviews list them, for when the host gives no list. Only the
|
||||
// two at aliyuncs.com have a way to read the plan's credits, with the
|
||||
// account's AccessKey (alibaba_usage.go); the Qwen AI platform's console
|
||||
// takes a browser sign-in (#5829).
|
||||
// overviews list them, for when the host gives no list. The two at
|
||||
// aliyuncs.com read the plan's credits with the account's AccessKey
|
||||
// (alibaba_usage.go); the Qwen AI platform's with a sign-in to the
|
||||
// platform, as its own QianWen CLI does (qianwen_plan.go).
|
||||
{ID: "qwen-token-plan", Name: "Qwen Token Plan", Short: "Qwen Plan", Icon: "qwen-color", Kind: KindVendor,
|
||||
Chat: "https://token-plan.maas.qianwenaiapi.com/compatible-mode/v1", Anthropic: "https://token-plan.maas.qianwenaiapi.com/apps/anthropic",
|
||||
Note: "Qwen AI platform · subscription",
|
||||
|
||||
@@ -1805,9 +1805,12 @@ func Delete(id string) error {
|
||||
if err := store(f); err != nil {
|
||||
return err
|
||||
}
|
||||
// its StepFun sign-in goes with it, not to a provider added later
|
||||
// under the same id
|
||||
return forgetStepFun(id)
|
||||
// its StepFun and Qwen AI platform sign-ins go with it, not to a
|
||||
// provider added later under the same id
|
||||
if err := forgetStepFun(id); err != nil {
|
||||
return err
|
||||
}
|
||||
return forgetQianwen(id)
|
||||
}
|
||||
|
||||
// keyOptional is true for a server on this computer or on the user's own
|
||||
|
||||
@@ -0,0 +1,592 @@
|
||||
package provider
|
||||
|
||||
// The Qwen AI platform's Token Plan (platform.qianwenai.com, sk-sp- keys at
|
||||
// token-plan.maas.qianwenaiapi.com) tells its monthly or weekly window only
|
||||
// to a sign-in on the platform, never to the plan's key: the console's
|
||||
// usage API answers the key BailianGateway.Login.NotLogined. magpie signs in
|
||||
// and reads it as the platform's own client, the QianWen CLI
|
||||
// (@qianwenai/qianwen-cli, `qianwen auth login` and its Token Plan usage),
|
||||
// does:
|
||||
//
|
||||
// 1. POST t.qianwenai.com/cli/device/code?client_id&code_challenge
|
||||
// &code_challenge_method=S256 gives a page for the user to approve the
|
||||
// sign-in on, in their own browser, and a token to wait on;
|
||||
// 2. POST t.qianwenai.com/cli/device/token?client_id&token&code_verifier,
|
||||
// every Interval seconds, answers Status authorization_pending until
|
||||
// the user approves, then complete with Credentials{AccessToken,
|
||||
// ExpireTime, User}. There is no refresh token: when it runs out the
|
||||
// user signs in again, as the CLI asks;
|
||||
// 3. POST cli.qianwenai.com/data/v2/api.json with Bearer the access token
|
||||
// and {product: ModelStudioRegional, action: GenerateCLIAccessToken}
|
||||
// gives a console token, cliAccessToken;
|
||||
// 4. POST cs-data.qianwenai.com/cli/api.json?action=BroadScopeAspnGateway
|
||||
// &product=sfm_bailian&api=…/tokenplan/personal/api/v2/usage with Bearer
|
||||
// that token answers as Alibaba Cloud's console does (aliAskUsage), with
|
||||
// consoleSite QIANWENAI: per1MonthPercentage or per1WeekPercentage and
|
||||
// their reset times.
|
||||
//
|
||||
// The sign-in is kept in qianwen-auth.json beside providers.json, readable
|
||||
// by the user alone, one per provider, as StepFun's is (stepfun_plan.go).
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/filememo"
|
||||
"github.com/yetone/magpie/internal/lastgood"
|
||||
)
|
||||
|
||||
const (
|
||||
qianwenAuthHost = "t.qianwenai.com"
|
||||
qianwenAPIHost = "cli.qianwenai.com"
|
||||
qianwenDataHost = "cs-data.qianwenai.com"
|
||||
// qianwenUA is the User-Agent the platform's own client sends
|
||||
qianwenUA = "qianwen-cli/1.10.0"
|
||||
qianwenRegion = "cn-beijing"
|
||||
qianwenPlanHost = "token-plan.maas.qianwenaiapi.com"
|
||||
)
|
||||
|
||||
// QianwenPlan says p is on the Qwen AI platform's Token Plan, whose usage
|
||||
// magpie reads with a sign-in to the platform.
|
||||
func QianwenPlan(p Provider) bool {
|
||||
if p.Account != nil {
|
||||
return false
|
||||
}
|
||||
for _, base := range []string{p.Chat, p.Anthropic, p.Responses} {
|
||||
if hostOf(base) == qianwenPlanHost {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// qianwenSession is a sign-in on the platform.
|
||||
type qianwenSession struct {
|
||||
Access string `json:"access"`
|
||||
// Expires is when the platform said the access token runs out; zero
|
||||
// when it said nothing magpie could read
|
||||
Expires time.Time `json:"expires,omitzero"`
|
||||
Email string `json:"email,omitempty"`
|
||||
User string `json:"user,omitempty"`
|
||||
ClientID string `json:"clientId,omitempty"`
|
||||
}
|
||||
|
||||
var qianwenMu sync.Mutex
|
||||
|
||||
func qianwenPath() string { return filepath.Join(filepath.Dir(Path()), "qianwen-auth.json") }
|
||||
|
||||
// loadQianwen is every provider's sign-in, by provider id; the caller holds
|
||||
// qianwenMu. A file that doesn't parse is no sign-in, and is left as it
|
||||
// is (saveQianwen keeps it aside before a sign-in writes over it).
|
||||
func loadQianwen() map[string]qianwenSession {
|
||||
out := map[string]qianwenSession{}
|
||||
b, err := os.ReadFile(qianwenPath())
|
||||
if err != nil {
|
||||
return out
|
||||
}
|
||||
if json.Unmarshal(b, &out) != nil {
|
||||
return map[string]qianwenSession{}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func saveQianwen(all map[string]qianwenSession) error {
|
||||
defer filememo.Forget() // read again, where a request holds it
|
||||
b, err := json.MarshalIndent(all, "", " ")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := os.MkdirAll(filepath.Dir(qianwenPath()), 0o700); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := lastgood.KeepUnparsed(qianwenPath(), lastgood.Into[map[string]qianwenSession]); err != nil {
|
||||
return err
|
||||
}
|
||||
return writeFileAtomic(qianwenPath(), b)
|
||||
}
|
||||
|
||||
// QianwenSignedIn reports whether magpie has a sign-in for the provider,
|
||||
// reading the file once until it changes: a provider list asks it on
|
||||
// every poll.
|
||||
func QianwenSignedIn(id string) bool {
|
||||
s, ok := qianwenSignIn(id)
|
||||
return ok && s.Access != ""
|
||||
}
|
||||
|
||||
// QianwenAccount is who the provider's sign-in is, as the platform named
|
||||
// them: an email, or "" when it gave none.
|
||||
func QianwenAccount(id string) string {
|
||||
s, _ := qianwenSignIn(id)
|
||||
return s.Email
|
||||
}
|
||||
|
||||
func qianwenSignIn(id string) (qianwenSession, bool) {
|
||||
all, err := filememo.Read("qianwen-auth", qianwenPath(), func(b []byte) (map[string]qianwenSession, error) {
|
||||
m := map[string]qianwenSession{}
|
||||
return m, json.Unmarshal(b, &m)
|
||||
})
|
||||
if err != nil {
|
||||
return qianwenSession{}, false
|
||||
}
|
||||
s, ok := all[id]
|
||||
return s, ok
|
||||
}
|
||||
|
||||
// SignOutQianwen forgets the provider's sign-in, and no other's.
|
||||
func SignOutQianwen(id string) error {
|
||||
CancelQianwenSignIn(id)
|
||||
qianwenMu.Lock()
|
||||
all := loadQianwen()
|
||||
_, had := all[id]
|
||||
delete(all, id)
|
||||
var err error
|
||||
if had {
|
||||
err = saveQianwen(all)
|
||||
}
|
||||
qianwenMu.Unlock()
|
||||
qianwenForgetToken(id)
|
||||
forgetPlanQuotas()
|
||||
return err
|
||||
}
|
||||
|
||||
// forgetQianwen drops the provider's sign-in, when it is removed.
|
||||
func forgetQianwen(id string) error { return SignOutQianwen(id) }
|
||||
|
||||
// renameQianwen moves the provider's sign-in with it to its new id.
|
||||
func renameQianwen(from, to string) error {
|
||||
qianwenMu.Lock()
|
||||
defer qianwenMu.Unlock()
|
||||
all := loadQianwen()
|
||||
s, ok := all[from]
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
delete(all, from)
|
||||
all[to] = s
|
||||
qianwenForgetToken(from)
|
||||
return saveQianwen(all)
|
||||
}
|
||||
|
||||
// a sign-in under way, by provider id
|
||||
type qianwenFlow struct {
|
||||
url string
|
||||
state string // "pending", "done" or "failed"
|
||||
err string
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
var qianwenFlows = struct {
|
||||
sync.Mutex
|
||||
m map[string]*qianwenFlow
|
||||
}{m: map[string]*qianwenFlow{}}
|
||||
|
||||
// qianwenPoll is how often the platform is asked whether the user has
|
||||
// approved, when it says nothing itself; a test shortens it.
|
||||
var qianwenPoll = 2 * time.Second
|
||||
|
||||
func qianwenUUID() string {
|
||||
b := make([]byte, 16)
|
||||
_, _ = rand.Read(b)
|
||||
b[6] = b[6]&0x0f | 0x40
|
||||
b[8] = b[8]&0x3f | 0x80
|
||||
h := hex.EncodeToString(b)
|
||||
return h[:8] + "-" + h[8:12] + "-" + h[12:16] + "-" + h[16:20] + "-" + h[20:]
|
||||
}
|
||||
|
||||
// qianwenPKCE is a code verifier and its S256 challenge.
|
||||
func qianwenPKCE() (verifier, challenge string) {
|
||||
b := make([]byte, 32)
|
||||
_, _ = rand.Read(b)
|
||||
verifier = base64.RawURLEncoding.EncodeToString(b)
|
||||
sum := sha256.Sum256([]byte(verifier))
|
||||
return verifier, base64.RawURLEncoding.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
// qianwenPost posts to the platform as its client does, the reply read
|
||||
// whole (up to 1MB).
|
||||
func qianwenPost(ctx context.Context, u, contentType string, body []byte, bearer string) (int, []byte, error) {
|
||||
var rd io.Reader
|
||||
if body != nil {
|
||||
rd = bytes.NewReader(body)
|
||||
}
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, u, rd)
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
req.Header.Set("User-Agent", qianwenUA)
|
||||
if contentType != "" {
|
||||
req.Header.Set("Content-Type", contentType)
|
||||
}
|
||||
if bearer != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+bearer)
|
||||
}
|
||||
res, err := Keyed(http.DefaultClient).Do(req)
|
||||
if err != nil {
|
||||
return 0, nil, err
|
||||
}
|
||||
defer res.Body.Close()
|
||||
b, err := io.ReadAll(io.LimitReader(res.Body, 1<<20))
|
||||
return res.StatusCode, b, err
|
||||
}
|
||||
|
||||
// StartQianwenSignIn starts a sign-in to the Qwen AI platform for the
|
||||
// provider id: the page the user approves it on, in their browser. magpie
|
||||
// waits for the approval itself (QianwenSignInState), until the page runs
|
||||
// out.
|
||||
func StartQianwenSignIn(ctx context.Context, id string) (string, error) {
|
||||
clientID := qianwenUUID()
|
||||
verifier, challenge := qianwenPKCE()
|
||||
q := url.Values{"client_id": {clientID}, "code_challenge": {challenge}, "code_challenge_method": {"S256"}}
|
||||
code, raw, err := qianwenPost(ctx, "https://"+qianwenAuthHost+"/cli/device/code?"+q.Encode(), "", nil, "")
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("couldn't reach the Qwen AI platform: %w", err)
|
||||
}
|
||||
var r struct {
|
||||
Success bool
|
||||
Data *struct {
|
||||
Token string
|
||||
VerificationURL string `json:"VerificationUrl"`
|
||||
ExpiresIn float64
|
||||
Interval float64
|
||||
}
|
||||
}
|
||||
if code >= 300 || json.Unmarshal(raw, &r) != nil || !r.Success || r.Data == nil || r.Data.Token == "" || r.Data.VerificationURL == "" {
|
||||
return "", fmt.Errorf("the Qwen AI platform didn't start a sign-in: %d %s", code, volcHead(raw))
|
||||
}
|
||||
life := time.Duration(r.Data.ExpiresIn) * time.Second
|
||||
if life <= 0 || life > 15*time.Minute {
|
||||
life = 5 * time.Minute
|
||||
}
|
||||
every := time.Duration(r.Data.Interval) * time.Second
|
||||
if every <= 0 {
|
||||
every = qianwenPoll
|
||||
}
|
||||
every = min(every, qianwenPoll)
|
||||
wait, cancel := context.WithTimeout(context.Background(), life)
|
||||
f := &qianwenFlow{url: r.Data.VerificationURL, state: "pending", cancel: cancel}
|
||||
qianwenFlows.Lock()
|
||||
if old := qianwenFlows.m[id]; old != nil && old.cancel != nil {
|
||||
old.cancel()
|
||||
}
|
||||
qianwenFlows.m[id] = f
|
||||
qianwenFlows.Unlock()
|
||||
go func() {
|
||||
defer cancel()
|
||||
err := qianwenWait(wait, id, clientID, r.Data.Token, verifier, every)
|
||||
qianwenFlows.Lock()
|
||||
defer qianwenFlows.Unlock()
|
||||
if qianwenFlows.m[id] != f {
|
||||
return // a newer sign-in, or one cancelled
|
||||
}
|
||||
if err != nil {
|
||||
f.state, f.err = "failed", err.Error()
|
||||
return
|
||||
}
|
||||
f.state = "done"
|
||||
}()
|
||||
return f.url, nil
|
||||
}
|
||||
|
||||
// QianwenSignInState is how the provider's sign-in under way goes:
|
||||
// "pending", "done" or "failed" with why, or "" when none is.
|
||||
func QianwenSignInState(id string) (state, why string) {
|
||||
qianwenFlows.Lock()
|
||||
defer qianwenFlows.Unlock()
|
||||
f := qianwenFlows.m[id]
|
||||
if f == nil {
|
||||
return "", ""
|
||||
}
|
||||
return f.state, f.err
|
||||
}
|
||||
|
||||
// CancelQianwenSignIn stops waiting on the provider's sign-in.
|
||||
func CancelQianwenSignIn(id string) {
|
||||
qianwenFlows.Lock()
|
||||
defer qianwenFlows.Unlock()
|
||||
if f := qianwenFlows.m[id]; f != nil {
|
||||
if f.cancel != nil {
|
||||
f.cancel()
|
||||
}
|
||||
delete(qianwenFlows.m, id)
|
||||
}
|
||||
}
|
||||
|
||||
var qianwenStatusWord = regexp.MustCompile(`(?i)expired|access_denied|slow_down`)
|
||||
|
||||
// qianwenWait asks the platform whether the user approved the sign-in,
|
||||
// until they have, refused, or the page ran out, and keeps it.
|
||||
func qianwenWait(ctx context.Context, id, clientID, token, verifier string, every time.Duration) error {
|
||||
q := url.Values{"client_id": {clientID}, "token": {token}, "code_verifier": {verifier}}
|
||||
u := "https://" + qianwenAuthHost + "/cli/device/token?" + q.Encode()
|
||||
t := time.NewTimer(every)
|
||||
defer t.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
if errors.Is(ctx.Err(), context.DeadlineExceeded) {
|
||||
return errors.New("the sign-in page ran out before it was approved: sign in again")
|
||||
}
|
||||
return ctx.Err()
|
||||
case <-t.C:
|
||||
}
|
||||
code, raw, err := qianwenPost(ctx, u, "", nil, "")
|
||||
status := ""
|
||||
var r struct {
|
||||
Data struct {
|
||||
Status string
|
||||
Credentials *struct {
|
||||
AccessToken string
|
||||
ExpireTime any
|
||||
User *struct{ ID, Email, AliyunID string }
|
||||
}
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case err != nil:
|
||||
if ctx.Err() != nil {
|
||||
continue
|
||||
}
|
||||
status = "authorization_pending" // a dropped poll is asked again
|
||||
case code >= 300:
|
||||
// the client reads an error's text for these three
|
||||
status = strings.ToLower(qianwenStatusWord.FindString(string(raw)))
|
||||
if status == "expired" {
|
||||
status = "expired_token"
|
||||
}
|
||||
if status == "" {
|
||||
return fmt.Errorf("the Qwen AI platform: %d %s", code, volcHead(raw))
|
||||
}
|
||||
default:
|
||||
if json.Unmarshal(raw, &r) != nil {
|
||||
return fmt.Errorf("the Qwen AI platform answered in a form magpie doesn't know: %s", volcHead(raw))
|
||||
}
|
||||
status = strings.ToLower(r.Data.Status)
|
||||
if status == "" {
|
||||
status = "authorization_pending"
|
||||
}
|
||||
}
|
||||
switch status {
|
||||
case "authorization_pending":
|
||||
case "slow_down":
|
||||
every += every
|
||||
case "complete":
|
||||
c := r.Data.Credentials
|
||||
if c == nil || c.AccessToken == "" {
|
||||
return errors.New("the Qwen AI platform approved the sign-in but gave no token: sign in again")
|
||||
}
|
||||
s := qianwenSession{Access: c.AccessToken, Expires: qianwenTime(c.ExpireTime), ClientID: clientID}
|
||||
if c.User != nil {
|
||||
s.Email, s.User = c.User.Email, c.User.ID
|
||||
}
|
||||
qianwenMu.Lock()
|
||||
all := loadQianwen()
|
||||
all[id] = s
|
||||
err := saveQianwen(all)
|
||||
qianwenMu.Unlock()
|
||||
qianwenForgetToken(id)
|
||||
forgetPlanQuotas()
|
||||
return err
|
||||
case "expired_token":
|
||||
return errors.New("the sign-in page ran out before it was approved: sign in again")
|
||||
case "access_denied":
|
||||
return errors.New("the sign-in was refused on the Qwen AI platform's page")
|
||||
default:
|
||||
return fmt.Errorf("the Qwen AI platform ended the sign-in: %s", status)
|
||||
}
|
||||
t.Reset(every)
|
||||
}
|
||||
}
|
||||
|
||||
// qianwenTime reads ExpireTime as the client's Date.parse would: a date
|
||||
// and time, or a number of seconds or milliseconds; zero when it can't.
|
||||
func qianwenTime(v any) time.Time {
|
||||
switch x := v.(type) {
|
||||
case float64:
|
||||
if t, ok := stepfunTime(x); ok {
|
||||
return t
|
||||
}
|
||||
case string:
|
||||
x = strings.TrimSpace(x)
|
||||
if f, err := strconv.ParseFloat(x, 64); err == nil {
|
||||
return qianwenTime(f)
|
||||
}
|
||||
for _, layout := range []string{time.RFC3339Nano, "2006-01-02T15:04:05", "2006-01-02 15:04:05", time.RFC1123, time.RFC1123Z} {
|
||||
if t, err := time.ParseInLocation(layout, x, time.Local); err == nil {
|
||||
return t
|
||||
}
|
||||
}
|
||||
}
|
||||
return time.Time{}
|
||||
}
|
||||
|
||||
// errQianwenSession is a sign-in the platform no longer takes, or one past
|
||||
// its time: it has no refresh token, so the user signs in again.
|
||||
var errQianwenSession = errors.New("signed out of the Qwen AI platform: sign in again in the provider's settings")
|
||||
|
||||
// qianwenNoSignIn is why a Qwen AI platform plan's card has no windows
|
||||
// while magpie has no sign-in for it.
|
||||
func qianwenNoSignIn(p Provider) string {
|
||||
return "this plan's usage is told only to a sign-in on the Qwen AI platform: sign in in " + p.Name + "'s settings"
|
||||
}
|
||||
|
||||
var (
|
||||
qianwenTokensMu sync.Mutex
|
||||
qianwenTokens = map[string]aliToken{}
|
||||
)
|
||||
|
||||
func qianwenForgetToken(id string) {
|
||||
qianwenTokensMu.Lock()
|
||||
delete(qianwenTokens, id)
|
||||
qianwenTokensMu.Unlock()
|
||||
}
|
||||
|
||||
// qianwenMint makes the console token from the sign-in's access token.
|
||||
func qianwenMint(ctx context.Context, access string) (string, error) {
|
||||
body, _ := json.Marshal(map[string]any{
|
||||
"product": "ModelStudioRegional", "action": aliACSAction, "region": qianwenRegion,
|
||||
"params": map[string]any{}, "version": aliACSVersion,
|
||||
})
|
||||
code, raw, err := qianwenPost(ctx, "https://"+qianwenAPIHost+"/data/v2/api.json", "application/json", body, access)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
var r struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
SuccessResponse bool `json:"successResponse"`
|
||||
Data struct {
|
||||
CliAccessToken string `json:"cliAccessToken"`
|
||||
} `json:"data"`
|
||||
}
|
||||
_ = json.Unmarshal(raw, &r)
|
||||
tok := strings.TrimSpace(r.Data.CliAccessToken)
|
||||
switch {
|
||||
case r.Code == "200" && r.SuccessResponse && tok != "" && tok != access:
|
||||
return tok, nil
|
||||
case strings.Contains(r.Code, "NeedLogin"), strings.Contains(r.Code, "NotLogin"),
|
||||
code == http.StatusUnauthorized, code == http.StatusForbidden:
|
||||
return "", errQianwenSession
|
||||
case r.Code != "" || r.Message != "":
|
||||
return "", fmt.Errorf("the Qwen AI platform's %s: %s %s", aliACSAction, r.Code, r.Message)
|
||||
}
|
||||
return "", fmt.Errorf("the Qwen AI platform's %s gave no token: %d %s", aliACSAction, code, volcHead(raw))
|
||||
}
|
||||
|
||||
// qianwenConsole is the platform's console gateway.
|
||||
func qianwenConsole() aliConsole {
|
||||
return aliConsole{
|
||||
url: "https://" + qianwenDataHost + "/cli/api.json?action=BroadScopeAspnGateway&product=sfm_bailian&api=" + url.QueryEscape(aliUsageAPI),
|
||||
region: qianwenRegion, site: "QIANWENAI", who: "the Qwen AI platform's console", ua: qianwenUA,
|
||||
}
|
||||
}
|
||||
|
||||
// qianwenReadUsage reads the plan's windows with the provider's sign-in: the
|
||||
// console token kept for it, made again once when the console says it
|
||||
// isn't logged in; a fresh one refused is a sign-in ended.
|
||||
func qianwenReadUsage(ctx context.Context, id string, now func() time.Time) ([]QuotaWindow, error) {
|
||||
s, ok := qianwenSignIn(id)
|
||||
if !ok || s.Access == "" {
|
||||
return nil, errQianwenSession
|
||||
}
|
||||
if !s.Expires.IsZero() && now().After(s.Expires) {
|
||||
return nil, errQianwenSession
|
||||
}
|
||||
for try := 0; ; try++ {
|
||||
qianwenTokensMu.Lock()
|
||||
t, kept := qianwenTokens[id]
|
||||
qianwenTokensMu.Unlock()
|
||||
fresh := !kept || try > 0 || now().Sub(t.at) > aliTokenTTL
|
||||
if fresh {
|
||||
tok, err := qianwenMint(ctx, s.Access)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
t = aliToken{tok, now()}
|
||||
qianwenTokensMu.Lock()
|
||||
qianwenTokens[id] = t
|
||||
qianwenTokensMu.Unlock()
|
||||
}
|
||||
raw, err := aliAskUsage(ctx, t.token, qianwenConsole())
|
||||
if err == errAliNotLogged {
|
||||
qianwenForgetToken(id)
|
||||
if !fresh {
|
||||
continue
|
||||
}
|
||||
return nil, errQianwenSession
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ws := aliReadWindows(raw)
|
||||
if len(ws) == 0 {
|
||||
return nil, fmt.Errorf("the Qwen AI platform told no window for this account (it may have no personal Token Plan): %s", volcHead(raw))
|
||||
}
|
||||
return ws, nil
|
||||
}
|
||||
}
|
||||
|
||||
// qianwenPlanQuota is p's plan as a card, read with its sign-in.
|
||||
func qianwenPlanQuota(ctx context.Context, p Provider) SubscriptionQuota {
|
||||
q := SubscriptionQuota{Provider: p.ID, Name: p.Name, Icon: p.Icon, Plan: aliPlanName, Windows: []QuotaWindow{}}
|
||||
if !QianwenSignedIn(p.ID) {
|
||||
q.Error, q.NeedsAccessKey = qianwenNoSignIn(p), true
|
||||
return q
|
||||
}
|
||||
q.User = QianwenAccount(p.ID)
|
||||
ws, err := qianwenReadUsage(ctx, p.ID, time.Now)
|
||||
if err != nil {
|
||||
q.Error = err.Error()
|
||||
q.NeedsAccessKey = errors.Is(err, errQianwenSession)
|
||||
return q
|
||||
}
|
||||
q.Windows = ws
|
||||
return q
|
||||
}
|
||||
|
||||
// qianwenPlanQuotas is a card for each Qwen AI platform plan in use: one
|
||||
// per provider, as two can be two accounts. One magpie has no sign-in for
|
||||
// says so, with the way to its settings.
|
||||
func qianwenPlanQuotas(ctx context.Context) []SubscriptionQuota {
|
||||
var jobs []Provider
|
||||
for _, p := range All() {
|
||||
if p.Hidden || p.Off || !QianwenPlan(p) || !wantsCard(ctx, p.ID, "") {
|
||||
continue
|
||||
}
|
||||
jobs = append(jobs, p)
|
||||
}
|
||||
out := make([]SubscriptionQuota, len(jobs))
|
||||
var wg sync.WaitGroup
|
||||
for i, p := range jobs {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
out[i] = qianwenPlanQuota(p.Via(ctx), p)
|
||||
if out[i].Error == "" {
|
||||
// what routing goes by, read just now (KeyAllowance)
|
||||
noteKeyAllowance(p, out[i].Windows, time.Now())
|
||||
}
|
||||
if QianwenSignedIn(p.ID) {
|
||||
out[i] = keepReading(ctx, out[i], keyTag("qianwen", p.ID))
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,398 @@
|
||||
package provider
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/yetone/magpie/internal/agentenv"
|
||||
)
|
||||
|
||||
// The replies below are the shapes the QianWen CLI (@qianwenai/qianwen-cli
|
||||
// 1.10.0) reads: device/code's is a real one (its token changed), the
|
||||
// rest are what its loginPoll, GenerateCLIAccessToken and cs-data usage
|
||||
// readers take, with BailianGateway.Login.NotLogined and ConsoleNeedLogin
|
||||
// as the platform answered them to a request with no sign-in.
|
||||
|
||||
const qianwenCodeReply = `{"Data":{"Token":"devtok1","ExpiresIn":300,"VerificationUrl":"https://account.qianwenai.com/sso/OIDCAuth?app_type=qianwenai_cli&lang=en&auth_token=devtok1","Interval":2},"RequestId":"01A1D8E9-1E96-5A84-B19B-1EB6C862D2F9","Success":true}`
|
||||
|
||||
func qianwenUsageReply(month float64) string {
|
||||
b, _ := json.Marshal(map[string]any{
|
||||
"code": "200", "successResponse": true,
|
||||
"data": map[string]any{"success": true, "DataV2": map[string]any{
|
||||
"ret": []string{"SUCCESS::调用成功"},
|
||||
"data": map[string]any{"code": "SUCCESS", "success": true, "data": map[string]any{"per1MonthPercentage": month, "per1MonthResetTime": 1780000000000}},
|
||||
}},
|
||||
})
|
||||
return string(b)
|
||||
}
|
||||
|
||||
const qianwenNotLogged = `{"code":"200","successResponse":true,"data":{"success":false,"errorCode":"BailianGateway.Login.NotLogined","errorMsg":"not logined"}}`
|
||||
|
||||
// fakeQianwen is the platform's three hosts. polls is how many times
|
||||
// device/token answers authorization_pending before its last reply.
|
||||
type fakeQianwen struct {
|
||||
mu sync.Mutex
|
||||
t *testing.T
|
||||
challenge string
|
||||
polls int
|
||||
last string // device/token's reply once pending is done
|
||||
lastCode int
|
||||
mints map[string]string // access token → console token ("" refuses)
|
||||
usage map[string]string // console token → reply
|
||||
minted int
|
||||
reads int
|
||||
asked []string
|
||||
}
|
||||
|
||||
func newFakeQianwen(t *testing.T) *fakeQianwen {
|
||||
f := &fakeQianwen{t: t, mints: map[string]string{}, usage: map[string]string{}, lastCode: 200}
|
||||
srv := httptest.NewServer(http.HandlerFunc(f.serve))
|
||||
t.Cleanup(srv.Close)
|
||||
old := http.DefaultClient.Transport
|
||||
http.DefaultClient.Transport = rewrite{srv}
|
||||
t.Cleanup(func() { http.DefaultClient.Transport = old })
|
||||
return f
|
||||
}
|
||||
|
||||
func (f *fakeQianwen) serve(w http.ResponseWriter, r *http.Request) {
|
||||
body, _ := io.ReadAll(r.Body)
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
t := f.t
|
||||
host := r.Header.Get("X-Host")
|
||||
f.asked = append(f.asked, host+r.URL.Path)
|
||||
if r.Method != http.MethodPost || r.Header.Get("User-Agent") != qianwenUA {
|
||||
t.Errorf("%s %s%s as %q", r.Method, host, r.URL.Path, r.Header.Get("User-Agent"))
|
||||
}
|
||||
q := r.URL.Query()
|
||||
switch host + r.URL.Path {
|
||||
case qianwenAuthHost + "/cli/device/code":
|
||||
if q.Get("client_id") == "" || q.Get("code_challenge_method") != "S256" || q.Get("code_challenge") == "" {
|
||||
t.Errorf("device/code %s", r.URL.RawQuery)
|
||||
}
|
||||
f.challenge = q.Get("code_challenge")
|
||||
io.WriteString(w, qianwenCodeReply)
|
||||
case qianwenAuthHost + "/cli/device/token":
|
||||
sum := sha256.Sum256([]byte(q.Get("code_verifier")))
|
||||
if q.Get("token") != "devtok1" || q.Get("client_id") == "" || base64.RawURLEncoding.EncodeToString(sum[:]) != f.challenge {
|
||||
t.Errorf("device/token %s (challenge %s)", r.URL.RawQuery, f.challenge)
|
||||
}
|
||||
if f.polls > 0 {
|
||||
f.polls--
|
||||
io.WriteString(w, `{"Data":{"Status":"authorization_pending"},"Success":true}`)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(f.lastCode)
|
||||
io.WriteString(w, f.last)
|
||||
case qianwenAPIHost + "/data/v2/api.json":
|
||||
var m map[string]any
|
||||
_ = json.Unmarshal(body, &m)
|
||||
if r.Header.Get("Content-Type") != "application/json" || m["product"] != "ModelStudioRegional" || m["action"] != "GenerateCLIAccessToken" || m["region"] != "cn-beijing" || m["version"] != "2026-02-10" {
|
||||
t.Errorf("mint %s %q", r.Header.Get("Content-Type"), body)
|
||||
}
|
||||
access := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")
|
||||
if strings.HasPrefix(access, "sk-sp-") {
|
||||
t.Errorf("the plan's key was sent: %s", access)
|
||||
}
|
||||
tok, ok := f.mints[access]
|
||||
if !ok || tok == "" {
|
||||
io.WriteString(w, `{"code":"ConsoleNeedLogin","message":"Please login first","successResponse":false}`)
|
||||
return
|
||||
}
|
||||
f.minted++
|
||||
io.WriteString(w, `{"code":"200","successResponse":true,"data":{"cliAccessToken":"`+tok+`"}}`)
|
||||
case qianwenDataHost + "/cli/api.json":
|
||||
f.reads++
|
||||
form, _ := url.ParseQuery(string(body))
|
||||
if q.Get("action") != "BroadScopeAspnGateway" || q.Get("product") != "sfm_bailian" || q.Get("api") != aliUsageAPI ||
|
||||
form.Get("region") != "cn-beijing" || !strings.Contains(form.Get("params"), "QIANWENAI") || !strings.Contains(form.Get("params"), aliUsageAPI) {
|
||||
t.Errorf("usage %s with %q", r.URL, body)
|
||||
}
|
||||
reply, ok := f.usage[strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")]
|
||||
if !ok {
|
||||
reply = qianwenNotLogged
|
||||
}
|
||||
io.WriteString(w, reply)
|
||||
default:
|
||||
t.Errorf("asked %s %s", host, r.URL)
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}
|
||||
}
|
||||
|
||||
func qianwenHome(t *testing.T) {
|
||||
t.Helper()
|
||||
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, "")
|
||||
}
|
||||
old := qianwenPoll
|
||||
qianwenPoll = 5 * time.Millisecond
|
||||
t.Cleanup(func() { qianwenPoll = old })
|
||||
qianwenTokensMu.Lock()
|
||||
qianwenTokens = map[string]aliToken{}
|
||||
qianwenTokensMu.Unlock()
|
||||
forgetPlanQuotas()
|
||||
t.Cleanup(forgetPlanQuotas)
|
||||
}
|
||||
|
||||
// waitQianwen waits for the provider's sign-in to end, as the GUI does.
|
||||
func waitQianwen(t *testing.T, id string) (string, string) {
|
||||
t.Helper()
|
||||
for end := time.Now().Add(20 * time.Second); time.Now().Before(end); time.Sleep(2 * time.Millisecond) {
|
||||
if s, why := QianwenSignInState(id); s != "pending" {
|
||||
return s, why
|
||||
}
|
||||
}
|
||||
t.Fatal("the sign-in never ended")
|
||||
return "", ""
|
||||
}
|
||||
|
||||
func TestQianwenPlanHost(t *testing.T) {
|
||||
for base, want := range map[string]bool{
|
||||
"https://token-plan.maas.qianwenaiapi.com/compatible-mode/v1": true,
|
||||
"https://token-plan.maas.qianwenaiapi.com/apps/anthropic": true,
|
||||
"https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1": false,
|
||||
"https://token-plan.maas.qwencloudapi.com/compatible-mode/v1": false,
|
||||
"https://dashscope.aliyuncs.com/compatible-mode/v1": false,
|
||||
} {
|
||||
if got := QianwenPlan(Provider{Chat: base}); got != want {
|
||||
t.Errorf("%s: %v", base, got)
|
||||
}
|
||||
}
|
||||
if QianwenPlan(Provider{Chat: "https://token-plan.maas.qianwenaiapi.com/compatible-mode/v1", Account: &Account{}}) {
|
||||
t.Error("an account is a plan's")
|
||||
}
|
||||
p, err := FromPreset("qwen-token-plan")
|
||||
if err != nil || !QianwenPlan(p) {
|
||||
t.Fatalf("the preset isn't the platform's plan: %v %+v", err, p)
|
||||
}
|
||||
p.Key = "sk-sp-x"
|
||||
if accountPlanOf(p) != "qianwen" {
|
||||
t.Errorf("accountPlanOf %q", accountPlanOf(p))
|
||||
}
|
||||
}
|
||||
|
||||
func TestQianwenSignIn(t *testing.T) {
|
||||
qianwenHome(t)
|
||||
f := newFakeQianwen(t)
|
||||
f.polls = 2
|
||||
f.last = `{"Data":{"Status":"complete","Credentials":{"AccessToken":"acc1","ExpireTime":"2099-01-02T03:04:05Z","User":{"Id":"u1","Email":"a@example.com","AliyunId":"x"}}},"Success":true}`
|
||||
u, err := StartQianwenSignIn(context.Background(), "qwen-token-plan")
|
||||
if err != nil || !strings.HasPrefix(u, "https://account.qianwenai.com/sso/OIDCAuth?") {
|
||||
t.Fatalf("%q %v", u, err)
|
||||
}
|
||||
if s, why := waitQianwen(t, "qwen-token-plan"); s != "done" {
|
||||
t.Fatalf("%s %s", s, why)
|
||||
}
|
||||
if !QianwenSignedIn("qwen-token-plan") || QianwenAccount("qwen-token-plan") != "a@example.com" || QianwenSignedIn("other") {
|
||||
t.Fatal("not kept for the provider alone")
|
||||
}
|
||||
s, _ := qianwenSignIn("qwen-token-plan")
|
||||
if s.Access != "acc1" || s.User != "u1" || !s.Expires.Equal(time.Date(2099, 1, 2, 3, 4, 5, 0, time.UTC)) {
|
||||
t.Errorf("%+v", s)
|
||||
}
|
||||
if fi, err := os.Stat(qianwenPath()); err != nil || fi.Mode().Perm()&0o077 != 0 {
|
||||
t.Errorf("qianwen-auth.json readable by others: %v %v", fi, err)
|
||||
}
|
||||
|
||||
for name, c := range map[string]struct {
|
||||
code int
|
||||
reply string
|
||||
want string
|
||||
}{
|
||||
"refused": {200, `{"Data":{"Status":"access_denied"},"Success":true}`, "refused"},
|
||||
"ran out": {200, `{"Data":{"Status":"expired_token"},"Success":true}`, "ran out"},
|
||||
"ran out, as error": {400, `{"Code":"DeviceCode.Expired","Message":"token expired"}`, "ran out"},
|
||||
"no token": {200, `{"Data":{"Status":"complete"},"Success":true}`, "gave no token"},
|
||||
"other error": {500, `{"Code":"InternalError"}`, "500"},
|
||||
} {
|
||||
f.mu.Lock()
|
||||
f.polls, f.lastCode, f.last = 1, c.code, c.reply
|
||||
f.mu.Unlock()
|
||||
if _, err := StartQianwenSignIn(context.Background(), "p2"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if s, why := waitQianwen(t, "p2"); s != "failed" || !strings.Contains(why, c.want) {
|
||||
t.Errorf("%s: %s %q", name, s, why)
|
||||
}
|
||||
if QianwenSignedIn("p2") {
|
||||
t.Errorf("%s: kept a sign-in", name)
|
||||
}
|
||||
}
|
||||
// the first provider's sign-in is still there
|
||||
if !QianwenSignedIn("qwen-token-plan") {
|
||||
t.Fatal("another provider's failed sign-in dropped this one")
|
||||
}
|
||||
|
||||
// cancelled: nothing is kept, and the state is gone
|
||||
f.mu.Lock()
|
||||
f.polls = 1 << 20
|
||||
f.mu.Unlock()
|
||||
if _, err := StartQianwenSignIn(context.Background(), "p3"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
CancelQianwenSignIn("p3")
|
||||
if s, _ := QianwenSignInState("p3"); s != "" {
|
||||
t.Errorf("cancelled sign-in is %q", s)
|
||||
}
|
||||
|
||||
if err := SignOutQianwen("qwen-token-plan"); err != nil || QianwenSignedIn("qwen-token-plan") {
|
||||
t.Fatalf("sign-out: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func saveQianwenSession(t *testing.T, id string, s qianwenSession) {
|
||||
t.Helper()
|
||||
qianwenMu.Lock()
|
||||
defer qianwenMu.Unlock()
|
||||
all := loadQianwen()
|
||||
all[id] = s
|
||||
if err := saveQianwen(all); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestQianwenPlanQuotas(t *testing.T) {
|
||||
qianwenHome(t)
|
||||
f := newFakeQianwen(t)
|
||||
f.mints["acc1"] = "cli2"
|
||||
f.usage["cli2"] = qianwenUsageReply(0.25)
|
||||
// cli1 is a console token kept from before that the console no longer
|
||||
// takes: the reader makes another once
|
||||
qianwenTokensMu.Lock()
|
||||
qianwenTokens["qwen-token-plan"] = aliToken{"cli1", time.Now()}
|
||||
qianwenTokensMu.Unlock()
|
||||
|
||||
const base = "https://token-plan.maas.qianwenaiapi.com/compatible-mode/v1"
|
||||
for _, p := range []Provider{
|
||||
{ID: "qwen-token-plan", Name: "Qwen Token Plan", Chat: base, Key: "sk-sp-key"},
|
||||
// not signed in: a card that says where to sign in
|
||||
{ID: "qwen-two", Name: "Qwen Two", Chat: base, Key: "sk-sp-key2"},
|
||||
// signed in, but the platform no longer takes the sign-in
|
||||
{ID: "qwen-old", Name: "Qwen Old", Chat: base, Key: "sk-sp-key3"},
|
||||
// signed in, past the time the platform gave it
|
||||
{ID: "qwen-late", Name: "Qwen Late", Chat: base, Key: "sk-sp-key4"},
|
||||
// Alibaba Cloud's plan: not this one
|
||||
{ID: "bailian", Name: "Bailian", Chat: "https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1", Key: "sk-sp-key5"},
|
||||
} {
|
||||
if err := Save(p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
saveQianwenSession(t, "qwen-token-plan", qianwenSession{Access: "acc1", Email: "a@example.com", Expires: time.Now().Add(time.Hour)})
|
||||
saveQianwenSession(t, "qwen-old", qianwenSession{Access: "gone"})
|
||||
saveQianwenSession(t, "qwen-late", qianwenSession{Access: "acc1", Expires: time.Now().Add(-time.Minute)})
|
||||
|
||||
got := map[string]SubscriptionQuota{}
|
||||
for _, q := range PlanQuotas(context.Background()) {
|
||||
if strings.HasPrefix(q.Provider, "qwen-") {
|
||||
got[q.Provider] = q
|
||||
}
|
||||
}
|
||||
if len(got) != 4 {
|
||||
t.Fatalf("%+v", got)
|
||||
}
|
||||
q := got["qwen-token-plan"]
|
||||
if q.Error != "" || len(q.Windows) != 1 || q.Windows[0].Name != "Month" || q.Windows[0].Used != 25 ||
|
||||
q.Windows[0].ResetsAt.UnixMilli() != 1780000000000 || q.User != "a@example.com" || q.NeedsAccessKey {
|
||||
t.Fatalf("%+v", q)
|
||||
}
|
||||
if q := got["qwen-two"]; !q.NeedsAccessKey || !strings.HasPrefix(q.Error, "this plan's usage is told only to a sign-in on the Qwen AI platform") || !strings.Contains(q.Error, "Qwen Two") {
|
||||
t.Errorf("not signed in: %+v", q)
|
||||
}
|
||||
for _, id := range []string{"qwen-old", "qwen-late"} {
|
||||
if q := got[id]; !q.NeedsAccessKey || q.Error != errQianwenSession.Error() {
|
||||
t.Errorf("%s: %+v", id, q)
|
||||
}
|
||||
}
|
||||
f.mu.Lock()
|
||||
minted, reads := f.minted, f.reads
|
||||
f.mu.Unlock()
|
||||
// cli1 refused, cli2 made and read; "gone" refused at the mint, the
|
||||
// late one never asked
|
||||
if minted != 1 || reads != 2 {
|
||||
t.Errorf("minted %d, reads %d", minted, reads)
|
||||
}
|
||||
|
||||
// the console token is kept: a second read makes none
|
||||
ws, err := qianwenReadUsage(context.Background(), "qwen-token-plan", time.Now)
|
||||
if err != nil || len(ws) != 1 {
|
||||
t.Fatalf("%v %+v", err, ws)
|
||||
}
|
||||
f.mu.Lock()
|
||||
if f.minted != 1 {
|
||||
t.Errorf("minted again: %d", f.minted)
|
||||
}
|
||||
// a fresh console token the console refuses is a sign-in ended, not a
|
||||
// loop
|
||||
f.usage = map[string]string{}
|
||||
f.mu.Unlock()
|
||||
qianwenForgetToken("qwen-token-plan")
|
||||
if _, err := qianwenReadUsage(context.Background(), "qwen-token-plan", time.Now); !errors.Is(err, errQianwenSession) {
|
||||
t.Errorf("fresh token refused: %v", err)
|
||||
}
|
||||
// an account with no Token Plan tells no window: said, not a 0% card
|
||||
f.mu.Lock()
|
||||
f.usage["cli2"] = strings.Replace(qianwenUsageReply(0), `"per1MonthPercentage":0,"per1MonthResetTime":1780000000000`, `"planName":null`, 1)
|
||||
f.mu.Unlock()
|
||||
if _, err := qianwenReadUsage(context.Background(), "qwen-token-plan", time.Now); err == nil || !strings.Contains(err.Error(), "told no window") {
|
||||
t.Errorf("no window: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// the sign-in goes with its provider: renamed, it follows; removed, it is
|
||||
// gone, and no provider added later under the id has it
|
||||
func TestQianwenFollowsProvider(t *testing.T) {
|
||||
qianwenHome(t)
|
||||
const base = "https://token-plan.maas.qianwenaiapi.com/compatible-mode/v1"
|
||||
if err := Save(Provider{ID: "qwen-a", Name: "Qwen A", Chat: base, Key: "sk-sp-a"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
saveQianwenSession(t, "qwen-a", qianwenSession{Access: "acc1"})
|
||||
saveQianwenSession(t, "keep", qianwenSession{Access: "acc2"})
|
||||
if err := Rename("qwen-a", "qwen-b"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if QianwenSignedIn("qwen-a") || !QianwenSignedIn("qwen-b") {
|
||||
t.Fatal("the sign-in didn't follow the rename")
|
||||
}
|
||||
if err := Delete("qwen-b"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if QianwenSignedIn("qwen-b") || !QianwenSignedIn("keep") {
|
||||
t.Fatal("removing the provider didn't drop its sign-in alone")
|
||||
}
|
||||
}
|
||||
|
||||
func TestQianwenTime(t *testing.T) {
|
||||
want := time.Date(2026, 12, 1, 0, 0, 0, 0, time.UTC)
|
||||
for _, v := range []any{float64(want.Unix()), float64(want.UnixMilli()), "2026-12-01T00:00:00Z", strconvInt(want.UnixMilli())} {
|
||||
if got := qianwenTime(v); !got.Equal(want) {
|
||||
t.Errorf("%v: %v", v, got)
|
||||
}
|
||||
}
|
||||
if !qianwenTime("").IsZero() || !qianwenTime(nil).IsZero() || !qianwenTime("soon").IsZero() {
|
||||
t.Error("a time from nothing")
|
||||
}
|
||||
}
|
||||
|
||||
func strconvInt(n int64) string { b, _ := json.Marshal(n); return string(b) }
|
||||
@@ -22,8 +22,8 @@ import (
|
||||
// Rename gives a provider another id, the one its models are picked by
|
||||
// (<id>/<model>). What magpie keeps that names it by id follows: the
|
||||
// routing groups it is in and their rules and classifiers, the other
|
||||
// providers' fallbacks, which agents are shown it, and its StepFun sign-in. The old id stays
|
||||
// with it (Was), so an agent still running on a config that names it the
|
||||
// providers' fallbacks, which agents are shown it, and its StepFun and
|
||||
// Qwen AI platform sign-ins. The old id stays with it (Was), so an agent still running on a config that names it the
|
||||
// old way reaches it, and its usage so far is counted with it; the agents'
|
||||
// own files are the agent package's to rewrite (agent.RenameProvider).
|
||||
// A signed-in account keeps the id of its agent.
|
||||
@@ -101,10 +101,13 @@ func Rename(from, to string) error {
|
||||
if err := store(f); err != nil {
|
||||
return err
|
||||
}
|
||||
// so is its StepFun sign-in, kept by provider id
|
||||
// so are its StepFun and Qwen AI platform sign-ins, kept by provider id
|
||||
if err := renameStepFun(from, to); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := renameQianwen(from, to); err != nil {
|
||||
return err
|
||||
}
|
||||
s := settings.Load()
|
||||
changed := renameModelPrefs(&s, from, to)
|
||||
for a, names := range s.Visible {
|
||||
|
||||
Reference in New Issue
Block a user