loomy: add the iFlytek Loomy plugin (#175)
Adds packages/loomy (iFlytek Loomy): SMS sign-in, paste-a-session sign-in, models, chat, daily wallet usage and check-in. Hosts: account.xfinfr.com and loomyad.xunfei.cn only; no dependencies or scripts.
Answers the 10-17 review: the paste method now returns { url, instructions, method, callback } as internal/plugin/host.js calls it; the limit/remaining pair alone renders the daily wallet; a failed pre-check-in read reports failed instead of refreshing.
Run at fd963f1 (PR head 836ed7b with origin/main merged; registry.json conflict resolved keeping both entries), on mote with a sandbox HOME:
- bun test packages/loomy: 18 pass, 0 fail
- bun scripts/check.mjs: exit 0 (loomy ✓); bun test scripts: 3 pass, 0 fail
- Broken by hand, each red then restored: paste callback reverted (1 fail), pairPresent removed (1 fail), pre-read failure reverted (1 fail)
Not tried: a real Loomy account. Not on npm yet: served from the dist branch until the first version is published by hand.
This commit is contained in:
@@ -23,6 +23,7 @@ subscription and makes its requests. The packages work in OpenCode and in
|
||||
| [joycode](packages/joycode) | JoyCode IDE credits with JD account browser sign-in, live models and credit multipliers (unofficial) | `joycode` |
|
||||
| [kimi-work](packages/kimi-work) | Ordinary Kimi desktop Work subscription, through the desktop app's local sign-in; separate from Kimi Code | `kimi-work` |
|
||||
| [kiro](packages/kiro) | Kiro (Free, Pro, Pro+, Power), with Kiro's sign-in, kiro-cli's or the IDE's, or an API key | `kiro` |
|
||||
| [loomy](packages/loomy) | iFlytek's Loomy (loomyad.xunfei.cn), with SMS sign-in | `loomy` |
|
||||
| [minimax](packages/minimax) | MiniMax Code (China): account credits and M Plan, with MiniMax Code's device sign-in | `minimax-code` |
|
||||
| [minimax](packages/minimax) | MiniMax Code (international): account credits and M Plan, with MiniMax Code's device sign-in | `minimax-code-global` |
|
||||
| [mimo](packages/mimo) | Xiaomi MiMo, with a Xiaomi account | `mimo-app` |
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
# @magpie-community/opencode-loomy-auth
|
||||
|
||||
[OpenCode](https://opencode.ai) / [magpie](https://usemagpie.ai) provider 插件:**Loomy(讯飞,`loomyad.xunfei.cn`)**——登录、模型清单、聊天转发、双积分钱包与每日赠送积分刷新(签到)。
|
||||
|
||||
请求形态移植自 [aimod-cc/agent2api](https://github.com/aimod-cc/agent2api)(MIT)的 `providers/loomy`,按 magpie 插件 API 重写。
|
||||
|
||||
## 安装
|
||||
|
||||
```
|
||||
magpie plugin add @magpie-community/opencode-loomy-auth
|
||||
magpie plugin login loomy # 选「短信验证码登录」或「手动粘贴 session」
|
||||
```
|
||||
|
||||
## 能力
|
||||
|
||||
- **登录**:`短信验证码登录`(发码 → 输入 6 位码完成,session **14 天**)或 `手动粘贴 session`。
|
||||
- **无续期接口**:session 过期(业务码 `020002`/`100002`)需重新登录(短信或粘贴)。
|
||||
- **聊天**:`POST {modelBase}/chat/completions`,OpenAI 形态基本透传,两处适配(参照实现 `reasoning_patch` / `images.rs`):思考档折进 low/medium/high(超档删除)、DeepSeek 系模型的 data-URI 图片转 `<image_base64>` 标记;SSE;请求头必须带 `charset=utf-8`(上游对无 charset 的 body 按 GBK 解码)。
|
||||
- **模型**:登录前给静态表(2026-10-16 实抓 `/api/v1/models` 的 chat 模型:DeepSeek-V4.1-Flash / deepseek-v4-flash-0731 / MiniMax-M3 / Kimi-k2.6 / qwen-3.8-max / GLM-5.3-Flash / qwen3.8-flash / spark-x / mimo-v2.5 / auto),登录后以 `GET /api/v1/models` 的实时目录为准(能力位读 `capabilities`;展示名尾部倍率 `(x3.0)` 拆为 rate 字段)。
|
||||
- **余额(usage)**:`GET /api/v2/points/records?...` → 永久积分 + 每日赠送积分两个窗口;每日窗口用厂商自己的 `dailyLimitPoints`/`dailyRemainingPoints` 报「已用/剩余/上限」,厂商未带这一对时按无上限的余额展示(不编造上限)。响应缺余额字段时报 error("未知"不冒充 0)。
|
||||
- **签到判定**:`first-login` 接口对"当天首登"与"重复调用"都返回成功,插件用调用前后的每日余额差判定——涨了 = `claimed`(今日首登奖励),没涨 = `done`(已领过/无每日钱包)。
|
||||
- **每日签到(checkin)**:`POST /api/v1/points/first-login`(body `{}`)——服务端按"当天是否第一次"把每日赠送刷回;按天幂等,重复调=成功。这是厂商客户端自己就会发的那个单请求(判定见上)。
|
||||
|
||||
## 账号域签名说明
|
||||
|
||||
登录两步(`POST https://account.xfinfr.com/login/phone/{sendMsgCode,checkCode}`)带 HMAC-SHA1 签名头(9 段待签串,AK/SK 为客户端内置常量),插件按参照实现同款实现(见 `index.mjs` 的 `signHeaders`)。
|
||||
|
||||
## 环境变量(测试 / 镜像用,与 agent2api 同名)
|
||||
|
||||
| 变量 | 默认 |
|
||||
|---|---|
|
||||
| `LOOMY_XFYUN_BASE_URL` | `https://account.xfinfr.com`(登录域,HMAC 签名;来自客户端安装包 `app.asar` 内解密的 `.env.prod` 的 `VITE_XFYUN_BASE_URL`,是讯飞账号域 CAccount 自己的 host) |
|
||||
| `LOOMY_POINTS_BASE_URL` | `https://loomyad.xunfei.cn`(积分/签到/模型网关) |
|
||||
|
||||
## 测试
|
||||
|
||||
```
|
||||
bun test packages/loomy
|
||||
```
|
||||
|
||||
测试打到本地假上游(`fake.mjs`),不触网、不使用真实 token。
|
||||
|
||||
## 许可
|
||||
|
||||
MIT。请求逻辑移植自 aimod-cc/agent2api(MIT)。
|
||||
@@ -0,0 +1,171 @@
|
||||
// the fake Loomy upstream: the account domain (HMAC-signed SMS login) and
|
||||
// the integration gateway (models, chat, points, first-login) on local ports.
|
||||
|
||||
import { createHash, createHmac } from "node:crypto"
|
||||
|
||||
const json = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } })
|
||||
const OK = "000000"
|
||||
|
||||
// the client's TASK_POINTS registry, key by key (the server knows these and
|
||||
// refuses anything else)
|
||||
const TASK_POINTS = {
|
||||
first_message: 500,
|
||||
pick_skill: 1000,
|
||||
generate_ppt: 1500,
|
||||
set_schedule: 1000,
|
||||
install_skill: 1500,
|
||||
configure_remote: 1000,
|
||||
create_soul: 1500,
|
||||
share_soul: 2000,
|
||||
}
|
||||
|
||||
export function fakeLoomy() {
|
||||
const state = {
|
||||
session: "sess-1",
|
||||
phone: "13800138000",
|
||||
smsSent: null, // {phone, msgid}
|
||||
logins: 0,
|
||||
chatCalls: [],
|
||||
firstLoginCalls: 0,
|
||||
dailyBalance: 3000, // the day's first first-login refreshes it to 5000
|
||||
recordsReads: 0,
|
||||
modelsReads: 0,
|
||||
// onboarding: done[key]=true once its complete call lands (idempotent)
|
||||
onboardingDone: {},
|
||||
onboardingQueries: 0,
|
||||
onboardingCompletes: 0,
|
||||
reset() {
|
||||
state.smsSent = null
|
||||
state.logins = 0
|
||||
state.chatCalls = []
|
||||
state.firstLoginCalls = 0
|
||||
state.dailyBalance = 3000
|
||||
state.recordsReads = 0
|
||||
state.modelsReads = 0
|
||||
state.onboardingDone = {}
|
||||
state.onboardingQueries = 0
|
||||
state.onboardingCompletes = 0
|
||||
},
|
||||
}
|
||||
const AK = "2thryby66wxi53sk"
|
||||
const SK = "zsak6eadrbawz683wf5r3m2snrwj868r"
|
||||
|
||||
// the account domain: every request must carry the client's HMAC-SHA1
|
||||
// signature over the 9-part string, as the real one checks
|
||||
const account = Bun.serve({
|
||||
port: 0,
|
||||
async fetch(req) {
|
||||
const url = new URL(req.url)
|
||||
const bodyString = await req.text()
|
||||
const auth = req.headers.get("authorization") ?? ""
|
||||
if (!auth.startsWith(`account ${AK}:`)) return json(401, { code: "020002", desc: "no signature" })
|
||||
// re-sign what arrived and compare: path, date, nonce, md5 all take part
|
||||
const path = url.pathname
|
||||
let clean = path.startsWith("/") ? path : `/${path}`
|
||||
if (clean.length > 1 && clean.endsWith("/")) clean = clean.slice(0, -1)
|
||||
const escaped = clean.split("/").map((s) => encodeURIComponent(s)).join("/")
|
||||
const md5 = bodyString ? createHash("md5").update(bodyString).digest("base64") : ""
|
||||
const date = req.headers.get("date") ?? ""
|
||||
const nonce = req.headers.get("nonce") ?? ""
|
||||
const stringToSign = ["POST", escaped, "", md5, "application/json", date, nonce, "", ""].join("\n")
|
||||
const expect = createHmac("sha1", SK).update(stringToSign).digest("base64")
|
||||
if (auth !== `account ${AK}:${expect}`) return json(401, { code: "020002", desc: "bad signature" })
|
||||
if (md5 && req.headers.get("content-md5") !== md5) return json(400, { code: "020003", desc: "md5 mismatch" })
|
||||
|
||||
const body = JSON.parse(bodyString || "{}")
|
||||
if (url.pathname === "/login/phone/sendMsgCode") {
|
||||
if (body?.param?.ccode !== "86") return json(400, { code: "020004", desc: "ccode" })
|
||||
if (body?.param?.phone !== state.phone) return json(400, { code: "020005", desc: "phone" })
|
||||
const msgid = `msg-${Date.now()}`
|
||||
state.smsSent = { phone: body.param.phone, msgid }
|
||||
return json(200, { code: OK, desc: "sent", data: { msgid } })
|
||||
}
|
||||
if (url.pathname === "/login/phone/checkCode") {
|
||||
if (!state.smsSent || body?.param?.msgid !== state.smsSent.msgid) return json(400, { code: "020006", desc: "msgid" })
|
||||
if (body?.param?.mcode !== "123456") return json(400, { code: "020007", desc: "wrong code" })
|
||||
state.logins++
|
||||
state.session = `sess-${state.logins}`
|
||||
return json(200, { code: OK, desc: "ok", data: { session: state.session, userid: "261014155255771375" } })
|
||||
}
|
||||
return json(404, { code: "020008", desc: "no route" })
|
||||
},
|
||||
})
|
||||
|
||||
// the integration gateway: double auth headers on everything
|
||||
const gateway = Bun.serve({
|
||||
port: 0,
|
||||
async fetch(req) {
|
||||
const url = new URL(req.url)
|
||||
const token = req.headers.get("token") ?? ""
|
||||
const bearer = (req.headers.get("authorization") ?? "").replace(/^Bearer\s+/i, "")
|
||||
if (token !== state.session || bearer !== state.session) return json(401, { code: "100002", desc: "session refused" })
|
||||
|
||||
if (url.pathname === "/api/v1/models") {
|
||||
state.modelsReads++
|
||||
return json(200, {
|
||||
data: [
|
||||
{ id: "spark-x", name: "Spark X2.5 (x0.1)", capabilities: { reasoning: true, function_calling: true, vision: false }, context_window: 128000, max_tokens: 8192 },
|
||||
{ id: "deepseek-v4-flash", name: "DeepSeek V4 Flash 0731 (x3.0)", capabilities: { reasoning: true, function_calling: false, vision: true } },
|
||||
{ id: "glm-5.3-flash", name: "GLM 5.3 Flash(x0.8)", capabilities: { reasoning: false, function_calling: false, vision: true } },
|
||||
{ id: "plain", name: "No Suffix At All", capabilities: {} },
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
if (url.pathname === "/api/v1/chat/completions") {
|
||||
// charset=utf-8 is load-bearing: without it the real upstream reads
|
||||
// the body as GBK; the fake checks it is sent
|
||||
const ct = req.headers.get("content-type") ?? ""
|
||||
if (!/charset\s*=\s*"?utf-8/i.test(ct)) return json(400, { code: "100009", desc: "content-type must name utf-8" })
|
||||
const body = await req.json().catch(() => ({}))
|
||||
state.chatCalls.push({ body })
|
||||
const reply = body.stream
|
||||
? new Response(
|
||||
[
|
||||
`data: ${JSON.stringify({ id: "c1", model: body.model, choices: [{ index: 0, delta: { role: "assistant", content: "你" } }] })}\n\n`,
|
||||
`data: ${JSON.stringify({ id: "c1", model: body.model, choices: [{ index: 0, delta: { content: "好" } }] })}\n\n`,
|
||||
`data: ${JSON.stringify({ id: "c1", model: body.model, choices: [{ index: 0, delta: {}, finish_reason: "stop" }] })}\n\n`,
|
||||
"data: [DONE]\n\n",
|
||||
].join(""),
|
||||
{ headers: { "content-type": "text/event-stream" } },
|
||||
)
|
||||
: json(200, { id: "c1", model: body.model, choices: [{ index: 0, message: { role: "assistant", content: "你好" }, finish_reason: "stop" }] })
|
||||
return reply
|
||||
}
|
||||
|
||||
if (url.pathname === "/api/v1/points/first-login") {
|
||||
state.firstLoginCalls++
|
||||
// the vendor's own semantics: the day's first call refreshes the
|
||||
// daily wallet (up), a repeat answers success with no change (flat)
|
||||
if (state.firstLoginCalls === 1) state.dailyBalance = 5000
|
||||
return json(200, { code: OK, desc: "ok", data: { dailyBalance: state.dailyBalance } })
|
||||
}
|
||||
|
||||
if (url.pathname === "/api/v2/points/records") {
|
||||
state.recordsReads++
|
||||
return json(200, { code: OK, desc: "ok", data: { balance: 5000, dailyBalance: state.dailyBalance, dailyLimitPoints: 5000, dailyRemainingPoints: state.dailyBalance, list: [], total: 0 } })
|
||||
}
|
||||
|
||||
// onboarding: the task status table and the per-key completion report
|
||||
// (the report carries no proof; the real vendor credits real points and
|
||||
// answers alreadyCompleted=true idempotently)
|
||||
if (url.pathname === "/api/v1/onboarding/tasks") {
|
||||
state.onboardingQueries++
|
||||
return json(200, { code: OK, desc: "ok", data: { tasks: { ...state.onboardingDone } } })
|
||||
}
|
||||
if (url.pathname === "/api/v1/onboarding/tasks/complete") {
|
||||
state.onboardingCompletes++
|
||||
const reqBody = await req.json().catch(() => ({}))
|
||||
const key = String(reqBody?.key ?? "")
|
||||
if (!key || !(key in TASK_POINTS)) return json(200, { code: "100001", desc: `未知的 task key:${key}` })
|
||||
const already = !!state.onboardingDone[key]
|
||||
state.onboardingDone[key] = true
|
||||
return json(200, { code: OK, desc: "ok", data: { alreadyCompleted: already } })
|
||||
}
|
||||
|
||||
return json(404, { code: "100003", desc: "no route" })
|
||||
},
|
||||
})
|
||||
|
||||
return { account, gateway, state, accountUrl: `http://127.0.0.1:${account.port}`, gatewayUrl: `http://127.0.0.1:${gateway.port}` }
|
||||
}
|
||||
@@ -0,0 +1,543 @@
|
||||
// @magpie-community/opencode-loomy-auth — the Loomy (讯飞) provider plugin
|
||||
// for OpenCode and magpie.
|
||||
//
|
||||
// Signs in with a Loomy account (SMS code or a pasted session), forwards
|
||||
// chat completions to its OpenAI-compatible model gateway, lists its models,
|
||||
// reads its two point wallets, and presses its daily first-login grant (the
|
||||
// 每日赠送积分 refresh). Request shapes are ported from aimod-cc/agent2api
|
||||
// (MIT), providers/loomy, rewritten for magpie's plugin API.
|
||||
|
||||
import { createHash, createHmac, randomUUID } from "node:crypto"
|
||||
|
||||
const ID = "loomy"
|
||||
const NAME = "Loomy(讯飞)"
|
||||
|
||||
// the three planes (agent2api endpoints.rs; env-overridable the same way)
|
||||
const env = (name, fallback) => {
|
||||
const v = process.env[name]?.trim()
|
||||
return v ? v.replace(/\/+$/, "") : fallback
|
||||
}
|
||||
const integrationBase = () => env("LOOMY_POINTS_BASE_URL", "https://loomyad.xunfei.cn")
|
||||
// the account host is the Loomy client's own CAccount domain: it comes from
|
||||
// the install package's encrypted .env.prod (VITE_XFYUN_BASE_URL, unpacked
|
||||
// from app.asar with the client's own env-file-crypto.js) — xfinfr.com is
|
||||
// xfyun's account infrastructure, not a third-party host (reference
|
||||
// endpoints.rs, itself sourced from the installed client)
|
||||
const xfyunBase = () => env("LOOMY_XFYUN_BASE_URL", "https://account.xfinfr.com")
|
||||
const accessKeyId = () => env("LOOMY_XFYUN_ACCESS_KEY_ID", "2thryby66wxi53sk")
|
||||
const accessKeySecret = () => env("LOOMY_XFYUN_ACCESS_KEY_SECRET", "zsak6eadrbawz683wf5r3m2snrwj868r")
|
||||
const appId = () => env("LOOMY_XFYUN_APP_ID", "GM3LOOMY")
|
||||
const modelBase = () => `${integrationBase()}/api/v1`
|
||||
|
||||
// business codes (agent2api client.rs): 000000 ok; 020002/100002 sign-in gone
|
||||
const OK = "000000"
|
||||
const AUTH_CODES = new Set(["020002", "100002"])
|
||||
|
||||
const REQUEST_TIMEOUT = 20_000
|
||||
|
||||
|
||||
// the chat models the live /api/v1/models returned on 2026-10-16 (the image
|
||||
// models are served through the same gateway too, but only chat models
|
||||
// register as provider models). The live list replaces or extends this —
|
||||
// entries here only make the picker usable before the first sign-in.
|
||||
const STATIC_MODELS = {
|
||||
"DeepSeek-V4.1-Flash": { name: "DeepSeek V4.1 Flash (x2.0)", limit: { context: 1_048_576, output: 384_000 } },
|
||||
"deepseek-v4-flash-0731": { name: "DeepSeek V4 Flash 0731 (x3.0)", limit: { context: 1_048_576, output: 384_000 } },
|
||||
"MiniMax-M3": { name: "MiniMax M3 (x4.0)", limit: { context: 1_048_576, output: 512_000 } },
|
||||
"Kimi-k2.6": { name: "Kimi k2.6 (x6.5)", limit: { context: 262_144, output: 65_536 } },
|
||||
"qwen-3.8-max": { name: "Qwen 3.8 Max (x12.0)", limit: { context: 1_000_000, output: 65_536 } },
|
||||
"GLM-5.3-Flash": { name: "GLM 5.3 Flash (x0.8)", limit: { context: 1_048_576, output: 131_072 } },
|
||||
"qwen3.8-flash": { name: "qwen 3.8 flash (x0.8)", limit: { context: 1_000_000, output: 131_072 } },
|
||||
"spark-x": { name: "Spark-X2.5 (限时免费) (x0.0)", limit: { context: 1_048_576, output: 65_536 } },
|
||||
"mimo-v2.5": { name: "MiMo V2.5 (x3.3)", limit: { context: 1_048_576, output: 131_072 } },
|
||||
auto: { name: "自动 · 均衡" },
|
||||
}
|
||||
|
||||
// the client's _makeBase() envelope for the account domain
|
||||
const makeBase = () => ({
|
||||
appid: appId(),
|
||||
modelid: "Web",
|
||||
version: "1.0.0",
|
||||
devid: "web",
|
||||
ua: "Loomy|Desktop|Electron|macOS",
|
||||
traceid: [...createHash("md5").update(randomUUID()).digest().slice(0, 16)].map((b) => b.toString(16).padStart(2, "0")).join(""),
|
||||
})
|
||||
|
||||
// ── small helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
const toNum = (v) => {
|
||||
const n = typeof v === "number" ? v : typeof v === "string" && v.trim() ? Number(v) : NaN
|
||||
return Number.isFinite(n) ? n : null
|
||||
}
|
||||
const codeOf = (payload) => String(payload?.code ?? "").trim()
|
||||
const messageOf = (payload) => String(payload?.desc ?? payload?.message ?? "").trim()
|
||||
|
||||
const beijingMidnight = () => Math.floor((Date.now() + 8 * 3600e3) / 86400e3) * 86400e3 + 86400e3 - 8 * 3600e3
|
||||
|
||||
class SignedOut extends Error {}
|
||||
const expired = (message) => Object.assign(new Error(message), { signIn: "expired" })
|
||||
|
||||
const errorResponse = (status, message) =>
|
||||
new Response(JSON.stringify({ error: { message } }), { status, headers: { "content-type": "application/json" } })
|
||||
|
||||
async function bodyText(input, init) {
|
||||
const b = init.body ?? (input instanceof Request ? await input.clone().text() : undefined)
|
||||
return typeof b === "string" ? b : new TextDecoder().decode(b)
|
||||
}
|
||||
|
||||
// ── the account domain's HMAC-SHA1 signature (agent2api sign.rs, itself a
|
||||
// copy of the client's electron/xfyun/sign.js). Nine parts, \n-joined; the
|
||||
// last two (signed headers, canonicalized headers) are always empty here.
|
||||
// This is client-fingerprint reproduction, not a security boundary.
|
||||
|
||||
function escapeSegment(segment) {
|
||||
return encodeURIComponent(segment).replace(/[!'()*]/g, (ch) => "%" + ch.charCodeAt(0).toString(16).toUpperCase())
|
||||
}
|
||||
function escapedPath(path) {
|
||||
let clean = path.startsWith("/") ? path : `/${path}`
|
||||
if (clean.length > 1 && clean.endsWith("/")) clean = clean.slice(0, -1)
|
||||
return clean.split("/").map(escapeSegment).join("/")
|
||||
}
|
||||
function contentMD5(bodyString) {
|
||||
if (!bodyString) return ""
|
||||
return createHash("md5").update(bodyString).digest("base64")
|
||||
}
|
||||
function utcDateString() {
|
||||
return new Date().toUTCString()
|
||||
}
|
||||
function signHeaders(method, path, bodyString) {
|
||||
const md5 = contentMD5(bodyString)
|
||||
const date = utcDateString()
|
||||
const nonce = randomUUID() // with hyphens, as the client signs it
|
||||
const stringToSign = [method.toUpperCase(), escapedPath(path), "", md5, "application/json", date, nonce, "", ""].join("\n")
|
||||
const signature = createHmac("sha1", accessKeySecret()).update(stringToSign).digest("base64")
|
||||
const headers = {
|
||||
Authorization: `account ${accessKeyId()}:${signature}`,
|
||||
Date: date,
|
||||
Nonce: nonce,
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
if (md5) headers["Content-MD5"] = md5
|
||||
return headers
|
||||
}
|
||||
|
||||
// one signed POST on the account domain (the login chain); the signature
|
||||
// must cover the exact bytes sent, so the body is serialized once here
|
||||
async function signedPost(pathname, body) {
|
||||
const bodyString = JSON.stringify(body)
|
||||
const res = await fetch(xfyunBase() + pathname, {
|
||||
method: "POST",
|
||||
headers: signHeaders("POST", pathname, bodyString),
|
||||
body: bodyString,
|
||||
signal: AbortSignal.timeout(REQUEST_TIMEOUT),
|
||||
})
|
||||
const payload = await res.json().catch(() => null)
|
||||
if (!payload) throw new Error(`Loomy 账号接口返回了无法解析的内容(HTTP ${res.status})`)
|
||||
if (!res.ok) throw new Error(`Loomy 账号接口返回 HTTP ${res.status}: ${messageOf(payload)}`)
|
||||
return payload
|
||||
}
|
||||
|
||||
// one request on the integration gateway with the session's double headers
|
||||
// (the model and points gateways prefer different header names; the client
|
||||
// sends both, and so does this)
|
||||
async function tokenRequest(method, path, session, body) {
|
||||
if (!session?.trim()) throw new SignedOut("Loomy 账号缺少 session")
|
||||
const init = {
|
||||
method,
|
||||
headers: { token: session, Authorization: `Bearer ${session}` },
|
||||
signal: AbortSignal.timeout(REQUEST_TIMEOUT),
|
||||
}
|
||||
if (body !== undefined) {
|
||||
init.headers["Content-Type"] = "application/json"
|
||||
init.body = JSON.stringify(body)
|
||||
}
|
||||
const res = await fetch(integrationBase() + path, init)
|
||||
if (res.status === 401 || res.status === 403) throw expired("Loomy 登录态已失效,请重新登录")
|
||||
const payload = await res.json().catch(() => null)
|
||||
if (!res.ok) throw new Error(`Loomy 接口返回 HTTP ${res.status}`)
|
||||
if (!payload) throw new Error("Loomy 接口返回了无法解析的内容")
|
||||
return payload
|
||||
}
|
||||
|
||||
|
||||
// the phone number as the client normalizes it (agent2api login.rs)
|
||||
function normalizePhone(raw) {
|
||||
const trimmed = String(raw ?? "").replace(/[\s-]/g, "")
|
||||
let digits = trimmed.replace(/^\+86/, "")
|
||||
if (digits.length === 13 && digits.startsWith("86")) digits = digits.slice(2)
|
||||
if (/^1[3-9]\d{9}$/.test(digits)) return digits
|
||||
return null
|
||||
}
|
||||
|
||||
// ── chat body adaptation ───────────────────────────────────────────────────
|
||||
|
||||
// the thinking levels Loomy's client offers are low/medium/high; a wider
|
||||
// level the agent asked is folded into them, off/none and unknowns are left
|
||||
// off (agent2api mod.rs reasoning_patch)
|
||||
function foldReasoning(body) {
|
||||
let changed = false
|
||||
const of = (v) => {
|
||||
if (v === "minimal" || v === "low") return "low"
|
||||
if (v === "medium") return "medium"
|
||||
if (v === "high" || v === "max") return "high"
|
||||
return null
|
||||
}
|
||||
if (typeof body.reasoning_effort === "string") {
|
||||
const folded = of(body.reasoning_effort)
|
||||
if (folded !== body.reasoning_effort) {
|
||||
if (folded) body.reasoning_effort = folded
|
||||
else delete body.reasoning_effort
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
if (body.reasoning && typeof body.reasoning === "object" && typeof body.reasoning.effort === "string") {
|
||||
const folded = of(body.reasoning.effort)
|
||||
if (folded !== body.reasoning.effort) {
|
||||
if (folded) body.reasoning.effort = folded
|
||||
else delete body.reasoning.effort
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
return changed
|
||||
}
|
||||
|
||||
// deepseek models on Loomy read images only as <image_base64> markers, not
|
||||
// OpenAI image_url parts; data-URI images are turned into the marker and
|
||||
// merged into the text before them (agent2api images.rs)
|
||||
function prefersTagFormat(model) {
|
||||
return String(model ?? "").toLowerCase().includes("deepseek")
|
||||
}
|
||||
function toTagText(part) {
|
||||
const kind = String(part?.type ?? "").trim().toLowerCase()
|
||||
if (kind !== "image_url" && kind !== "input_image") return null
|
||||
const url = typeof part.image_url === "string" ? part.image_url : part.image_url?.url
|
||||
if (typeof url !== "string" || !url.startsWith("data:")) return null
|
||||
return `<image_base64>${url}</image_base64>`
|
||||
}
|
||||
function rewriteImagesToTags(body) {
|
||||
let converted = 0
|
||||
for (const message of body.messages ?? []) {
|
||||
if (!Array.isArray(message.content)) continue
|
||||
for (let i = message.content.length - 1; i >= 0; i--) {
|
||||
const tag = toTagText(message.content[i])
|
||||
if (!tag) continue
|
||||
message.content.splice(i, 1)
|
||||
const prev = i > 0 && message.content[i - 1]?.type === "text" ? message.content[i - 1] : null
|
||||
if (prev) prev.text += `\n${tag}`
|
||||
else if (message.content[i]?.type === "text") message.content[i].text = `${tag}\n${message.content[i].text}`
|
||||
else message.content.splice(i, 0, { type: "text", text: tag })
|
||||
converted++
|
||||
}
|
||||
}
|
||||
return converted
|
||||
}
|
||||
|
||||
// the vendor's /models: OpenAI-shaped entries whose capabilities say what a
|
||||
// model does, and whose display name ends in its point rate "(x3.0)"
|
||||
// (agent2api models.rs)
|
||||
function splitRateSuffix(name) {
|
||||
const trimmed = String(name ?? "").trimEnd()
|
||||
for (const [close, open] of [
|
||||
[")", "("],
|
||||
[")", "("],
|
||||
]) {
|
||||
if (!trimmed.endsWith(close)) continue
|
||||
const body = trimmed.slice(0, -1)
|
||||
const at = body.lastIndexOf(open)
|
||||
if (at < 0) continue
|
||||
const inner = body.slice(at + 1).trim()
|
||||
if (!/^x\d+(\.\d+)?$/i.test(inner)) return { name: trimmed, rate: undefined }
|
||||
const bare = body.slice(0, at).trimEnd()
|
||||
return { name: bare || trimmed, rate: inner.toLowerCase() }
|
||||
}
|
||||
return { name: trimmed, rate: undefined }
|
||||
}
|
||||
function catalogModel(entry) {
|
||||
const id = String(entry?.id ?? "").trim()
|
||||
if (!id) return null
|
||||
const caps = entry?.capabilities ?? {}
|
||||
const { name, rate } = splitRateSuffix(entry?.name ?? entry?.display_name ?? id)
|
||||
const config = { name: name || id }
|
||||
const limit = {}
|
||||
const context = toNum(entry?.context_window ?? entry?.context_length ?? entry?.limit?.context)
|
||||
const output = toNum(entry?.max_tokens ?? entry?.limit?.output)
|
||||
if (context != null) limit.context = context
|
||||
if (output != null) limit.output = output
|
||||
if (Object.keys(limit).length) config.limit = limit
|
||||
if (caps.reasoning) config.reasoning = true
|
||||
if (caps.function_calling) config.tool_call = true
|
||||
if (caps.vision) config.modalities = { input: ["text", "image"], output: ["text"] }
|
||||
if (rate) config.rate = rate
|
||||
return { id, config }
|
||||
}
|
||||
|
||||
// ── the plugin ─────────────────────────────────────────────────────────────
|
||||
|
||||
export async function LoomyAuthPlugin({ client } = {}) {
|
||||
const methods = []
|
||||
|
||||
methods.push({
|
||||
type: "oauth",
|
||||
label: "短信验证码登录(SMS sign-in)",
|
||||
prompts: [{ type: "text", key: "phone", message: "手机号(中国大陆 11 位)", validate: (v) => (normalizePhone(v) ? undefined : "请填写 11 位中国大陆手机号") }],
|
||||
authorize: async (inputs) => {
|
||||
const phone = normalizePhone(inputs?.phone)
|
||||
if (!phone) return { type: "failed", error: "请填写 11 位中国大陆手机号" }
|
||||
// send the code now; the code the user pastes next completes it
|
||||
let msgid
|
||||
try {
|
||||
const sent = await signedPost("/login/phone/sendMsgCode", { base: makeBase(), param: { ccode: "86", phone, expire: 300 } })
|
||||
if (codeOf(sent) !== OK) return { type: "failed", error: `验证码发送失败:${messageOf(sent) || `code=${codeOf(sent)}`}` }
|
||||
msgid = sent?.data?.msgid
|
||||
if (!msgid) return { type: "failed", error: "验证码发送成功但上游没有返回 msgid" }
|
||||
} catch (e) {
|
||||
return { type: "failed", error: String(e?.message ?? e) }
|
||||
}
|
||||
return {
|
||||
url: "",
|
||||
instructions: `验证码已发送到 ${phone.slice(0, 3)}****${phone.slice(-4)},请输入收到的 6 位验证码。`,
|
||||
method: "code",
|
||||
callback: async (code) => {
|
||||
const mcode = String(code ?? "").trim()
|
||||
if (!/^\d{6}$/.test(mcode)) return { type: "failed", error: "请输入 6 位数字验证码" }
|
||||
try {
|
||||
const answer = await signedPost("/login/phone/checkCode", {
|
||||
base: makeBase(),
|
||||
param: { ccode: "86", phone, mcode, msgid, expire: 1209600 },
|
||||
})
|
||||
if (AUTH_CODES.has(codeOf(answer)))
|
||||
return { type: "failed", error: "登录失败:登录态已失效,请重新获取验证码" }
|
||||
if (codeOf(answer) !== OK) return { type: "failed", error: `登录失败:${messageOf(answer) || `code=${codeOf(answer)}`}` }
|
||||
const session = String(answer?.data?.session ?? "").trim()
|
||||
if (!session) return { type: "failed", error: "登录成功但上游没有返回 session" }
|
||||
return {
|
||||
type: "success",
|
||||
refresh: "",
|
||||
access: session,
|
||||
expires: Date.now() + 14 * 86400e3, // the session the client asks for is 14 days
|
||||
accountId: `${phone.slice(0, 3)}****${phone.slice(-4)}`,
|
||||
userId: String(answer?.data?.userid ?? ""),
|
||||
source: "sms",
|
||||
}
|
||||
} catch (e) {
|
||||
return { type: "failed", error: String(e?.message ?? e) }
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
})
|
||||
methods.push({
|
||||
type: "oauth",
|
||||
label: "手动粘贴 session(Paste token)",
|
||||
prompts: [{ type: "text", key: "session", message: "session(token 头的值,14 天有效)", validate: (v) => (v && v.trim() ? undefined : "必填") }],
|
||||
// an oauth authorize() hands back {url, method, instructions, callback}
|
||||
// and the host finishes the sign-in by calling callback() — returning
|
||||
// the account directly leaves the host on a callback that doesn't exist
|
||||
authorize: async (inputs) => {
|
||||
const session = String(inputs?.session ?? "").trim()
|
||||
if (!session) return { type: "failed", error: "session 必填" }
|
||||
return {
|
||||
url: "",
|
||||
instructions: "已取到粘贴的 session,确认即完成登录。",
|
||||
method: "auto",
|
||||
callback: async () => ({ type: "success", refresh: "", access: session, expires: 0, accountId: "手动粘贴", source: "manual" }),
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
return {
|
||||
auth: {
|
||||
provider: ID,
|
||||
// Loomy has no renewal: a session lives 14 days, and its end is
|
||||
// refreshed only by signing in again (SMS or import)
|
||||
async loader(getAuth) {
|
||||
const a = await getAuth()
|
||||
if (a?.type !== "oauth") return {}
|
||||
return {
|
||||
baseURL: modelBase(),
|
||||
apiKey: "loomy",
|
||||
async fetch(input, init = {}) {
|
||||
const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url
|
||||
if (!/\/chat\/completions$/.test(new URL(url).pathname))
|
||||
return errorResponse(404, "only chat completions are served")
|
||||
let chat
|
||||
try {
|
||||
chat = JSON.parse(await bodyText(input, init))
|
||||
} catch {
|
||||
return errorResponse(400, "a request that isn't JSON")
|
||||
}
|
||||
const session = (await getAuth())?.access ?? a.access
|
||||
if (!session) return errorResponse(401, "Loomy 登录态缺失,请重新登录")
|
||||
|
||||
// the body as Loomy's own client writes it: reasoning folded to
|
||||
// its three levels, and deepseek's images as base64 markers
|
||||
try {
|
||||
foldReasoning(chat)
|
||||
if (prefersTagFormat(chat.model)) rewriteImagesToTags(chat)
|
||||
} catch {}
|
||||
let res
|
||||
try {
|
||||
res = await fetch(`${modelBase()}/chat/completions`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
// charset=utf-8 is load-bearing: without it the upstream
|
||||
// reads the body as GBK and CJK text arrives corrupted
|
||||
"Content-Type": "application/json;charset=utf-8",
|
||||
Accept: "text/event-stream",
|
||||
token: session,
|
||||
Authorization: `Bearer ${session}`,
|
||||
},
|
||||
body: JSON.stringify(chat),
|
||||
signal: init.signal,
|
||||
})
|
||||
} catch (e) {
|
||||
return errorResponse(502, e?.message ?? String(e))
|
||||
}
|
||||
if (res.status === 401 || res.status === 403) return errorResponse(401, "Loomy 登录态已失效,请重新登录")
|
||||
if (!res.ok)
|
||||
return errorResponse(res.status, `Loomy 上游返回 ${res.status}: ${(await res.text().catch(() => "")).slice(0, 4096) || "无错误说明"}`)
|
||||
// the answer streams through as it came (OpenAI-shaped)
|
||||
return res
|
||||
},
|
||||
}
|
||||
},
|
||||
async usage(getAuth) {
|
||||
try {
|
||||
const a = await getAuth()
|
||||
if (a?.type !== "oauth") return { error: "not signed in", signIn: "kept" }
|
||||
const payload = await tokenRequest("GET", "/api/v2/points/records?pageNo=1&pageSize=1&direction=debit&granularity=chat", a.access)
|
||||
const code = codeOf(payload)
|
||||
if (AUTH_CODES.has(code)) return { error: "Loomy 登录态已失效,请重新登录", signIn: "expired" }
|
||||
if (code !== OK) return { error: `积分查询失败:${messageOf(payload) || `code=${code}`}`, signIn: "kept" }
|
||||
const data = payload?.data?.data ?? payload?.data ?? {}
|
||||
const daily = toNum(data.dailyBalance)
|
||||
const permanent = toNum(data.balance)
|
||||
// this endpoint is a records list, so a reply without the balance
|
||||
// fields is a realistic case — "unknown" must not read as a
|
||||
// confident zero
|
||||
const pairPresent = toNum(data.dailyLimitPoints) != null && toNum(data.dailyRemainingPoints) != null
|
||||
if (daily == null && permanent == null && !pairPresent)
|
||||
return { error: `积分响应没有返回余额字段(${JSON.stringify(data).slice(0, 120)})`, signIn: "kept" }
|
||||
// the daily wallet from the vendor's own numbers: spent is
|
||||
// dailyLimitPoints - dailyRemainingPoints. When the pair is absent
|
||||
// the wallet is an amount with no limit — a made-up limit would
|
||||
// always read as full
|
||||
const dailyLimit = toNum(data.dailyLimitPoints)
|
||||
const dailyRemaining = toNum(data.dailyRemainingPoints)
|
||||
|
||||
// the daily wallet shows from whichever numbers came back: the
|
||||
// limit/remaining pair alone is enough (remaining IS its number);
|
||||
// with only dailyBalance it is an amount without a limit; with
|
||||
// neither, no daily wallet at all — a missing one is not 0
|
||||
const dailyWallet =
|
||||
dailyLimit != null && dailyRemaining != null
|
||||
? { name: "每日赠送积分", used: Math.max(0, dailyLimit - dailyRemaining), amount: dailyRemaining, limit: dailyLimit, unit: "credits", resetsAt: beijingMidnight(), span: 86400 }
|
||||
: daily != null
|
||||
? { name: "每日赠送积分", used: 0, display: `${daily} credits`, aside: true }
|
||||
: null
|
||||
const windows = [
|
||||
...(dailyWallet ? [dailyWallet] : []),
|
||||
...(permanent != null ? [{ name: "永久积分", used: 0, display: `${permanent} credits`, aside: true }] : []),
|
||||
]
|
||||
// no `signIn` on a clean read: that absence is how magpie takes an
|
||||
// expired mark back off the account (Loomy has no renewal, so a
|
||||
// "kept" here would leave a transient 401's lapse on forever)
|
||||
return { plan: NAME, user: a.name || a.accountId, windows }
|
||||
} catch (e) {
|
||||
return { error: String(e?.message ?? e), signIn: e?.signIn === "expired" ? "expired" : "kept" }
|
||||
}
|
||||
},
|
||||
// the daily grant: the first login of the vendor's day refreshes the
|
||||
// daily wallet; the same call pressed here keeps it refreshed for an
|
||||
// account that isn't logging in (agent2api checkin.rs). The endpoint
|
||||
// answers success whether it granted or not, so claimed vs done is
|
||||
// decided by the daily balance around the call: up means the day's
|
||||
// grant landed, flat means it was already in (or carries no daily
|
||||
// wallet) — "done", with the refreshed balance in the message either way
|
||||
async checkin(getAuth) {
|
||||
const a = await getAuth()
|
||||
if (a?.type !== "oauth" || !a.access) throw new SignedOut("Loomy:未登录")
|
||||
const readDaily = async () => {
|
||||
const rec = await tokenRequest("GET", "/api/v2/points/records?pageNo=1&pageSize=1&direction=debit&granularity=chat", a.access)
|
||||
return toNum(rec?.data?.data?.dailyBalance ?? rec?.data?.dailyBalance)
|
||||
}
|
||||
let before
|
||||
try {
|
||||
before = await readDaily()
|
||||
} catch (e) {
|
||||
if (e?.signIn === "expired" || e instanceof SignedOut) throw expired("Loomy 登录态已失效,无法刷新每日积分(请重新登录)")
|
||||
// without the pre-read there is no honest claimed/done verdict —
|
||||
// say failed with the reason rather than "already done"
|
||||
return { outcome: "failed", message: `无法读取签到前余额,未执行每日刷新:${e?.message ?? e}` }
|
||||
}
|
||||
let payload
|
||||
try {
|
||||
payload = await tokenRequest("POST", "/api/v1/points/first-login", a.access, {})
|
||||
} catch (e) {
|
||||
if (e?.signIn === "expired" || e instanceof SignedOut) throw expired("Loomy 登录态已失效,无法刷新每日积分(请重新登录)")
|
||||
return { outcome: "failed", message: `每日积分刷新失败:${e?.message ?? e}` }
|
||||
}
|
||||
const code = codeOf(payload)
|
||||
if (AUTH_CODES.has(code)) throw expired("Loomy 登录态已失效,无法刷新每日积分(请重新登录)")
|
||||
if (code !== OK) return { outcome: "failed", message: `每日积分刷新失败:${messageOf(payload) || `code=${code}`}` }
|
||||
const after = toNum(payload?.data?.dailyBalance ?? payload?.data?.data?.dailyBalance) ?? (await readDaily().catch(() => null))
|
||||
const dailyMsg = after != null ? `每日赠送积分已刷新(当前 ${after})` : "每日赠送积分已刷新"
|
||||
if (before != null && after != null && after > before) return { outcome: "claimed", credit: after - before, message: `${dailyMsg};今日首登奖励 +${after - before}` }
|
||||
return { outcome: "done", message: dailyMsg }
|
||||
},
|
||||
methods,
|
||||
},
|
||||
async config(config) {
|
||||
config.provider ??= {}
|
||||
const was = config.provider[ID] ?? {}
|
||||
// the static table (captured from the live endpoint) keeps the picker
|
||||
// usable before the first sign-in; the models hook extends it from
|
||||
// /api/v1/models once signed in
|
||||
config.provider[ID] = {
|
||||
name: NAME,
|
||||
npm: "@ai-sdk/openai-compatible",
|
||||
api: modelBase(),
|
||||
...was,
|
||||
models: { ...STATIC_MODELS, ...(was.models ?? {}) },
|
||||
}
|
||||
},
|
||||
provider: {
|
||||
id: ID,
|
||||
async models(p, { auth } = {}) {
|
||||
if (auth?.type !== "oauth" || !auth.access) return p.models
|
||||
try {
|
||||
const payload = await tokenRequest("GET", "/api/v1/models", auth.access)
|
||||
if (codeOf(payload) && codeOf(payload) !== OK) return p.models
|
||||
const entries = Array.isArray(payload?.data) ? payload.data : []
|
||||
for (const entry of entries) {
|
||||
const m = catalogModel(entry)
|
||||
if (!m) continue
|
||||
p.models[m.id] = m.config
|
||||
}
|
||||
return p.models
|
||||
} catch {
|
||||
return p.models
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// for tests
|
||||
export const _internal = {
|
||||
ID,
|
||||
NAME,
|
||||
STATIC_MODELS,
|
||||
signHeaders,
|
||||
escapedPath,
|
||||
contentMD5,
|
||||
foldReasoning,
|
||||
prefersTagFormat,
|
||||
rewriteImagesToTags,
|
||||
splitRateSuffix,
|
||||
catalogModel,
|
||||
normalizePhone,
|
||||
makeBase,
|
||||
toNum,
|
||||
beijingMidnight,
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
import { describe, test, expect, beforeAll, afterAll, beforeEach } from "bun:test"
|
||||
import { LoomyAuthPlugin, _internal } from "./index.mjs"
|
||||
import { fakeLoomy } from "./fake.mjs"
|
||||
|
||||
// every test runs against the fake upstream in fake.mjs: no network, no real
|
||||
// token ever leaves this process
|
||||
|
||||
let fake
|
||||
let plugin
|
||||
let saved = {}
|
||||
const client = { auth: { set: async ({ body }) => (saved = body) } }
|
||||
const getAuth = async () => saved
|
||||
|
||||
beforeAll(async () => {
|
||||
fake = fakeLoomy()
|
||||
process.env.LOOMY_POINTS_BASE_URL = fake.gatewayUrl
|
||||
process.env.LOOMY_XFYUN_BASE_URL = fake.accountUrl
|
||||
})
|
||||
|
||||
afterAll(() => {
|
||||
fake.account.stop(true)
|
||||
fake.gateway.stop(true)
|
||||
})
|
||||
|
||||
beforeEach(async () => {
|
||||
fake.state.reset()
|
||||
saved = { type: "oauth", access: fake.state.session, expires: 0, accountId: "138****8000", name: "138****8000", source: "manual" }
|
||||
plugin = await LoomyAuthPlugin({ client })
|
||||
})
|
||||
|
||||
describe("sign-in methods", () => {
|
||||
test("SMS: sends the code, then trades it for a 14-day session", async () => {
|
||||
const method = plugin.auth.methods.find((m) => m.label.includes("SMS"))
|
||||
const flow = await method.authorize({ phone: "138 0013 8000" }) // spaces tolerated
|
||||
expect(flow.method).toBe("code")
|
||||
expect(flow.instructions).toContain("已发送")
|
||||
expect(fake.state.smsSent).toBeTruthy()
|
||||
// wrong code fails with a reason
|
||||
expect((await flow.callback("000000")).type).toBe("failed")
|
||||
const result = await flow.callback("123456")
|
||||
expect(result.type).toBe("success")
|
||||
expect(result.access).toBe("sess-1")
|
||||
expect(result.expires).toBeGreaterThan(Date.now() + 13 * 86400e3)
|
||||
expect(result.accountId).toBe("138****8000")
|
||||
})
|
||||
|
||||
test("SMS: an invalid phone is refused before anything is sent", async () => {
|
||||
const method = plugin.auth.methods.find((m) => m.label.includes("SMS"))
|
||||
const bad = await method.authorize({ phone: "12345" })
|
||||
expect(bad.type).toBe("failed")
|
||||
expect(fake.state.smsSent).toBeNull()
|
||||
})
|
||||
|
||||
test("manual paste works through the host's authorize → callback contract", async () => {
|
||||
const method = plugin.auth.methods.find((m) => m.label.includes("Paste"))
|
||||
const flow = await method.authorize({ session: "pasted" })
|
||||
expect(flow.method).toBe("auto")
|
||||
expect(typeof flow.callback).toBe("function")
|
||||
const result = await flow.callback()
|
||||
expect(result.type).toBe("success")
|
||||
expect(result.access).toBe("pasted")
|
||||
expect(await method.authorize({ session: "" })).toMatchObject({ type: "failed" })
|
||||
})
|
||||
})
|
||||
|
||||
describe("chat", () => {
|
||||
test("forwards with the double auth headers and streams through", async () => {
|
||||
const loader = await plugin.auth.loader(getAuth)
|
||||
const res = await loader.fetch(`${fake.gatewayUrl}/api/v1/v1/chat/completions`.replace("/v1/v1/", "/api/v1/"), {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ model: "spark-x", stream: true, messages: [{ role: "user", content: "hi" }] }),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
const text = await res.text()
|
||||
expect(text).toContain('"content":"你"')
|
||||
expect(text).toContain("data: [DONE]")
|
||||
expect(fake.state.chatCalls.length).toBe(1)
|
||||
expect(fake.state.chatCalls[0].body.model).toBe("spark-x")
|
||||
})
|
||||
|
||||
test("reasoning effort folds to low/medium/high", async () => {
|
||||
const loader = await plugin.auth.loader(getAuth)
|
||||
await loader.fetch(`${fake.gatewayUrl}/api/v1/chat/completions`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ model: "spark-x", stream: false, reasoning_effort: "minimal", messages: [] }),
|
||||
})
|
||||
await loader.fetch(`${fake.gatewayUrl}/api/v1/chat/completions`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ model: "spark-x", stream: false, reasoning_effort: "max", messages: [] }),
|
||||
})
|
||||
await loader.fetch(`${fake.gatewayUrl}/api/v1/chat/completions`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ model: "spark-x", stream: false, reasoning_effort: "none", messages: [] }),
|
||||
})
|
||||
expect(fake.state.chatCalls[0].body.reasoning_effort).toBe("low")
|
||||
expect(fake.state.chatCalls[1].body.reasoning_effort).toBe("high")
|
||||
expect(fake.state.chatCalls[2].body.reasoning_effort).toBeUndefined()
|
||||
})
|
||||
|
||||
test("deepseek images become base64 markers merged into the text", async () => {
|
||||
const loader = await plugin.auth.loader(getAuth)
|
||||
await loader.fetch(`${fake.gatewayUrl}/api/v1/chat/completions`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
model: "deepseek-v4-flash",
|
||||
stream: false,
|
||||
messages: [
|
||||
{ role: "user", content: [
|
||||
{ type: "text", text: "看这张图" },
|
||||
{ type: "image_url", image_url: { url: "data:image/png;base64,QUJD" } },
|
||||
{ type: "image_url", image_url: { url: "https://example.com/x.png" } },
|
||||
] },
|
||||
],
|
||||
}),
|
||||
})
|
||||
const content = fake.state.chatCalls[0].body.messages[0].content
|
||||
expect(content).toHaveLength(2)
|
||||
expect(content[0].text).toContain("看这张图")
|
||||
expect(content[0].text).toContain("<image_base64>data:image/png;base64,QUJD</image_base64>")
|
||||
// an http(s) URL stays as it was (no evidence the marker accepts URLs)
|
||||
expect(content[1].type).toBe("image_url")
|
||||
})
|
||||
|
||||
test("a refused session says 401", async () => {
|
||||
saved = { type: "oauth", access: "gone", expires: 0 }
|
||||
const loader = await plugin.auth.loader(getAuth)
|
||||
const res = await loader.fetch(`${fake.gatewayUrl}/api/v1/chat/completions`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ model: "spark-x", stream: false, messages: [] }),
|
||||
})
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
test("only chat completions are served", async () => {
|
||||
const loader = await plugin.auth.loader(getAuth)
|
||||
const res = await loader.fetch(`${fake.gatewayUrl}/api/v1/embeddings`, { method: "POST", body: "{}" })
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
})
|
||||
|
||||
describe("checkin", () => {
|
||||
test("the day's first call claims the grant, a repeat is done", async () => {
|
||||
// the daily wallet moves 3000 → 5000 on the day's first call: claimed
|
||||
const result = await plugin.auth.checkin(getAuth)
|
||||
expect(result.outcome).toBe("claimed")
|
||||
expect(result.credit).toBe(2000)
|
||||
expect(result.message).toContain("5000")
|
||||
expect(fake.state.firstLoginCalls).toBe(1)
|
||||
// the endpoint answers success on a repeat too, but the wallet is flat:
|
||||
// done, not a second claim
|
||||
const again = await plugin.auth.checkin(getAuth)
|
||||
expect(again.outcome).toBe("done")
|
||||
expect(again.credit).toBeUndefined()
|
||||
expect(fake.state.firstLoginCalls).toBe(2)
|
||||
})
|
||||
|
||||
test("a refused session says the sign-in expired", async () => {
|
||||
saved = { type: "oauth", access: "gone", expires: 0 }
|
||||
await expect(plugin.auth.checkin(getAuth)).rejects.toThrow(/失效/)
|
||||
})
|
||||
|
||||
test("a failed pre-read is failed, not silently done", async () => {
|
||||
const realFetch = globalThis.fetch
|
||||
globalThis.fetch = (input, init) => {
|
||||
const url = typeof input === "string" ? input : String(input?.url ?? input)
|
||||
// fail only the records read; the first-login POST still goes through
|
||||
if (String(url).includes("/api/v2/points/records")) return new Response("boom", { status: 502 })
|
||||
return realFetch(input, init)
|
||||
}
|
||||
try {
|
||||
const result = await plugin.auth.checkin(getAuth)
|
||||
expect(result.outcome).toBe("failed")
|
||||
expect(result.message).toContain("无法读取签到前余额")
|
||||
expect(fake.state.firstLoginCalls).toBe(0)
|
||||
} finally {
|
||||
globalThis.fetch = realFetch
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe("models", () => {
|
||||
test("the catalog, with rates split out of the names", async () => {
|
||||
const p = { models: {} }
|
||||
const list = await plugin.provider.models(p, { auth: saved })
|
||||
expect(Object.keys(list)).toEqual(["spark-x", "deepseek-v4-flash", "glm-5.3-flash", "plain"])
|
||||
expect(list["spark-x"].rate).toBe("x0.1")
|
||||
expect(list["spark-x"].name).toBe("Spark X2.5")
|
||||
expect(list["spark-x"].reasoning).toBe(true)
|
||||
expect(list["spark-x"].tool_call).toBe(true)
|
||||
expect(list["deepseek-v4-flash"].rate).toBe("x3.0")
|
||||
expect(list["glm-5.3-flash"].modalities).toEqual({ input: ["text", "image"], output: ["text"] })
|
||||
expect(list["plain"].rate).toBeUndefined()
|
||||
expect(list["plain"].name).toBe("No Suffix At All")
|
||||
})
|
||||
})
|
||||
|
||||
describe("usage", () => {
|
||||
test("the two wallets as windows", async () => {
|
||||
const usage = await plugin.auth.usage(getAuth)
|
||||
// a clean read says nothing about the sign-in, so magpie can clear a lapse
|
||||
expect(usage.signIn).toBeUndefined()
|
||||
const daily = usage.windows.find((w) => w.name === "每日赠送积分")
|
||||
// the vendor's own numbers: spent = dailyLimitPoints - dailyRemainingPoints
|
||||
expect(daily.limit).toBe(5000)
|
||||
expect(daily.amount).toBe(fake.state.dailyBalance)
|
||||
expect(daily.resetsAt).toBeGreaterThan(Date.now())
|
||||
const permanent = usage.windows.find((w) => w.name === "永久积分")
|
||||
expect(permanent.display).toBe("5000 credits")
|
||||
})
|
||||
|
||||
test("a daily wallet without the limit pair is an amount without a limit", async () => {
|
||||
const realFetch = globalThis.fetch
|
||||
globalThis.fetch = (input, init) => {
|
||||
const url = typeof input === "string" ? input : String(input?.url ?? input)
|
||||
if (String(url).includes("/api/v2/points/records"))
|
||||
return new Response(JSON.stringify({ code: "000000", desc: "ok", data: { balance: 5000, dailyBalance: 3000, list: [], total: 0 } }), { status: 200 })
|
||||
return realFetch(input, init)
|
||||
}
|
||||
try {
|
||||
const usage = await plugin.auth.usage(getAuth)
|
||||
const daily = usage.windows.find((w) => w.name === "每日赠送积分")
|
||||
expect(daily.limit).toBeUndefined()
|
||||
expect(daily.display).toBe("3000 credits")
|
||||
// a reply with only the limit/remaining pair still shows the daily
|
||||
// wallet (remaining IS its number), without dailyBalance
|
||||
globalThis.fetch = (input, init) => {
|
||||
const url = typeof input === "string" ? input : String(input?.url ?? input)
|
||||
if (String(url).includes("/api/v2/points/records"))
|
||||
return new Response(JSON.stringify({ code: "000000", desc: "ok", data: { dailyLimitPoints: 5000, dailyRemainingPoints: 4200, list: [] } }), { status: 200 })
|
||||
return realFetch(input, init)
|
||||
}
|
||||
try {
|
||||
const pairOnly = await plugin.auth.usage(getAuth)
|
||||
const dw = pairOnly.windows.find((w) => w.name === "每日赠送积分")
|
||||
expect(dw).toBeTruthy()
|
||||
expect(dw.used).toBe(800)
|
||||
expect(dw.amount).toBe(4200)
|
||||
expect(dw.limit).toBe(5000)
|
||||
expect(pairOnly.windows.find((w) => w.name === "永久积分")).toBeUndefined()
|
||||
} finally {
|
||||
globalThis.fetch = realFetch
|
||||
}
|
||||
// a reply with neither balance field is an error, not a confident zero
|
||||
globalThis.fetch = (input, init) => {
|
||||
const url = typeof input === "string" ? input : String(input?.url ?? input)
|
||||
if (String(url).includes("/api/v2/points/records"))
|
||||
return new Response(JSON.stringify({ code: "000000", desc: "ok", data: { records: [] } }), { status: 200 })
|
||||
return realFetch(input, init)
|
||||
}
|
||||
try {
|
||||
const missing = await plugin.auth.usage(getAuth)
|
||||
expect(missing.error).toContain("没有返回余额字段")
|
||||
} finally {
|
||||
globalThis.fetch = realFetch
|
||||
}
|
||||
} finally {
|
||||
globalThis.fetch = realFetch
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe("signature", () => {
|
||||
test("the 9-part HMAC string matches the client's shape", () => {
|
||||
const headers = _internal.signHeaders("POST", "/login/phone/sendMsgCode", '{"a":1}')
|
||||
expect(headers.Authorization).toMatch(/^account 2thryby66wxi53sk:[A-Za-z0-9+/=]+$/)
|
||||
expect(headers.Date).toMatch(/GMT$/)
|
||||
expect(headers.Nonce).toMatch(/^[0-9a-f-]{36}$/)
|
||||
expect(headers["Content-MD5"]).toBe(_internal.contentMD5('{"a":1}'))
|
||||
// no body: no MD5 header, and the empty part sits in the string
|
||||
const empty = _internal.signHeaders("GET", "/x", "")
|
||||
expect(empty["Content-MD5"]).toBeUndefined()
|
||||
})
|
||||
|
||||
test("paths are escaped and trailing slashes dropped", () => {
|
||||
expect(_internal.escapedPath("/login/phone/sendMsgCode")).toBe("/login/phone/sendMsgCode")
|
||||
expect(_internal.escapedPath("a/b/")).toBe("/a/b")
|
||||
expect(_internal.escapedPath("/带中文/段")).toBe(`/${encodeURIComponent("带中文")}/${encodeURIComponent("段")}`)
|
||||
})
|
||||
})
|
||||
|
||||
describe("helpers", () => {
|
||||
test("phone normalization", () => {
|
||||
expect(_internal.normalizePhone("13800138000")).toBe("13800138000")
|
||||
expect(_internal.normalizePhone("+86 138-0013-8000")).toBe("13800138000")
|
||||
expect(_internal.normalizePhone("8613800138000")).toBe("13800138000")
|
||||
expect(_internal.normalizePhone("12345")).toBeNull()
|
||||
expect(_internal.normalizePhone("12800138000")).toBeNull() // second digit not 3-9
|
||||
})
|
||||
|
||||
test("rate suffix split", () => {
|
||||
expect(_internal.splitRateSuffix("DeepSeek V4 Flash 0731 (x3.0)")).toEqual({ name: "DeepSeek V4 Flash 0731", rate: "x3.0" })
|
||||
expect(_internal.splitRateSuffix("GLM 5.3 Flash(x0.8)")).toEqual({ name: "GLM 5.3 Flash", rate: "x0.8" })
|
||||
expect(_internal.splitRateSuffix("Spark X2.5 (x0.1)")).toEqual({ name: "Spark X2.5", rate: "x0.1" })
|
||||
expect(_internal.splitRateSuffix("限时免费")).toEqual({ name: "限时免费", rate: undefined })
|
||||
expect(_internal.splitRateSuffix("Model (free)")).toEqual({ name: "Model (free)", rate: undefined })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-loomy-auth",
|
||||
"version": "0.1.0",
|
||||
"description": "OpenCode & Magpie provider plugin for Loomy (讯飞, loomyad.xunfei.cn): SMS sign-in, chat, models, the two point wallets and the daily first-login grant",
|
||||
"type": "module",
|
||||
"main": "./index.mjs",
|
||||
"exports": "./index.mjs",
|
||||
"files": [
|
||||
"index.mjs",
|
||||
"README.md"
|
||||
],
|
||||
"keywords": [
|
||||
"opencode",
|
||||
"opencode-plugin",
|
||||
"magpie",
|
||||
"loomy",
|
||||
"xunfei",
|
||||
"讯飞"
|
||||
],
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/magpie-community/plugins.git",
|
||||
"directory": "packages/loomy"
|
||||
}
|
||||
}
|
||||
@@ -38,6 +38,9 @@
|
||||
"summary": { "en": "Trae CN (trae.cn) and Trae international (trae.ai) models with your own account, free tier included — Trae's own browser sign-in. Experimental.", "zh": "用 Trae CN(trae.cn)与 Trae 国际版(trae.ai)账号使用各自的模型,含免费版,使用 Trae 自己的浏览器登录。实验性。" } },
|
||||
{ "package": "@magpie-community/opencode-opendesign-auth", "name": "Open Design", "providers": ["opendesign"], "community": true,
|
||||
"summary": { "en": "Open Design Cloud's Design Plan (open-design.ai): the account's device sign-in, the models the plan entitles it to, and the plan's 5-hour and 7-day allowance and wallet balance.", "zh": "Open Design Cloud 的 Design Plan(open-design.ai):账号设备登录、套餐可用的模型,以及 5 小时与 7 天额度、钱包余额。" } },
|
||||
{ "package": "@magpie-community/opencode-loomy-auth", "name": "Loomy", "providers": ["loomy"], "community": true,
|
||||
"summary": { "en": "iFlytek's Loomy (loomyad.xunfei.cn): SMS sign-in, OpenAI-compatible chat with reasoning-effort folding and image markers, the live model catalog, two point wallets and the daily first-login grant.",
|
||||
"zh": "讯飞 Loomy(loomyad.xunfei.cn):短信验证码登录,OpenAI 兼容对话(思考档折叠与图片标记适配),实时模型目录、双积分钱包与每日首登赠送。" } },
|
||||
{ "package": "@magpie-community/opencode-nous-auth", "name": "Nous Portal (OAuth)", "icon": "nousresearch", "providers": ["nous-portal"], "community": true,
|
||||
"summary": { "en": "Nous Portal models, with Nous Portal's device sign-in.", "zh": "通过 Nous Portal 自己的设备码登录使用 Nous Portal 模型。" } },
|
||||
{ "package": "@magpie-community/opencode-raccoon-auth", "name": "商汤小浣熊", "icon": "sensenova-color", "providers": ["raccoon"], "community": true,
|
||||
|
||||
Reference in New Issue
Block a user