diff --git a/README.md b/README.md index b0a07fd..90d4f02 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ subscription and makes its requests. The packages work in OpenCode and in | Package | Signs in to | Provider id | |---|---|---| | [cline](packages/cline) | Cline (cline.bot): usage-billed models, ClinePass's and Cline's free ones, with Cline's device sign-in or an API key | `cline` | +| [codearts](packages/codearts) | Huawei Cloud CodeArts (码道) coding plans (Trial, personal and enterprise credits), with Huawei Cloud OAuth sign-in (unofficial) | `codearts` | | [commandcode](packages/commandcode) | Command Code plans (Pro, GOAT, Max, Ultra, Go, Teams Pro) | `commandcode-plan` | | [cursor](packages/cursor) | Cursor subscriptions (Pro, Pro+, Ultra, Teams), on the API cursor-agent talks to | `cursor` | | [devin](packages/devin) | Devin subscription (the devin CLI's account) | `devin` | diff --git a/packages/codearts/LICENSE b/packages/codearts/LICENSE new file mode 100644 index 0000000..41f7596 --- /dev/null +++ b/packages/codearts/LICENSE @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2026 yuweihao17 +Copyright (c) 2026 Sakura-Natsu + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/codearts/README.md b/packages/codearts/README.md new file mode 100644 index 0000000..b4977dd --- /dev/null +++ b/packages/codearts/README.md @@ -0,0 +1,121 @@ +# @magpie-community/opencode-codearts-auth + +Signs in to **Huawei Cloud CodeArts** (华为云码道, the CodeArts Agent coding plans: Trial, +personal and enterprise credit plans) and serves its models — GLM, DeepSeek, openPangu and +more — in OpenCode and magpie. Provider id: `codearts`. + +> **Unofficial.** This package is not affiliated with, authorized or endorsed by Huawei, +> Huawei Cloud or CodeArts; their names and marks belong to their owners. It talks to the +> non-public APIs the CodeArts client uses and identifies itself the way that client does +> (including claiming the daily free benefit and check-in), which may not be allowed by Huawei +> Cloud's terms of service, and those APIs may change at any time. Use it at your own risk, +> including the risk of restrictions on your account. + +## Install + +```sh +magpie plugin add @magpie-community/opencode-codearts-auth +magpie plugin login codearts +``` + +or install it from magpie's Plugins tab and sign in there. + +## Sign-in + +**Sign in with Huawei Cloud** opens Huawei Cloud's consent page. The plugin listens on a +loopback port (`127.0.0.1`, ≥ 10000) for the redirect and exchanges the code at Huawei Cloud +STS — a PKCE flow whose token requests carry an ES256 DPoP proof, as the CodeArts client does. +STS answers with temporary AK/SK/security-token credentials and a refresh token. + +**Where it is kept:** the whole credential (AK/SK/security token, expiry, refresh token, the +PKCE verifier and the DPoP private key) is a JSON string in the account's `access` field, in +magpie's (or OpenCode's) own account store. `auth.refresh` renews it 30 minutes before it +expires, reusing the same verifier and DPoP key; a stale credential met on a request +(`401`, `APIG.0602`) is renewed once and the request sent again. The account id is the signer +named in the refresh token, so signing in again replaces the account instead of adding one. + +## Models + +The account's live list: CodeArts' builtin models, plus the free models of its daily benefit +once today's benefit has been claimed (`POST /api/v1/benefit/claim`, once a Beijing day, as the +client does). Each model's credit rate (the client's 「消耗系数」) is reported as magpie's `rate`, +with its reasoning flag and limits, from the account's main agent (`build`) model list. Before +signing in, a short built-in catalog stands in. + +## Requests + +- Every request is signed with Huawei's SDK-HMAC-SHA256 using the temporary credentials. +- The gateway allows 3 concurrent sessions per account and tells them apart by + `x-ot-session-id`; the plugin sends one stable session id per account (and a fresh trace per + request) like the client, keeps at most 3 chats in flight per account, retries + `TM.00001041` with backoff, and waits in the gateway's own queue (`429` + + `queue-status: queued`) the way the client does. Only then does magpie get a `429`. +- Chats always go upstream as streams — CodeArts meters only streamed answers — and are folded + back into one `chat.completion` when the caller asked for JSON. +- `thinking: { type: "enabled" }` is sent unless the caller set it, so the reasoning lands in + `reasoning_content` and `content` is only the reply. +- Errors the gateway puts inside a `200` stream (spent quota, unknown model) come back as + `429` / `400` / `502` with the vendor's words. The `codearts/` prefix is stripped and output + budgets are clamped to 65536. + +## Usage and check-in + +- Usage: the credit buckets of `snap-manager/v1/statistics/plugin` (only the package total + pauses the account; the basic / on-demand / bonus buckets are shown aside) and the free daily + token pool. +- When each credit batch expires is read from the CodeArts console's own calls + (`snap-manager/v1/package/credit/page`, `v1/ops/credit/*`); when those can't be read, the + plugin falls back to a small ledger of the check-ins it claimed, + `~/.config/magpie/codearts-checkins.json` (or `MAGPIE_CODEARTS_LEDGER`). This part is still + being checked against more accounts — trust the CodeArts console where they differ. +- `auth.checkin`: the client's 「限时福利 → 每日领取」 — `GET /v1/ops/delivery?channel=IDE`, + `POST /v1/ops/claim`, then `POST /v1/ops/confirm` when the claim answers an id. Turn on + *Auto check-in* for CodeArts under **Settings → Usage → Plugins**. + +## Options + +| Option | Default | What it does | +|---|---|---| +| `maxInflight` | `3` | chats in flight per account; it can only lower the vendor's cap of 3 sessions | +| `retryBudgetMs` | `150000` | how long to retry `TM.00001041` before answering `429` | +| `retryDelays` | `[2000,4000,6000,8000,10000]` | retry waits in ms (the last repeats) | +| `queueBudgetMs` | `300000` | how long to wait in the gateway's queue | +| `thinking` | `true` | `false` stops adding `thinking: { type: "enabled" }` | + +## Credits + +First written by [yuweihao17](https://github.com/yuweihao17/codearts); this version carries the +fixes of [yuweihao17/codearts#8](https://github.com/yuweihao17/codearts/pull/8). It builds on the +measurements and code of [HuHong-Tao](https://github.com/yuweihao17/codearts/pull/6) and +[ReachForStar](https://github.com/ReachForStar/codearts), and on the CodeArts channel of +[Ebony-Vinyl/dsh-our-free-model](https://github.com/Ebony-Vinyl/dsh-our-free-model). + +## 中文 + +接入**华为云码道(CodeArts Agent)**的编码套餐(体验版、个人与企业积分套餐),在 OpenCode 和 +magpie 里使用其 GLM、DeepSeek、openPangu 等模型。provider id:`codearts`。 + +> **非官方插件**:与华为、华为云及 CodeArts(码道)没有任何关联,也未获其授权或认可。插件调用的是 +> 码道客户端使用的非公开接口,并以与官方客户端相同的方式标识自己(含自动领取每日免费权益与签到), +> 这可能不符合华为云的服务条款,接口也可能随时变更。使用风险(包括账号受限)由使用者自行承担。 + +- **登录**:华为云 OAuth(PKCE + DPoP),本机 `127.0.0.1`(端口 ≥ 10000)接收回调,向 STS 换取临时 + AK/SK/security-token。完整凭据(含 refresh_token、PKCE verifier、DPoP 私钥)以 JSON 存在账号的 + `access` 字段里,保存在 magpie / OpenCode 自己的账号存储中;过期前 30 分钟自动续期,请求遇到临时凭据 + 过期时就地续期并重发一次;账号标识取自 refresh_token,重复登录不会多出账号。 +- **模型**:账号实时的内置模型列表;领取当日免费权益成功后,再加上免费模型(每个北京自然日领一次,与 + 客户端一致)。每个模型的「消耗系数」作为 magpie 的倍率上报,来自账号主智能体(`build`)的模型列表。 +- **请求**:SDK-HMAC-SHA256 签名;像客户端一样发送 `x-ot-session-id` 会话头(每账号一个会话),账号内 + 在途请求不超过 3 个,`TM.00001041` 退避重试,网关排队时按客户端的方式等待;总是以流式请求上游(码道 + 只对流式回答计量积分),调用方要非流式时折叠回 JSON;默认注入 `thinking: { type: "enabled" }`,思考与 + 正文分开;200 里内嵌的错误换算为 `429` / `400` / `502` 并带厂商原话。 +- **用量与签到**:总积分决定账号是否可用,其余积分桶只做明细;另有每日免费额度窗口。各批积分的到期 + 时间读自码道控制台同一批接口,读不到时退回插件的签到账本 `~/.config/magpie/codearts-checkins.json` + (这部分仍在用更多账号验证,请以控制台为准)。`auth.checkin` 与客户端「限时福利 → 每日领取」一致, + 在 **设置 → 用量 → Plugins** 打开「每日自动签到」即可。 +- **致谢**:原作者 [yuweihao17](https://github.com/yuweihao17/codearts);HuHong-Tao、ReachForStar 的 + 实测与实现;[Ebony-Vinyl/dsh-our-free-model](https://github.com/Ebony-Vinyl/dsh-our-free-model)。 + +## License + +MIT — see [LICENSE](./LICENSE). diff --git a/packages/codearts/index.mjs b/packages/codearts/index.mjs new file mode 100644 index 0000000..6a753ee --- /dev/null +++ b/packages/codearts/index.mjs @@ -0,0 +1,2264 @@ +// CodeArts (华为云码道 代码智能体) as a magpie / OpenCode provider plugin. +// +// CodeArts, Huawei Cloud's coding agent (码道), serves its models over an +// OpenAI-compatible Chat Completions API at +// https://snap-access.cn-north-4.myhuaweicloud.com/api/v2 — but unlike a plain +// OpenAI-compatible provider it does NOT take an API key. Requests are signed +// with临时 AK/SK/security-token credentials using Huawei's SDK-HMAC-SHA256 +// scheme, and those credentials are obtained by signing in to Huawei Cloud +// with OAuth. +// +// This plugin implements exactly that flow, mirroring the real CodeArts agent +// (and the `Ebony-Vinyl/dsh-our-free-model` CodeArts channel, which this plugin +// is modelled on): +// +// 1. `auth.methods[0]` is `{ type: "oauth" }`. `authorize()` starts a +// loopback callback server on 127.0.0.1 (port >= 10000), returns the +// Huawei Cloud portal URL for magpie to open, and completes with the +// credentials once the browser is redirected back with an auth code. +// 2. The sign-in is PKCE: a random code_verifier is sent to the STS token +// endpoint together with the code and the S256 challenge's pre-image. It +// is also a DPoP flow: a fresh ES256 (P-256) key pair signs each token +// request, and the private key JWK is persisted so refresh requests can +// sign with it too. +// 3. STS answers with rotating AK/SK/security-token credentials plus a +// refresh_token. The whole credential (including the verifier and DPoP +// key) is stored as JSON in the account's `access` field. +// 4. `auth.refresh` silently renews before expiry via `grant_type = +// refresh_token`; the same verifier and DPoP key are reused. +// 5. Every model request is signed with SDK-HMAC-SHA256 in the loader's +// `fetch`, and the account's live model list + quota are read from +// signed GETs. +// 6. The gateway caps an account at 3 concurrent sessions (`TM.00001041`). +// Each account keeps one stable session id (`x-ot-session-id`), at most +// 3 of its chats are in flight, and a cap answer is retried until a +// session frees, then handed to magpie as a 429 so it can fail over. +// 7. Chats always go upstream as SSE streams: CodeArts meters only streamed +// answers, so a caller that asked for JSON gets the stream folded back. +// 8. `auth.checkin` presses the daily 「每日领取」 check-in the way the +// CodeArts IDE does (`/v1/ops/delivery` → `/claim` → `/confirm`). +// +// It imitates @magpie-community/opencode-workbuddy-auth for structure but +// replaces its browser sign-in + bearer-token requests with CodeArts' OAuth + +// signed-request flow. See README.md. + +import { createServer } from "node:http" +import fs from "node:fs" +import os from "node:os" +import path from "node:path" + +const PROVIDER = "codearts" +const NPM = "@ai-sdk/openai-compatible" // chat completions + +// ---- endpoints & flow constants -------------------------------------------- + +// Chat Completions base (loader `baseURL`). A chat goes to +// `${CHAT_API_BASE}/chat/completions`. +const CHAT_API_BASE = "https://snap-access.cn-north-4.myhuaweicloud.com/api/v2" +// Snap-access manager host: model list, account/quota, check-in. +const SNAP_HOST = "https://snap-access.cn-north-4.myhuaweicloud.com" +const SNAP_MODEL_BUILTIN_URL = `${SNAP_HOST}/v1/model/builtin` +const SNAP_STATISTICS_URL = `${SNAP_HOST}/snap-manager/v1/statistics/plugin` +// The only hosts the account's credentials are signed for and sent to. +const HUAWEI_HOST = /(^|\.)(myhuaweicloud\.com|myhuaweicloud\.cn|huaweicloud\.com)$/i +// opengw gateway config: the benefit/free-quota model set. +const OPENGW_GATEWAY_CONFIG_URL = "https://opengw.developer.huaweicloud.com/api/v1/gateway/config" +// The daily free token pool a `maas_type: benefit` chat draws on (never the +// credit packages), so a free model's spend shows up in the usage panel. +const BENEFIT_BALANCE_URL = "https://opengw.developer.huaweicloud.com/api/v1/user/tokens/balance" +// The free models are the account's only once today's benefit is claimed: the +// CodeArts agent POSTs this before it lists them (`claimBenefit`), and leaves +// them out when it fails (4004 no benefit / expired, 4006 today's places gone). +const BENEFIT_CLAIM_URL = "https://opengw.developer.huaweicloud.com/api/v1/benefit/claim" +const BENEFIT_OK = "0000" +// The agent's own model list, with each model's credit rate (`credit[]. +// ratio_display`, shown as "1.50x") and its parameters: the CodeAgent's detail. +const AGENT_LIST_URL = `${SNAP_HOST}/v1/agent-center/agents/useragents?offset=0&limit=100` +const AGENT_DETAIL_URL = (id) => `${SNAP_HOST}/v1/agent-center/agents/detail?agent_id=${encodeURIComponent(id)}` +const CODE_AGENT_ID = "CodeAgent" +// The agent the IDE reads its model list from (its CODE_AGENT_AGENT_ID): the +// one whose `original_id` is "build", 「自主规划与执行」; older lists call it +// CodeAgent. Its id, as the IDE asks for it, stands in when the list can't be read. +const MAIN_AGENT_ORIGINAL_IDS = ["build", CODE_AGENT_ID] +const MAIN_AGENT_FALLBACK_ID = "a8bcb36232554267a5142361cc25a393" +// Agents tried for a model list before giving up. +const AGENT_DETAIL_TRIES = 3 +const AGENT_CENTER_HEADERS = { "Content-Type": "application/json", "Agent-Type": "AgentCenter", "X-Language": "zh-cn" } +// Check-in credits are good for 30 days from when they are given. +const CHECKIN_CREDIT_DAYS = 30 +// Every credit batch with its own expiry, as the console's 「获取明细」 reads +// them (its /portal/snap-manager and /portal/promptcenter calls are these): +// the plan's and bought packages, then the campaigns' grants (sign-up, check-in). +const PACKAGE_CREDIT_PAGE_URL = `${SNAP_HOST}/snap-manager/v1/package/credit/page` +const PACKAGE_CREDIT_QUERIES = [ + { pageNum: 1, pageSize: 100, sortField: "created_time", sortOrder: "desc", packageTypes: ["basic", "ondemand"] }, + { pageNum: 1, pageSize: 100, packageTypes: ["bonus"] }, +] +const OPS_CREDIT_OVERVIEW_URL = `${SNAP_HOST}/v1/ops/credit/overview` +const OPS_CREDIT_CAMPAIGN_URL = (id) => `${SNAP_HOST}/v1/ops/credit/campaign/${encodeURIComponent(id)}?pageNum=1&pageSize=100` +// The batches change slowly; read them again this often (and after a check-in). +const CREDIT_BATCHES_TTL_MS = 10 * 60 * 1000 +// Daily check-in (「限时福利 → 每日领取」), as the IDE's ActivityWelfarePane calls it. +const OPS_DELIVERY_URL = `${SNAP_HOST}/v1/ops/delivery?channel=IDE` +const OPS_CLAIM_URL = `${SNAP_HOST}/v1/ops/claim` +const OPS_CONFIRM_URL = `${SNAP_HOST}/v1/ops/confirm` +const OPS_CHANNEL = "IDE" +const DAILY_CHECKIN_TYPE = "USER_LOGIN" +// States the IDE disables the claim button in: today's benefit is in already. +const CLAIMED_STATUSES = ["CLAIMED", "CONFIRMED", "CONSUMED"] +// Unsigned headers snap-access routes on (signing them breaks the signature). +const SNAP_EXTRA_HEADERS = { "Agent-Type": "PromptCenter", "X-Language": "zh-cn" } +// OAuth portal (new IAM flow) and the STS token endpoint. +const PORTAL_AUTHORIZE_BASE = "https://codearts.huaweicloud.com/portal/authorize" +const PORTAL_LOGIN_BASE = "https://codearts.huaweicloud.com/portal/login" +const STS_TOKEN_ENDPOINT = "https://sts.cn-north-4.myhuaweicloud.com/v1/oauth2/tokens" + +// OAuth client id (equals the plugin's URI scheme) and local callback path. +const CLIENT_ID = "codearts-agent" +const REDIRECT_PATH = "/oauth/callback" +// What the portal expects the calling plugin to be called (reverse-engineered +// constants — the plugin/version match the real IDE extension, not this package). +const LOGIN_PLUGIN_NAME = "snap_AIIDE" +const LOGIN_PLUGIN_VERSION = "5.2.0" +const OAUTH_THEME = "2" // activeColorTheme.kind: 2 = Dark +const OAUTH_LOCALE = "zh-cn" + +const GRANT_AUTHORIZATION_CODE = "authorization_code" +const GRANT_REFRESH_TOKEN = "refresh_token" + +const TOKEN_TIMEOUT_MS = 60_000 +const REQUEST_TIMEOUT_MS = 30_000 +const OAUTH_CALLBACK_TIMEOUT_MS = 180_000 +const MIN_CALLBACK_PORT = 10_000 + +// magpie renews this long before the credential expires. +const REFRESH_LEAD_MS = 30 * 60 * 1000 +// The loader renews in-band only this close to expiry, well after magpie's own +// renewal, so the two never spend the one-time refresh token twice. +const INBAND_REFRESH_LEAD_MS = 2 * 60 * 1000 + +// The gateway allows 3 concurrent sessions per account; the 4th is answered +// `TM.00001041` (并发会话数已达上限(3个)) — as an HTTP 400, or as the first event +// of a 200 SSE stream — and a finished streaming session holds its slot for +// about a minute. Our own in-flight chats are capped first, and a cap answer is +// retried (re-signed each time) within a budget, then handed back as a 429. +const SESSION_LIMIT_ERROR = "TM.00001041" +// The gateway tells sessions apart by `x-ot-session-id` (the CodeArts agent +// sends its conversation id there; `Chat-Id`/`Session-Id` count for nothing): +// a request without it is a session of its own, held for about a minute, so +// three requests in a minute used to fill the account. +const SESSION_HEADER = "x-ot-session-id" +// A gateway that queues the request answers 429 with `queue-status: queued` +// and a `trace-id`; the agent polls this until the trace is `promoted`, then +// sends the request again, and DELETEs it when it gives up. +const TRACE_QUEUE_URL = (traceId) => `${SNAP_HOST}/api/v1/concurrency/trace-queues/${encodeURIComponent(traceId)}` +const QUEUE_BUDGET_MS = 300_000 +// Every chat of an account goes out under its one session id, so this gate is +// what keeps the account within the vendor's 3 sessions: an option may only +// lower it. +const ACCOUNT_MAX_INFLIGHT = 3 +const SESSION_RETRY_DELAYS_MS = [2_000, 4_000, 6_000, 8_000, 10_000] // the last repeats +const SESSION_RETRY_BUDGET_MS = 150_000 +// A body nobody drains must not hold an in-flight permit forever. +const PERMIT_MAX_HOLD_MS = 15 * 60 * 1000 +// How much of a 200 body to read while looking for an embedded error. +const SSE_PEEK_LIMIT = 16 * 1024 +// The gateway rejects a larger output budget (RANGE_VALIDATOR, 0..65536). +const MAX_OUTPUT_TOKENS = 65_536 +// Left to its default the gateway streams the reasoning inside `content`, so a +// caller shows the thinking as the answer; asked for explicitly it goes to +// `reasoning_content` and `content` is the reply only. +const ENABLE_THINKING = { type: "enabled" } + +// Benefits (free-quota) models require `maas_type: benefit` as a *signed* +// header, or the backend answers InferHub.002002009.404 "model is not +// registered". The authoritative list comes from opengw gateway/config at +// runtime; these are the known defaults so a cold start still works. +// +// The dated ids are the registered free models (measured: with the benefit +// header `deepseek-v4-flash-0731` answers 200 against the free pool, while the +// bare `deepseek-v4-flash` is a different, paid model that refuses the header +// with `InferHub.4005.200`), so they are sent exactly as published. +const BENEFIT_MODEL_FALLBACK = [ + "glm-5.3-flash", + "deepseek-v4.1-flash", + "deepseek-v4-flash-0731", + "deepseek-v4-pro-0813", +] +// Which models draw on the free pool is each account's own answer, kept on the +// account's state (`state.benefit`, with its builtin ids in `state.regular`): +// the fallback stands only until that account's gateway/config has been read. +// An account without the free campaign lists `deepseek-v4.1-flash` as a plain +// builtin model, and the benefit header then gets `InferHub.4004.200 benefit +// not found`. Nothing about models is shared between accounts. + +// Context windows (in tokens), keyed by the exact chat model id. Models +// without an entry leave the window to the backend's default. +const CONTEXT_WINDOWS = { + "GLM-5.2": 202752, + "glm-5.3-flash": 1048576, + "deepseek-v4-flash": 1048576, + "deepseek-v4-pro": 1048576, + "deepseek-v4.1-flash": 1000000, +} + +// The models offered before (or instead of) the account's own live list. `GLM-5` +// is gone: the endpoint answers `InferHub.002002009.404` for it. +const CATALOG = [ + { id: "GLM-5.2", name: "GLM-5.2" }, + { id: "GLM-5.1", name: "GLM-5.1" }, + { id: "glm-5.3-flash", name: "GLM-5.3 Flash" }, + { id: "openpangu-2.0-flash", name: "openPangu 2.0 Flash" }, + { id: "openpangu-2.0-pro", name: "openPangu 2.0 Pro" }, + { id: "deepseek-v4-flash-0731", name: "DeepSeek V4 Flash" }, + { id: "deepseek-v4-pro-0813", name: "DeepSeek V4 Pro" }, + { id: "deepseek-v4.1-flash", name: "DeepSeek V4.1 Flash" }, +] + +// ---- small helpers --------------------------------------------------------- + +const firstOf = (...vs) => vs.find((v) => typeof v === "string" && v.trim())?.trim() ?? "" + +const asRecord = (v) => (typeof v === "object" && v !== null && !Array.isArray(v) ? v : {}) + +function safeJson(text) { + try { + const parsed = JSON.parse(text) + return typeof parsed === "object" && parsed !== null ? parsed : null + } catch { + return null + } +} + +function num(v) { + if (typeof v === "number" && Number.isFinite(v)) return v + if (typeof v === "string" && v.trim()) { + const n = Number(v) + if (Number.isFinite(n)) return n + } + return 0 +} + +const clamp = (n) => Math.max(0, Math.min(100, n)) + +// prettify is a model id as a name: openpangu-2.0-flash -> "Openpangu 2.0 Flash" +function prettify(id) { + return String(id) + .split(/[-_]/) + .filter(Boolean) + .map((w) => w.charAt(0).toUpperCase() + w.slice(1)) + .join(" ") +} + +// normalizeModelId drops a trailing 4-digit version tag: deepseek-v4-flash-0731 +// -> deepseek-v4-flash. Only for display names and the CONTEXT_WINDOWS lookup: +// the dated id is the registered free model, so ids sent upstream keep it. +function normalizeModelId(id) { + if (typeof id === "string" && id.length > 5) { + const suffix = id.slice(-5) + if (suffix.startsWith("-") && /^\d{4}$/.test(suffix.slice(1))) return id.slice(0, -5) + } + return id +} + +const BEIJING_MS = 8 * 3600 * 1000 + +/** Today as CodeArts counts days: a Beijing (UTC+8) date, "2026-10-21". */ +const beijingDay = (at = Date.now()) => new Date(at + BEIJING_MS).toISOString().slice(0, 10) + +/** The next Beijing midnight after `at`, in ms: when a daily allowance comes back. */ +const nextBeijingMidnight = (at = Date.now()) => Date.parse(`${beijingDay(at)}T00:00:00+08:00`) + 86_400_000 + +/** + * A date as CodeArts writes it, in ms (undefined when it can't be read): + * epoch seconds or ms, ISO, or a zone-less "2026-11-01[ 00:00:00]", which is + * Beijing time. + */ +function vendorDate(v) { + if (typeof v === "number" && Number.isFinite(v) && v > 0) return v < 1e11 ? v * 1000 : v + if (typeof v !== "string" || !v.trim()) return undefined + const s = v.trim() + if (/^\d+$/.test(s)) return vendorDate(Number(s)) + const local = /^(\d{4}-\d{2}-\d{2})(?:[ T](\d{2}:\d{2}(?::\d{2})?))?$/.exec(s) + const at = local ? Date.parse(`${local[1]}T${local[2] ?? "00:00:00"}+08:00`) : Date.parse(s) + return Number.isNaN(at) ? undefined : at +} + +/** + * A model's credit rate (官方「消耗系数」, shown "1.50x"): `credit` is one price + * tier or a list of them, `ratio_display` the multiple. 0 when it has none. + */ +function creditRateOf(credit) { + const tier = asRecord(Array.isArray(credit) ? credit[0] : credit) + const n = parseFloat(String(tier.ratio_display ?? tier.ratioDisplay ?? "")) + return Number.isFinite(n) && n > 0 ? n : 0 +} + +// upstreamModelId drops the provider prefix a host may leave on the id +// (`codearts/deepseek-v4.1-flash`): the gateway knows only the bare id, and +// answers anything else `InferHub.002002009.404`, inside a 200 when streaming. +function upstreamModelId(id) { + return typeof id === "string" && id.startsWith(`${PROVIDER}/`) ? id.slice(PROVIDER.length + 1) : id +} + +// ---- WebCrypto primitives -------------------------------------------------- + +function subtle() { + const c = globalThis.crypto + if (!c?.subtle) throw new Error("CodeArts: WebCrypto (globalThis.crypto.subtle) is unavailable") + return c.subtle +} + +const typed = (u8) => (u8 instanceof Uint8Array ? u8 : new Uint8Array(u8)) + +function randomBytes(n) { + const out = new Uint8Array(n) + globalThis.crypto.getRandomValues(out) + return out +} + +const hex = (u8) => Array.from(u8).map((b) => b.toString(16).padStart(2, "0")).join("") + +function randomHex(n) { + return hex(randomBytes(n)) +} + +function b64url(u8) { + let s = "" + for (const b of u8) s += String.fromCharCode(b) + return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "") +} + +const utf8 = (s) => new TextEncoder().encode(s) + +async function sha256Hex(data) { + const digest = await subtle().digest("SHA-256", typed(data)) + return hex(new Uint8Array(digest)) +} + +async function hmacSha256Hex(key, data) { + const cryptoKey = await subtle().importKey( + "raw", typed(key), { name: "HMAC", hash: "SHA-256" }, false, ["sign"], + ) + const sig = await subtle().sign("HMAC", cryptoKey, typed(data)) + return hex(new Uint8Array(sig)) +} + +/** PKCE pair: a random 48-byte base64url verifier + its S256 challenge. */ +async function generatePkcePair() { + const codeVerifier = b64url(randomBytes(48)) + const digest = await subtle().digest("SHA-256", utf8(codeVerifier)) + return { codeVerifier, codeChallenge: b64url(new Uint8Array(digest)) } +} + +/** Generate an ES256 (P-256) DPoP key pair as JWKs. */ +async function generateDpopKeyPair() { + const pair = await subtle().generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, ["sign", "verify"]) + const jwk = await subtle().exportKey("jwk", pair.privateKey) + return { + privateKeyJwk: { kty: "EC", crv: "P-256", x: jwk.x, y: jwk.y, d: jwk.d }, + publicKeyJwk: { kty: "EC", crv: "P-256", x: jwk.x, y: jwk.y }, + } +} + +/** Recover a DPoP key pair from a persisted private JWK. */ +function keyPairFromStoredJwk(jwk) { + return { + privateKeyJwk: { kty: "EC", crv: "P-256", x: jwk.x, y: jwk.y, d: jwk.d }, + publicKeyJwk: { kty: "EC", crv: "P-256", x: jwk.x, y: jwk.y }, + } +} + +/** Sign a `dpop+jwt` proof (htm=method, htu=URL) with the DPoP private key. */ +async function signDpopJws(keyPair, htm, htu) { + const header = { alg: "ES256", typ: "dpop+jwt", jwk: keyPair.publicKeyJwk } + const payload = { htm, htu, iat: Math.floor(Date.now() / 1000), jti: randomHex(32) } + const signingInput = `${b64url(utf8(JSON.stringify(header)))}.${b64url(utf8(JSON.stringify(payload)))}` + const key = await subtle().importKey( + "jwk", keyPair.privateKeyJwk, { name: "ECDSA", namedCurve: "P-256" }, false, ["sign"], + ) + const sig = await subtle().sign({ name: "ECDSA", hash: "SHA-256" }, key, utf8(signingInput)) + // WebCrypto ECDSA returns raw r||s, which is exactly the JWS ES256 format. + return `${signingInput}.${b64url(new Uint8Array(sig))}` +} + +// ---- Huawei SDK-HMAC-SHA256 request signing -------------------------------- + +function buildCanonicalRequest(method, uri, query, headers, payloadHash) { + const signedHeaders = [...headers.keys()].sort() + const headerLines = signedHeaders.map((k) => `${k}:${headers.get(k) ?? ""}`) + return [method, uri, query, headerLines.join("\n"), "", signedHeaders.join(";"), payloadHash].join("\n") +} + +// RFC 3986: everything but the unreserved characters is %-encoded, as the +// gateway encodes it when it checks the signature. +const rfc3986 = (s) => encodeURIComponent(s).replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`) + +/** The query as the signature has it: pairs sorted by key, then value, each encoded. */ +function canonicalQuery(url) { + return [...url.searchParams.entries()] + .sort(([a, x], [b, y]) => (a < b ? -1 : a > b ? 1 : x < y ? -1 : x > y ? 1 : 0)) + .map(([k, v]) => `${rfc3986(k)}=${rfc3986(v)}`) + .join("&") +} + +/** + * Sign a Huawei request; returns the header map to merge into the request. + * Extra headers (e.g. `maas_type: benefit`) participate in the canonical + * request and must be sent verbatim, or the server rejects the signature. + */ +async function signRequestHuawei(ak, sk, securityToken, method, urlStr, body, extraHeaders, dateStampOverride) { + const url = new URL(urlStr) + let uri = url.pathname + if (!uri.endsWith("/")) uri += "/" + const query = canonicalQuery(url) + const dateStamp = dateStampOverride + ?? new Date().toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z") + const payloadHash = await sha256Hex(body) + + const headers = new Map() + headers.set("host", url.host) + headers.set("x-sdk-date", dateStamp) + headers.set("x-sdk-content-sha256", payloadHash) + headers.set("x-security-token", securityToken) + if (extraHeaders !== undefined) { + for (const [k, v] of Object.entries(extraHeaders)) headers.set(k, v) + } + if (method.toUpperCase() !== "GET") headers.set("content-type", "application/json") + + const signedHeaders = [...headers.keys()].sort() + const canonicalRequest = buildCanonicalRequest(method.toUpperCase(), uri, query, headers, payloadHash) + const canonicalHash = await sha256Hex(utf8(canonicalRequest)) + const stringToSign = `SDK-HMAC-SHA256\n${dateStamp}\n${canonicalHash}` + const signature = await hmacSha256Hex(utf8(sk), utf8(stringToSign)) + headers.set( + "Authorization", + `SDK-HMAC-SHA256 Access=${ak},SignedHeaders=${signedHeaders.join(";")},Signature=${signature}`, + ) + return headers +} + +// ---- OAuth token exchange -------------------------------------------------- + +/** Normalize an STS token response into a persisted CodeArts credential. */ +function credentialFromTokenResponse(token, codeVerifier, keyPair) { + const c = token?.credentials ?? {} + return { + access_key_id: c.access_key_id ?? "", + secret_access_key: c.secret_access_key ?? "", + security_token: c.security_token ?? "", + expires_at: c.expiration ?? "", + refresh_token: token?.refresh_token, + code_verifier: codeVerifier, + dpop_private_key_jwk: keyPair.privateKeyJwk, + // Minted once per sign-in and kept across refreshes: the account's one + // upstream session, whichever process sends the request. + session_id: randomHex(16), + } +} + +/** Base64url (or plain base64) text to a parsed JSON object, or null. */ +function b64Json(s) { + if (typeof s !== "string" || !s) return null + try { + const t = s.replace(/-/g, "+").replace(/_/g, "/") + return safeJson(new TextDecoder().decode(Uint8Array.from(atob(t + "=".repeat((4 - (t.length % 4)) % 4)), (c) => c.charCodeAt(0)))) + } catch { + return null + } +} + +/** + * Who signed in. STS answers with no user fields, so without this every + * sign-in looked like a new account to magpie (one more `codearts#xxxxxx`); + * the refresh_token is a JWT whose `user_profile` claim names the signer. + * `id` tells accounts apart, `name` is what the usage card shows. + */ +function accountIdentityOf(cred) { + const legacy = { id: firstOf(cred?.user_name, cred?.user_id), name: firstOf(cred?.user_name) } + const token = typeof cred?.refresh_token === "string" ? cred.refresh_token : "" + const parts = token.split(".") + if (parts.length !== 3) return legacy + const payload = b64Json(parts[1]) + const raw = payload?.user_profile + const profile = typeof raw === "string" ? (safeJson(raw) ?? b64Json(raw)) : asRecord(raw) + const id = firstOf(profile?.principal_urn, profile?.account_name, profile?.account_id, profile?.user_id, legacy.id) + const name = firstOf(profile?.user_name, profile?.account_name, profile?.domain_name, legacy.name) + return { id, name } +} + +/** The credential a sign-in carries; magpie keeps it in the `access` field. */ +function credentialOf(auth) { + if (!auth || auth.type !== "oauth") return null + const raw = typeof auth.access === "string" ? auth.access : "" + if (!raw) return null + const cred = safeJson(raw) + return cred && typeof cred.access_key_id === "string" && cred.access_key_id ? cred : null +} + +function expiresFromCredential(cred) { + if (cred?.expires_at) { + const parsed = Date.parse(cred.expires_at) + if (!Number.isNaN(parsed)) return parsed + } + return Date.now() + 86_400_000 +} + +/** POST the STS token endpoint with a DPoP proof. */ +async function requestToken(body, keyPair, fetcher) { + const dpop = await signDpopJws(keyPair, "POST", STS_TOKEN_ENDPOINT) + let response + try { + response = await fetcher(STS_TOKEN_ENDPOINT, { + method: "POST", + headers: { DPoP: dpop, "Content-Type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams(body).toString(), + signal: AbortSignal.timeout(TOKEN_TIMEOUT_MS), + }) + } catch (e) { + throw new Error(`CodeArts token request network error: ${String(e)}`) + } + let data = null + try { + data = await response.json() + } catch { + data = null + } + if (!response.ok || !data?.credentials) { + const message = `CodeArts token request failed: ${response.status}${data ? ` ${JSON.stringify(data)}` : ""}` + // Only refresh_token invalidation is terminal; a transient DPoP rejection + // must not permanently mark the account. + if (data?.error === "invalid_grant" || isDeadRefreshToken(message)) { + throw Object.assign(new Error(message), { signIn: "expired" }) + } + throw new Error(message) + } + return data +} + +/** + * A refresh STS turns away for good: the token expired, or the one-time token + * was already spent (`STS5.1806`). Only signing in again brings the account + * back; a network hiccup or DPoP rejection must not read as this. + */ +function isDeadRefreshToken(text) { + return /ExpiredRefreshToken|STS5\.1806|invalid refresh token|refresh token has been used/i.test(String(text ?? "")) +} + +const isPermanentRefreshFailure = (e) => e?.signIn === "expired" || isDeadRefreshToken(e?.message ?? e) + +function exchangeAuthorizationCode(code, codeVerifier, port, keyPair, fetcher) { + return requestToken({ + client_id: CLIENT_ID, + code, + code_verifier: codeVerifier, + grant_type: GRANT_AUTHORIZATION_CODE, + redirect_uri: `http://127.0.0.1:${port}${REDIRECT_PATH}`, + }, keyPair, fetcher) +} + +function exchangeRefreshToken(refreshToken, codeVerifier, keyPair, fetcher) { + return requestToken({ + client_id: CLIENT_ID, + code_verifier: codeVerifier, + grant_type: GRANT_REFRESH_TOKEN, + refresh_token: refreshToken, + }, keyPair, fetcher) +} + +/** Refresh a stored credential, reusing its verifier + DPoP private key. */ +async function refreshCredential(cred, fetcher) { + const refreshToken = firstOf(cred.refresh_token) + if (!refreshToken || !cred.code_verifier || !cred.dpop_private_key_jwk) { + // Nothing to renew it with: it lapses for good, so the account is marked + // to sign in again rather than retried forever. + throw Object.assign( + new Error("CodeArts: credential cannot be refreshed (missing refresh_token/code_verifier/dpop key); sign in again"), + { signIn: "expired" }, + ) + } + const keyPair = keyPairFromStoredJwk(cred.dpop_private_key_jwk) + const token = await exchangeRefreshToken(refreshToken, cred.code_verifier, keyPair, fetcher) + const next = credentialFromTokenResponse(token, cred.code_verifier, keyPair) + if (!next.refresh_token) next.refresh_token = refreshToken + // Preserve non-rotating identity fields a legacy login may have carried, and + // the session id: it belongs to the account, not to the token. + for (const k of ["domain_id", "user_id", "user_name", "session_id"]) { + if (cred[k]) next[k] = cred[k] + } + return next +} + +/** + * The account's upstream session headers, the same in every process and across + * refreshes: a fresh Chat-Id per request opened a new session each time and + * pinned the 3-session cap. Credentials from before `session_id` existed fall + * back to the signer's identity, then to the access key. + */ +async function accountSessionIds(cred) { + const seed = firstOf(cred.session_id, accountIdentityOf(cred).id, cred.access_key_id) + const digest = await sha256Hex(utf8(`codearts-session:${seed}`)) + return { sessionId: digest.slice(0, 32), chatId: digest.slice(32, 64) } +} + +// ---- OAuth login: URL + loopback callback ---------------------------------- + +/** Build the Huawei Cloud portal authorize URL (params mirror the real IDE). */ +function buildOAuthLoginUrl(port, pkce, ticketId) { + return `${PORTAL_AUTHORIZE_BASE}?theme=${OAUTH_THEME}&locale=${OAUTH_LOCALE}` + + `&uri_scheme=${CLIENT_ID}&client_id=${CLIENT_ID}&port=${port}` + + `&code_challenge=${pkce.codeChallenge}&code_challenge_method=SHA-256` + + `&ticket_id=${ticketId}&plugin-name=${LOGIN_PLUGIN_NAME}&plugin-version=${LOGIN_PLUGIN_VERSION}` +} + +const buildPortalLoginResultUrl = (ok) => + `${PORTAL_LOGIN_BASE}?login_succeed=${ok}&uri_scheme=${CLIENT_ID}&locale=${OAUTH_LOCALE}` + +/** + * Start the loopback callback server, listening on 127.0.0.1:port>=10000. It + * takes one thing: a GET to the callback path with the authorization code, + * which it exchanges at STS (PKCE + DPoP), then sends the browser on to the + * portal's own result page. The redirect target is always that page, never a + * parameter of the request. + */ +function startOAuthCallbackServer(ticketId, pkce, keyPair, fetcher) { + let resolveResult + let rejectResult + const result = new Promise((resolve, reject) => { + resolveResult = resolve + rejectResult = reject + }) + let exchanging = false + + const server = createServer((request, response) => { + const url = new URL(request.url ?? "/", `http://127.0.0.1:${request.socket.localPort}`) + if (url.pathname !== REDIRECT_PATH) { + response.writeHead(404).end("Not found") + return + } + if (request.method !== "GET") { + response.writeHead(405, { Allow: "GET" }).end("Method not allowed") + return + } + const code = url.searchParams.get("code") + if (!code) { + response.writeHead(400).end("Missing authorization code") + return + } + // One sign-in, one code: a second callback for the same flow is refused. + if (exchanging) { + response.writeHead(409).end("This sign-in is already being completed") + return + } + exchanging = true + const port = request.socket.localPort ?? 0 + void exchangeAuthorizationCode(code, pkce.codeVerifier, port, keyPair, fetcher).then( + (token) => { + response.writeHead(307, { Location: buildPortalLoginResultUrl(true) }).end() + const cred = credentialFromTokenResponse(token, pkce.codeVerifier, keyPair) + resolveResult({ access: JSON.stringify(cred), expires: expiresFromCredential(cred) }) + }, + (error) => { + response.writeHead(307, { Location: buildPortalLoginResultUrl(false) }).end() + rejectResult(error) + }, + ) + }) + + return listenOnCallbackPort(server).then((port) => ({ port, server, result })) +} + +/** Listen on 127.0.0.1, retrying with a random port >= 10000 if needed. */ +function listenOnCallbackPort(server) { + return new Promise((resolve, reject) => { + const tryListen = (port) => { + server.once("error", reject) + server.listen(port, "127.0.0.1", () => { + const address = server.address() + const assigned = typeof address === "object" && address ? address.port : 0 + if (assigned >= MIN_CALLBACK_PORT) { + resolve(assigned) + return + } + server.close(() => tryListen(Math.floor(Math.random() * (65_536 - MIN_CALLBACK_PORT)) + MIN_CALLBACK_PORT)) + }) + } + tryListen(0) + }) +} + +/** + * Start an OAuth flow and return its login URL immediately (magpie opens it). + * The result resolves once the browser is redirected back and STS answers; + * the callback server is closed as soon as the result settles. + */ +async function startOAuthFlow(fetcher) { + const ticketId = randomHex(32) + const pkce = await generatePkcePair() + const keyPair = await generateDpopKeyPair() + const { port, server, result } = await startOAuthCallbackServer(ticketId, pkce, keyPair, fetcher) + const loginUrl = buildOAuthLoginUrl(port, pkce, ticketId) + + let closed = false + const close = async () => { + if (closed) return + closed = true + await new Promise((resolve) => server.close(() => resolve())) + } + + const resultWithUrl = Promise.race([ + result, + new Promise((_, reject) => { + const timer = setTimeout(() => reject(new Error("CodeArts OAuth login timed out")), OAUTH_CALLBACK_TIMEOUT_MS) + timer.unref?.() + }), + ]).then((outcome) => ({ ...outcome, loginUrl })) + + // Settle in the background so an early result never becomes an unhandled + // rejection, and so the listening socket is always released. + resultWithUrl.catch(() => {}).finally(() => { void close() }) + + return { loginUrl, result: resultWithUrl, close } +} + +// ---- signed requests to CodeArts ------------------------------------------- + +/** Turn a request body (string / bytes / stream / blob) into bytes. */ +async function toBytes(body) { + if (body == null) return new Uint8Array() + if (typeof body === "string") return utf8(body) + if (body instanceof Uint8Array) return body + if (body instanceof ArrayBuffer) return new Uint8Array(body) + if (ArrayBuffer.isView(body)) return new Uint8Array(body.buffer, body.byteOffset, body.byteLength) + if (typeof body?.getReader === "function") { + const chunks = [] + const reader = body.getReader() + for (;;) { + const { done, value } = await reader.read() + if (done) break + chunks.push(typed(value)) + } + const total = chunks.reduce((n, c) => n + c.length, 0) + const out = new Uint8Array(total) + let offset = 0 + for (const c of chunks) { + out.set(c, offset) + offset += c.length + } + return out + } + if (typeof body?.arrayBuffer === "function") return new Uint8Array(await body.arrayBuffer()) + return utf8(String(body)) +} + +/** + * Is `model` one of the account's free models, sent with the signed + * `maas_type: benefit` header? `state.benefit` is the account's own list once + * read (null until then, when the fallback stands); one the gateway said has + * no benefit (`state.noBenefit`) is not. + */ +function isBenefitModel(model, state) { + const id = String(upstreamModelId(model) ?? "") + const free = state?.benefit ? state.benefit.has(id) : BENEFIT_MODEL_FALLBACK.includes(id) + return free && !state?.noBenefit?.has(id) +} + +/** Can `model` be called without the benefit header: one of the account's builtin models, or not known yet? */ +function isRegularModel(model, state) { + return !state?.regular || state.regular.has(String(upstreamModelId(model) ?? "")) +} + +/** + * Reshape a chat body into what the gateway accepts and meters: + * - the bare model id, without the host's `codearts/` prefix; + * - thinking asked for explicitly (unless the caller said, or the plugin's + * `thinking: false` option), so `content` carries only the reply; + * - the output budget inside the gateway's 65536; + * - always `stream: true`. CodeArts meters only streamed answers — a + * non-streaming 200 returns tokens yet leaves the credits untouched — so a + * caller that asked for JSON gets the stream folded back (`fold`). + * A body that is not a chat (no `model` + `messages`) gives null. + */ +function prepareChatBody(parsed, { thinking = true } = {}) { + if (!parsed || typeof parsed.model !== "string" || !Array.isArray(parsed.messages)) return null + const body = { ...parsed, model: upstreamModelId(parsed.model) } + // `injected`: ours to take back should a model refuse the parameter. + const injected = thinking && body.thinking === undefined + if (injected) body.thinking = ENABLE_THINKING + for (const k of ["max_tokens", "max_completion_tokens"]) { + if (typeof body[k] === "number" && body[k] > MAX_OUTPUT_TOKENS) body[k] = MAX_OUTPUT_TOKENS + } + const fold = body.stream !== true + body.stream = true + return { body, fold, injected } +} + +// ---- reading the gateway's answers ----------------------------------------- + +/** The JSON payloads of an SSE body, in arrival order, `[DONE]` skipped. */ +function parseSseEvents(text) { + const events = [] + for (const line of String(text).split(/\r?\n/)) { + const s = line.trim() + if (!s.startsWith("data:")) continue + const payload = s.slice(5).trim() + if (!payload || payload === "[DONE]") continue + const parsed = safeJson(payload) + if (parsed) events.push(parsed) + } + return events +} + +/** The error code an answer carries (`TM.00001041`, `InferHub.4291.200`, …), or "". */ +function errorCodeOf(text) { + const m = /"(?:error_code|code)"\s*:\s*"([A-Za-z]*\.?[0-9][0-9A-Za-z.]*)"/.exec(String(text ?? "")) + return m ? m[1] : "" +} + +/** The vendor's own words for an error, so the agent can show them. */ +function errorMessageOf(text) { + const m = /"(?:error_msg|message)"\s*:\s*"((?:[^"\\]|\\.)*)"/.exec(String(text ?? "")) + if (!m) return "" + try { + return JSON.parse(`"${m[1]}"`) + } catch { + return m[1] + } +} + +/** A 401/400 that only means the temporary AK/SK/security-token went stale. */ +function isStaleCredential(text) { + return /APIG\.0(301|307|602)|security token has expired|verify ak sk signature fail/i.test(String(text ?? "")) +} + +/** Codes magpie should treat as "try another account later": quota or a rate limit. */ +function isRateLimitCode(code) { + return /4291|8111\d|(^|\.)429(\.|$)/.test(String(code ?? "")) +} + +/** + * The status for an error the gateway put inside a 200: 429 for a spent quota + * or a rate limit (magpie moves to another account), 400 for a model or benefit + * the account doesn't have (retrying can't help), 502 for the rest. + */ +function embeddedErrorStatus(code) { + if (isRateLimitCode(code)) return 429 + if (/(^|\.)40[0-4](\.|$)|InferHub\.400[0-9]\./.test(String(code ?? ""))) return 400 + return 502 +} + +/** Does this event carry part of an answer (not only a role or a keepalive)? */ +function eventHasContent(event) { + const choice = Array.isArray(event?.choices) ? event.choices[0] : undefined + if (!choice) return false + if (choice.finish_reason != null || choice.message) return true + const delta = asRecord(choice.delta) + if (typeof delta.content === "string" && delta.content) return true + if (typeof delta.reasoning_content === "string" && delta.reasoning_content) return true + return Array.isArray(delta.tool_calls) && delta.tool_calls.length > 0 +} + +/** + * What the head of a 200 body is: "answer", an error code, or undefined (read + * on). The gateway reports the session cap, a spent quota or an unknown model + * as an error event inside a 200, sometimes after an empty role-only delta, and + * a 200 never fails over — the caller just saw an empty reply. + */ +function classifyHead(text, done) { + if (parseSseEvents(text).some(eventHasContent)) return "answer" + if (done && Array.isArray(safeJson(text)?.choices)) return "answer" + const code = errorCodeOf(text) + // Wait for the error event's end, so its message is whole. + if (code) return done || /\n/.test(text.slice(text.indexOf(code))) ? code : undefined + if (done || text.includes("[DONE]")) return "answer" + return undefined +} + +/** Read a 200's head until it is an answer or an error; keep what was read. */ +async function peekAnswer(res) { + const head = { code: "", text: "", chunks: [], reader: null, decoder: new TextDecoder() } + if (!res.body) return head + head.reader = res.body.getReader() + let done = false + for (;;) { + const verdict = classifyHead(head.text, done) + if (verdict) { + if (verdict !== "answer") head.code = verdict + break + } + if (head.text.length >= SSE_PEEK_LIMIT) break + const r = await head.reader.read() + if (r.done) { + done = true + continue + } + head.chunks.push(typed(r.value)) + head.text += head.decoder.decode(r.value, { stream: true }) + } + // An error answer is dropped; not awaited, as Node's cancel can hang on a live body. + if (head.code) void head.reader.cancel().catch(() => {}) + return head +} + +/** Headers for a body handed over re-read: length/encoding no longer hold. */ +function streamHeaders(headers) { + const out = new Headers(headers) + out.delete("content-encoding") + out.delete("content-length") + return out +} + +/** The peeked bytes, then the rest of the stream; `release` once it ends. */ +function replayBody(head, release) { + let i = 0 + return new ReadableStream({ + async pull(controller) { + try { + if (i < head.chunks.length) { + controller.enqueue(head.chunks[i++]) + return + } + const { done, value } = head.reader ? await head.reader.read() : { done: true } + if (done) { + release() + controller.close() + return + } + controller.enqueue(typed(value)) + } catch (e) { + release() + controller.error(e) + } + }, + cancel(reason) { + release() + void head.reader?.cancel(reason).catch(() => {}) + }, + }) +} + +/** Fold streamed `choices[].delta` chunks into one OpenAI completion object. */ +function completionFromChunks(events) { + const first = events[0] ?? {} + const content = [] + const reasoning = [] + const toolCalls = [] + let finish = null + let usage = null + let model = first.model + for (const ev of events) { + if (ev.usage) usage = ev.usage + if (typeof ev.model === "string" && ev.model) model = ev.model + const choice = Array.isArray(ev.choices) ? ev.choices[0] : undefined + if (!choice) continue + if (choice.finish_reason != null) finish = choice.finish_reason + const delta = asRecord(choice.delta) + if (typeof delta.content === "string") content.push(delta.content) + if (typeof delta.reasoning_content === "string") reasoning.push(delta.reasoning_content) + for (const call of Array.isArray(delta.tool_calls) ? delta.tool_calls : []) { + const slot = (toolCalls[num(call.index)] ??= { id: "", type: "function", function: { name: "", arguments: "" } }) + if (typeof call.id === "string" && call.id) slot.id = call.id + if (typeof call.type === "string" && call.type) slot.type = call.type + if (typeof call.function?.name === "string") slot.function.name += call.function.name + if (typeof call.function?.arguments === "string") slot.function.arguments += call.function.arguments + } + } + const message = { role: "assistant", content: content.join("") } + if (reasoning.length > 0) message.reasoning_content = reasoning.join("") + const calls = toolCalls.filter(Boolean) + if (calls.length > 0) message.tool_calls = calls + return { + id: firstOf(first.id) || `chatcmpl-${randomHex(12)}`, + object: "chat.completion", + created: num(first.created) || Math.floor(Date.now() / 1000), + model, + choices: [{ index: 0, message, finish_reason: finish ?? (calls.length ? "tool_calls" : "stop") }], + ...(usage ? { usage } : {}), + } +} + +/** Answer a caller that asked for JSON: read the whole stream, fold it. */ +async function foldAnswer(res, head) { + let text = head.text + if (head.reader) { + for (;;) { + const { done, value } = await head.reader.read() + if (done) break + text += head.decoder.decode(value, { stream: true }) + } + text += head.decoder.decode() + } + const headers = streamHeaders(res.headers) + headers.set("content-type", "application/json") + const events = parseSseEvents(text) + if (events.some((ev) => Array.isArray(ev.choices) && ev.choices.length > 0)) { + return new Response(JSON.stringify(completionFromChunks(events)), { status: res.status, statusText: res.statusText, headers }) + } + // The gateway answered JSON after all, or nothing at all. + if (Array.isArray(safeJson(text)?.choices)) return new Response(text, { status: res.status, statusText: res.statusText, headers }) + return errorResponse(502, errorCodeOf(text), firstOf(errorMessageOf(text), "the gateway returned an empty answer")) +} + +/** An OpenAI-shaped error carrying the vendor's code and words (magpie adds the provider name). */ +function errorResponse(status, code, message, extraHeaders = {}) { + return new Response( + JSON.stringify({ error: { message: `${message}${code ? ` (${code})` : ""}`, type: status === 429 ? "rate_limit_exceeded" : "upstream_error", code: code || null } }), + { status, headers: { "content-type": "application/json", ...extraHeaders } }, + ) +} + +/** A 401 magpie reads as "this sign-in is gone": it marks it and fails over. */ +function signInExpiredResponse(text) { + const body = text || JSON.stringify({ error: { message: "the sign-in expired; sign in again", type: "authentication_error" } }) + return new Response(body, { status: 401, headers: { "content-type": "application/json", "X-Magpie-Sign-In": "expired" } }) +} + +/** Rebuild a response whose body was read, keeping the vendor's answer. */ +function rebuildResponse(res, text, extraHeaders = {}) { + const headers = streamHeaders(res.headers) + for (const [k, v] of Object.entries(extraHeaders)) headers.set(k, v) + return new Response(text, { status: res.status, statusText: res.statusText, headers }) +} + +// ---- the account's session budget ------------------------------------------ + +/** + * Per-account gate for in-flight chats: a burst queues here rather than come + * back as `TM.00001041`. `acquire` resolves to that permit's release (safe to + * call twice); a permit is let go by itself after PERMIT_MAX_HOLD_MS. + */ +function createConcurrencyGate(limit) { + let active = 0 + const waiters = [] + const grant = () => { + active += 1 + let held = true + const release = () => { + if (!held) return + held = false + clearTimeout(timer) + active -= 1 + while (active < limit && waiters.length > 0) waiters.shift().admit() + } + const timer = setTimeout(release, PERMIT_MAX_HOLD_MS) + timer.unref?.() + return release + } + return { + get active() { return active }, + get waiting() { return waiters.length }, + acquire(signal) { + if (signal?.aborted) return Promise.reject(abortError(signal)) + if (active < limit) return Promise.resolve(grant()) + return new Promise((resolve, reject) => { + const onAbort = () => { + const i = waiters.indexOf(waiter) + if (i >= 0) waiters.splice(i, 1) + reject(abortError(signal)) + } + const waiter = { + admit() { + signal?.removeEventListener("abort", onAbort) + resolve(grant()) + }, + } + signal?.addEventListener("abort", onAbort, { once: true }) + waiters.push(waiter) + }) + }, + } +} + +function abortError(signal) { + return signal?.reason instanceof Error ? signal.reason : new DOMException("The operation was aborted.", "AbortError") +} + +/** Sleep, but give up as soon as the caller aborts the request. */ +function delay(ms, signal) { + return new Promise((resolve, reject) => { + if (signal?.aborted) { + reject(abortError(signal)) + return + } + const onAbort = () => { + clearTimeout(timer) + reject(abortError(signal)) + } + const timer = setTimeout(() => { + signal?.removeEventListener("abort", onAbort) + resolve() + }, ms) + signal?.addEventListener("abort", onAbort, { once: true }) + }) +} + +/** The wait before retry `attempt` (±20% so concurrent callers spread out). */ +function retryDelayMs(attempt, delays = SESSION_RETRY_DELAYS_MS) { + const base = delays[Math.min(attempt, delays.length - 1)] ?? 0 + return Math.round(base * (0.8 + Math.random() * 0.4)) +} + +/** The queue a 429 put the request in, from its headers; undefined when it is no queue. */ +function queueInfoOf(headers) { + if (String(headers?.get("queue-status") ?? "").toLowerCase() !== "queued") return undefined + const traceId = headers.get("trace-id") + if (!traceId) return undefined + const after = Number(headers.get("retry-after") ?? 5) + return { traceId, retryAfter: Number.isFinite(after) && after >= 0 ? after : 5 } +} + +/** One signed call on a queued trace: GET is where it stands, DELETE takes it out. */ +async function traceQueueCall(method, cred, traceId, context, signal) { + const url = TRACE_QUEUE_URL(traceId) + const signed = await signRequestHuawei( + cred.access_key_id, cred.secret_access_key, cred.security_token, + method, url, new Uint8Array(), + ) + const headers = new Headers() + signed.forEach((value, key) => { + if (key !== "host") headers.set(key, value) + }) + headers.set(SESSION_HEADER, context.sessionId) + return context.fetcher(url, { method, headers, ...(signal ? { signal } : {}) }) +} + +/** + * Wait in the gateway's queue the way the CodeArts agent does: poll every + * `retry-after` seconds until the trace is promoted (then the request is sent + * again), and leave the queue when the caller gives up or the wait runs out. + * Gives "promoted" or "gone"; throws the abort. + */ +async function waitInQueue(cred, queued, context, signal, deadline) { + const leave = () => void traceQueueCall("DELETE", cred, queued.traceId, context).catch(() => {}) + let retryAfter = queued.retryAfter + let failures = 0 + try { + for (;;) { + if (Date.now() + retryAfter * 1000 > deadline) { + leave() + return "gone" + } + await delay(retryAfter * 1000, signal) + let body = null + try { + const res = await traceQueueCall("GET", cred, queued.traceId, context, signal) + body = safeJson(await res.text()) + if (!res.ok && !body?.status) throw new Error(`HTTP ${res.status}`) + } catch (e) { + if (signal?.aborted) throw e + if (++failures >= 3) return "gone" + continue + } + const status = String(body?.status ?? "queued") + if (status === "promoted") return "promoted" + if (status === "not_found" || status === "error") return "gone" + retryAfter = num(body?.retry_after) || retryAfter + } + } catch (e) { + leave() + throw e + } +} + +/** The host of a URL, "" when it isn't one. */ +function hostOf(url) { + try { + return new URL(url).hostname + } catch { + return "" + } +} + +/** Is this an https URL on one of Huawei Cloud's hosts, the only ones the credentials go to? */ +function isHuaweiUrl(url) { + try { + const u = new URL(url) + return u.protocol === "https:" && HUAWEI_HOST.test(u.hostname) + } catch { + return false + } +} + +/** Mark a 401/403 the way magpie reads a sign-in that is gone. */ +function withSignInMark(res) { + if (res.status !== 401 && res.status !== 403) return res + const h = new Headers(res.headers) + h.set("X-Magpie-Sign-In", "expired") + return new Response(res.body, { status: res.status, statusText: res.statusText, headers: h }) +} + +/** + * The plugin's per-request fetch. A chat is reshaped (see prepareChatBody), + * signed with the account's temporary credentials and sent under the account's + * one Chat-Id/Session-Id, after taking one of its in-flight permits. Then: + * - `TM.00001041` (a 400, or a 200's first event) is retried, re-signed, until + * a session frees or the budget runs out — then a 429, which magpie fails + * over on; + * - a stale credential (401, `APIG.0602`) is renewed once and the request sent + * again; when that can't be done, a 401 marks the sign-in; + * - a 200 carrying only an error (a spent quota, an unknown model) becomes a + * 429/502 with the vendor's words instead of an empty reply. + * The permit is held until the answer's body ends: the gateway counts the + * session while it streams. Only Huawei Cloud hosts are signed for: a request + * anywhere else (an overridden `api`, say) is refused before the access key or + * security token leave. + */ +async function signedFetch(cred, input, init, context) { + const req = typeof Request !== "undefined" && input instanceof Request ? input : null + const url = req ? req.url : String(input) + if (!isHuaweiUrl(url)) { + return errorResponse(400, "", `refusing to sign a request to ${hostOf(url) || "an unknown host"}: only Huawei Cloud hosts get the account's credentials`) + } + const method = String(init?.method ?? req?.method ?? "GET").toUpperCase() + const baseHeaders = new Headers(init?.headers ?? req?.headers) + let body + if (init?.body != null) body = await toBytes(init.body) + else if (req) body = new Uint8Array(await req.clone().arrayBuffer()) + else body = new Uint8Array() + // The body is part of the signature, so it is reshaped before signing. + const parsed = body.length > 0 ? safeJson(new TextDecoder().decode(body)) : null + const chat = prepareChatBody(parsed, context) + if (chat) body = utf8(JSON.stringify(chat.body)) + const model = upstreamModelId(parsed?.model) + let extra = isBenefitModel(model, context.state) ? { maas_type: "benefit" } : undefined + const signal = init?.signal ?? req?.signal ?? undefined + + let active = cred + const send = async () => { + const signed = await signRequestHuawei( + active.access_key_id, active.secret_access_key, active.security_token, + method, url, body, extra, + ) + const headers = new Headers(baseHeaders) + signed.forEach((value, key) => { + if (key !== "host") headers.set(key, value) + }) + headers.set("Chat-Id", context.chatId) + headers.set("Session-Id", context.sessionId) + // The session headers the CodeArts agent sends: one session per account, + // a fresh trace per request. + headers.set(SESSION_HEADER, context.sessionId) + headers.set("user-session-id", context.sessionId) + headers.set("x-ot-parent-session-id", "") + headers.set("x-ot-trace-id", randomHex(16)) + headers.set("x-ot-span-id", randomHex(8)) + headers.set("x-snap-traceid", randomHex(16)) + headers.set("lang", "en") + return context.fetcher(url, { + ...init, + method, + headers, + ...(body.length > 0 ? { body } : {}), + ...(signal ? { signal } : {}), + }) + } + + // A sign-in known to be beyond renewal never reaches the network again. + if (context.signInDead?.()) return signInExpiredResponse() + if (!chat) return withSignInMark(await send()) + + const release = await context.gate.acquire(signal) + let handedOver = false + try { + const clock = context.now ?? Date.now + const started = clock() + let renewed = false + let queueDeadline = 0 + for (let attempt = 0; ; attempt += 1) { + const res = await send() + let text + let code + if (res.status === 429) { + const queued = queueInfoOf(res.headers) + if (queued) { + void res.body?.cancel().catch(() => {}) + queueDeadline ||= Date.now() + (context.queueBudgetMs ?? QUEUE_BUDGET_MS) + if ((await waitInQueue(active, queued, context, signal, queueDeadline)) === "promoted") continue + return errorResponse(429, "", "排队等待超时或已被移出队列,请稍后再试") + } + } + if (res.ok) { + const head = await peekAnswer(res) + if (!head.code) { + if (chat.fold) return await foldAnswer(res, head) + handedOver = true + return new Response(replayBody(head, release), { status: res.status, statusText: res.statusText, headers: streamHeaders(res.headers) }) + } + text = head.text + code = head.code + } else { + text = await res.text().catch(() => "") + code = errorCodeOf(text) + } + + if (res.status === 401 || isStaleCredential(text)) { + if (!renewed && context.renewCredential) { + renewed = true + const next = await context.renewCredential(active) + if (next) { + active = next + continue + } + } + return signInExpiredResponse(text) + } + if (res.status === 403) return rebuildResponse(res, text, { "X-Magpie-Sign-In": "expired" }) + // The thinking parameter is the plugin's own: a model that refuses it + // gets the request again as the caller wrote it. + if (res.status === 400 && chat.injected && /thinking/i.test(text)) { + chat.injected = false + delete chat.body.thinking + body = utf8(JSON.stringify(chat.body)) + continue + } + // No free benefit for this model on this account (`4004`), or the header + // isn't taken for it (`4005`): it is the account's plain builtin model. + if (extra && /InferHub\.400[45]\.200|benefit not found/i.test(code || text) && isRegularModel(model, context.state)) { + context.state?.noBenefit.add(model) + extra = undefined + continue + } + if (code === SESSION_LIMIT_ERROR || text.includes(SESSION_LIMIT_ERROR)) { + const wait = retryDelayMs(attempt, context.retryDelays) + if (clock() - started + wait <= (context.retryBudgetMs ?? SESSION_RETRY_BUDGET_MS)) { + await (context.sleep ?? delay)(wait, signal) + continue + } + return errorResponse(429, SESSION_LIMIT_ERROR, firstOf(errorMessageOf(text), "并发会话数已达上限,请稍后再试")) + } + if (!res.ok) return rebuildResponse(res, text) + return errorResponse(embeddedErrorStatus(code), code, firstOf(errorMessageOf(text), "the gateway answered with an error")) + } + } finally { + if (!handedOver) release() + } +} + +/** A signed GET returning the response text, or undefined on any failure. */ +async function signedGet(url, cred, fetcher, extraUnsignedHeaders) { + const signed = await signRequestHuawei( + cred.access_key_id, cred.secret_access_key, cred.security_token, + "GET", url, new Uint8Array(), + ) + const headers = new Headers() + signed.forEach((value, key) => { + if (key !== "host") headers.set(key, value) + }) + if (extraUnsignedHeaders !== undefined) { + for (const [k, v] of Object.entries(extraUnsignedHeaders)) headers.set(k, v) + } + try { + const res = await fetcher(url, { method: "GET", headers, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) }) + if (!res.ok) return undefined + return await res.text() + } catch { + return undefined + } +} + +/** A failed answer as one line: the gateway's own code and words, not just the status. */ +function describeHttpFailure(status, text) { + const raw = safeJson(text) + const detail = raw + ? [firstOf(raw.error_code, String(raw.code ?? "")), firstOf(raw.error_msg, raw.message, raw.msg)].filter(Boolean).join(" ") + : String(text ?? "").trim().slice(0, 200) + return detail ? `HTTP ${status}: ${detail}` : `HTTP ${status}` +} + +/** + * A signed snap-access call the way the IDE's ActivityWelfarePane makes it: + * `{ code, message, data }` back, `code !== 0` being a refusal. + * Gives `{ ok: true, data }` or `{ ok: false, message }`, never throws. + */ +async function snapRequest(method, url, cred, fetcher, payload) { + const body = payload === undefined ? new Uint8Array() : utf8(JSON.stringify(payload)) + let res + let text + try { + const signed = await signRequestHuawei( + cred.access_key_id, cred.secret_access_key, cred.security_token, + method, url, body, + ) + const headers = new Headers() + signed.forEach((value, key) => { + if (key !== "host") headers.set(key, value) + }) + for (const [k, v] of Object.entries(SNAP_EXTRA_HEADERS)) headers.set(k, v) + res = await fetcher(url, { + method, + headers, + ...(payload === undefined ? {} : { body }), + signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS), + }) + text = await res.text() + } catch (e) { + return { ok: false, message: e?.message ?? String(e) } + } + if (!res.ok) return { ok: false, message: describeHttpFailure(res.status, text) } + const raw = safeJson(text) + if (!raw || Array.isArray(raw)) return { ok: false, message: "the answer could not be read" } + if (raw.code !== undefined && Number(raw.code) !== 0) { + return { ok: false, message: firstOf(raw.message, raw.msg, `code ${raw.code}`) } + } + return { ok: true, data: "data" in raw ? raw.data : raw } +} + +// ---- daily check-in ---------------------------------------------------------- + +/** The account's 「每日领取」 campaign from the activity list, or a reason it can't be read. */ +async function dailyCampaign(cred, fetcher) { + const listed = await snapRequest("GET", OPS_DELIVERY_URL, cred, fetcher) + if (!listed.ok) return { error: `活动列表读取失败:${listed.message}` } + const items = asRecord(listed.data).items + if (!Array.isArray(items)) return { error: "活动列表缺少 items" } + return { item: items.find((it) => asRecord(it).type === DAILY_CHECKIN_TYPE) } +} + +const isClaimedToday = (item) => !item?.claimable && CLAIMED_STATUSES.includes(item?.status) + +// ---- credit batches and when they lapse ------------------------------------ + +const PACKAGE_TYPE_METRICS = { + basic: "usageBasicPackageCredit", + ondemand: "usageOnDemandPackageCredit", + bonus: "usageBonusPackageCredit", +} + +/** + * Every credit batch the account holds, as `{ metric, amount, left, expiresAt }` + * (`metric` the statistics bucket it counts in, `expiresAt` ms): the packages + * from `package/credit/page`, and each campaign's grants from `ops/credit`. + * Undefined when none of it could be read. + */ +async function fetchCreditBatches(cred, fetcher) { + const batches = [] + let reached = false + for (const query of PACKAGE_CREDIT_QUERIES) { + const r = await snapRequest("POST", PACKAGE_CREDIT_PAGE_URL, cred, fetcher, query) + const list = asRecord(r.data).list + if (!r.ok || !Array.isArray(list)) continue + reached = true + for (const p of list) { + const metric = PACKAGE_TYPE_METRICS[asRecord(p).packageType] + if (!metric) continue + const amount = num(p.creditAmount) + batches.push({ metric, amount, left: Math.max(0, amount - num(p.creditUsed)), expiresAt: vendorDate(p.expiredTime) }) + } + } + const overview = await snapRequest("GET", OPS_CREDIT_OVERVIEW_URL, cred, fetcher) + const campaigns = asRecord(overview.data).items + if (overview.ok && Array.isArray(campaigns)) { + reached = true + for (const c of campaigns) { + const left = num(c?.totalClaimed) - num(c?.totalConsumed) - num(c?.totalExpired) + if (left <= 0 || c.campaignId === undefined || c.campaignId === null) continue + const page = await snapRequest("GET", OPS_CREDIT_CAMPAIGN_URL(c.campaignId), cred, fetcher) + for (const b of Array.isArray(asRecord(page.data).benefits) ? page.data.benefits : []) { + const amount = num(b?.claimedAmount) + batches.push({ + metric: PACKAGE_TYPE_METRICS.bonus, + amount, + left: Math.max(0, amount - num(b.consumedAmount) - num(b.expiredAmount)), + expiresAt: vendorDate(b.expireAt), + }) + } + } + } + return reached ? batches : undefined +} + +/** + * When the soonest still-good batch lapses, and what lapses that Beijing day + * (a sign-up grant and that day's check-in go a minute apart). Undefined when + * nothing is left to lapse. + */ +function soonestLapse(batches, now = Date.now()) { + const live = (batches ?? []).filter((b) => b.left > 0 && b.expiresAt > now) + if (live.length === 0) return undefined + const at = Math.min(...live.map((b) => b.expiresAt)) + const day = beijingDay(at) + return { at, credit: live.filter((b) => beijingDay(b.expiresAt) === day).reduce((n, b) => n + b.left, 0) } +} + +/** The plugin's own check-in ledger as batches, for when the vendor's can't be read. */ +const grantBatches = (grants) => + (grants ?? []).map((g) => ({ metric: PACKAGE_TYPE_METRICS.bonus, amount: num(g.credit), left: num(g.credit), expiresAt: vendorDate(g.expiresAt) })) + +// ---- the check-in ledger ----------------------------------------------------- +// +// CodeArts tells how many credits a bucket holds, never when each given batch +// lapses; check-in credits are good for 30 days from their day. The plugin keeps +// the claims it made, per account, so the usage card can say when the soonest +// of them runs out. Best effort: a ledger that can't be read or written only +// leaves that line out. + +const LEDGER_KEEP_DAYS = 40 + +const defaultLedgerPath = () => + process.env.MAGPIE_CODEARTS_LEDGER || path.join(os.homedir(), ".config", "magpie", "codearts-checkins.json") + +function readLedger(file) { + try { + const raw = safeJson(fs.readFileSync(file, "utf8")) + return raw && !Array.isArray(raw) ? raw : {} + } catch { + return {} + } +} + +/** The check-in credits the plugin claimed for `account`. */ +function readGrants(file, account) { + const list = readLedger(file)[account] + return Array.isArray(list) ? list : [] +} + +/** Keep one claim (one a Beijing day), dropping what lapsed long ago. */ +function recordGrant(file, account, grant) { + try { + const all = readLedger(file) + const keep = Date.now() - LEDGER_KEEP_DAYS * 86_400_000 + const day = beijingDay(vendorDate(grant.at)) + const list = (Array.isArray(all[account]) ? all[account] : []) + .filter((g) => (vendorDate(g.expiresAt) ?? 0) > keep && beijingDay(vendorDate(g.at) ?? 0) !== day) + all[account] = [...list, grant] + fs.mkdirSync(path.dirname(file), { recursive: true }) + const tmp = `${file}.${process.pid}.tmp` + fs.writeFileSync(tmp, JSON.stringify(all, null, 2)) + fs.renameSync(tmp, file) + } catch { + /* best effort */ + } +} + +/** When a claimed benefit lapses: the vendor's date when the claim says one, else 30 days on. */ +function grantExpiry(benefit, at) { + for (const k of ["expire_time", "expireTime", "expired_time", "expiredTime", "expire_at", "expireAt", "valid_end_time", "end_time", "endTime"]) { + const v = vendorDate(benefit?.[k]) + if (v) return v + } + return at + CHECKIN_CREDIT_DAYS * 86_400_000 +} + +/** + * Press the daily check-in, exactly as the IDE's 「限时福利 → 每日领取」 does: + * list the activities, claim the `USER_LOGIN` one with `{campaignId, channel}`, + * and confirm it when the claim answers an id (`benefit.id !== null`), or the + * credits stay pending. Answers magpie's check-in outcome; never throws. + */ +async function dailyCheckin(cred, fetcher) { + const first = await dailyCampaign(cred, fetcher) + if (first.error) return { outcome: "failed", message: first.error } + const item = first.item + if (!item) return { outcome: "inactive", message: "当前没有每日领取活动" } + const credit = num(item.benefitAmount) + if (isClaimedToday(item)) return { outcome: "done", message: "今天已领取" } + if (!item.claimable) return { outcome: "ineligible", message: `当前不可领取(status=${item.status ?? "null"})` } + if (item.campaignId === undefined || item.campaignId === null || item.campaignId === "") { + return { outcome: "failed", message: "活动缺少 campaignId" } + } + + const claimed = await snapRequest("POST", OPS_CLAIM_URL, cred, fetcher, { campaignId: item.campaignId, channel: OPS_CHANNEL }) + if (!claimed.ok) { + // Claimed elsewhere a moment ago (the IDE, another magpie): look again. + const again = await dailyCampaign(cred, fetcher) + if (isClaimedToday(again.item)) return { outcome: "done", message: "今天已领取" } + return { outcome: "failed", message: `领取失败:${claimed.message}` } + } + const benefit = asRecord(claimed.data) + if (claimed.data && benefit.id !== null) { + const confirmed = await snapRequest("POST", OPS_CONFIRM_URL, cred, fetcher, { campaignId: item.campaignId }) + if (!confirmed.ok) return { outcome: "failed", message: `领取确认失败:${confirmed.message}` } + } + const got = num(benefit.benefitAmount) || credit + const at = Date.now() + const grant = { at: new Date(at).toISOString(), credit: got, expiresAt: new Date(grantExpiry(benefit, at)).toISOString() } + return { outcome: "claimed", ...(got > 0 ? { credit: got } : {}), message: got > 0 ? `+${got} 积分` : "已领取", grant } +} + +// ---- model list & account info --------------------------------------------- + +/** + * One gateway/builtin entry as a model row. The id is the one published, never + * the date-stripped one (a dated id and its bare form are two models with + * opposite billing), so dedupe is by exact id too. + */ +function parseModelInfo(m, seen) { + const id = m?.model_id + if (typeof id !== "string" || !id) return undefined + const base = normalizeModelId(id) + // Hide vision models: small context, no tool calls — not agent main models. + // Case-insensitive: the gateway lists some lowercase (`kimi-k2.6-vl`). + if (/-vl(-|$)/i.test(base)) return undefined + if (seen.has(id)) return undefined + seen.add(id) + const rawName = m.model_name + const name = typeof rawName === "string" && rawName ? normalizeModelId(rawName) : prettify(base) + const info = { id, name, context: num(m.context_window) || CONTEXT_WINDOWS[base] } + const output = num(m.max_tokens) + if (output > 0) info.output = Math.min(output, MAX_OUTPUT_TOKENS) + return info +} + +function extractArray(text, path) { + const root = safeJson(text) + if (!root) return undefined + let value = root + for (const key of path) { + if (typeof value !== "object" || value === null) return undefined + value = value[key] + } + return Array.isArray(value) ? value : undefined +} + +/** + * Claim today's free benefit (`POST /api/v1/benefit/claim`, an empty JSON + * body), as the CodeArts agent does before it offers the free models. + * Gives `{ ok, code, message }`; `network: true` when the vendor wasn't reached. + */ +async function claimBenefit(cred, fetcher) { + const body = utf8("{}") + try { + const signed = await signRequestHuawei( + cred.access_key_id, cred.secret_access_key, cred.security_token, + "POST", BENEFIT_CLAIM_URL, body, + ) + const headers = new Headers() + signed.forEach((value, key) => { + if (key !== "host") headers.set(key, value) + }) + headers.set("x-snap-traceid", randomHex(16)) + const res = await fetcher(BENEFIT_CLAIM_URL, { method: "POST", headers, body, signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS) }) + const data = safeJson(await res.text()) + const code = firstOf(String(data?.error_code ?? "")) || `HTTP ${res.status}` + return { ok: code === BENEFIT_OK, code, message: firstOf(data?.error_msg, data?.message) } + } catch (e) { + return { ok: false, network: true, code: "", message: e?.message ?? String(e) } + } +} + +// A refused claim is asked again this long after, not on every listing. +const CLAIM_RETRY_MS = 60 * 60 * 1000 + +/** + * Is today's free benefit the account's? Claimed once a Beijing day (one claim + * at a time); a refusal is asked again an hour later, and a vendor that can't + * be reached leaves the last answer standing. + */ +function ensureBenefitClaimed(cred, fetcher, state) { + const day = beijingDay() + const was = state.claim + if (was?.day === day && (was.ok || Date.now() - was.at < CLAIM_RETRY_MS)) return Promise.resolve(was.ok) + state.claiming ??= claimBenefit(cred, fetcher) + .then((r) => { + if (r.network) return was?.ok ?? false + state.claim = { day, ok: r.ok, at: Date.now(), code: r.code, message: r.message } + return r.ok + }) + .finally(() => { state.claiming = null }) + return state.claiming +} + +/** + * One model of the CodeAgent's detail: its id is `model_parameters.model_id` + * (what a request names), with the credit rate and the parameters the agent + * itself reads — `thinking_type` set means a reasoning model. + */ +function parseAgentModel(m) { + const p = asRecord(m?.model_parameters) + const id = firstOf(p.model_id, m?.model_id) + if (!id) return undefined + const output = num(p.max_tokens) + return { + id, + name: firstOf(m.display_name, m.model_name), + rate: creditRateOf(m.credit ?? p.credit), + ...(p.thinking_type != null ? { reasoning: true } : {}), + context: num(p.context_window), + ...(output > 0 ? { output: Math.min(output, MAX_OUTPUT_TOKENS) } : {}), + // Configured by a user or a tenant, not one of CodeArts' own. + own: m.model_type === "third" || m.model_type === "custom" || m.is_custom_model === true, + hidden: m.display_enabled === false || p.display_enabled === false, + } +} + +/** + * The agents to ask for a model list, best first: the account's main agent + * (`original_id` "build", else CodeAgent), the rest of its agents, then the + * IDE's own id for the main agent. + */ +async function agentCandidates(cred, fetcher) { + const root = safeJson(await signedGet(AGENT_LIST_URL, cred, fetcher, AGENT_CENTER_HEADERS) ?? "") + const agents = (Array.isArray(root?.agents) ? root.agents : Array.isArray(root?.data?.agents) ? root.data.agents : []) + .filter((a) => typeof a?.agent_id === "string" && a.agent_id) + const rank = (a) => { + const i = MAIN_AGENT_ORIGINAL_IDS.indexOf(firstOf(a.original_id) || a.agent_id) + return i < 0 ? MAIN_AGENT_ORIGINAL_IDS.length : i + } + const ids = [...agents].sort((a, b) => rank(a) - rank(b)).map((a) => a.agent_id) + return [...new Set([...ids, MAIN_AGENT_FALLBACK_ID])] +} + +/** + * The main agent's models (`agents/detail` → `gpts.models`), carrying each + * model's credit rate. The agent that answered with a list is kept on `state`. + */ +async function fetchAgentModels(cred, fetcher, state) { + const read = async (id) => { + const root = safeJson(await signedGet(AGENT_DETAIL_URL(id), cred, fetcher, AGENT_CENTER_HEADERS) ?? "") + const models = root?.gpts?.models ?? root?.data?.gpts?.models + return Array.isArray(models) && models.length ? models.map(parseAgentModel).filter(Boolean) : undefined + } + if (state.agentId) { + const known = await read(state.agentId) + if (known) return known + state.agentId = "" + } + for (const id of (await agentCandidates(cred, fetcher)).slice(0, AGENT_DETAIL_TRIES)) { + const models = await read(id) + if (models) { + state.agentId = id + return models + } + } + return undefined +} + +/** + * Fetch the account's live model list and merge it: + * - the free models gateway/config lists, but only once today's benefit is + * claimed for the account (else they are left out: they answer `benefit not + * found`, and the plain builtin model of the same id stays); + * - the builtin models; + * - the main agent's own list, which gives every model its credit rate and + * adds the ones the builtin list leaves out. + * `state` is the account's own: its claim, agent id, free models + * (`state.benefit`) and builtin ones (`state.regular`) are kept there and + * nowhere else. Without one the free list is taken as it is published. + */ +async function fetchRemoteModels(cred, fetcher, state) { + const models = [] + const seen = new Set() + const benefitIds = [] + + const gatewayText = await signedGet(OPENGW_GATEWAY_CONFIG_URL, cred, fetcher) + const gateway = gatewayText === undefined ? undefined : extractArray(gatewayText, ["result", "models"]) + const claimed = gateway?.length ? (state ? await ensureBenefitClaimed(cred, fetcher, state) : true) : false + for (const item of claimed ? gateway : []) { + if (typeof item !== "object" || item === null) continue + const mi = parseModelInfo(item, seen) + if (!mi) continue + mi.benefit = true + benefitIds.push(mi.id) + models.push(mi) + } + + const snapText = await signedGet(SNAP_MODEL_BUILTIN_URL, cred, fetcher, { + "Content-Type": "application/json", + ...SNAP_EXTRA_HEADERS, + }) + const builtin = snapText === undefined ? undefined : extractArray(snapText, ["builtinModels"]) + const regularIds = [] + for (const item of builtin ?? []) { + if (typeof item !== "object" || item === null) continue + if (typeof item.model_id === "string") regularIds.push(item.model_id) + const mi = parseModelInfo(item, seen) + if (mi) models.push(mi) + } + + // Rates and parameters from the agent's own list; a model only it lists is + // one more the account can call. + const agent = await fetchAgentModels(cred, fetcher, state ?? {}).catch(() => undefined) + for (const a of agent ?? []) { + const mi = models.find((m) => m.id === a.id) + if (mi) { + if (a.rate > 0 && !mi.benefit) mi.rate = a.rate + if (a.reasoning) mi.reasoning = true + // The limits the agent itself runs the model with. + if (a.context > 0) mi.context = a.context + if (a.output) mi.output = a.output + } else if (!a.own && !a.hidden && !/-vl(-|$)/i.test(normalizeModelId(a.id))) { + models.push({ + id: a.id, + name: a.name ? normalizeModelId(a.name) : prettify(normalizeModelId(a.id)), + context: a.context || CONTEXT_WINDOWS[normalizeModelId(a.id)], + ...(a.output ? { output: a.output } : {}), + ...(a.rate > 0 ? { rate: a.rate } : {}), + ...(a.reasoning ? { reasoning: true } : {}), + }) + regularIds.push(a.id) + } + } + + // The account's own lists: an answered list is the truth, an empty one + // included; a failed read keeps what was known. + if (state) { + if (gateway) state.benefit = new Set(benefitIds) + if (builtin) state.regular = new Set(regularIds) + } + return models +} + +/** Chinese labels for the credit metric buckets CodeArts reports. */ +const CREDIT_METRIC_LABELS = { + usageTotalPackageCredit: "总积分", + usageBasicPackageCredit: "基础积分包", + usageOnDemandPackageCredit: "按需积分包", + usageBonusPackageCredit: "赠送积分包", +} +const TOTAL_CREDIT_METRIC = "usageTotalPackageCredit" + +/** Compact credit counts for the display string (12345 → "1.2万"). */ +function formatCredit(n) { + const v = Math.max(0, Number.isFinite(n) ? n : 0) + if (v >= 1e8) return `${(v / 1e8).toFixed(1)}亿` + if (v >= 1e4) return `${(v / 1e4).toFixed(1)}万` + return String(Math.round(v)) +} + +const BENEFIT_WINDOW_LABEL = "免费额度" + +/** + * A credit bucket as a usage window. magpie takes its routing cap from every + * window it is given, so only the package total may pause the account: the + * buckets are that same money broken down, and a spent 500-credit basic bucket + * used to stop an account with 30 000 credits left elsewhere. + */ +function creditWindow(name, limit, remain, { resetsAt, expiring = 0 } = {}) { + const used = Math.max(0, limit - remain) + return { + name, + used: clamp(limit > 0 ? (used / limit) * 100 : 0), + display: `${formatCredit(used)} / ${formatCredit(limit)}${expiring > 0 ? ` · ${formatCredit(expiring)} 即将过期` : ""}`, + amount: used, + limit, + unit: "credits", + ...(resetsAt ? { resetsAt } : {}), + ...(name !== CREDIT_METRIC_LABELS[TOTAL_CREDIT_METRIC] ? { aside: true } : {}), + } +} + +// The buckets that are the month's allowance and come back at the period's +// end (the IDE's 「等待至 {resetDate} 额度重置」); bought and given credits run +// out on their own dates instead. +const MONTHLY_CREDIT_METRICS = ["usageTotalPackageCredit", "usageBasicPackageCredit"] + +/** + * The free daily token pool as a window, scoped to the models that draw on it. + * `aside`: an empty free pool leaves the paid models usable. + */ +function benefitWindow(raw, ids = BENEFIT_MODEL_FALLBACK) { + const rec = asRecord(asRecord(raw).result ?? asRecord(raw).data ?? raw) + const limit = num(rec.daily_token_limit) + if (limit <= 0) return undefined + const used = Math.max(0, Math.min(num(rec.daily_tokens_used), limit)) + return { + name: BENEFIT_WINDOW_LABEL, + used: clamp((used / limit) * 100), + display: `${formatCredit(used)} / ${formatCredit(limit)}`, + amount: used, + limit, + unit: "tokens", + // A daily pool: back at the next Beijing midnight. + resetsAt: new Date(nextBeijingMidnight()).toISOString(), + span: 86_400, + aside: true, + ...(ids.length ? { models: [...ids].sort() } : {}), + } +} + +/** + * Map the account's `statistics/plugin` (+ free pool) answer to magpie's usage + * shape. `batches` are its credit batches with their own expiry (see + * fetchCreditBatches): the plan's batch gives the month's reset to the second, + * and the soonest of the rest to lapse is each bucket's (and the total's) + * `runsOutAt`/`runsOut`. Without them, `grants` (the check-ins the plugin + * claimed, 30 days each) stand in, and the reset is `end_date`. + */ +function usageFromStatistics(raw, benefitRaw, { batches, grants, benefitIds } = {}) { + let data = raw + if (raw && typeof raw.code === "number") { + if (raw.code !== 0) return { error: firstOf(raw.message, raw.msg, `CodeArts code ${raw.code}`), windows: [] } + data = asRecord(raw.data) + } + if (!data || typeof data !== "object") return { error: "CodeArts could not be parsed", windows: [] } + const pkg = asRecord(data.package) + const plan = firstOf(pkg.package_name_cn, pkg.package_name_en, pkg.spec_code) + const metrics = Array.isArray(data.metrics) ? data.metrics : [] + const now = Date.now() + const known = batches ?? grantBatches(grants) + // The plan's own batch ends when the month's allowance comes back. + const planEnds = known.filter((b) => b.metric === PACKAGE_TYPE_METRICS.basic && b.expiresAt > now).map((b) => b.expiresAt) + const reset = planEnds.length ? Math.min(...planEnds) : vendorDate(data.end_date) + const resetsAt = reset ? new Date(reset).toISOString() : undefined + + const windows = [] + const metricOf = new Map() + for (const item of metrics) { + const rec = asRecord(item) + const name = CREDIT_METRIC_LABELS[rec.name] + if (!name) continue + const limit = num(rec.package_credit_amount) + const remain = num(rec.package_credit_remain) + if (limit <= 0 && remain <= 0) continue // empty bucket, nothing to show + const w = creditWindow(name, limit, remain, { + resetsAt: MONTHLY_CREDIT_METRICS.includes(rec.name) ? resetsAt : undefined, + expiring: num(rec.package_credit_expiring_amount), + }) + metricOf.set(w, rec.name) + windows.push(w) + } + + // What lapses soonest, apart from the month's reset: a bucket's own + // batches; for the total, every batch but the plan's. + for (const w of windows) { + const metric = metricOf.get(w) + if (metric === PACKAGE_TYPE_METRICS.basic) continue + const own = known.filter((b) => (metric === TOTAL_CREDIT_METRIC ? b.metric !== PACKAGE_TYPE_METRICS.basic : b.metric === metric)) + const lapse = soonestLapse(own, now) + const left = Math.max(0, w.limit - w.amount) + if (lapse && left > 0) { + w.runsOutAt = new Date(lapse.at).toISOString() + w.runsOut = Math.min(lapse.credit, left) + } + } + + // Keep the package total on top, then the per-bucket breakdown, then the + // separate free pool. + const totalLabel = CREDIT_METRIC_LABELS[TOTAL_CREDIT_METRIC] + windows.sort((a, b) => (a.name === totalLabel ? -1 : b.name === totalLabel ? 1 : 0)) + + const benefit = benefitRaw ? benefitWindow(benefitRaw, benefitIds) : undefined + if (benefit) windows.push(benefit) + + if (windows.length > 0) return { plan: plan || undefined, signIn: "kept", windows } + return { plan: plan || undefined, windows, error: "该账号无积分额度" } +} + +// ---- the plugin ------------------------------------------------------------- + +export const CodeArtsAuthPlugin = async ({ client } = {}, options = {}) => { + const fetcher = typeof options?.fetch === "function" ? options.fetch : fetch + // Tunables (magpie: `magpie plugin options '{…}'`). `maxInflight` can + // only lower the gate: above 3 the account would pass the vendor's cap. + const maxInflight = Number.isInteger(options?.maxInflight) && options.maxInflight > 0 + ? Math.min(options.maxInflight, ACCOUNT_MAX_INFLIGHT) + : ACCOUNT_MAX_INFLIGHT + const retryBudgetMs = Number.isFinite(options?.retryBudgetMs) ? Math.max(0, options.retryBudgetMs) : SESSION_RETRY_BUDGET_MS + const retryDelays = Array.isArray(options?.retryDelays) && options.retryDelays.length ? options.retryDelays : SESSION_RETRY_DELAYS_MS + const queueBudgetMs = Number.isFinite(options?.queueBudgetMs) ? Math.max(0, options.queueBudgetMs) : QUEUE_BUDGET_MS + const thinking = options?.thinking !== false + const ledgerPath = typeof options?.ledgerPath === "string" && options.ledgerPath ? options.ledgerPath : defaultLedgerPath() + // Test hooks: the clock and the sleep the retry budget runs on. + const now = typeof options?.now === "function" ? options.now : Date.now + const sleep = typeof options?.sleep === "function" ? options.sleep : delay + + // Per account, shared by every loader this process runs for it and by + // nothing else: the gate; its free models today (null until its + // gateway/config was read; the fallback stands until then), its builtin + // ones, and the ones the gateway said it has no benefit for; today's + // benefit claim; its main agent's id; its credit batches. + const accounts = new Map() + const accountState = (key) => { + if (!accounts.has(key)) { + accounts.set(key, { + gate: createConcurrencyGate(maxInflight), benefit: null, regular: null, noBenefit: new Set(), + claim: null, claiming: null, agentId: "", batches: undefined, batchesAt: 0, + }) + } + return accounts.get(key) + } + const stateOf = async (cred) => accountState((await accountSessionIds(cred)).sessionId) + // The ledger's key: the signer, which outlives a sign-in; else the session. + const ledgerKey = async (cred) => accountIdentityOf(cred).id || (await accountSessionIds(cred)).sessionId + + const configModel = (m) => ({ + name: m.name ?? m.id, + // Declared so a caller never sends its own, larger default. + limit: { context: m.context ?? 0, output: MAX_OUTPUT_TOKENS }, + tool_call: true, + }) + + const modelOf = (provider, live, state) => { + const base = provider.models?.[live.id] ?? {} + const capabilities = { + temperature: true, toolcall: true, attachment: false, input: { text: true }, output: { text: true }, + ...(base.capabilities ?? {}), + ...(live.reasoning ? { reasoning: true } : {}), + } + // magpie's own fields: `free` (from the free daily pool, the same answer + // the signed `maas_type: benefit` header follows, so a model never shows + // as free while billed as paid) and `rate` (the credits a request costs, + // as a multiple: the IDE's 「消耗系数」). + const free = live.benefit === true && !state?.noBenefit.has(live.id) + return { + ...base, + id: live.id, + name: live.name || base.name || live.id, + limit: { context: live.context ?? base.limit?.context ?? 0, output: live.output ?? MAX_OUTPUT_TOKENS }, + capabilities, + free, + ...(!free && live.rate > 0 ? { rate: live.rate } : {}), + } + } + + return { + // The provider and the models it has before anyone is signed in. + config: async (config) => { + config.provider ??= {} + config.provider[PROVIDER] ??= {} + const p = config.provider[PROVIDER] + p.name ??= "CodeArts" + p.npm ??= NPM + p.api ??= CHAT_API_BASE + p.models = { ...Object.fromEntries(CATALOG.map((m) => [m.id, configModel(m)])), ...(p.models ?? {}) } + }, + + // The account's own list when signed in and CodeArts answers. + provider: { + id: PROVIDER, + async models(provider, { auth } = {}) { + const cred = credentialOf(auth) + if (!cred?.access_key_id) return provider.models + try { + const state = await stateOf(cred) + const list = await fetchRemoteModels(cred, fetcher, state) + if (!list.length) return provider.models + return Object.fromEntries(list.map((m) => [m.id, modelOf(provider, m, state)])) + } catch { + return provider.models + } + }, + }, + + auth: { + provider: PROVIDER, + refreshLead: REFRESH_LEAD_MS, + // The gateway's own cap: more in flight only queues in the plugin. + maxConcurrency: maxInflight, + + // magpie's own hook: renew the temporary credentials before they expire. + async refresh(auth) { + const cred = credentialOf(auth) + if (!cred) return undefined + const next = await refreshCredential(cred, fetcher) + const accountId = auth.accountId ? "" : accountIdentityOf(next).id + return { + access: JSON.stringify(next), + refresh: next.refresh_token, + expires: expiresFromCredential(next), + ...(accountId ? { accountId } : {}), + } + }, + + // Every request the account makes is signed here. + async loader(getAuth) { + let account = await getAuth() + let cred = credentialOf(account) + if (!cred?.access_key_id || !cred?.secret_access_key) return {} + + // magpie renews ahead of expiry by itself; this covers hosts that + // ignore `auth.refresh` (OpenCode) and a credential that went stale + // anyway (a 401 / APIG.0602). One renewal at a time; null when it fails. + let refreshing = null + let signInDead = false + const renewCredential = (stale) => { + if (signInDead) return Promise.resolve(null) + refreshing ??= (async () => { + // Another renewal may have landed already (magpie's own, or another + // process): take that over rather than spend the refresh token twice. + const latest = await getAuth().catch(() => null) + const stored = credentialOf(latest) + if (stored && stored.access_key_id !== stale.access_key_id && !nearExpiry(stored)) { + cred = stored + account = latest + return stored + } + const base = stored ?? cred + if (!base.refresh_token) return null + const next = await refreshCredential(base, fetcher) + cred = next + account = await persistCredential(client, latest ?? account, next) + return next + })() + .catch((e) => { + if (isPermanentRefreshFailure(e)) signInDead = true + return null + }) + .finally(() => { refreshing = null }) + return refreshing + } + const current = async () => { + if (signInDead || !nearExpiry(cred)) return cred + return (await renewCredential(cred)) ?? cred + } + + // One account = one upstream session and one in-flight budget. + const ids = await accountSessionIds(cred) + const state = accountState(ids.sessionId) + const context = { + ...ids, + gate: state.gate, + // The account's own model lists, read at each request (the models + // hook keeps them current). + state, + now, + sleep, + fetcher, + retryBudgetMs, + retryDelays, + queueBudgetMs, + thinking, + renewCredential, + signInDead: () => signInDead, + } + return { + baseURL: CHAT_API_BASE, + async fetch(input, init = {}) { + const c = await current() + return signedFetch(c, input, init, context) + }, + } + }, + + // magpie's own hook: how much of the plan is left. + async usage(getAuth) { + const auth = await getAuth() + const cred = credentialOf(auth) + if (!cred?.access_key_id) return { error: "not signed in", windows: [] } + try { + const text = await signedGet(SNAP_STATISTICS_URL, cred, fetcher, SNAP_EXTRA_HEADERS) + if (text === undefined) return { error: "CodeArts answered an error", windows: [] } + const state = await stateOf(cred) + // The free pool only once today's benefit is the account's; best + // effort either way: a credit account without one is normal. + const free = state.benefit === null || state.benefit.size > 0 + const benefitText = free ? await signedGet(BENEFIT_BALANCE_URL, cred, fetcher) : undefined + // Each batch's own expiry, read again every ten minutes (and after a + // check-in); a failed read keeps the last one, else the ledger stands in. + if (!state.batchesAt || Date.now() - state.batchesAt > CREDIT_BATCHES_TTL_MS) { + const read = await fetchCreditBatches(cred, fetcher).catch(() => undefined) + if (read) state.batches = read + state.batchesAt = Date.now() + } + const usage = usageFromStatistics(safeJson(text), benefitText === undefined ? undefined : safeJson(benefitText), { + batches: state.batches, + grants: readGrants(ledgerPath, await ledgerKey(cred)), + benefitIds: state.benefit ? [...state.benefit] : BENEFIT_MODEL_FALLBACK, + }) + const user = accountIdentityOf(cred).name + return user ? { ...usage, user } : usage + } catch (e) { + return { error: e?.message ?? String(e), windows: [] } + } + }, + + // magpie's own hook: the daily 「每日领取」 check-in (OpenCode ignores it). + // magpie renews the sign-in before asking, and asks once a Beijing day. + async checkin(getAuth) { + const cred = credentialOf(await getAuth()) + if (!cred?.access_key_id) return { outcome: "failed", message: "not signed in" } + const { grant, ...r } = await dailyCheckin(cred, fetcher) + if (r.outcome === "claimed") { + // The new batch shows at the next usage read; the ledger keeps it in + // case the vendor's batch list can't be read. + ;(await stateOf(cred)).batchesAt = 0 + if (grant) recordGrant(ledgerPath, await ledgerKey(cred), grant) + } + return r + }, + + methods: [ + { + type: "oauth", + label: "Sign in with Huawei Cloud", + async authorize() { + const flow = await startOAuthFlow(fetcher) + return { + url: flow.loginUrl, + instructions: "Sign in to Huawei Cloud in the browser; this window closes itself when done.", + method: "auto", + async callback() { + try { + const outcome = await flow.result + const cred = safeJson(outcome.access) + if (!cred?.access_key_id) return { type: "failed", error: "CodeArts did not return a credential" } + // Who signed in, so signing in again replaces the account + // instead of adding a `codearts#xxxxxx` beside it. + const accountId = accountIdentityOf(cred).id + return { + type: "success", + access: outcome.access, + refresh: cred.refresh_token, + expires: outcome.expires, + ...(accountId ? { accountId } : {}), + } + } catch (e) { + return { type: "failed", error: e?.message ?? String(e) } + } finally { + await flow.close() + } + }, + } + }, + }, + ], + }, + } +} + +/** Is the credential this close to its expiry (unknown expiry: no)? */ +function nearExpiry(cred) { + const at = Date.parse(cred?.expires_at || "") + return Number.isFinite(at) && at - Date.now() <= INBAND_REFRESH_LEAD_MS +} + +/** + * Best-effort: store a freshly refreshed credential back on the account, and + * give the record as stored. The host keeps what it is given whole (nothing is + * merged), so the account's other fields — its accountId — go along. + */ +async function persistCredential(client, account, cred) { + const accountId = firstOf(account?.accountId, accountIdentityOf(cred).id) + const body = { + ...asRecord(account), + type: "oauth", + access: JSON.stringify(cred), + refresh: cred.refresh_token, + expires: expiresFromCredential(cred), + ...(accountId ? { accountId } : {}), + } + try { + await client?.auth?.set?.({ path: { id: PROVIDER }, body }) + } catch { + /* best effort */ + } + return body +} + +// for tests (never a plugin: magpie only calls exported functions) +export const _internal = { + PROVIDER, NPM, CATALOG, CONTEXT_WINDOWS, BENEFIT_MODEL_FALLBACK, MAX_OUTPUT_TOKENS, + CHAT_API_BASE, SNAP_MODEL_BUILTIN_URL, SNAP_STATISTICS_URL, OPENGW_GATEWAY_CONFIG_URL, BENEFIT_BALANCE_URL, + OPS_DELIVERY_URL, OPS_CLAIM_URL, OPS_CONFIRM_URL, SESSION_LIMIT_ERROR, ACCOUNT_MAX_INFLIGHT, + PORTAL_AUTHORIZE_BASE, STS_TOKEN_ENDPOINT, CLIENT_ID, REDIRECT_PATH, + firstOf, asRecord, safeJson, num, clamp, prettify, normalizeModelId, upstreamModelId, formatCredit, + b64url, utf8, sha256Hex, hmacSha256Hex, + generatePkcePair, generateDpopKeyPair, keyPairFromStoredJwk, signDpopJws, + buildCanonicalRequest, signRequestHuawei, + credentialFromTokenResponse, credentialOf, expiresFromCredential, accountIdentityOf, accountSessionIds, + requestToken, exchangeAuthorizationCode, exchangeRefreshToken, refreshCredential, + isDeadRefreshToken, isPermanentRefreshFailure, nearExpiry, persistCredential, + buildOAuthLoginUrl, buildPortalLoginResultUrl, + startOAuthCallbackServer, listenOnCallbackPort, startOAuthFlow, isHuaweiUrl, hostOf, + BENEFIT_CLAIM_URL, AGENT_LIST_URL, AGENT_DETAIL_URL, CODE_AGENT_ID, + canonicalQuery, beijingDay, nextBeijingMidnight, vendorDate, creditRateOf, + claimBenefit, ensureBenefitClaimed, parseAgentModel, fetchAgentModels, + readGrants, recordGrant, grantExpiry, grantBatches, soonestLapse, fetchCreditBatches, + PACKAGE_CREDIT_PAGE_URL, OPS_CREDIT_OVERVIEW_URL, OPS_CREDIT_CAMPAIGN_URL, + toBytes, isBenefitModel, prepareChatBody, signedFetch, signedGet, + parseSseEvents, errorCodeOf, errorMessageOf, isStaleCredential, isRateLimitCode, embeddedErrorStatus, classifyHead, + peekAnswer, completionFromChunks, createConcurrencyGate, delay, retryDelayMs, + isRegularModel, queueInfoOf, waitInQueue, TRACE_QUEUE_URL, SESSION_HEADER, + snapRequest, dailyCheckin, + parseModelInfo, extractArray, fetchRemoteModels, creditWindow, benefitWindow, usageFromStatistics, +} diff --git a/packages/codearts/index.test.mjs b/packages/codearts/index.test.mjs new file mode 100644 index 0000000..3ed924e --- /dev/null +++ b/packages/codearts/index.test.mjs @@ -0,0 +1,1656 @@ +// Unit tests for the CodeArts OAuth plugin. Run with: bun test (node --test +// runs them too). +// +// These tests exercise the pieces magpie calls (_internal helpers) and the +// hooks the plugin returns, with the network stubbed out via `options.fetch`. + +import test from "node:test" +import assert from "node:assert/strict" +import fs from "node:fs" +import os from "node:os" +import path from "node:path" + +import { CodeArtsAuthPlugin, _internal as x } from "./index.mjs" + +// Never the real ledger in ~/.config/magpie: every plugin made here keeps its +// check-ins in a scratch file of its own. +const ledgerDir = fs.mkdtempSync(path.join(os.tmpdir(), "codearts-ledger-")) +process.env.MAGPIE_CODEARTS_LEDGER = path.join(ledgerDir, "default.json") +test.after(() => fs.rmSync(ledgerDir, { recursive: true, force: true })) + +const buf = (s) => new TextEncoder().encode(s) + +// ---- crypto primitives ----------------------------------------------------- + +test("sha256Hex matches the known SHA-256 of the empty string", async () => { + assert.equal( + await x.sha256Hex(new Uint8Array()), + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + ) +}) + +test("hmacSha256Hex matches RFC 4231 test case 2", async () => { + assert.equal( + await x.hmacSha256Hex(buf("Jefe"), buf("what do ya want for nothing?")), + "5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843", + ) +}) + +test("generatePkcePair derives the S256 challenge from the verifier", async () => { + const pkce = await x.generatePkcePair() + assert.match(pkce.codeVerifier, /^[A-Za-z0-9_-]{64}$/) + const expected = x.b64url(new Uint8Array(await crypto.subtle.digest("SHA-256", buf(pkce.codeVerifier)))) + assert.equal(pkce.codeChallenge, expected) +}) + +test("signDpopJws produces a verifiable ES256 dpop+jwt", async () => { + const keyPair = await x.generateDpopKeyPair() + const jws = await x.signDpopJws(keyPair, "POST", "https://sts.example.com/tokens") + const [h, p, s] = jws.split(".") + assert.equal(jws.split(".").length, 3) + + const header = JSON.parse(Buffer.from(h, "base64url").toString()) + assert.equal(header.alg, "ES256") + assert.equal(header.typ, "dpop+jwt") + assert.deepEqual(header.jwk, keyPair.publicKeyJwk) + + const payload = JSON.parse(Buffer.from(p, "base64url").toString()) + assert.equal(payload.htm, "POST") + assert.equal(payload.htu, "https://sts.example.com/tokens") + assert.equal(typeof payload.iat, "number") + assert.equal(typeof payload.jti, "string") + + const key = await crypto.subtle.importKey( + "jwk", keyPair.publicKeyJwk, { name: "ECDSA", namedCurve: "P-256" }, false, ["verify"], + ) + const ok = await crypto.subtle.verify( + { name: "ECDSA", hash: "SHA-256" }, key, Buffer.from(s, "base64url"), buf(`${h}.${p}`), + ) + assert.ok(ok, "the DPoP signature must verify against the advertised public key") +}) + +// ---- SDK-HMAC-SHA256 signing ----------------------------------------------- + +test("buildCanonicalRequest lays out the canonical request exactly", () => { + const headers = new Map([ + ["host", "example.com"], + ["x-sdk-content-sha256", "H"], + ["x-sdk-date", "D"], + ["x-security-token", "ST"], + ]) + const expected = [ + "GET", + "/path/", + "", + "host:example.com", + "x-sdk-content-sha256:H", + "x-sdk-date:D", + "x-security-token:ST", + "", + "host;x-sdk-content-sha256;x-sdk-date;x-security-token", + "H", + ].join("\n") + assert.equal(x.buildCanonicalRequest("GET", "/path/", "", headers, "H"), expected) +}) + +test("signRequestHuawei signs a GET with the expected header set", async () => { + const signed = await x.signRequestHuawei( + "AK", "SK", "ST", "GET", "https://example.com/path", new Uint8Array(), undefined, "20260101T000000Z", + ) + assert.equal(signed.get("x-sdk-date"), "20260101T000000Z") + assert.equal( + signed.get("x-sdk-content-sha256"), + "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", + ) + assert.equal(signed.get("x-security-token"), "ST") + // GET carries no content-type. + assert.equal(signed.has("content-type"), false) + assert.match( + signed.get("Authorization"), + /^SDK-HMAC-SHA256 Access=AK,SignedHeaders=host;x-sdk-content-sha256;x-sdk-date;x-security-token,Signature=[0-9a-f]{64}$/, + ) +}) + +test("signRequestHuawei includes content-type and maas_type in a signed POST", async () => { + const signed = await x.signRequestHuawei( + "AK", "SK", "ST", "POST", "https://example.com/api/v2/chat/completions", + buf('{"model":"glm-5.3-flash"}'), { maas_type: "benefit" }, "20260101T000000Z", + ) + const auth = signed.get("Authorization") + assert.match(auth, /SignedHeaders=content-type;host;maas_type;x-sdk-content-sha256;x-sdk-date;x-security-token,/) + assert.equal(signed.get("content-type"), "application/json") + assert.equal(signed.get("maas_type"), "benefit") +}) + +test("canonicalQuery sorts and RFC 3986-encodes the query the way the gateway checks it", () => { + assert.equal(x.canonicalQuery(new URL("https://h/p?offset=0&limit=100")), "limit=100&offset=0") + assert.equal(x.canonicalQuery(new URL("https://h/p?agent_id=a b&x=(1)*")), "agent_id=a%20b&x=%281%29%2A") + assert.equal(x.canonicalQuery(new URL("https://h/p")), "") +}) + +test("vendorDate reads CodeArts' dates; a zone-less one is Beijing time", () => { + assert.equal(x.vendorDate("2026-11-01"), Date.parse("2026-10-31T16:00:00Z")) + assert.equal(x.vendorDate("2026-11-01 08:30:00"), Date.parse("2026-11-01T00:30:00Z")) + assert.equal(x.vendorDate("2026-11-01T00:00:00Z"), Date.parse("2026-11-01T00:00:00Z")) + assert.equal(x.vendorDate(1793462400), 1793462400000) + assert.equal(x.vendorDate("1793462400000"), 1793462400000) + assert.equal(x.vendorDate("soon"), undefined) + assert.equal(x.vendorDate(""), undefined) +}) + +test("creditRateOf reads the 消耗系数 from one tier or a list of them", () => { + assert.equal(x.creditRateOf({ ratio: 2, ratio_display: "1.5" }), 1.5) + assert.equal(x.creditRateOf([{ ratio_display: 0.3 }, { ratio_display: 2 }]), 0.3) + assert.equal(x.creditRateOf(undefined), 0) + assert.equal(x.creditRateOf({ ratio_display: "0" }), 0) +}) + +test("signRequestHuawei is deterministic for a fixed date stamp", async () => { + const args = ["AK", "SK", "ST", "POST", "https://example.com/x", buf("body"), undefined, "20260101T000000Z"] + const a = await x.signRequestHuawei(...args) + const b = await x.signRequestHuawei(...args) + assert.equal(a.get("Authorization"), b.get("Authorization")) +}) + +test("signRequestHuawei matches an independent SDK-HMAC-SHA256 implementation", async () => { + // A known answer, from an independent (Python) SDK-HMAC-SHA256: an unsorted + // query, a signed extra header, a URI that needs its trailing slash. Signing + // the wrong hash, dropping the slash or the query order all change it. + const signed = await x.signRequestHuawei( + "AK", "SK", "ST", "POST", "https://example.com/api/v2/chat/completions?b=2&a=1", + buf('{"m":1}'), { maas_type: "benefit" }, "20260101T000000Z", + ) + assert.equal( + signed.get("Authorization"), + "SDK-HMAC-SHA256 Access=AK,SignedHeaders=content-type;host;maas_type;x-sdk-content-sha256;x-sdk-date;x-security-token," + + "Signature=f33e9f9e8fa23cb4dbac42f858e310657f72cc67179a098e0b3a2fa9a693e161", + ) +}) + +// ---- helpers --------------------------------------------------------------- + +test("normalizeModelId strips only a trailing 4-digit date", () => { + assert.equal(x.normalizeModelId("deepseek-v4-flash-0731"), "deepseek-v4-flash") + assert.equal(x.normalizeModelId("glm-5.3-flash"), "glm-5.3-flash") + assert.equal(x.normalizeModelId("GLM-5.2"), "GLM-5.2") +}) + +test("upstreamModelId drops the host's provider prefix only", () => { + assert.equal(x.upstreamModelId("codearts/deepseek-v4.1-flash"), "deepseek-v4.1-flash") + assert.equal(x.upstreamModelId("GLM-5.2"), "GLM-5.2") + assert.equal(x.upstreamModelId("other/GLM-5.2"), "other/GLM-5.2") +}) + +test("parseModelInfo drops vision models, dedupes, and fills context", () => { + const seen = new Set() + assert.equal(x.parseModelInfo({ model_id: "Qwen3-VL-235B", model_name: "Qwen3-VL-235B" }, seen), undefined) + assert.equal(x.parseModelInfo({ model_id: "kimi-k2.6-vl" }, seen), undefined) + const a = x.parseModelInfo({ model_id: "GLM-5.2", model_name: "GLM-5.2" }, seen) + assert.deepEqual(a, { id: "GLM-5.2", name: "GLM-5.2", context: 202752 }) + assert.equal(x.parseModelInfo({ model_id: "GLM-5.2", model_name: "GLM-5.2" }, seen), undefined) +}) + +test("parseModelInfo keeps the dated id, and its bare form as another model", () => { + const seen = new Set() + const dated = x.parseModelInfo({ model_id: "deepseek-v4-flash-0731", model_name: "deepseek-v4-flash-0731", max_tokens: 131072 }, seen) + assert.deepEqual(dated, { id: "deepseek-v4-flash-0731", name: "deepseek-v4-flash", context: 1048576, output: x.MAX_OUTPUT_TOKENS }) + assert.equal(x.parseModelInfo({ model_id: "deepseek-v4-flash" }, seen).id, "deepseek-v4-flash") +}) + +test("prepareChatBody reshapes a chat into what the gateway accepts and meters", () => { + const out = x.prepareChatBody({ model: "codearts/GLM-5.2", messages: [], max_tokens: 128000 }) + assert.equal(out.fold, true) + assert.deepEqual(out.body, { model: "GLM-5.2", messages: [], max_tokens: x.MAX_OUTPUT_TOKENS, thinking: { type: "enabled" }, stream: true }) + + const streamed = x.prepareChatBody({ model: "GLM-5.2", messages: [], stream: true, thinking: { type: "disabled" } }) + assert.equal(streamed.fold, false) + assert.deepEqual(streamed.body.thinking, { type: "disabled" }) + + assert.equal(x.prepareChatBody({ model: "GLM-5.2", messages: [] }, { thinking: false }).body.thinking, undefined) + assert.equal(x.prepareChatBody({ model: "GLM-5.2" }), null) + assert.equal(x.prepareChatBody(null), null) +}) + +test("classifyHead tells an answer from an embedded error", () => { + const role = `data: ${JSON.stringify({ choices: [{ delta: { role: "assistant" } }] })}\n\n` + const content = `data: ${JSON.stringify({ choices: [{ delta: { content: "hi" } }] })}\n\n` + const cap = `data: {"error_code":"TM.00001041","error_msg":"并发会话数已达上限(3个)"}\n\n` + assert.equal(x.classifyHead(role, false), undefined) // a role-only delta decides nothing + assert.equal(x.classifyHead(role + content, false), "answer") + assert.equal(x.classifyHead(role + cap, false), "TM.00001041") + assert.equal(x.classifyHead(`data: {"error_code":"TM.00001041"`, false), undefined) // not whole yet + assert.equal(x.classifyHead("", true), "answer") + assert.equal(x.classifyHead(JSON.stringify({ choices: [{ message: { content: "x" } }] }), true), "answer") +}) + +test("errorCodeOf / errorMessageOf / isRateLimitCode read the gateway's errors", () => { + const text = '{"error_code":"InferHub.4291.200","error_msg":"insufficient \\"quota\\""}' + assert.equal(x.errorCodeOf(text), "InferHub.4291.200") + assert.equal(x.errorMessageOf(text), 'insufficient "quota"') + assert.equal(x.isRateLimitCode("InferHub.4291.200"), true) + assert.equal(x.isRateLimitCode("81111.429"), true) + assert.equal(x.isRateLimitCode("InferHub.002002009.404"), false) + assert.equal(x.isStaleCredential('{"error_code":"APIG.0602"}'), true) + assert.equal(x.isStaleCredential('{"error_code":"APIG.0301","error_msg":"verify ak sk signature fail"}'), true) +}) + +test("accountIdentityOf reads the signer from the refresh token's user_profile", () => { + const b64u = (o) => Buffer.from(JSON.stringify(o)).toString("base64url") + const profile = { principal_urn: "iam::d1:user:alice", user_name: "alice" } + const asString = `h.${b64u({ user_profile: JSON.stringify(profile) })}.s` + assert.deepEqual(x.accountIdentityOf({ refresh_token: asString }), { id: "iam::d1:user:alice", name: "alice" }) + const asB64 = `h.${b64u({ user_profile: b64u(profile) })}.s` + assert.deepEqual(x.accountIdentityOf({ refresh_token: asB64 }), { id: "iam::d1:user:alice", name: "alice" }) + assert.deepEqual(x.accountIdentityOf({ refresh_token: "opaque", user_name: "bob" }), { id: "bob", name: "bob" }) +}) + +test("accountSessionIds is stable per account and differs between accounts", async () => { + const a = await x.accountSessionIds({ session_id: "s1", access_key_id: "AK1" }) + assert.deepEqual(await x.accountSessionIds({ session_id: "s1", access_key_id: "AK2" }), a) + assert.notDeepEqual(await x.accountSessionIds({ session_id: "s2", access_key_id: "AK1" }), a) + assert.match(a.sessionId, /^[0-9a-f]{32}$/) + assert.match(a.chatId, /^[0-9a-f]{32}$/) +}) + +test("createConcurrencyGate caps permits, admits in order, and honours abort", async () => { + const gate = x.createConcurrencyGate(2) + const r1 = await gate.acquire() + const r2 = await gate.acquire() + let third = false + const p3 = gate.acquire().then((r) => { third = true; return r }) + const ctl = new AbortController() + const p4 = gate.acquire(ctl.signal) + await new Promise((r) => setTimeout(r, 5)) + assert.equal(third, false) + assert.equal(gate.waiting, 2) + ctl.abort() + await assert.rejects(p4, { name: "AbortError" }) + r1() + r1() // a second release is a no-op + const r3 = await p3 + assert.equal(gate.active, 2) + r2() + r3() + assert.equal(gate.active, 0) +}) + +test("credentialOf round-trips a credential stored in the access field", async () => { + const keyPair = await x.generateDpopKeyPair() + const cred = x.credentialFromTokenResponse( + { credentials: { access_key_id: "AK", secret_access_key: "SK", security_token: "ST", expiration: "2030-01-01T00:00:00Z" }, refresh_token: "R" }, + "verifier", + keyPair, + ) + const auth = { type: "oauth", access: JSON.stringify(cred), refresh: "R" } + const back = x.credentialOf(auth) + assert.equal(back.access_key_id, "AK") + assert.equal(back.refresh_token, "R") + assert.equal(back.code_verifier, "verifier") + assert.deepEqual(back.dpop_private_key_jwk, keyPair.privateKeyJwk) + assert.equal(x.credentialOf({ type: "api", key: "k" }), null) +}) + +test("expiresFromCredential parses the STS expiration or falls back to +1d", () => { + assert.equal(x.expiresFromCredential({ expires_at: "2030-01-01T00:00:00Z" }), Date.parse("2030-01-01T00:00:00Z")) + const soon = x.expiresFromCredential({}) + assert.ok(soon > Date.now() + 86_000_000 && soon <= Date.now() + 86_400_000) +}) + +test("buildOAuthLoginUrl matches the real IDE parameters", () => { + const url = new URL(x.buildOAuthLoginUrl(12345, { codeChallenge: "CH" }, "TICKET")) + assert.equal(url.origin + url.pathname, "https://codearts.huaweicloud.com/portal/authorize") + const q = url.searchParams + assert.equal(q.get("client_id"), "codearts-agent") + assert.equal(q.get("uri_scheme"), "codearts-agent") + assert.equal(q.get("port"), "12345") + assert.equal(q.get("code_challenge"), "CH") + assert.equal(q.get("code_challenge_method"), "SHA-256") + assert.equal(q.get("ticket_id"), "TICKET") + assert.equal(q.get("plugin-name"), "snap_AIIDE") + // The real plugin never sends auth_callback_url (portal derives it from port). + assert.equal(q.has("auth_callback_url"), false) +}) + +test("usageFromStatistics maps credit metrics to windows with real numbers", () => { + const usage = x.usageFromStatistics({ + package: { package_name_cn: "企业版" }, + metrics: [ + { name: "usageTotalPackageCredit", package_credit_amount: 1000, package_credit_remain: 250, package_credit_used: 750 }, + { name: "usageBasicPackageCredit", package_credit_amount: 1000, package_credit_remain: 250, package_credit_used: 750 }, + { name: "usageOnDemandPackageCredit", package_credit_amount: 20000, package_credit_remain: 20000 }, + ], + }) + assert.equal(usage.plan, "企业版") + assert.equal(usage.signIn, "kept") + // The package total is listed first, then the buckets, all with display + // numbers; only the total may pause the account, the buckets are aside. + assert.deepEqual(usage.windows, [ + { name: "总积分", used: 75, display: "750 / 1000", amount: 750, limit: 1000, unit: "credits" }, + { name: "基础积分包", used: 75, display: "750 / 1000", amount: 750, limit: 1000, unit: "credits", aside: true }, + { name: "按需积分包", used: 0, display: "0 / 2.0万", amount: 0, limit: 20000, unit: "credits", aside: true }, + ]) +}) + +test("usageFromStatistics adds the free daily pool as an aside window for the free models", () => { + const usage = x.usageFromStatistics( + { metrics: [{ name: "usageTotalPackageCredit", package_credit_amount: 1000, package_credit_remain: 1000 }] }, + { result: { daily_token_limit: 10_000_000, daily_tokens_used: 2_500_000 } }, + ) + const free = usage.windows.find((w) => w.name === "免费额度") + assert.equal(free.used, 25) + assert.equal(free.display, "250.0万 / 1000.0万") + assert.equal(free.unit, "tokens") + assert.equal(free.aside, true) + assert.ok(free.models.includes("glm-5.3-flash")) + assert.equal(x.benefitWindow({ result: {} }), undefined) +}) + +test("usageFromStatistics: the monthly buckets reset at end_date, expiring credits are said", () => { + const usage = x.usageFromStatistics({ + end_date: "2026-11-01", + metrics: [ + { name: "usageTotalPackageCredit", package_credit_amount: 6500, package_credit_remain: 6000 }, + { name: "usageBasicPackageCredit", package_credit_amount: 500, package_credit_remain: 0 }, + { name: "usageBonusPackageCredit", package_credit_amount: 6000, package_credit_remain: 6000, package_credit_expiring_amount: 1000 }, + ], + }) + const [total, basic, bonus] = usage.windows + const reset = new Date(Date.parse("2026-10-31T16:00:00Z")).toISOString() + assert.equal(total.resetsAt, reset) + assert.equal(basic.resetsAt, reset) + assert.equal(bonus.resetsAt, undefined, "given credits don't come back at the month's end") + assert.equal(bonus.display, "0 / 6000 · 1000 即将过期") +}) + +test("usageFromStatistics: the soonest check-in credits to lapse show on the bonus bucket", () => { + const now = Date.now() + const day = 86_400_000 + const grants = [ + { at: new Date(now - 40 * day).toISOString(), credit: 1000, expiresAt: new Date(now - 10 * day).toISOString() }, // gone + { at: new Date(now - 25 * day).toISOString(), credit: 1000, expiresAt: new Date(now + 5 * day).toISOString() }, + { at: new Date(now - 2 * day).toISOString(), credit: 1000, expiresAt: new Date(now + 28 * day).toISOString() }, + ] + const usage = x.usageFromStatistics({ + metrics: [ + { name: "usageTotalPackageCredit", package_credit_amount: 7000, package_credit_remain: 6500 }, + { name: "usageBonusPackageCredit", package_credit_amount: 2000, package_credit_remain: 1500 }, + ], + }, undefined, { grants }) + const bonus = usage.windows.find((w) => w.name === "赠送积分包") + assert.equal(bonus.runsOutAt, grants[1].expiresAt) + assert.equal(bonus.runsOut, 1000) + // The total loses them too. + assert.equal(usage.windows.find((w) => w.name === "总积分").runsOutAt, grants[1].expiresAt) + assert.equal(x.soonestLapse(x.grantBatches([grants[0]])), undefined) +}) + +// Shaped as the console's own answers (personal-usage → 获取明细). +const day = 86_400_000 +const iso = (ms) => new Date(ms).toISOString() +function creditFetcher(now = Date.now()) { + const planEnd = now + 31 * day + const signUp = now + 30 * day + const checkin = signUp + 52_000 // the same Beijing day, a minute later + const ok = (data) => new Response(JSON.stringify({ code: 0, message: "ok", data }), { status: 200 }) + const fetcher = async (url, init) => { + const u = String(url) + const body = init?.body ? JSON.parse(new TextDecoder().decode(init.body)) : undefined + if (u === x.PACKAGE_CREDIT_PAGE_URL) { + const list = body.packageTypes.includes("basic") + ? [{ packageType: "basic", creditAmount: 500.0, creditUsed: 0.0, validityPeriod: "31", expiredTime: iso(planEnd).replace("Z", "+00:00"), status: 1 }] + : [] + return new Response(JSON.stringify({ list, total: list.length, pageNum: 1, pageSize: 100 }), { status: 200 }) + } + if (u === x.OPS_CREDIT_OVERVIEW_URL) { + return ok({ items: [ + { campaignId: 4, campaignTitle: "新用户注册送 4000 积分", totalClaimed: 4000, totalConsumed: 0, totalExpired: 0 }, + { campaignId: 1, campaignTitle: "每日签到领1000积分", totalClaimed: 1000, totalConsumed: 0, totalExpired: 0 }, + { campaignId: 9, campaignTitle: "用完了", totalClaimed: 1000, totalConsumed: 1000, totalExpired: 0 }, + ] }) + } + if (u === x.OPS_CREDIT_CAMPAIGN_URL(4)) { + return ok({ campaignId: 4, benefits: [{ status: "CONFIRMED", claimedAmount: 4000, consumedAmount: 0, expiredAmount: 0, claimedAt: iso(signUp - 30 * day), expireAt: iso(signUp) }] }) + } + if (u === x.OPS_CREDIT_CAMPAIGN_URL(1)) { + return ok({ campaignId: 1, expirePolicy: { strategy: "DURATION", duration: 30, durationUnit: "DAYS" }, benefits: [{ status: "CONFIRMED", claimedAmount: 1000, consumedAmount: 0, expiredAmount: 0, claimedAt: iso(checkin - 30 * day), expireAt: iso(checkin) }] }) + } + throw new Error(`unexpected ${u}`) + } + return { fetcher, planEnd, signUp, checkin } +} + +test("fetchCreditBatches reads every batch with its own expiry, signed", async () => { + const { fetcher, planEnd, signUp, checkin } = creditFetcher() + const seen = [] + const batches = await x.fetchCreditBatches({ access_key_id: "AK", secret_access_key: "SK", security_token: "ST" }, async (url, init) => { + seen.push([init.method, String(url), new Headers(init.headers).get("authorization")]) + return fetcher(url, init) + }) + assert.deepEqual(batches, [ + { metric: "usageBasicPackageCredit", amount: 500, left: 500, expiresAt: planEnd }, + { metric: "usageBonusPackageCredit", amount: 4000, left: 4000, expiresAt: signUp }, + { metric: "usageBonusPackageCredit", amount: 1000, left: 1000, expiresAt: checkin }, + ]) + // A spent campaign is not asked for its grants. + assert.equal(seen.some((s) => s[1] === x.OPS_CREDIT_CAMPAIGN_URL(9)), false) + assert.ok(seen.every((s) => String(s[2]).startsWith("SDK-HMAC-SHA256 "))) + // Nothing reached: no batches, so the caller falls back. + assert.equal(await x.fetchCreditBatches({ access_key_id: "AK", secret_access_key: "SK", security_token: "ST" }, async () => new Response("", { status: 401 })), undefined) +}) + +test("usage with the vendor's batches: the plan's end is the reset, the grants' the lapse", async () => { + const cred = await makeCred() + const { fetcher: credit, planEnd, signUp } = creditFetcher() + const fetcher = async (url, init) => { + if (String(url).endsWith("/snap-manager/v1/statistics/plugin")) { + return new Response(JSON.stringify({ + end_date: "2099-01-01", + metrics: [ + { name: "usageTotalPackageCredit", package_credit_amount: 5500, package_credit_remain: 5500 }, + { name: "usageBasicPackageCredit", package_credit_amount: 500, package_credit_remain: 500 }, + { name: "usageBonusPackageCredit", package_credit_amount: 5000, package_credit_remain: 5000 }, + ], + }), { status: 200 }) + } + if (String(url) === x.BENEFIT_BALANCE_URL) return new Response("", { status: 404 }) + return credit(url, init) + } + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: fetcher, ledgerPath: path.join(ledgerDir, "unused.json") }) + const usage = await plugin.auth.usage(async () => makeAuth(cred)) + const [total, basic, bonus] = usage.windows + // To the second, from the plan's batch, not end_date's day. + assert.equal(total.resetsAt, iso(planEnd)) + assert.equal(basic.resetsAt, iso(planEnd)) + assert.equal(basic.runsOutAt, undefined, "the plan's credits come back, they don't lapse") + // The sign-up grant and that day's check-in lapse together. + assert.equal(bonus.runsOutAt, iso(signUp)) + assert.equal(bonus.runsOut, 5000) + assert.equal(total.runsOutAt, iso(signUp)) + assert.equal(total.runsOut, 5000) +}) + +test("the free pool window comes back at the next Beijing midnight", () => { + const w = x.benefitWindow({ result: { daily_token_limit: 100, daily_tokens_used: 10 } }) + const at = Date.parse(w.resetsAt) + assert.ok(at > Date.now() && at - Date.now() <= 86_400_000) + assert.equal(new Date(at + 8 * 3600 * 1000).toISOString().slice(11, 19), "00:00:00") +}) + +test("usageFromStatistics reports no credit plan when every bucket is empty", () => { + const usage = x.usageFromStatistics({ + metrics: [{ name: "usageTotalPackageCredit", package_credit_amount: 0, package_credit_remain: 0 }], + }) + assert.deepEqual(usage.windows, []) + assert.equal(usage.error, "该账号无积分额度") +}) + +test("usageFromStatistics surfaces a business error code", () => { + const usage = x.usageFromStatistics({ code: 500, message: "boom" }) + assert.equal(usage.error, "boom") +}) + +test("toBytes normalizes strings and views", async () => { + assert.deepEqual(await x.toBytes("hi"), buf("hi")) + assert.deepEqual(await x.toBytes(buf("hi")), buf("hi")) + assert.equal((await x.toBytes(null)).length, 0) +}) + +test("isBenefitModel honours the static fallback and the host's prefix", () => { + assert.equal(x.isBenefitModel("glm-5.3-flash"), true) + assert.equal(x.isBenefitModel("codearts/glm-5.3-flash"), true) + assert.equal(x.isBenefitModel("deepseek-v4-flash-0731"), true) + // The bare id is a different, paid model. + assert.equal(x.isBenefitModel("deepseek-v4-flash"), false) + assert.equal(x.isBenefitModel("GLM-5.2"), false) +}) + +test("isBenefitModel / isRegularModel read the account's own lists once it has them", () => { + const state = { benefit: new Set(["glm-5.3-flash"]), regular: new Set(["GLM-5.2"]), noBenefit: new Set() } + assert.equal(x.isBenefitModel("deepseek-v4.1-flash", state), false, "the fallback no longer stands") + assert.equal(x.isBenefitModel("glm-5.3-flash", state), true) + state.noBenefit.add("glm-5.3-flash") + assert.equal(x.isBenefitModel("glm-5.3-flash", state), false) + assert.equal(x.isRegularModel("GLM-5.2", state), true) + assert.equal(x.isRegularModel("glm-5.3-flash", state), false) + assert.equal(x.isRegularModel("anything", { regular: null }), true, "not known yet") +}) + +// ---- remote model list ----------------------------------------------------- + +const gatewayBody = JSON.stringify({ + result: { + models: [ + { model_id: "glm-5.3-flash", model_name: "glm-5.3-flash" }, + { model_id: "deepseek-v4-flash-0731", model_name: "deepseek-v4-flash-0731" }, + { model_id: "Qwen3-VL-235B", model_name: "Qwen3-VL-235B" }, + ], + }, +}) +const builtinBody = JSON.stringify({ builtinModels: [{ model_id: "GLM-5.2", model_name: "GLM-5.2" }] }) + +function modelsFetcher(seen, { claim = "0000", agents, detail } = {}) { + return async (url, init) => { + const u = String(url) + seen.push({ url: u, method: init?.method, auth: new Headers(init?.headers).get("authorization") }) + if (u === x.BENEFIT_CLAIM_URL) return new Response(JSON.stringify({ error_code: claim, error_msg: claim === "0000" ? "ok" : "权益不存在" }), { status: 200 }) + if (u === x.AGENT_LIST_URL) return new Response(JSON.stringify(agents ?? { total: 0, agents: [] }), { status: 200 }) + if (u.startsWith(`${x.AGENT_DETAIL_URL("")}`)) return new Response(JSON.stringify(detail ?? { gpts: { models: [] } }), { status: 200 }) + const body = u.includes("opengw") ? gatewayBody : builtinBody + return new Response(body, { status: 200 }) + } +} + +test("fetchRemoteModels merges both endpoints, filters VL, and keeps the published ids", async () => { + const seen = [] + const models = await x.fetchRemoteModels( + { access_key_id: "AK", secret_access_key: "SK", security_token: "ST" }, + modelsFetcher(seen), + ) + const ids = models.map((m) => m.id) + assert.deepEqual(ids, ["glm-5.3-flash", "deepseek-v4-flash-0731", "GLM-5.2"]) + // Everything gateway/config publishes is a free model. + assert.deepEqual(models.map((m) => m.benefit === true), [true, true, false]) + assert.ok(seen.every((s) => String(s.auth).startsWith("SDK-HMAC-SHA256"))) +}) + +test("signedGet returns undefined on a non-2xx response", async () => { + const fetcher = async () => new Response("nope", { status: 401 }) + const text = await x.signedGet("https://example.com/x", { access_key_id: "AK", secret_access_key: "SK", security_token: "ST" }, fetcher) + assert.equal(text, undefined) +}) + +// ---- plugin hooks ---------------------------------------------------------- + +function makeAuth(cred) { + return { type: "oauth", access: JSON.stringify(cred), refresh: cred.refresh_token, expires: x.expiresFromCredential(cred) } +} + +async function makeCred() { + const keyPair = await x.generateDpopKeyPair() + return x.credentialFromTokenResponse( + { credentials: { access_key_id: "AK", secret_access_key: "SK", security_token: "ST", expiration: "2030-01-01T00:00:00Z" }, refresh_token: "R" }, + "verifier", + keyPair, + ) +} + +test("plugin exposes config, provider.models, and an oauth auth method", async () => { + const plugin = await CodeArtsAuthPlugin({ client: {} }, {}) + assert.equal(typeof plugin.config, "function") + assert.equal(plugin.provider.id, "codearts") + assert.equal(plugin.auth.provider, "codearts") + assert.equal(plugin.auth.methods.length, 1) + assert.equal(plugin.auth.methods[0].type, "oauth") + assert.equal(typeof plugin.auth.checkin, "function") + assert.equal(plugin.auth.maxConcurrency, x.ACCOUNT_MAX_INFLIGHT) + + const config = {} + await plugin.config(config) + const p = config.provider.codearts + assert.equal(p.npm, "@ai-sdk/openai-compatible") + assert.equal(p.api, x.CHAT_API_BASE) + assert.ok(p.models["GLM-5.2"]) + assert.equal(p.models["GLM-5"], undefined) + // The output budget is declared; nothing is called free before the + // account's own list says so. + assert.equal(p.models["GLM-5.2"].limit.output, x.MAX_OUTPUT_TOKENS) + assert.equal(p.models["GLM-5.2"].free, undefined) + assert.equal(p.models["glm-5.3-flash"].free, undefined) +}) + +const CHAT_URL = "https://snap-access.cn-north-4.myhuaweicloud.com/api/v2/chat/completions" +const sse = (...events) => events.map((e) => `data: ${typeof e === "string" ? e : JSON.stringify(e)}\n\n`).join("") +const sseResponse = (text) => new Response(text, { status: 200, headers: { "content-type": "text/event-stream" } }) +const chatInit = (body) => ({ method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }) +const okStream = sse( + { id: "c1", model: "GLM-5.2", choices: [{ index: 0, delta: { role: "assistant" } }] }, + { id: "c1", choices: [{ index: 0, delta: { content: "你好" } }] }, + { id: "c1", choices: [{ index: 0, delta: {}, finish_reason: "stop" }] }, + "[DONE]", +) +const fastRetry = { retryDelays: [1], retryBudgetMs: 2_000 } + +test("loader signs each chat request with SDK-HMAC-SHA256 and sends it metered", async () => { + const cred = await makeCred() + const seen = [] + const fetcher = async (url, init) => { + seen.push({ url: String(url), init }) + return sseResponse(okStream) + } + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: fetcher }) + const loaded = await plugin.auth.loader(async () => makeAuth(cred)) + assert.equal(loaded.baseURL, x.CHAT_API_BASE) + + const res = await loaded.fetch(CHAT_URL, chatInit({ model: "codearts/GLM-5.2", messages: [] })) + + const headers = new Headers(seen[0].init.headers) + assert.match(headers.get("authorization"), /^SDK-HMAC-SHA256 Access=AK,/) + assert.equal(headers.get("lang"), "en") + assert.match(headers.get("chat-id"), /^[0-9a-f]{32}$/) + assert.match(headers.get("session-id"), /^[0-9a-f]{32}$/) + assert.equal(headers.has("maas_type"), false) + // The body signed and sent: bare model, explicit thinking, streamed. + assert.deepEqual(JSON.parse(new TextDecoder().decode(seen[0].init.body)), { + model: "GLM-5.2", messages: [], thinking: { type: "enabled" }, stream: true, + }) + // The caller asked for JSON, so the stream comes back folded. + assert.equal(res.headers.get("content-type"), "application/json") + const json = await res.json() + assert.equal(json.object, "chat.completion") + assert.deepEqual(json.choices[0].message, { role: "assistant", content: "你好" }) + assert.equal(json.choices[0].finish_reason, "stop") +}) + +test("one account keeps one Chat-Id/Session-Id across requests and loaders", async () => { + const cred = await makeCred() + const seen = [] + const fetcher = async (url, init) => { + seen.push(new Headers(init.headers)) + return sseResponse(okStream) + } + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: fetcher }) + const a = await plugin.auth.loader(async () => makeAuth(cred)) + const b = await plugin.auth.loader(async () => makeAuth(cred)) + await (await a.fetch(CHAT_URL, chatInit({ model: "GLM-5.2", messages: [] }))).text() + await (await a.fetch(CHAT_URL, chatInit({ model: "GLM-5.2", messages: [] }))).text() + await (await b.fetch(CHAT_URL, chatInit({ model: "GLM-5.2", messages: [] }))).text() + assert.equal(new Set(seen.map((h) => h.get("chat-id"))).size, 1) + assert.equal(new Set(seen.map((h) => h.get("session-id"))).size, 1) +}) + +test("a streaming caller gets the upstream stream intact, peeked bytes included", async () => { + const cred = await makeCred() + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: async () => sseResponse(okStream) }) + const loaded = await plugin.auth.loader(async () => makeAuth(cred)) + const res = await loaded.fetch(CHAT_URL, chatInit({ model: "GLM-5.2", messages: [], stream: true })) + assert.equal(res.status, 200) + assert.equal(await res.text(), okStream) +}) + +test("a folded answer keeps reasoning, tool calls and usage apart", async () => { + const cred = await makeCred() + const stream = sse( + { id: "c2", model: "deepseek-v4.1-flash", choices: [{ delta: { reasoning_content: "想一想" } }] }, + { id: "c2", choices: [{ delta: { tool_calls: [{ index: 0, id: "call_1", type: "function", function: { name: "read", arguments: '{"pa' } }] } }] }, + { id: "c2", choices: [{ delta: { tool_calls: [{ index: 0, function: { arguments: 'th":"a"}' } }] } }] }, + { id: "c2", choices: [{ delta: {}, finish_reason: "tool_calls" }], usage: { prompt_tokens: 5, completion_tokens: 7, total_tokens: 12 } }, + "[DONE]", + ) + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: async () => sseResponse(stream) }) + const loaded = await plugin.auth.loader(async () => makeAuth(cred)) + const json = await (await loaded.fetch(CHAT_URL, chatInit({ model: "deepseek-v4.1-flash", messages: [] }))).json() + const msg = json.choices[0].message + assert.equal(msg.content, "") + assert.equal(msg.reasoning_content, "想一想") + assert.deepEqual(msg.tool_calls, [{ id: "call_1", type: "function", function: { name: "read", arguments: '{"path":"a"}' } }]) + assert.equal(json.choices[0].finish_reason, "tool_calls") + assert.deepEqual(json.usage, { prompt_tokens: 5, completion_tokens: 7, total_tokens: 12 }) +}) + +const capBody = JSON.stringify({ error_code: "TM.00001041", error_msg: "并发会话数已达上限(3个),请关闭部分会话后重试。" }) + +test("TM.00001041 as a 400 is retried, re-signed, until a session frees", async () => { + const cred = await makeCred() + let calls = 0 + const fetcher = async () => { + calls += 1 + return calls <= 2 ? new Response(capBody, { status: 400 }) : sseResponse(okStream) + } + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: fetcher, ...fastRetry }) + const loaded = await plugin.auth.loader(async () => makeAuth(cred)) + const res = await loaded.fetch(CHAT_URL, chatInit({ model: "GLM-5.2", messages: [], stream: true })) + assert.equal(calls, 3) + assert.equal(res.status, 200) + assert.equal(await res.text(), okStream) +}) + +test("TM.00001041 inside a 200 stream is retried too", async () => { + const cred = await makeCred() + let calls = 0 + const fetcher = async () => { + calls += 1 + return calls === 1 ? sseResponse(sse({ choices: [{ delta: { role: "assistant" } }] }, JSON.parse(capBody))) : sseResponse(okStream) + } + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: fetcher, ...fastRetry }) + const loaded = await plugin.auth.loader(async () => makeAuth(cred)) + const json = await (await loaded.fetch(CHAT_URL, chatInit({ model: "GLM-5.2", messages: [] }))).json() + assert.equal(calls, 2) + assert.equal(json.choices[0].message.content, "你好") +}) + +test("a session cap that outlasts the budget comes back as a 429 magpie fails over on", async () => { + const cred = await makeCred() + let calls = 0 + const fetcher = async () => { + calls += 1 + return new Response(capBody, { status: 400 }) + } + // A virtual clock that moves only when the plugin sleeps: however slow the + // signing is, the budget is spent by the waits alone. + let t = 0 + const now = () => t + const sleep = async (ms) => { t += ms } + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: fetcher, retryDelays: [10], retryBudgetMs: 13, now, sleep }) + const loaded = await plugin.auth.loader(async () => makeAuth(cred)) + const res = await loaded.fetch(CHAT_URL, chatInit({ model: "GLM-5.2", messages: [] })) + assert.equal(res.status, 429) + // A wait is 10 ms ±20%: one (8–12) always fits the 13 ms budget, two (≥ 16) + // never do. So exactly one retry, whatever the jitter. + assert.equal(calls, 2) + const body = await res.json() + assert.equal(body.error.code, "TM.00001041") + assert.match(body.error.message, /并发会话数已达上限/) +}) + +test("an abort while waiting for a session stops the retries", async () => { + const cred = await makeCred() + const fetcher = async () => new Response(capBody, { status: 400 }) + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: fetcher, retryDelays: [10_000], retryBudgetMs: 60_000 }) + const loaded = await plugin.auth.loader(async () => makeAuth(cred)) + const ctl = new AbortController() + setTimeout(() => ctl.abort(), 20) + await assert.rejects( + loaded.fetch(CHAT_URL, { ...chatInit({ model: "GLM-5.2", messages: [] }), signal: ctl.signal }), + { name: "AbortError" }, + ) +}) + +test("an error inside a 200 becomes a status magpie acts on, with the vendor's words", async () => { + const cred = await makeCred() + const quota = sse({ error_code: "InferHub.4291.200", error_msg: "insufficient quota" }) + const unknown = sse({ error_code: "InferHub.002002009.404", error_msg: "model is not registered" }) + let next = quota + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: async () => sseResponse(next) }) + const loaded = await plugin.auth.loader(async () => makeAuth(cred)) + + const a = await loaded.fetch(CHAT_URL, chatInit({ model: "GLM-5.2", messages: [], stream: true })) + assert.equal(a.status, 429) + assert.match((await a.json()).error.message, /insufficient quota \(InferHub\.4291\.200\)/) + + // A model the account doesn't have: retrying can't help, so a 400. + next = unknown + const b = await loaded.fetch(CHAT_URL, chatInit({ model: "GLM-5.2", messages: [] })) + assert.equal(b.status, 400) + const body = await b.json() + assert.equal(body.error.code, "InferHub.002002009.404") + assert.equal(body.error.message.startsWith("CodeArts"), false, "magpie adds the provider name itself") +}) + +test("embeddedErrorStatus sorts the gateway's codes into what magpie acts on", () => { + assert.equal(x.embeddedErrorStatus("InferHub.4291.200"), 429) + assert.equal(x.embeddedErrorStatus("81114.429"), 429) + assert.equal(x.embeddedErrorStatus("InferHub.4004.200"), 400) + assert.equal(x.embeddedErrorStatus("ModelArts.81009.404"), 400) + assert.equal(x.embeddedErrorStatus("InferHub.001001005.400"), 400) + assert.equal(x.embeddedErrorStatus("InferHub.5000.500"), 502) +}) + +test("every chat carries the agent's session headers: one session, a fresh trace", async () => { + const cred = await makeCred() + const seen = [] + const plugin = await CodeArtsAuthPlugin({ client: {} }, { + fetch: async (url, init) => { + seen.push(new Headers(init.headers)) + return sseResponse(okStream) + }, + }) + const loaded = await plugin.auth.loader(async () => makeAuth(cred)) + await (await loaded.fetch(CHAT_URL, chatInit({ model: "GLM-5.2", messages: [] }))).text() + await (await loaded.fetch(CHAT_URL, chatInit({ model: "GLM-5.2", messages: [] }))).text() + const [a, b] = seen + assert.match(a.get("x-ot-session-id"), /^[0-9a-f]{32}$/) + assert.equal(a.get("x-ot-session-id"), b.get("x-ot-session-id")) + assert.equal(a.get("user-session-id"), a.get("x-ot-session-id")) + assert.notEqual(a.get("x-ot-trace-id"), b.get("x-ot-trace-id")) + assert.notEqual(a.get("x-snap-traceid"), b.get("x-snap-traceid")) +}) + +const signedCred = { access_key_id: "AK", secret_access_key: "SK", security_token: "ST" } + +test("only the account's live free list decides the benefit header", async () => { + const state = {} + const fetcher = async (url) => String(url).includes("opengw") + ? new Response(JSON.stringify({ result: { models: [{ model_id: "glm-5.3-flash" }] } }), { status: 200 }) + : new Response(JSON.stringify({ builtinModels: [{ model_id: "deepseek-v4.1-flash", model_name: "DeepSeek-V4.1-Flash" }] }), { status: 200 }) + // The claim answers with the gateway's own body here, so it is no 0000: read + // the published list as it is (no state), then check the account's lists. + const models = await x.fetchRemoteModels(signedCred, fetcher) + assert.deepEqual(models.map((m) => [m.id, m.benefit === true]), [["glm-5.3-flash", true], ["deepseek-v4.1-flash", false]]) + const claimed = async (url, init) => (String(url) === x.BENEFIT_CLAIM_URL ? new Response('{"error_code":"0000"}', { status: 200 }) : fetcher(url, init)) + await x.fetchRemoteModels(signedCred, claimed, state) + // In the fallback, but this account lists it as a plain builtin model. + assert.equal(x.isBenefitModel("deepseek-v4.1-flash", state), false) + assert.equal(x.isBenefitModel("glm-5.3-flash", state), true) + assert.deepEqual([...state.regular], ["deepseek-v4.1-flash"]) + // A failed read keeps what was known. + await x.fetchRemoteModels(signedCred, async () => new Response("", { status: 500 }), state) + assert.equal(x.isBenefitModel("glm-5.3-flash", state), true) +}) + +test("one account's model lists never decide another's", async () => { + // Two accounts in one plugin: A has the free model, B lists it only as builtin. + const credA = await makeCred() + const credB = { ...(await makeCred()), access_key_id: "AKB", session_id: "b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0" } + const listFor = (ak) => async (url, init) => { + const u = String(url) + if (u === x.BENEFIT_CLAIM_URL) return new Response(JSON.stringify({ error_code: ak === "AK" ? "0000" : "4004" }), { status: 200 }) + if (u.includes("opengw")) return new Response(JSON.stringify({ result: { models: [{ model_id: "deepseek-v4.1-flash" }] } }), { status: 200 }) + if (u === x.CHAT_API_BASE + "/chat/completions") { + return new Headers(init.headers).get("maas_type") && ak !== "AK" + ? sseResponse(sse({ error_code: "InferHub.4004.200", error_msg: "benefit not found" })) + : sseResponse(okStream) + } + return new Response(JSON.stringify({ builtinModels: ak === "AK" ? [] : [{ model_id: "deepseek-v4.1-flash" }] }), { status: 200 }) + } + const sent = [] + const plugin = await CodeArtsAuthPlugin({ client: {} }, { + fetch: async (url, init) => { + const ak = /Access=([^,]+),/.exec(new Headers(init.headers).get("authorization") ?? "")?.[1] + if (String(url) === CHAT_URL) sent.push([ak, new Headers(init.headers).get("maas_type")]) + return listFor(ak)(url, init) + }, + }) + const a = await plugin.provider.models({ models: {} }, { auth: makeAuth(credA) }) + const b = await plugin.provider.models({ models: {} }, { auth: makeAuth(credB) }) + assert.equal(a["deepseek-v4.1-flash"].free, true) + assert.equal(b["deepseek-v4.1-flash"].free, false) + const loadedA = await plugin.auth.loader(async () => makeAuth(credA)) + const loadedB = await plugin.auth.loader(async () => makeAuth(credB)) + await (await loadedB.fetch(CHAT_URL, chatInit({ model: "deepseek-v4.1-flash", messages: [] }))).text() + await (await loadedA.fetch(CHAT_URL, chatInit({ model: "deepseek-v4.1-flash", messages: [] }))).text() + // B bills it as its builtin model; A still sends it as its free one. + assert.deepEqual(sent, [["AKB", null], ["AK", "benefit"]]) +}) + +test("benefit not found sends the request again as the plain builtin model, and remembers it", async () => { + const cred = await makeCred() + const sent = [] + const plugin = await CodeArtsAuthPlugin({ client: {} }, { + fetch: async (url, init) => { + const u = String(url) + // The free list and the builtin list both name the model, and today's + // benefit is claimed. + if (u === x.BENEFIT_CLAIM_URL) return new Response('{"error_code":"0000"}', { status: 200 }) + if (u.includes("opengw")) return new Response(JSON.stringify({ result: { models: [{ model_id: "deepseek-v4.1-flash" }] } }), { status: 200 }) + if (u !== CHAT_URL) return new Response(JSON.stringify({ builtinModels: [{ model_id: "deepseek-v4.1-flash" }] }), { status: 200 }) + const benefit = new Headers(init.headers).get("maas_type") + sent.push(benefit) + return benefit + ? sseResponse(sse({ error_code: "InferHub.4004.200", error_msg: "benefit not found" })) + : sseResponse(okStream) + }, + }) + await plugin.provider.models({ models: {} }, { auth: makeAuth(cred) }) + const loaded = await plugin.auth.loader(async () => makeAuth(cred)) + const a = await loaded.fetch(CHAT_URL, chatInit({ model: "codearts/deepseek-v4.1-flash", messages: [] })) + assert.equal(a.status, 200) + assert.equal((await a.json()).choices[0].message.content, "你好") + const b = await loaded.fetch(CHAT_URL, chatInit({ model: "deepseek-v4.1-flash", messages: [] })) + await b.text() + assert.deepEqual(sent, ["benefit", null, null]) +}) + +test("a 429 that queues the request is waited out the agent's way, then sent again", async () => { + const cred = await makeCred() + const calls = [] + let polls = 0 + const fetcher = async (url, init) => { + calls.push([init.method, String(url), new Headers(init.headers).get("authorization")]) + if (String(url) === x.TRACE_QUEUE_URL("T1")) { + polls += 1 + return new Response(JSON.stringify(polls < 2 ? { status: "queued", queue_length: 2, retry_after: 0 } : { status: "promoted" }), { status: 200 }) + } + return calls.filter((c) => c[1] === CHAT_URL).length === 1 + ? new Response("{}", { status: 429, headers: { "queue-status": "queued", "trace-id": "T1", "retry-after": "0" } }) + : sseResponse(okStream) + } + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: fetcher }) + const loaded = await plugin.auth.loader(async () => makeAuth(cred)) + const res = await loaded.fetch(CHAT_URL, chatInit({ model: "GLM-5.2", messages: [], stream: true })) + assert.equal(res.status, 200) + assert.equal(await res.text(), okStream) + assert.deepEqual(calls.map((c) => [c[0], c[1]]), [ + ["POST", CHAT_URL], + ["GET", x.TRACE_QUEUE_URL("T1")], + ["GET", x.TRACE_QUEUE_URL("T1")], + ["POST", CHAT_URL], + ]) + assert.ok(calls.every((c) => String(c[2]).startsWith("SDK-HMAC-SHA256 "))) +}) + +test("giving up in the queue takes the request out of it", async () => { + const cred = await makeCred() + const calls = [] + // The DELETE is sent in the background (it signs first): wait for the DELETE + // itself, never for a fixed time. + let deleted + let sawDelete = new Promise((r) => { deleted = r }) + // The caller gives up once the request is queued, never before it is sent. + const ctl = new AbortController() + const fetcher = async (url, init) => { + calls.push([init.method, String(url)]) + if (init.method === "DELETE") deleted() + if (String(url) === x.TRACE_QUEUE_URL("T2")) return new Response(JSON.stringify({ status: "queued", retry_after: 30 }), { status: 200 }) + setTimeout(() => ctl.abort(), 0) + return new Response("{}", { status: 429, headers: { "queue-status": "queued", "trace-id": "T2", "retry-after": "30" } }) + } + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: fetcher }) + const loaded = await plugin.auth.loader(async () => makeAuth(cred)) + await assert.rejects(loaded.fetch(CHAT_URL, { ...chatInit({ model: "GLM-5.2", messages: [] }), signal: ctl.signal }), { name: "AbortError" }) + await sawDelete + assert.deepEqual(calls.at(-1), ["DELETE", x.TRACE_QUEUE_URL("T2")]) + + // A queue the wait budget can't cover is left at once, and answered 429. + calls.length = 0 + sawDelete = new Promise((r) => { deleted = r }) + const quick = await CodeArtsAuthPlugin({ client: {} }, { fetch: fetcher, queueBudgetMs: 1_000 }) + const res = await (await quick.auth.loader(async () => makeAuth(cred))).fetch(CHAT_URL, chatInit({ model: "GLM-5.2", messages: [] })) + assert.equal(res.status, 429) + await sawDelete + assert.deepEqual(calls.map((c) => c[0]), ["POST", "DELETE"]) +}) + +test("a 429 that is no queue passes through for magpie to fail over", async () => { + const cred = await makeCred() + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: async () => new Response('{"error_code":"81111.429"}', { status: 429 }) }) + const loaded = await plugin.auth.loader(async () => makeAuth(cred)) + const res = await loaded.fetch(CHAT_URL, chatInit({ model: "GLM-5.2", messages: [] })) + assert.equal(res.status, 429) + assert.equal(await res.text(), '{"error_code":"81111.429"}') +}) + +test("a model that refuses the injected thinking parameter gets the caller's request", async () => { + const cred = await makeCred() + const bodies = [] + const fetcher = async (url, init) => { + bodies.push(JSON.parse(new TextDecoder().decode(init.body))) + return bodies.length === 1 + ? new Response('{"error_code":"InferHub.001001005.400","error_msg":"unknown field: thinking"}', { status: 400 }) + : sseResponse(okStream) + } + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: fetcher }) + const loaded = await plugin.auth.loader(async () => makeAuth(cred)) + const res = await loaded.fetch(CHAT_URL, chatInit({ model: "openpangu-2.0-pro", messages: [], stream: true })) + assert.equal(res.status, 200) + assert.deepEqual(bodies[0].thinking, { type: "enabled" }) + assert.equal("thinking" in bodies[1], false) +}) + +test("other upstream errors pass through untouched", async () => { + const cred = await makeCred() + const body = JSON.stringify({ error_code: "InferHub.001001005.400", error_msg: "RANGE_VALIDATOR" }) + let calls = 0 + const plugin = await CodeArtsAuthPlugin({ client: {} }, { + fetch: async () => { + calls += 1 + return new Response(body, { status: 400 }) + }, + ...fastRetry, + }) + const loaded = await plugin.auth.loader(async () => makeAuth(cred)) + const res = await loaded.fetch(CHAT_URL, chatInit({ model: "GLM-5.2", messages: [] })) + assert.equal(res.status, 400) + assert.equal(await res.text(), body) + assert.equal(calls, 1) +}) + +const stsBody = (ak, refresh) => JSON.stringify({ + credentials: { access_key_id: ak, secret_access_key: `SK-${ak}`, security_token: `ST-${ak}`, expiration: "2031-01-01T00:00:00Z" }, + refresh_token: refresh, +}) + +test("a stale credential is renewed once, the request sent again, and the renewal kept", async () => { + const cred = await makeCred() + const sets = [] + const chats = [] + const fetcher = async (url, init) => { + if (String(url) === x.STS_TOKEN_ENDPOINT) return new Response(stsBody("AK2", "R2"), { status: 200 }) + chats.push(new Headers(init.headers).get("authorization")) + return chats.length === 1 + ? new Response(JSON.stringify({ error_code: "APIG.0602", error_msg: "the security token has expired" }), { status: 400 }) + : sseResponse(okStream) + } + const client = { auth: { set: async (o) => { sets.push(o) } } } + const plugin = await CodeArtsAuthPlugin({ client }, { fetch: fetcher }) + const loaded = await plugin.auth.loader(async () => ({ ...makeAuth(cred), accountId: "alice" })) + const res = await loaded.fetch(CHAT_URL, chatInit({ model: "GLM-5.2", messages: [], stream: true })) + assert.equal(res.status, 200) + assert.match(chats[0], /Access=AK,/) + assert.match(chats[1], /Access=AK2,/) + assert.equal(sets.length, 1) + const saved = sets[0].body + assert.equal(saved.accountId, "alice") // the host keeps the record whole: nothing may be lost + assert.equal(saved.refresh, "R2") + const next = JSON.parse(saved.access) + assert.equal(next.access_key_id, "AK2") + assert.equal(next.session_id, cred.session_id) +}) + +test("a stale credential takes over a renewal already stored instead of refreshing again", async () => { + const cred = await makeCred() + const renewed = { ...cred, access_key_id: "AK9", secret_access_key: "SK9", security_token: "ST9" } + let reads = 0 + const getAuth = async () => (reads++ === 0 ? makeAuth(cred) : makeAuth(renewed)) + const chats = [] + const fetcher = async (url, init) => { + assert.notEqual(String(url), x.STS_TOKEN_ENDPOINT, "the stored renewal must be used, not a second refresh") + chats.push(new Headers(init.headers).get("authorization")) + return chats.length === 1 ? new Response('{"error_code":"APIG.0301"}', { status: 401 }) : sseResponse(okStream) + } + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: fetcher }) + const loaded = await plugin.auth.loader(getAuth) + const res = await loaded.fetch(CHAT_URL, chatInit({ model: "GLM-5.2", messages: [], stream: true })) + assert.equal(res.status, 200) + assert.match(chats[1], /Access=AK9,/) +}) + +test("a spent refresh token marks the sign-in and stops calling the vendor", async () => { + const cred = await makeCred() + let chats = 0 + const fetcher = async (url) => { + if (String(url) === x.STS_TOKEN_ENDPOINT) { + return new Response(JSON.stringify({ error_code: "STS5.1806", error_msg: "refresh token has been used" }), { status: 400 }) + } + chats += 1 + return new Response('{"error_code":"APIG.0602","error_msg":"the security token has expired"}', { status: 400 }) + } + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: fetcher }) + const loaded = await plugin.auth.loader(async () => makeAuth(cred)) + const a = await loaded.fetch(CHAT_URL, chatInit({ model: "GLM-5.2", messages: [] })) + assert.equal(a.status, 401) + assert.equal(a.headers.get("x-magpie-sign-in"), "expired") + const b = await loaded.fetch(CHAT_URL, chatInit({ model: "GLM-5.2", messages: [] })) + assert.equal(b.status, 401) + assert.equal(chats, 1) +}) + +test("a 403 is a sign-in the account no longer has, on chats and other requests alike", async () => { + const cred = await makeCred() + const denied = '{"error_code":"APIG.0305","error_msg":"access denied"}' + let calls = 0 + const plugin = await CodeArtsAuthPlugin({ client: {} }, { + fetch: async () => { + calls += 1 + return new Response(denied, { status: 403 }) + }, + }) + const loaded = await plugin.auth.loader(async () => makeAuth(cred)) + const chat = await loaded.fetch(CHAT_URL, chatInit({ model: "GLM-5.2", messages: [] })) + assert.equal(chat.status, 403) + assert.equal(chat.headers.get("x-magpie-sign-in"), "expired") + assert.equal(await chat.text(), denied) + const other = await loaded.fetch("https://snap-access.cn-north-4.myhuaweicloud.com/api/v1/models", { method: "GET" }) + assert.equal(other.status, 403) + assert.equal(other.headers.get("x-magpie-sign-in"), "expired") + assert.equal(await other.text(), denied) + assert.equal(calls, 2, "a 403 is not retried") +}) + +test("isHuaweiUrl takes only https URLs on Huawei Cloud's own hosts", () => { + assert.equal(x.isHuaweiUrl(CHAT_URL), true) + assert.equal(x.isHuaweiUrl("https://codearts.huaweicloud.com/x"), true) + assert.equal(x.isHuaweiUrl("https://iam.myhuaweicloud.cn/v3"), true) + assert.equal(x.isHuaweiUrl("http://snap-access.cn-north-4.myhuaweicloud.com/api"), false, "not over plain http") + assert.equal(x.isHuaweiUrl("https://myhuaweicloud.com.example.com/"), false) + assert.equal(x.isHuaweiUrl("https://evilmyhuaweicloud.com/"), false) + assert.equal(x.isHuaweiUrl("https://example.com/?u=myhuaweicloud.com"), false) + assert.equal(x.isHuaweiUrl("not a url"), false) +}) + +test("a request to any other host is refused before the credentials leave", async () => { + const cred = await makeCred() + let calls = 0 + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: async () => { calls += 1; return sseResponse(okStream) } }) + const loaded = await plugin.auth.loader(async () => makeAuth(cred)) + for (const url of ["https://api.example.com/v1/chat/completions", "http://snap-access.cn-north-4.myhuaweicloud.com/api/v2/chat/completions"]) { + const res = await loaded.fetch(url, chatInit({ model: "GLM-5.2", messages: [] })) + assert.equal(res.status, 400) + assert.match((await res.json()).error.message, /refusing to sign a request to/) + } + assert.equal(calls, 0) +}) + +test("requestToken reads a spent refresh token as a sign-in gone for good", async () => { + const keyPair = await x.generateDpopKeyPair() + const fetcher = async () => new Response(JSON.stringify({ error_code: "STS5.1806", error_msg: "refresh token has been used" }), { status: 400 }) + await assert.rejects(x.requestToken({ grant_type: "refresh_token" }, keyPair, fetcher), (e) => e.signIn === "expired") + const flaky = async () => new Response(JSON.stringify({ error_code: "STS.0001", error_msg: "dpop proof rejected" }), { status: 400 }) + await assert.rejects(x.requestToken({ grant_type: "refresh_token" }, keyPair, flaky), (e) => e.signIn === undefined) +}) + +test("in-flight chats per account are capped, and a permit comes back when the body ends", async () => { + const cred = await makeCred() + // Each upstream stream is kept under the request that opened it (its body + // names it): requests reach the fetcher in no set order, as each one signs + // with WebCrypto first, so `first[i]` is paired with stream `i` by name. + const streams = new Map() + const fetcher = async (url, init) => { + const n = JSON.parse(new TextDecoder().decode(init.body)).messages[0].content + let ctl + const body = new ReadableStream({ start(c) { ctl = c } }) + ctl.enqueue(new TextEncoder().encode(sse({ choices: [{ delta: { content: "x" } }] }))) + streams.set(n, ctl) + return sseResponse(body) + } + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: fetcher }) + const loaded = await plugin.auth.loader(async () => makeAuth(cred)) + const send = (n) => loaded.fetch(CHAT_URL, chatInit({ model: "GLM-5.2", messages: [{ role: "user", content: n }], stream: true })) + const first = await Promise.all(["0", "1", "2"].map(send)) + const fourth = send("3") + // Three streams are open, so the fourth holds; give it a chance to get past + // the gate, which it must not. + await new Promise((r) => setTimeout(r, 30)) + assert.deepEqual([...streams.keys()].sort(), ["0", "1", "2"], "the 4th waits for a permit") + streams.get("0").close() + await first[0].text() + const res = await fourth + assert.ok(streams.has("3")) + for (const n of ["1", "2", "3"]) streams.get(n).close() + await Promise.all([...first.slice(1), res].map((r) => r.text())) +}) + +test("maxInflight can lower the gate but never lift it past the vendor's 3 sessions", async () => { + const cred = await makeCred() + const open = (opts, cap) => async () => { + const streams = [] + const plugin = await CodeArtsAuthPlugin({ client: {} }, { + ...opts, + fetch: async () => { + let ctl + const body = new ReadableStream({ start(c) { ctl = c } }) + ctl.enqueue(new TextEncoder().encode(sse({ choices: [{ delta: { content: "x" } }] }))) + streams.push(ctl) + return sseResponse(body) + }, + }) + const loaded = await plugin.auth.loader(async () => makeAuth(cred)) + // Each answer is read as it comes; a permit comes back when its body ends. + const read = Array.from({ length: 5 }, () => + loaded.fetch(CHAT_URL, chatInit({ model: "GLM-5.2", messages: [], stream: true })).then((r) => r.text())) + // Wait for the cap to fill, however slow the signing, then give one more + // request the chance to slip past it. + while (streams.length < cap) await new Promise((r) => setTimeout(r, 5)) + await new Promise((r) => setTimeout(r, 30)) + const inFlight = streams.length + let finished = false + const all = Promise.all(read).then(() => { finished = true }) + while (!finished) { + for (const c of streams.splice(0)) c.close() + await new Promise((r) => setTimeout(r, 10)) + } + await all + return { inFlight, maxConcurrency: plugin.auth.maxConcurrency } + } + assert.deepEqual(await open({ maxInflight: 10 }, 3)(), { inFlight: 3, maxConcurrency: 3 }) + assert.deepEqual(await open({ maxInflight: 1 }, 1)(), { inFlight: 1, maxConcurrency: 1 }) +}) + +test("loader adds a signed maas_type header for benefit models", async () => { + const cred = await makeCred() + const seen = [] + const fetcher = async (url, init) => { + seen.push(init) + return new Response("ok", { status: 200 }) + } + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: fetcher }) + const loaded = await plugin.auth.loader(async () => makeAuth(cred)) + await loaded.fetch("https://snap-access.cn-north-4.myhuaweicloud.com/api/v2/chat/completions", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ model: "glm-5.3-flash" }), + }) + const headers = new Headers(seen[0].headers) + assert.equal(headers.get("maas_type"), "benefit") + assert.match(headers.get("authorization"), /SignedHeaders=[^,]*,/) + assert.ok(headers.get("authorization").split("SignedHeaders=")[1].split(",")[0].includes("maas_type")) +}) + +test("loader returns nothing when not signed in", async () => { + const plugin = await CodeArtsAuthPlugin({ client: {} }, {}) + assert.deepEqual(await plugin.auth.loader(async () => ({ type: "api", key: "k" })), {}) +}) + +test("auth.refresh exchanges the refresh token for fresh credentials", async () => { + const cred = await makeCred() + const fetcher = async (url, init) => { + assert.equal(String(url), x.STS_TOKEN_ENDPOINT) + assert.equal(init.method, "POST") + assert.ok(new Headers(init.headers).get("dpop")) + return new Response(JSON.stringify({ + credentials: { access_key_id: "AK2", secret_access_key: "SK2", security_token: "ST2", expiration: "2031-01-01T00:00:00Z" }, + refresh_token: "R2", + }), { status: 200 }) + } + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: fetcher }) + const next = await plugin.auth.refresh(makeAuth(cred)) + const parsed = JSON.parse(next.access) + assert.equal(parsed.access_key_id, "AK2") + assert.equal(next.refresh, "R2") + assert.equal(next.expires, Date.parse("2031-01-01T00:00:00Z")) +}) + +/** Check a token request's DPoP proof: it verifies against the stored key, for POST to the STS endpoint. */ +async function assertDpopFor(proof, publicKeyJwk) { + const [h, p, s] = proof.split(".") + const header = JSON.parse(Buffer.from(h, "base64url").toString()) + const payload = JSON.parse(Buffer.from(p, "base64url").toString()) + assert.equal(header.typ, "dpop+jwt") + assert.deepEqual(header.jwk, publicKeyJwk, "signed with the credential's own DPoP key") + assert.equal(payload.htm, "POST") + assert.equal(payload.htu, x.STS_TOKEN_ENDPOINT) + const key = await crypto.subtle.importKey("jwk", header.jwk, { name: "ECDSA", namedCurve: "P-256" }, false, ["verify"]) + assert.ok(await crypto.subtle.verify({ name: "ECDSA", hash: "SHA-256" }, key, Buffer.from(s, "base64url"), buf(`${h}.${p}`))) +} + +test("token requests carry a DPoP proof for POST to the STS endpoint, signed with the credential's key", async () => { + const cred = await makeCred() + const { publicKeyJwk } = x.keyPairFromStoredJwk(cred.dpop_private_key_jwk) + const proofs = [] + const bodies = [] + const fetcher = async (url, init) => { + proofs.push(new Headers(init.headers).get("dpop")) + bodies.push(new URLSearchParams(init.body)) + return new Response(JSON.stringify({ + credentials: { access_key_id: "AK2", secret_access_key: "SK2", security_token: "ST2", expiration: "2031-01-01T00:00:00Z" }, + refresh_token: "R2", + }), { status: 200 }) + } + // A refresh, and an authorization-code exchange. + await x.refreshCredential(cred, fetcher) + await x.exchangeAuthorizationCode("CODE", "verifier", 12345, x.keyPairFromStoredJwk(cred.dpop_private_key_jwk), fetcher) + for (const proof of proofs) await assertDpopFor(proof, publicKeyJwk) + assert.equal(bodies[0].get("grant_type"), "refresh_token") + assert.equal(bodies[0].get("refresh_token"), "R") + assert.equal(bodies[0].get("code_verifier"), "verifier") + assert.equal(bodies[1].get("grant_type"), "authorization_code") + assert.equal(bodies[1].get("code"), "CODE") + assert.equal(bodies[1].get("redirect_uri"), "http://127.0.0.1:12345/oauth/callback") +}) + +test("a credential with nothing to renew it with is a sign-in gone for good", async () => { + const cred = { ...(await makeCred()), refresh_token: undefined } + await assert.rejects(x.refreshCredential(cred, async () => { throw new Error("no network expected") }), (e) => e.signIn === "expired") +}) + +test("provider.models returns the account's live list", async () => { + const cred = await makeCred() + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: modelsFetcher([]) }) + const provider = { models: { "GLM-5.2": { name: "GLM-5.2", limit: { context: 0, output: 0 } } } } + const models = await plugin.provider.models(provider, { auth: makeAuth(cred) }) + assert.deepEqual(Object.keys(models).sort(), ["GLM-5.2", "deepseek-v4-flash-0731", "glm-5.3-flash"]) + assert.equal(models["GLM-5.2"].limit.context, 202752) + assert.equal(models["GLM-5.2"].limit.output, x.MAX_OUTPUT_TOKENS) + assert.equal(models["GLM-5.2"].free, false) + assert.equal(models["deepseek-v4-flash-0731"].free, true) +}) + +const agentList = { total: 2, agents: [{ agent_id: "a-other", original_id: "DT-Agent" }, { agent_id: "a-code-1", original_id: "CodeAgent" }] } +const agentDetail = { + gpts: { + models: [ + { model_name: "GLM-5.2", model_parameters: { model_id: "GLM-5.2", thinking_type: "enabled", context_window: 202752, max_tokens: 131072 }, credit: [{ ratio: 1, ratio_display: "1.50" }] }, + { model_name: "GLM-5.3", model_parameters: { model_id: "glm-5.3", context_window: 1048576 }, credit: { ratio_display: 0.8 } }, + { model_name: "My Own", model_type: "custom", model_parameters: { model_id: "my-own" } }, + ], + }, +} + +test("provider.models: free models once claimed, rates and parameters from the CodeAgent", async () => { + const cred = await makeCred() + const seen = [] + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: modelsFetcher(seen, { agents: agentList, detail: agentDetail }) }) + const provider = { models: {} } + const models = await plugin.provider.models(provider, { auth: makeAuth(cred) }) + assert.deepEqual(Object.keys(models).sort(), ["GLM-5.2", "deepseek-v4-flash-0731", "glm-5.3", "glm-5.3-flash"]) + // Today's benefit claimed: the gateway's models are free and carry no rate. + assert.equal(models["glm-5.3-flash"].free, true) + assert.equal(models["glm-5.3-flash"].rate, undefined) + // The rest bill credits at the agent's own rate. + assert.equal(models["GLM-5.2"].free, false) + assert.equal(models["GLM-5.2"].rate, 1.5) + assert.equal(models["GLM-5.2"].capabilities.reasoning, true) + assert.equal(models["GLM-5.2"].limit.output, x.MAX_OUTPUT_TOKENS) + // Only the agent lists it: one more model; a user's own is left out. + assert.equal(models["glm-5.3"].rate, 0.8) + assert.equal(models["glm-5.3"].limit.context, 1048576) + assert.equal(models["my-own"], undefined) + // The claim went out signed, and the detail named the CodeAgent's own id. + const claim = seen.find((s) => s.url === x.BENEFIT_CLAIM_URL) + assert.equal(claim.method, "POST") + assert.match(claim.auth, /^SDK-HMAC-SHA256 /) + assert.ok(seen.some((s) => s.url === x.AGENT_DETAIL_URL("a-code-1"))) + // Listed again the same day: no second claim, no second agent list. + await plugin.provider.models(provider, { auth: makeAuth(cred) }) + assert.equal(seen.filter((s) => s.url === x.BENEFIT_CLAIM_URL).length, 1) + assert.equal(seen.filter((s) => s.url === x.AGENT_LIST_URL).length, 1) +}) + +test("the model list comes from the main agent: original_id build, then CodeAgent, then the IDE's id", async () => { + const cred = { access_key_id: "AK", secret_access_key: "SK", security_token: "ST" } + const detailOf = (models) => new Response(JSON.stringify({ gpts: { models } }), { status: 200 }) + const glm = [{ model_name: "GLM-5.2", model_parameters: { model_id: "GLM-5.2", context_window: 1048576 }, credit: [{ ratio: 0.05, ratio_display: 0.7 }] }] + const run = async (agents, detail) => { + const asked = [] + const state = {} + const models = await x.fetchAgentModels(cred, async (url) => { + const u = String(url) + if (u === x.AGENT_LIST_URL) return agents ? new Response(JSON.stringify({ total: agents.length, agents }), { status: 200 }) : new Response("", { status: 500 }) + const id = new URL(u).searchParams.get("agent_id") + asked.push(id) + return detailOf(detail(id)) + }, state) + return { models, asked, state } + } + // The account's own agents, as the IDE lists them: the main one is "build". + const agents = [ + { agent_id: "9f0e5cb64a104dcfb4aa90dbedab7dcf", original_id: "team-leader" }, + { agent_id: "a8bcb36232554267a5142361cc25a393", original_id: "build" }, + { agent_id: "c0de", original_id: "CodeAgent" }, + ] + let r = await run(agents, (id) => (id === "a8bcb36232554267a5142361cc25a393" ? glm : [])) + assert.deepEqual(r.asked, ["a8bcb36232554267a5142361cc25a393"]) + assert.equal(r.models[0].rate, 0.7) + assert.equal(r.state.agentId, "a8bcb36232554267a5142361cc25a393") + // An agent with an empty list: the next one is asked. + r = await run(agents, (id) => (id === "c0de" ? glm : [])) + assert.deepEqual(r.asked, ["a8bcb36232554267a5142361cc25a393", "c0de"]) + // No agent list at all: the IDE's own id for the main agent. + r = await run(undefined, (id) => (id === "a8bcb36232554267a5142361cc25a393" ? glm : [])) + assert.deepEqual(r.asked, ["a8bcb36232554267a5142361cc25a393"]) + assert.equal(r.models[0].context, 1048576) +}) + +test("a benefit the account can't claim: no free models, and no benefit header", async () => { + const cred = await makeCred() + const seen = [] + const list = modelsFetcher(seen, { claim: "4004" }) + const sent = [] + const fetcher = async (url, init) => { + if (String(url) === CHAT_URL) { + sent.push(new Headers(init.headers).get("maas_type")) + return sseResponse(okStream) + } + return list(url, init) + } + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: fetcher }) + const models = await plugin.provider.models({ models: {} }, { auth: makeAuth(cred) }) + // The gateway's free-only models can't be called without the benefit. + assert.deepEqual(Object.keys(models), ["GLM-5.2"]) + const loaded = await plugin.auth.loader(async () => makeAuth(cred)) + await (await loaded.fetch(CHAT_URL, chatInit({ model: "glm-5.3-flash", messages: [] }))).text() + assert.deepEqual(sent, [null]) +}) + +test("ensureBenefitClaimed claims once a day and asks again only an hour after a refusal", async () => { + const cred = await makeCred() + let claims = 0 + let answer = "4006" + const fetcher = async () => { + claims += 1 + return new Response(JSON.stringify({ error_code: answer }), { status: 200 }) + } + const state = {} + assert.equal(await x.ensureBenefitClaimed(cred, fetcher, state), false) + answer = "0000" + assert.equal(await x.ensureBenefitClaimed(cred, fetcher, state), false) // within the hour + assert.equal(claims, 1) + state.claim.at -= 61 * 60 * 1000 + assert.equal(await x.ensureBenefitClaimed(cred, fetcher, state), true) + assert.equal(await x.ensureBenefitClaimed(cred, fetcher, state), true) + assert.equal(claims, 2) + // Unreachable: the last answer stands, nothing is cached over it. + const down = async () => { throw new Error("offline") } + assert.equal(await x.ensureBenefitClaimed(cred, down, { claim: { day: "2000-01-01", ok: true, at: 0 } }), true) +}) + +test("provider.models falls back to the catalog when unsigned", async () => { + const plugin = await CodeArtsAuthPlugin({ client: {} }, {}) + const provider = { models: { "GLM-5.2": {} } } + assert.deepEqual(await plugin.provider.models(provider, {}), provider.models) +}) + +test("auth.usage reports the plan's credit window (the free pool is best-effort)", async () => { + const cred = await makeCred() + const asked = [] + const fetcher = async (url) => { + asked.push(String(url)) + if (String(url) === x.BENEFIT_BALANCE_URL) return new Response("nope", { status: 404 }) + // The batch reads fail here: the usage read goes on without them. + if (String(url) === x.PACKAGE_CREDIT_PAGE_URL || String(url) === x.OPS_CREDIT_OVERVIEW_URL) return new Response("", { status: 500 }) + assert.ok(String(url).endsWith("/snap-manager/v1/statistics/plugin")) + return new Response(JSON.stringify({ + package: { package_name_cn: "企业版" }, + metrics: [{ name: "usageTotalPackageCredit", package_credit_amount: 1000, package_credit_remain: 400 }], + }), { status: 200 }) + } + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: fetcher }) + const usage = await plugin.auth.usage(async () => makeAuth(cred)) + assert.equal(usage.plan, "企业版") + assert.deepEqual(usage.windows, [ + { name: "总积分", used: 60, display: "600 / 1000", amount: 600, limit: 1000, unit: "credits" }, + ]) + assert.deepEqual(asked, [x.SNAP_STATISTICS_URL, x.BENEFIT_BALANCE_URL, x.PACKAGE_CREDIT_PAGE_URL, x.PACKAGE_CREDIT_PAGE_URL, x.OPS_CREDIT_OVERVIEW_URL]) + // Read again within ten minutes: the batches aren't. + await plugin.auth.usage(async () => makeAuth(cred)) + assert.equal(asked.filter((u) => u === x.OPS_CREDIT_OVERVIEW_URL).length, 1) +}) + +// ---- daily check-in ---------------------------------------------------------- + +/** A stand-in for the three ops endpoints: `state` is the USER_LOGIN item. */ +function opsFetcher(state, { claim, confirm } = {}) { + const calls = [] + const ok = (data) => new Response(JSON.stringify({ code: 0, message: "ok", data }), { status: 200 }) + const fetcher = async (url, init) => { + const u = String(url) + const headers = new Headers(init.headers) + const body = init.body ? JSON.parse(new TextDecoder().decode(init.body)) : undefined + calls.push({ url: u, method: init.method, body, headers }) + if (u === x.OPS_DELIVERY_URL) { + const items = [{ campaignId: 7, type: "INVITE_USER", claimable: false }] + if (state.item) items.push(state.item) + return state.listStatus ? new Response('{"error_code":"APIG.0301","error_msg":"verify ak sk signature fail"}', { status: state.listStatus }) : ok({ items }) + } + if (u === x.OPS_CLAIM_URL) { + if (claim) return claim(state) + state.item = { ...state.item, claimable: false, status: "CLAIMED" } + return ok({ id: 42, benefitAmount: 1000 }) + } + if (u === x.OPS_CONFIRM_URL) { + if (confirm) return confirm(state) + state.item = { ...state.item, status: "CONFIRMED" } + return ok(null) + } + throw new Error(`unexpected ${u}`) + } + return { fetcher, calls } +} + +const daily = (extra) => ({ campaignId: 1, type: "USER_LOGIN", title: "每日领取", claimable: true, status: "ENTRY", benefitAmount: 1000, ...extra }) + +test("checkin claims and confirms the daily benefit the way the IDE does", async () => { + const cred = await makeCred() + const { fetcher, calls } = opsFetcher({ item: daily() }) + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: fetcher }) + const r = await plugin.auth.checkin(async () => makeAuth(cred)) + assert.deepEqual(r, { outcome: "claimed", credit: 1000, message: "+1000 积分" }) + assert.deepEqual(calls.map((c) => [c.method, c.url]), [ + ["GET", x.OPS_DELIVERY_URL], + ["POST", x.OPS_CLAIM_URL], + ["POST", x.OPS_CONFIRM_URL], + ]) + assert.deepEqual(calls[1].body, { campaignId: 1, channel: "IDE" }) + assert.deepEqual(calls[2].body, { campaignId: 1 }) + for (const c of calls) { + const auth = c.headers.get("authorization") + assert.match(auth, /^SDK-HMAC-SHA256 Access=AK,/) + // Routing headers go along unsigned: signing them breaks the signature. + assert.equal(c.headers.get("agent-type"), "PromptCenter") + assert.equal(auth.split("SignedHeaders=")[1].split(",")[0].includes("agent-type"), false) + } + // Asked again the same day: in already, and nothing is claimed twice. + const again = await plugin.auth.checkin(async () => makeAuth(cred)) + assert.equal(again.outcome, "done") + assert.equal(calls.filter((c) => c.url === x.OPS_CLAIM_URL).length, 1) +}) + +test("a claimed check-in is kept, and the usage card says when those credits run out", async () => { + const cred = await makeCred() + const ledgerPath = path.join(ledgerDir, "integrated.json") + const ops = opsFetcher({ item: daily() }) + const fetcher = async (url, init) => { + if (String(url).endsWith("/snap-manager/v1/statistics/plugin")) { + return new Response(JSON.stringify({ + metrics: [ + { name: "usageTotalPackageCredit", package_credit_amount: 6500, package_credit_remain: 6500 }, + { name: "usageBonusPackageCredit", package_credit_amount: 1000, package_credit_remain: 1000 }, + ], + }), { status: 200 }) + } + if (String(url) === x.BENEFIT_BALANCE_URL) return new Response("", { status: 404 }) + return ops.fetcher(url, init) + } + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: fetcher, ledgerPath }) + const r = await plugin.auth.checkin(async () => makeAuth(cred)) + assert.equal(r.outcome, "claimed") + assert.equal("grant" in r, false) + const kept = JSON.parse(fs.readFileSync(ledgerPath, "utf8")) + const [grant] = Object.values(kept)[0] + assert.equal(grant.credit, 1000) + assert.equal(Date.parse(grant.expiresAt) - Date.parse(grant.at), 30 * 86_400_000) + + const usage = await plugin.auth.usage(async () => makeAuth(cred)) + const bonus = usage.windows.find((w) => w.name === "赠送积分包") + assert.equal(bonus.runsOutAt, grant.expiresAt) + assert.equal(bonus.runsOut, 1000) +}) + +test("grantExpiry takes the vendor's date when the claim gives one", () => { + const at = Date.parse("2026-10-21T00:00:00Z") + assert.equal(x.grantExpiry({}, at), at + 30 * 86_400_000) + assert.equal(x.grantExpiry({ expire_time: "2026-11-15 00:00:00" }, at), Date.parse("2026-11-14T16:00:00Z")) +}) + +test("checkin skips the confirm when the claim answers no id", async () => { + const cred = await makeCred() + const ok = (data) => new Response(JSON.stringify({ code: 0, data }), { status: 200 }) + const { fetcher, calls } = opsFetcher({ item: daily() }, { claim: () => ok({ id: null }) }) + const { grant, ...r } = await x.dailyCheckin(cred, fetcher) + assert.deepEqual(r, { outcome: "claimed", credit: 1000, message: "+1000 积分" }) + assert.equal(grant.credit, 1000) + assert.equal(calls.some((c) => c.url === x.OPS_CONFIRM_URL), false) +}) + +test("checkin tells done, inactive and ineligible apart", async () => { + const cred = await makeCred() + for (const status of ["CLAIMED", "CONFIRMED", "CONSUMED"]) { + const { fetcher, calls } = opsFetcher({ item: daily({ claimable: false, status }) }) + assert.equal((await x.dailyCheckin(cred, fetcher)).outcome, "done") + assert.equal(calls.length, 1) + } + assert.equal((await x.dailyCheckin(cred, opsFetcher({}).fetcher)).outcome, "inactive") + const ineligible = await x.dailyCheckin(cred, opsFetcher({ item: daily({ claimable: false, status: null }) }).fetcher) + assert.equal(ineligible.outcome, "ineligible") +}) + +test("checkin looks again after a refused claim, and reports a real failure", async () => { + const cred = await makeCred() + const refused = (s) => { + s.item = { ...s.item, claimable: false, status: "CLAIMED" } // claimed elsewhere meanwhile + return new Response(JSON.stringify({ code: 1001, message: "already claimed" }), { status: 200 }) + } + assert.equal((await x.dailyCheckin(cred, opsFetcher({ item: daily() }, { claim: refused }).fetcher)).outcome, "done") + + const boom = () => new Response(JSON.stringify({ code: 500, message: "活动太火爆" }), { status: 200 }) + const failed = await x.dailyCheckin(cred, opsFetcher({ item: daily() }, { claim: boom }).fetcher) + assert.deepEqual(failed, { outcome: "failed", message: "领取失败:活动太火爆" }) + + const listFailed = await x.dailyCheckin(cred, opsFetcher({ item: daily(), listStatus: 401 }).fetcher) + assert.equal(listFailed.outcome, "failed") + assert.match(listFailed.message, /HTTP 401: APIG\.0301/) +}) + +test("checkin without a sign-in fails without calling the vendor", async () => { + const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: async () => { throw new Error("no network") } }) + assert.deepEqual(await plugin.auth.checkin(async () => ({ type: "api", key: "k" })), { outcome: "failed", message: "not signed in" }) +}) + +// ---- OAuth callback server ------------------------------------------------- + +test("startOAuthFlow serves a callback server and a valid login URL", async () => { + const flow = await x.startOAuthFlow(async () => new Response("", { status: 200 })) + const url = new URL(flow.loginUrl) + assert.equal(url.origin + url.pathname, "https://codearts.huaweicloud.com/portal/authorize") + const port = Number(url.searchParams.get("port")) + assert.ok(port >= 10000, "callback port must be >= 10000") + + // A callback without a code is rejected. + const res = await fetch(`http://127.0.0.1:${port}/oauth/callback`) + assert.equal(res.status, 400) + + await flow.close() +}) + +/** Run a callback server for one test, its STS answered by `sts`. */ +async function withCallbackServer(sts, run) { + const pkce = await x.generatePkcePair() + const keyPair = await x.generateDpopKeyPair() + const exchanges = [] + const fetcher = async (url, init) => { + exchanges.push(new URLSearchParams(init.body)) + return sts() + } + const { port, server, result } = await x.startOAuthCallbackServer("ticket", pkce, keyPair, fetcher) + result.catch(() => {}) + const call = (query = "", init = {}) => + fetch(`http://127.0.0.1:${port}${x.REDIRECT_PATH}${query}`, { redirect: "manual", ...init }) + try { + await run({ port, call, result, exchanges, pkce }) + } finally { + server.closeAllConnections?.() + await new Promise((resolve) => server.close(() => resolve())) + } +} + +test("the callback server takes only a GET with a code, and never a redirect it is handed", async () => { + await withCallbackServer(() => new Response(stsBody("AK", "R"), { status: 200 }), async ({ port, call, exchanges }) => { + const post = await call("?code=C", { method: "POST" }) + assert.equal(post.status, 405) + assert.equal(post.headers.get("allow"), "GET") + // The old login's parameters are no way in: no code, no exchange, no redirect. + const legacy = await call(`?secret=${encodeURIComponent('{"access":"AK"}')}&redirect=${encodeURIComponent("https://evil.example/")}`) + assert.equal(legacy.status, 400) + assert.equal(legacy.headers.get("location"), null) + const elsewhere = await fetch(`http://127.0.0.1:${port}/other?code=C`, { redirect: "manual" }) + assert.equal(elsewhere.status, 404) + assert.equal(exchanges.length, 0) + }) +}) + +test("the callback server exchanges the code once, then sends the browser to the portal's result page", async () => { + await withCallbackServer(() => new Response(stsBody("AK", "R"), { status: 200 }), async ({ port, call, result, exchanges, pkce }) => { + const res = await call(`?code=C1&redirect=${encodeURIComponent("https://evil.example/")}`) + assert.equal(res.status, 307) + assert.equal(res.headers.get("location"), x.buildPortalLoginResultUrl(true)) + const signedIn = await result + const cred = JSON.parse(signedIn.access) + assert.equal(cred.access_key_id, "AK") + assert.equal(cred.code_verifier, pkce.codeVerifier) + assert.equal(exchanges.length, 1) + assert.equal(exchanges[0].get("code"), "C1") + assert.equal(exchanges[0].get("redirect_uri"), `http://127.0.0.1:${port}${x.REDIRECT_PATH}`) + // A second callback for the same sign-in is refused, and not exchanged. + const again = await call("?code=C2") + assert.equal(again.status, 409) + assert.equal(exchanges.length, 1) + }) +}) + +test("a code STS turns down sends the browser to the portal's failure page", async () => { + await withCallbackServer(() => new Response('{"error":"invalid_grant"}', { status: 400 }), async ({ call, result }) => { + const res = await call("?code=BAD") + assert.equal(res.status, 307) + assert.equal(res.headers.get("location"), x.buildPortalLoginResultUrl(false)) + await assert.rejects(result, /token request failed: 400/) + }) +}) diff --git a/packages/codearts/package.json b/packages/codearts/package.json new file mode 100644 index 0000000..8f7b41c --- /dev/null +++ b/packages/codearts/package.json @@ -0,0 +1,34 @@ +{ + "name": "@magpie-community/opencode-codearts-auth", + "version": "0.2.0", + "description": "Huawei Cloud CodeArts (码道) in OpenCode and magpie: its models through Huawei Cloud OAuth sign-in, signed requests, credit usage and the daily check-in (unofficial)", + "type": "module", + "main": "./index.mjs", + "exports": "./index.mjs", + "files": [ + "index.mjs", + "README.md", + "LICENSE" + ], + "scripts": { + "test": "bun test" + }, + "keywords": [ + "opencode", + "opencode-plugin", + "magpie", + "codearts", + "huaweicloud", + "oauth" + ], + "license": "MIT", + "repository": { + "type": "git", + "url": "git+https://github.com/magpie-community/plugins.git", + "directory": "packages/codearts" + }, + "magpie": { + "maxConcurrency": 3, + "icon": "data:image/svg+xml;base64,PHN2ZyBmaWxsPSIjQ0YwQTJDIiByb2xlPSJpbWciIHZpZXdCb3g9IjAgMCAyNCAyNCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48dGl0bGU+SHVhd2VpPC90aXRsZT48cGF0aCBkPSJNMy42NyA2LjE0UzEuODIgNy45MSAxLjcyIDkuNzh2LjM1Yy4wOCAxLjUxIDEuMjIgMi40IDEuMjIgMi40IDEuODMgMS43OSA2LjI2IDQuMDQgNy4zIDQuNTUgMCAwIC4wNi4wMy4xLS4wMWwuMDItLjA0di0uMDRDNy41MiAxMC44IDMuNjcgNi4xNCAzLjY3IDYuMTR6TTkuNjUgMTguNmMtLjAyLS4wOC0uMS0uMDgtLjEtLjA4bC03LjM4LjI2Yy44IDEuNDMgMi4xNSAyLjUzIDMuNTYgMi4yLjk2LS4yNSAzLjE2LTEuNzggMy44OC0yLjMuMDYtLjA1LjA0LS4wOS4wNC0uMDl6bS4wOC0uNzhDNi40OSAxNS42My4yMSAxMi4yOC4yMSAxMi4yOGMtLjE1LjQ2LS4yLjktLjIxIDEuM3YuMDdjMCAxLjA3LjQgMS44Mi40IDEuODIuOCAxLjY5IDIuMzQgMi4yIDIuMzQgMi4yLjcuMyAxLjQuMzEgMS40LjMxLjEyLjAyIDQuNCAwIDUuNTQgMCAuMDUgMCAuMDgtLjA1LjA4LS4wNXYtLjA2YzAtLjAzLS4wMy0uMDUtLjAzLS4wNXpNOS4wNiAzLjE5YTMuNDIgMy40MiAwIDAwLTIuNTcgMy4xNXYuNDFjLjAzLjYuMTYgMS4wNS4xNiAxLjA1LjY2IDIuOSAzLjg2IDcuNjUgNC41NSA4LjY1LjA1LjA1LjEuMDMuMS4wM2EuMS4xIDAgMDAuMDYtLjFjMS4wNi0xMC42LTEuMTEtMTMuNDItMS4xMS0xMy40Mi0uMzIuMDItMS4xOS4yMy0xLjE5LjIzem04LjI5OSAyLjI3cy0uNDktMS44LTIuNDQtMi4yOGMwIDAtLjU3LS4xNC0xLjE3LS4yMiAwIDAtMi4xOCAyLjgxLTEuMTIgMTMuNDMuMDEuMDcuMDYuMDguMDYuMDguMDcuMDMuMS0uMDMuMS0uMDMuNzItMS4wMyAzLjktNS43NiA0LjU1LTguNjQgMCAwIC4zNi0xLjQuMDItMi4zNHptLTIuOTIgMTMuMDdzLS4wNyAwLS4wOS4wNWMwIDAtLjAxLjA3LjAzLjEuNy41MSAyLjg1IDIgMy44OCAyLjMgMCAwIC4xNi4wNS40My4wNmguMTRjLjY5LS4wMiAxLjktLjM3IDMtMi4yNmwtNy40LS4yNXptNy44My04LjQxYy4xNC0yLjA2LTEuOTQtMy45Ny0xLjk0LTMuOTggMCAwLTMuODUgNC42Ni02LjY3IDEwLjggMCAwLS4wMy4wOC4wMi4xM2wuMDQuMDFoLjA2YzEuMDYtLjUzIDUuNDYtMi43NyA3LjI4LTQuNTQgMCAwIDEuMTUtLjkzIDEuMjEtMi40MnptMS41MiAyLjE0cy02LjI4IDMuMzctOS41MiA1LjU1YzAgMC0uMDUuMDQtLjAzLjExIDAgMCAuMDMuMDYuMDcuMDYgMS4xNiAwIDUuNTYgMCA1LjY3LS4wMiAwIDAgLjU3LS4wMiAxLjI3LS4yOSAwIDAgMS41Ni0uNSAyLjM3LTIuMjcgMCAwIC43My0xLjQ1LjE3LTMuMTR6Ii8+PC9zdmc+" + } +} diff --git a/registry.json b/registry.json index af14824..0c9b628 100644 --- a/registry.json +++ b/registry.json @@ -38,6 +38,8 @@ "summary": { "en": "SenseTime Raccoon (xiaohuanxiong.com) models, account credits and daily check-in, with browser sign-in or Raccoon desktop's live sign-in.", "zh": "商汤小浣熊(xiaohuanxiong.com)模型、积分余额与每日签到,支持浏览器登录或直接复用小浣熊桌面端登录态。" } }, { "package": "@magpie-community/opencode-autoclaw-auth", "name": "AutoClaw", "providers": ["autoclaw", "autoclaw-cn"], "community": true, "summary": { "en": "AutoClaw (Zhipu OpenClaw) cloud accounts: oversea web sign-in (Google/z.ai) or CN phone SMS, credit balance and daily check-in.", "zh": "AutoClaw(智谱澳龙/OpenClaw)云端账号:国际版网页登录(Google/z.ai)或国内手机验证码,积分余额与每日签到。" } }, + { "package": "@magpie-community/opencode-codearts-auth", "name": "CodeArts", "providers": ["codearts"], "community": true, + "summary": { "en": "Unofficial: Huawei Cloud CodeArts (码道) coding plans with Huawei Cloud OAuth sign-in — GLM, DeepSeek, openPangu, live models and credit rates, credit usage and daily check-in.", "zh": "非官方:华为云码道(CodeArts)编码套餐,华为云 OAuth 登录;GLM、DeepSeek、openPangu 等模型,实时模型与积分倍率、积分用量和每日签到。" } }, { "package": "@magpie-community/middleware-param-override", "name": "Param Override", "kind": "middleware", "community": true, "summary": { "en": "New API's parameter override: set, delete, move or rewrite fields of every request, by model or by condition.", "zh": "New API 的参数覆盖:按模型或条件设置、删除、移动或改写每个请求的字段。" } }, { "package": "@magpie-community/middleware-model-map", "name": "Model Map", "kind": "middleware", "community": true,