astudio 0.2.0: browser sign-in, one pool slot per account (#781)

Browser sign-in for AStudio (fresh Chrome/Edge profile, harvest ssoSessionId +
account_id, exchange through auth/bearer-token), one pool slot per account
(accountId = uid), and a check-in that reads the daily GRANT ledger first and
sends no write when today's grant is already there. Windows built in
Beijing time; transient-only retries; profiles removed on every path.

Reviewed at 11da33c74442328eae462311914eb0ef177946a7, run on a test machine
with a temp HOME:
- bun test packages/astudio 78/78 in Asia/Shanghai, UTC and
  America/Los_Angeles; node --test 78/78.
- bun scripts/check.mjs astudio ok; repo bun test 6275 pass, 0 fail.
- Merged onto main 86778e66: astudio 78/78, check.mjs ok, repo bun test
  6489 pass, 0 fail.
- Broken by hand, each red: 5xx not transient, catalog redirect dropped,
  browser precheck dropped, check-in gated on token, profile kept on
  abort/timeout/launch failure, the "0 分钟" label.
- 0.2.0 is the next version (dist index has 0.1.4).
Not tried: a real iFLYTEK account.
This commit is contained in:
Pursuit806
2026-11-06 22:47:26 +08:00
committed by GitHub
parent 86778e6646
commit 35ddd0d9bc
6 changed files with 1613 additions and 76 deletions
+19 -13
View File
@@ -1,6 +1,6 @@
# @magpie-community/opencode-astudio-auth
把 **AStudio(科大讯飞 Astron Studio 桌面端)** 的账号额度接入 [magpie](https://usemagpie.ai/) 与 [OpenCode](https://opencode.ai/):复用桌面端登录态,直连云端模型网关(OpenAI Responses 协议),agent 以 `astudio/<model>` 使用它的模型;支持每日登录积分自动签到与积分余额显示。
把 **AStudio(科大讯飞 Astron Studio)** 的账号额度接入 [magpie](https://usemagpie.ai/) 与 [OpenCode](https://opencode.ai/):浏览器登录或复用桌面端登录态,直连云端模型网关(OpenAI Responses 协议),agent 以 `astudio/<model>` 使用它的模型;支持每日登录积分自动签到、积分余额与到期时间显示,每个账号各占账号池一格。
## 与 Providers Hub 的 `hub-astudio` 的区别
@@ -8,31 +8,33 @@ AStudio 在 registry 里有两个入口,都保留([#614](https://github.com/
| | 本包(`astudio`) | [magpie-providers-hub](https://www.npmjs.com/package/magpie-providers-hub)(`hub-astudio`) |
| --- | --- | --- |
| 登录 | 读取本机 AStudio 桌面端的登录态,或粘贴 `modelBearerToken`;不需要再输手机号或密码 | 本机打开一个登录页:手机验证码、账号密码或微信扫码(含极验验证),不依赖桌面端 |
| 适合 | 装了 AStudio 桌面端的用户(数据目录按 `ASTUDIO_HOME`、Windows 注册表、`~/.acode` 查找;其他情况粘贴凭据) | 任何平台,没装桌面端也行 |
| 登录 | 浏览器登录(推荐,可多账号)、读取本机 AStudio 桌面端的登录态,或粘贴 `modelBearerToken` | 本机打开一个登录页:手机验证码、账号密码或微信扫码(含极验验证),不依赖桌面端 |
| 适合 | 装了桌面端就复用登录态;没装也可以用浏览器登录(可多账号);两者都不方便时粘贴凭据 | 任何平台,没装桌面端也行 |
| 模型端点 | `…/model-gateway/v1/responses`(OpenAI Responses,与桌面端一致) | `…/model-gateway/v1/chat/completions` |
| 每日积分 | 做一次会话活跃,按前后余额差与 `client-popups/pending` 待通知弹窗记录,不调用领取接口 | 调用 `client-popups` 领取每日奖励和新人礼包弹窗 |
| 每日积分 | 先读当日获得流水(与网页后台「获得明细」同源):有当日 GRANT 行即已发放,此时一个写请求都不发;流水为空才做一次会话活跃再读流水,流水不可用才退回余额差 + `client-popups/pending` 弹窗观测;不调用领取接口 | 调用 `client-popups` 领取每日奖励和新人礼包弹窗 |
两者用同一个 AStudio 账号时,读的是同一个 `points/balance`,模型调用也扣同一份积分:**每日登录积分是一个池子,装两个不会多一份。** 同一账号两边都登录只会重复显示同一笔余额。
English: two entries serve AStudio. This one reuses the AStudio desktop's
sign-in (or a pasted `modelBearerToken`) and calls the Responses endpoint;
English: two entries serve AStudio. This one signs in through a browser
(each account gets its own pool slot), reuses the AStudio desktop's sign-in,
or takes a pasted `modelBearerToken`, and calls the Responses endpoint;
Providers Hub's `hub-astudio` signs in on a local page (SMS code, password
or WeChat QR) and calls chat/completions. On one account both draw on the
same daily points balance.
## 登录什么
两种方式(登录时二选一):
三种方式(登录时选一种):
1. **读取 AStudio 桌面端登录态(推荐)**——本机装有 AStudio 桌面版并登录过即可,插件自动从它的数据目录读出模型凭据与网页会话(积分/签到用),不用填任何东西。没装/没登录时这一步会给出 [AStudio 官网](https://agent.xfyun.cn/) 链接并自动等待:装好登录后自动完成,不用回来点按钮。本机已有数据但读不出来(会话不是有效 JSON、没有凭据、账号被封禁)会直接说明原因,登录/修好后同样自动完成。数据目录按以下顺序查找:
1. **浏览器登录(推荐,可多账号)**——弹出的浏览器里登录讯飞账号(手机验证码或扫码),插件收割网页会话 Cookie(`ssoSessionId` + `account_id` 必需,`token` 有则一并带上),再调桌面端启动时的同款 `POST auth/bearer-token` 换发模型凭据(JWT,实测 3 年有效;换发后旧 token 仍可用)。不装桌面端也能用。每次登录用全新浏览器 profile,绝不带旧票;登录收尾后连 profile 一起删掉(会话已进账号 metadata,浏览器目录不留第二份凭据)。网页会话 Cookie 过期后积分/签到会提示重新登录(重新走一次浏览器登录即可;模型凭据是 3 年 JWT,聊天不受影响)。需要本机有 Chrome 或 Edge(或用 `ASTUDIO_CHROME_PATH` 指到可执行文件);profile 根目录是 `<配置目录>/magpie/astudio-browser-profiles`——Windows 为 `%APPDATA%`、macOS/Linux 为 `~/.config`(`XDG_CONFIG_HOME` 可改),`ASTUDIO_BROWSER_PROFILE` 可整体覆盖;登录收尾即删。
2. **读取 AStudio 桌面端登录态**——本机装有 AStudio 桌面版并登录过即可,插件自动从它的数据目录读出模型凭据与网页会话(积分/签到用),不用填任何东西。没装/没登录时这一步会给出 [AStudio 官网](https://agent.xfyun.cn/) 链接并自动等待:装好登录后自动完成,不用回来点按钮。本机已有数据但读不出来(会话不是有效 JSON、没有凭据、账号被封禁)会直接说明原因,登录/修好后同样自动完成。数据目录按以下顺序查找:
- `ASTUDIO_HOME`(或 `SYNARA_HOME`)环境变量指定的目录;
- Windows 注册表 `HKCU\Software\AStudioStorage` 的 `Production/Canary/DevelopmentDataRoot`;
- 兜底 `~/.acode/acode/`。
- 目标文件:`<数据根>/userdata/astron-session.json`(其次 `<数据根>/runtime/acode-home/config.toml`,该方式无网页会话,积分/签到不可用)。
2. **粘贴 modelBearerToken**——从 `astron-session.json` 的 `modelBearerToken`(或 `config.toml` 的 `experimental_bearer_token`)复制粘贴;可选填账号面 `accountId` 与网页会话 `token`(两者齐才能用积分/签到,另有 `ssoSessionId`/uid 可选)。
3. **粘贴 modelBearerToken**——从 `astron-session.json` 的 `modelBearerToken`(或 `config.toml` 的 `experimental_bearer_token`)复制粘贴;可选填账号面 `accountId` 与网页会话 `token`(两者齐才能用积分/签到,另有 `ssoSessionId`/uid 可选)。
每个 AStudio 账号登录一次即得一个 magpie 账号,可多账号故障切换。凭据保存在 magpie 的 `plugin-auth.json`(权限 600),不上传。
每个 AStudio 账号登录一次即得 magpie 账号池里的一格:签到、用量、模型调用都按账号各算各的,网关在账号间故障切换。同一账号用浏览器登录和桌面端登录会归到同一格(`accountId` 都是 uid)。凭据保存在 magpie 的 `plugin-auth.json`(权限 600),不上传。
## 模型
@@ -52,11 +54,15 @@ same daily points balance.
## 每日签到(每日登录积分)
AStudio 有「每日登录积分」:服务端在当天账号会话首次活跃时发放(体验版 100 分/天,标准版 200,高级/畅享 400;活动期 31 天有效),客户端弹窗只做通知、没有领取接口。插件为此提供 magpie 的 `auth.checkin`:每天替账号做一次会话活跃(只读请求,带桌面端 `clientType` / `studioVersion` 身份头;缺 `clientType` 会被服务端以 `11001001` 拒绝),再观测前后余额差与 `client-popups/pending` 的 `DAILY_REWARD_DIALOG` 待通知弹窗——涨了记为已领取,见到弹窗记为今日已发放,两者都没有则如实报「未观测到新发放」,**不谎称已签**。发放由服务端按账号会话判定,插件不能代替桌面端登录,也不保证某天一定有积分到账。签到需要账号带网页会话(桌面端登录态方式默认有)。
AStudio 有「每日登录积分」:服务端在当天账号会话首次活跃时发放(体验版 100 分/天,标准版 200,高级/畅享 400;活动期 31 天有效),客户端弹窗只做通知、没有领取接口。
插件为此提供 magpie 的 `auth.checkin`,**先读当日获得流水**(`points/details?direction=CREDIT`,与网页后台「获得明细」同源,时间窗口按北京时间算):有 `GRANT` 且 reason 为「每日登录赠送」的入账即已发放——此时**一个写请求都不发**,连会话活跃也不做。流水为空才替账号做一次会话活跃(`POST tenant-app/v2/init-app`,带桌面端 `clientType` / `studioVersion` 身份头;缺 `clientType` 会被服务端以 `11001001` 拒绝),再读一次流水:新出现的 GRANT 行记为本次领取;流水接口不可用时退回余额差 + `client-popups/pending` 的 `DAILY_REWARD_DIALOG` 弹窗观测。余额涨了但流水还没入账也记领取(流水滞后);流水通畅、余额没涨、也没有当日弹窗则如实报「未观测到新发放」,**不谎称已签**。
签到**不调用** `client-popups/complete`:桌面端的「知道了」是桌面端的交互,插件只读弹窗、不替用户点掉。除 init-app 外,签到发出的都是只读请求。发放由服务端按账号会话判定,插件不能代替桌面端登录,也不保证某天一定有积分到账。签到需要账号带网页会话(浏览器登录与桌面端登录态方式默认有)。
## 用量
有网页会话时显示真实数据:会员档(体验版/标准版/高级版/畅享版)、通用积分余额(含最近到期批次与时间)、星火积分余额。所有读取均不计费;模型调用本身才消耗账号额度。401/403/登录异常会把账号标记为需要重新登录。
有网页会话时显示真实数据:会员档(体验版/标准版/高级版/畅享版)、通用积分余额(含最近到期批次与时间)、星火积分余额与最早到期时间(`runsOutAt` / `runsOut`:60 天流水里未过期批次按到期日聚合,翻页读取,金额按余额封顶)。星火积分 7 天内到期时,签到消息会追加提醒。所有读取均不计费;模型调用本身才消耗账号额度。401/403/登录异常会把账号标记为需要重新登录。
## 协议与上游
@@ -72,7 +78,7 @@ AStudio 有「每日登录积分」:服务端在当天账号会话首次活跃
```
magpie plugin add @magpie-community/opencode-astudio-auth
magpie plugin login astudio # 选「读取 AStudio 桌面端登录态」或「粘贴 modelBearerToken」
magpie plugin login astudio # 选「浏览器登录」「读取 AStudio 桌面端登录态」或「粘贴 modelBearerToken」
magpie provider test astudio spark-x2.6-4b # 限免模型,验收一发
```
+375
View File
@@ -0,0 +1,375 @@
// AStudio 网页登录的浏览器收割(CDP 管道客户端,移植自 mclaw/browser.mjs,
// 后者整体移植自 gcp-ai 插件,MIT)。
//
// Chrome/Edge 以 --remote-debugging-pipe 启动:CDP 走本进程的 fd 3/4(NUL 分隔
// JSON),不监听任何 TCP 端口,机器上其他进程碰不到这个浏览器会话。每次登录用
// 全新 profile(随机子目录),绝不复用旧登录态——换账号登录、会话被吊销后重登
// 都不会捡到上一次的 Cookie;登录收尾后目录即删(会话已进账号 metadata.session,
// 浏览器目录只是第二份凭据副本)。
import { spawn } from "node:child_process"
import { access, mkdir, readFile, rm, writeFile } from "node:fs/promises"
import { createHash, randomBytes } from "node:crypto"
import { homedir, tmpdir } from "node:os"
import { join, dirname, resolve } from "node:path"
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
const configRoot = () => process.env.XDG_CONFIG_HOME
|| (process.platform === "win32" && process.env.APPDATA ? process.env.APPDATA : join(homedir(), ".config"))
const cacheRoot = () => process.env.XDG_CACHE_HOME
|| (process.platform === "win32" && process.env.LOCALAPPDATA ? process.env.LOCALAPPDATA : join(homedir(), ".cache"))
// 登录态 profile 的根(ASTUDIO_BROWSER_PROFILE 可覆盖)。
export const profilesRoot = () => process.env.ASTUDIO_BROWSER_PROFILE
? resolve(process.env.ASTUDIO_BROWSER_PROFILE.startsWith("~") ? join(homedir(), process.env.ASTUDIO_BROWSER_PROFILE.slice(2)) : process.env.ASTUDIO_BROWSER_PROFILE)
: join(configRoot(), "magpie", "astudio-browser-profiles")
// 一次新登录的专属 profile:随机子目录,绝不带旧票。
export const freshSigninProfile = () => join(profilesRoot(), `signin-${Date.now().toString(36)}-${randomBytes(4).toString("hex")}`)
// 删掉一个登录用过的 profile:成功、失败、取消、超时都不留——会话已进账号
// metadata.session,浏览器目录只是第二份凭据副本。
export async function removeProfile(profilePath) {
if (profilePath) await rm(profilePath, { recursive: true, force: true }).catch(() => {})
}
// ---------------------------------------------------------------- profile 锁
// 同一 profile 的多个操作串行化:mkdir 原子抢锁,抢不到就排队。锁从抢到那一刻
// 一直持到 release() 被调(浏览器关掉之后)。
const LOCK_TIMEOUT = 180_000
async function claimProfileLock(profilePath) {
const lockDir = join(cacheRoot(), "magpie", "astudio", "profiles",
createHash("sha256").update(profilePath).digest("hex").slice(0, 16))
await mkdir(dirname(lockDir), { recursive: true }).catch(() => {})
const deadline = Date.now() + LOCK_TIMEOUT
for (;;) {
try {
await mkdir(lockDir)
await writeFile(join(lockDir, "pid"), String(process.pid)).catch(() => {})
break
} catch (error) {
if (error.code !== "EEXIST") throw error
// 持锁进程已经死了(上次没来得及清理)就偷走这把锁。
const holder = await readFile(join(lockDir, "pid"), "utf8").then((t) => Number(t.trim())).catch(() => NaN)
if (Number.isFinite(holder) && holder !== process.pid) {
let alive = true
try { process.kill(holder, 0) } catch (e) { alive = e.code === "EPERM" }
if (!alive) {
await rm(lockDir, { recursive: true, force: true }).catch(() => {})
continue
}
}
if (Date.now() >= deadline) throw new Error("AStudio 浏览器 profile 被其他操作占用,请稍后重试")
await sleep(500)
}
}
let released = false
return async () => {
if (released) return
released = true
await rm(lockDir, { recursive: true, force: true }).catch(() => {})
}
}
// ---------------------------------------------------------------- CDP 管道客户端
const timeoutError = (message) => Object.assign(new Error(message), { name: "TimeoutError" })
// 超时提示按量级选单位:不足 1 分钟说「45 秒」,别渲染成「0 分钟」。
const durationLabel = (ms) => (ms >= 60_000
? `${Math.round(ms / 60_000)} 分钟`
: `${Math.max(1, Math.round(ms / 1000))} 秒`)
// Chrome 每写完一个 JSON 消息跟一个 NUL。
class Pipe {
constructor(child) {
this.child = child
this.toChrome = child.stdio[3]
this.fromChrome = child.stdio[4]
this.buffer = ""
this.nextId = 1
this.pending = new Map()
this.events = new Map()
this.closed = false
this.closedReason = "Chrome was closed"
this.fromChrome.setEncoding("utf8")
this.fromChrome.on("data", (chunk) => this.read(chunk))
this.fromChrome.on("end", () => this.shut("Chrome closed the debugging connection"))
this.fromChrome.on("error", () => this.shut("Chrome closed the debugging connection"))
this.toChrome.on("error", () => this.shut("Chrome closed the debugging connection"))
child.once("exit", (code) => this.shut(`Chrome exited (${code ?? "signal"})`))
}
read(chunk) {
this.buffer += chunk
for (let end = this.buffer.indexOf("\0"); end >= 0; end = this.buffer.indexOf("\0")) {
const raw = this.buffer.slice(0, end)
this.buffer = this.buffer.slice(end + 1)
let message
try { message = JSON.parse(raw) } catch { continue }
if (message.id === undefined) {
for (const listener of this.events.get(`${message.sessionId ?? ""}:${message.method}`) ?? []) listener(message.params ?? {})
continue
}
const pending = this.pending.get(message.id)
if (!pending) continue
this.pending.delete(message.id)
if (message.error) pending.reject(new Error(message.error.message ?? "Chrome refused the command"))
else pending.resolve(message.result ?? {})
}
}
shut(reason) {
if (this.closed) return
this.closed = true
this.closedReason = reason
for (const { reject } of this.pending.values()) reject(new Error(reason))
this.pending.clear()
}
send(method, params = {}, sessionId) {
if (this.closed) return Promise.reject(new Error(this.closedReason))
const id = this.nextId++
const message = { id, method, params, ...(sessionId ? { sessionId } : {}) }
return new Promise((resolve, reject) => {
this.pending.set(id, { resolve, reject })
this.toChrome.write(JSON.stringify(message) + "\0")
})
}
}
class Page {
constructor(connection, sessionId, targetId) {
this.connection = connection
this.sessionId = sessionId
this.targetId = targetId
this.closed = false
}
send(method, params) {
return this.connection.send(method, params, this.sessionId)
}
isClosed() {
return this.closed || this.connection.closed
}
async close() {
if (this.closed) return
this.closed = true
if (this.connection.closed) return
await this.connection.send("Target.closeTarget", { targetId: this.targetId }).catch(() => {})
}
}
export class Browser {
constructor(child, connection) {
this.child = child
this.connection = connection
this.pages = new Set()
}
async firstPage(timeout = 15000) {
const deadline = Date.now() + timeout
while (Date.now() < deadline) {
const { targetInfos = [] } = await this.connection.send("Target.getTargets").catch(() => ({}))
const found = targetInfos.find((target) => target.type === "page")
if (found) {
const { sessionId } = await this.connection.send("Target.attachToTarget", { targetId: found.targetId, flatten: true })
const page = new Page(this.connection, sessionId, found.targetId)
this.pages.add(page)
page.send("Page.enable").catch(() => {})
return page
}
if (this.connection.closed) throw new Error(this.connection.closedReason)
await sleep(100)
}
throw new Error("浏览器没有打开页面")
}
// 关进程 = 收掉 profile 会话:Cookie 留在磁盘上,也不会留下无主浏览器。
async close() {
for (const page of this.pages) page.closed = true
const exited = new Promise((resolve) => {
if (this.child.exitCode !== null || this.child.signalCode !== null) resolve()
else this.child.once("exit", resolve)
})
await this.connection.send("Browser.close").catch(() => {})
this.connection.shut("Browser was closed")
const gone = await Promise.race([
exited.then(() => true),
sleep(5000).then(() => false),
])
if (!gone) {
this.child.kill("SIGTERM")
const stopped = await Promise.race([exited.then(() => true), sleep(3000).then(() => false)])
if (!stopped) {
this.child.kill("SIGKILL")
await Promise.race([exited, sleep(2000)])
}
}
}
}
function launch(executable, args, { timeout = 30000 } = {}) {
const child = spawn(executable, [...args, "--remote-debugging-pipe"], {
stdio: ["ignore", "ignore", "ignore", "pipe", "pipe"],
detached: false,
})
const connection = new Pipe(child)
const failed = new Promise((_, reject) => {
child.once("error", (error) => {
connection.shut("Browser could not be started")
reject(error.code === "ENOENT"
? new Error("找不到浏览器;请安装 Chrome/Edge,或用 ASTUDIO_CHROME_PATH 指到可执行文件")
: new Error(`浏览器无法启动:${error.message}`))
})
child.once("exit", (code) => {
connection.shut(`Browser exited (${code ?? "signal"})`)
})
})
failed.catch(() => {})
const browser = new Browser(child, connection)
return Promise.race([browser.firstPage(timeout).then((page) => ({ browser, page })), failed])
}
// ---------------------------------------------------------------- 浏览器定位
export async function browserExecutable() {
const override = process.env.ASTUDIO_CHROME_PATH
if (override) return resolve(override.startsWith("~") ? join(homedir(), override.slice(2)) : override)
const candidates = process.platform === "win32"
? [
process.env.PROGRAMFILES && join(process.env.PROGRAMFILES, "Google", "Chrome", "Application", "chrome.exe"),
process.env["PROGRAMFILES(X86)"] && join(process.env["PROGRAMFILES(X86)"], "Google", "Chrome", "Application", "chrome.exe"),
process.env.LOCALAPPDATA && join(process.env.LOCALAPPDATA, "Google", "Chrome", "Application", "chrome.exe"),
process.env["PROGRAMFILES(X86)"] && join(process.env["PROGRAMFILES(X86)"], "Microsoft", "Edge", "Application", "msedge.exe"),
process.env.PROGRAMFILES && join(process.env.PROGRAMFILES, "Microsoft", "Edge", "Application", "msedge.exe"),
process.env.LOCALAPPDATA && join(process.env.LOCALAPPDATA, "Chromium", "Application", "chrome.exe"),
].filter(Boolean)
: process.platform === "darwin"
? [
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
join(homedir(), "Applications", "Google Chrome.app", "Contents", "MacOS", "Google Chrome"),
"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
]
: ["/usr/bin/google-chrome", "/usr/bin/google-chrome-stable", "/usr/bin/chromium", "/usr/bin/chromium-browser", "/snap/bin/chromium"]
for (const path of candidates) {
try { await access(path); return path } catch {}
}
throw new Error("找不到 Chrome/Edge;请安装其中一个,或用 ASTUDIO_CHROME_PATH 指到可执行文件")
}
// ---------------------------------------------------------------- 打开/收割
/** 用专属 profile 开浏览器(登录用 headless: false,用户手动操作窗口)。
* 返回 { browser, page, profilePath, release }:release() 在 close() 之后调用才放锁。 */
export async function openBrowser({ headless = false, startUrl = "about:blank", profilePath = freshSigninProfile() } = {}) {
const release = await claimProfileLock(profilePath)
try {
await mkdir(profilePath, { recursive: true, mode: 0o700 })
const args = [
`--user-data-dir=${profilePath}`,
"--no-first-run", "--no-default-browser-check",
"--disable-background-networking", "--disable-sync", "--disable-default-apps",
"--disable-component-update", "--disable-client-side-phishing-detection",
"--disable-domain-reliability",
"--disable-features=Translate,OptimizationHints,MediaRouter,DialMediaRouteProvider",
"--metrics-recording-only", "--no-service-autorun",
// Cookie 存储用 mock keychain,不碰 macOS 钥匙串 / Linux keyring。
...(process.platform === "darwin" ? ["--use-mock-keychain"] : process.platform === "linux" ? ["--password-store=basic"] : []),
"--window-size=1280,900",
...(headless ? ["--headless=new", "--disable-gpu"] : []),
"--crash-dumps-dir=" + tmpdir(),
startUrl,
]
const started = await launch(await browserExecutable(), args)
return { ...started, profilePath, release }
} catch (error) {
await release()
await removeProfile(profilePath)
throw error
}
}
// 网页登录成功后写进 Cookie 的三件套(web bundle 从 URL 参数落到 document.cookie)。
const COOKIE_DOMAIN = /(^|\.)xfyun\.cn$/i
// 同名 Cookie 可能在 .xfyun.cn 和 agent.xfyun.cn 各有一份:登录页写的是
// host-only 的 agent.xfyun.cn,优先它,其次根域,最后其他子域(如 passport)。
const domainRank = (cookie) => {
const domain = String(cookie?.domain ?? "").replace(/^\./, "").toLowerCase()
if (domain === "agent.xfyun.cn") return 3
if (domain === "xfyun.cn") return 2
return 1
}
const pickCookie = (cookies, names) =>
cookies
.filter((c) => names.includes(c?.name) && COOKIE_DOMAIN.test(String(c?.domain ?? "")) && c?.value)
.sort((a, b) => domainRank(b) - domainRank(a))[0]
/** 读 AStudio 网页会话 Cookie(含 httpOnly;CDP 直读浏览器 Cookie 库)。
* 返回 { session: {token, accountId, ssoSessionId?} } 或 undefined。 */
export async function harvestAstronSession(browser) {
const { cookies = [] } = await browser.connection.send("Storage.getCookies").catch(() => ({}))
const token = pickCookie(cookies, ["token"])
const account = pickCookie(cookies, ["account_id", "accountId"])
const sso = pickCookie(cookies, ["ssoSessionId", "sso_sessionid"])
// 网页登录写的是 ssoSessionId + account_id(token 只是 SSO 顺带给的,可能没有;
// 2026-11-06 实测账号面与换发接口只用前两个也能通过)。
if (!account?.value || !sso?.value) return undefined
return {
session: {
...(token?.value ? { token: token.value } : {}),
accountId: account.value,
ssoSessionId: sso.value,
},
}
}
/** 浏览器登录全流程:有头浏览器(全新 profile)→ 用户在窗口里完成讯飞登录 →
* 收割 Cookie。返回 { promise, abort }:promise resolve { session, profilePath,
* release, close }。abort() 随时可调(宿主取消);成功/失败/取消/超时都删掉
* profile 目录——会话已进账号 metadata,浏览器目录不留第二份凭据。
* removeProfileImpl 只为测试能观测清理动作,生产不传。 */
export function startBrowserHarvest({ deadlineMs = 600_000, startUrl, profilePath = freshSigninProfile(), open = openBrowser, removeProfileImpl = removeProfile } = {}) {
const harvest = { promise: undefined, abort: async () => {} }
harvest.promise = (async () => {
let aborted = false
let opened // { browser, release }:浏览器开出后持有,成功时移交 callback
let usedPath = profilePath
harvest.abort = async () => {
if (aborted) return
aborted = true
if (opened) {
await opened.browser.close().catch(() => {})
await opened.release()
}
// 宿主取消时 callback 不会再被调,profile 没人认领;成功路径下 callback
// 自己也会删(rm 幂等),所以这里一律删。
await removeProfileImpl(usedPath)
}
try {
const { browser, profilePath: used, release } = await open({ headless: false, startUrl, profilePath })
opened = { browser, release }
usedPath = used
if (aborted) throw new Error("登录已取消")
const deadline = Date.now() + deadlineMs
for (;;) {
if (aborted) throw new Error("登录已取消")
if (browser.connection.closed) throw new Error("浏览器被关闭,登录中断")
const found = await harvestAstronSession(browser).catch(() => undefined)
if (found) return { ...found, profilePath: used, release, close: () => browser.close() }
if (Date.now() >= deadline) throw timeoutError(`登录超时(${durationLabel(deadlineMs)}内没有检测到 AStudio 登录)`)
await sleep(1500)
}
} catch (error) {
if (opened) {
await opened.browser.close().catch(() => {})
await opened.release()
}
await removeProfileImpl(usedPath)
throw error
}
})()
return harvest
}
+352 -32
View File
@@ -13,17 +13,26 @@
// 账号面 https://agent.xfyun.cn/xingchen-studio/…(Cookie 会话鉴权):
// points/balance、membership/me、membership/plan-config、points/summary
//
// 本插件复用这份登录态:第一种登录方式直接从磁盘读取桌面端会话(Raccoon
// 「复用桌面端登录态」同款;magpie 的 oauth 方式,读不到时给出官网链接并轮询,
// 等用户装好桌面端登录),第二种让用户手动粘贴 modelBearerToken。目录与
// 思考档位按账号实时拉取(目录读取不计费)。AStudio 有「每日登录积分」
// (服务端在当天账号会话首次活跃时发放,客户端弹窗只做通知,无领取接口),
// auth.checkin 用「发放前后余额差」观测:涨了记 claimed,没涨不谎称已签——
// 记 inactive 并说明未观测到(宿主把 done 渲染成「今日已签到」,是没发生的断言)。
// 三种登录方式:①浏览器登录(推荐,可多账号)——弹出全新 profile 的专用浏览器,
// 用户在里面登录后收割网页会话 Cookie(ssoSessionId + account_id 必需,token 有
// 则带上),再用桌面端启动时的同款 POST auth/bearer-token 换发模型凭据(JWT,
// 实测 3 年有效;换发后旧 token 仍可用),accountId 用账号 uid,同一账号的桌面端
// 与网页登录因此归到同一格;②读取桌面端登录态——直接从磁盘读桌面端会话
// (magpie 的 oauth 方式,读不到时给出官网链接并轮询,等用户装好登录);
// ③粘贴 modelBearerToken。目录与思考档位按账号实时拉取(目录读取不计费)。
//
// AStudio 有「每日登录积分」:服务端在当天账号会话首次活跃时发放,客户端弹窗
// 只做通知、没有领取接口。auth.checkin 先读当日获得流水(points/details
// direction=CREDIT,与网页后台「获得明细」同源):已有「每日登录赠送」GRANT 行
// 即 done,此时一个写请求都不发;流水为空才补一次会话活跃(POST
// tenant-app/v2/init-app,复刻桌面端启动),再读一次流水。流水读失败退回余额差 +
// 弹窗观测。流水通畅、余额没涨、也无当日弹窗则记 inactive——宿主把 done 渲染成
// 「今日已签到」,没发生的不能断言。
import { spawnSync } from "node:child_process"
import { readFileSync } from "node:fs"
import { homedir as osHomedir } from "node:os"
import * as browserDefault from "./browser.mjs"
const ID = "astudio"
@@ -38,6 +47,10 @@ const STUDIO_VERSION = "3.5.5"
// 读取桌面端登录态失败时展示的跳转页:AStudio 官网(含桌面端下载)。
const OFFICIAL_SITE = "https://agent.xfyun.cn/"
// 网页登录的落地页:登录后 web bundle 把 ssoSessionId/account_id/token 写进 Cookie。
const STUDIO_WEB_URL = "https://agent.xfyun.cn/studio-credits"
// 浏览器登录窗口的等待上限(宿主取消时也会提前 abort)。
const WEB_SIGNIN_WAIT_MS = 10 * 60 * 1000
// 等待「用户去装桌面端并登录」的窗口与轮询间隔。
const DESKTOP_POLL_MS = 2000
const DESKTOP_WAIT_MS = 5 * 60 * 1000
@@ -272,7 +285,7 @@ async function studioJson(path, { session, fetchImpl, method = "GET", body, oper
redirect: "error",
})
} catch (error) {
throw new Error(`${operation} 网络失败:${error?.cause?.code || error?.message || "未知错误"}`)
throw Object.assign(new Error(`${operation} 网络失败:${error?.cause?.code || error?.message || "未知错误"}`), { transient: true })
}
if (res.status === 401 || res.status === 403) {
throw Object.assign(new Error(`AStudio 会话已失效(HTTP ${res.status}),请重新登录 AStudio`), { signIn: "expired" })
@@ -288,11 +301,41 @@ async function studioJson(path, { session, fetchImpl, method = "GET", body, oper
if (envelope.code === 80000 || /重新登录/.test(String(envelope.desc ?? ""))) {
throw Object.assign(new Error(`AStudio 会话已失效,请重新登录 AStudio`), { signIn: "expired" })
}
throw new Error(`${operation} 失败(HTTP ${res.status}${envelope.desc ? `:${envelope.desc}` : ""})`)
throw Object.assign(new Error(`${operation} 失败(HTTP ${res.status}${envelope.desc ? `:${envelope.desc}` : ""})`), {
transient: res.status >= 500,
})
}
return envelope.data
}
// 网页登录换发模型凭据:桌面端启动时的同款 POST(Cookie 鉴权),返回
// modelBearerToken(JWT,实测 3 年有效期;换发后旧 token 仍可用)。
// 请求装配与错误分类都走 studioJson,别再抄一份(抄本必然与正本漂移)。
async function exchangeModelToken(session, fetchImpl) {
const data = await studioJson("auth/bearer-token", {
session,
fetchImpl,
method: "POST",
operation: "换发模型凭据",
})
const token = data?.modelBearerToken
if (typeof token !== "string" || !token) throw new Error("换发模型凭据失败:返回里没有 modelBearerToken")
return token
}
// 登录回调里的两次网络读:只有网络/5xx 这类瞬时失败重试,会话失效与确定性
// 4xx 不重试——用户刚在浏览器里登完,一次抖动不该把整次登录作废。
async function retryTransient(fn, sleep, attempts = 3, delayMs = 2000) {
for (let i = 0; ; i++) {
try {
return await fn()
} catch (error) {
if (!error?.transient || i + 1 >= attempts) throw error
await sleep(delayMs)
}
}
}
async function fetchCatalog(key, fetchImpl) {
return await fetchImpl(MODEL_MANAGER_URL, {
headers: { authorization: `Bearer ${key}`, accept: "application/json" },
@@ -307,7 +350,9 @@ function authResult(cred) {
return {
type: "success",
key: cred.key,
accountId: cred.uid,
// 实测 uid === account_id;session 里缺 uid 的旧登录态退回 account_id,
// 否则 accountId 为空会让宿主把多个账号塌进同一格。
accountId: cred.uid || cred.session?.accountId,
metadata: {
uid: cred.uid,
source: cred.source,
@@ -347,13 +392,106 @@ function reasonOf(error) {
: "本机没有 AStudio 桌面端登录态"
}
function createPlugin({ fetchImpl = globalThis.fetch, env = process.env, homedir = osHomedir(), registryQuery, readFileImpl, sleepImpl, nowMsImpl = () => Date.now() } = {}) {
function createPlugin({ fetchImpl = globalThis.fetch, env = process.env, homedir = osHomedir(), registryQuery, readFileImpl, sleepImpl, nowMsImpl = () => Date.now(), browserModule = browserDefault } = {}) {
const sleep = sleepImpl ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)))
async function readBalance(session) {
return await studioJson("points/balance", { session, fetchImpl, operation: "积分余额" })
}
// points/details 的时间参数格式(网页端同款):`YYYY-MM-DD HH:mm:ss`,服务端
// 按北京时间解释。窗口必须用 +08:00 的墙上时间算:本地时区(TZ=America/
// Los_Angeles)或 UTC 机器会把当天的 GRANT 行算到窗口外,签到误报 inactive。
// 时间只从 nowMsImpl 取,测试才能把时钟钉住。
const CST_OFFSET_MS = 8 * 3600 * 1000
function cstStamp(ms) {
const d = new Date(ms + CST_OFFSET_MS)
const p2 = (n) => String(n).padStart(2, "0")
return `${d.getUTCFullYear()}-${p2(d.getUTCMonth() + 1)}-${p2(d.getUTCDate())} ${p2(d.getUTCHours())}:${p2(d.getUTCMinutes())}:${p2(d.getUTCSeconds())}`
}
const cstDayStart = (ms) => Math.floor((ms + CST_OFFSET_MS) / 86400000) * 86400000 - CST_OFFSET_MS
const cstDayOf = (ms) => Math.floor((ms + CST_OFFSET_MS) / 86400000)
// 当日「每日登录赠送」入账流水。网页后台的获得明细(points/details
// direction=CREDIT)是权威数据源:发放一旦发生就有 GRANT 行,不管由哪个
// 端触发(桌面端 init-app、服务端午夜批量),都比「余额差+弹窗」可靠。
async function readDailyGrantLedger(session) {
const now = nowMsImpl()
const query = `pageNum=1&pageSize=50&direction=CREDIT&startTime=${encodeURIComponent(cstStamp(cstDayStart(now)))}&endTime=${encodeURIComponent(cstStamp(now))}`
const data = await studioJson(`points/details?${query}`, { session, fetchImpl, operation: "获得明细" })
const items = Array.isArray(data?.items) ? data.items : []
return items.find((item) => item?.direction === "CREDIT" && item?.operation === "GRANT" && item?.reason === "每日登录赠送") ?? null
}
// 星火积分最近到期批次(raccoon 同款算法):流水按 expireTime 聚合,
// 取最近的未过期批次金额,供 usage 窗口挂 runsOutAt/runsOut。
// 服务端时间戳是北京时间的裸串(无时区标记),显式钉 +08:00:
// 不同运行时对无时区 ISO 串的解释不同(node=本地时区、bun=UTC)。
const parseCST = (s) => Date.parse(/(?:[zZ]|[+-]\d{2}:?\d{2})$/.test(s) ? s : `${s}+08:00`)
async function readSparkExpiry(session, cap) {
const now = nowMsImpl()
const startTime = encodeURIComponent(cstStamp(now - 60 * 86400000))
const endTime = encodeURIComponent(cstStamp(now))
// 60 天窗口里每天一笔 GRANT,一页 50 行装不下——逐页读,最多 10 页,
// 用整行去重防服务端忽略 pageNum 时重复累加。
const seen = new Set()
const rows = []
for (let page = 1; page <= 10; page++) {
const data = await studioJson(
`points/details?pageNum=${page}&pageSize=50&direction=CREDIT&startTime=${startTime}&endTime=${endTime}`,
{ session, fetchImpl, operation: "获得明细" },
)
const batch = Array.isArray(data?.items) ? data.items : []
for (const item of batch) {
const key = JSON.stringify(item)
if (seen.has(key)) continue
seen.add(key)
rows.push(item)
}
if (batch.length < 50) break
}
let soonestMs = 0
let expiring = 0
for (const item of rows) {
if (item?.assetCode !== "SPARK_POINTS") continue
const amount = Number(item?.amount)
const expMs = item?.expireTime ? parseCST(item.expireTime) : NaN
if (!Number.isFinite(amount) || amount <= 0) continue
if (!Number.isFinite(expMs) || expMs <= now) continue
if (!soonestMs || expMs < soonestMs) {
soonestMs = expMs
expiring = amount
} else if (expMs === soonestMs) {
expiring += amount
}
}
if (!soonestMs) return null
// 流水记的是发放额,余额才是还没花掉的量:到期提示不能超过余额。
const limit = Number(cap)
const runsOut = Number.isFinite(limit) && limit >= 0 ? Math.min(expiring, limit) : expiring
return { runsOutAt: new Date(soonestMs).toISOString(), runsOut }
}
async function readPopups(session) {
return await studioJson("client-popups/pending", { session, fetchImpl, operation: "每日奖励弹窗" })
}
// 桌面端启动时的两个 POST 里,签到只复刻 init-app(租户初始化)。另一个
// auth/bearer-token 会换发 modelBearerToken;2026-11-06 实测新旧 token 并存
// (换发后旧 token 仍可用),但签到没有换发需求,多换一次只是白白轮换,
// 故仍不调用——浏览器登录自己需要 key 时才换。失败不塌方,但原因要收集
// 起来交给上层,否则用户分不清「POST 失败」和「今天确实没发」。
async function desktopLogin(session) {
const warnings = []
try {
await studioJson("tenant-app/v2/init-app", { session, fetchImpl, method: "POST", operation: "租户初始化" })
} catch (error) {
if (error?.signIn === "expired") throw error
warnings.push(`init-app ${error?.message ?? "失败"}`)
}
return { warnings }
}
return {
config: async (cfg) => {
cfg.provider ??= {}
@@ -369,6 +507,72 @@ function createPlugin({ fetchImpl = globalThis.fetch, env = process.env, homedir
auth: {
provider: ID,
methods: [
{
// 网页登录:浏览器里登一次,插件收割 Cookie(ssoSessionId/account_id/
// token)后换发模型凭据。每次登录用全新 profile,不串票;登录收尾后
// 连 profile 一起删掉——会话已存进 metadata.session,浏览器目录只是
// 第二份凭据副本,留着只会随每次重登无限堆积。accountId 用 uid——
// 同一账号用桌面端登录时也是 uid,宿主因此把两路登录归到同一格。
type: "oauth",
label: "浏览器登录(推荐,可多账号)",
async authorize(_inputs, { signal } = {}) {
// 先确认本机有 Chrome/Edge:没有就当场报错,别先说「已弹出」再失败。
await browserModule.browserExecutable?.()
const harvesting = browserModule.startBrowserHarvest({ deadlineMs: WEB_SIGNIN_WAIT_MS, startUrl: STUDIO_WEB_URL })
harvesting.promise.catch(() => {})
const cleanup = setTimeout(() => { harvesting.abort().catch(() => {}) }, WEB_SIGNIN_WAIT_MS)
// 别让这个兜底定时器拖住宿主的事件循环(测试里变成 5 分钟不退出)。
cleanup.unref?.()
const onAbort = () => { harvesting.abort().catch(() => {}) }
if (signal?.aborted) onAbort()
else if (typeof signal?.addEventListener === "function") signal.addEventListener("abort", onAbort, { once: true })
return {
url: "",
opened: true, // 浏览器已由本插件弹出,宿主不要再开 url
instructions: "已弹出专用浏览器窗口:请在里面登录讯飞账号(手机验证码或扫码均可),登录成功后本流程自动继续。",
method: "auto",
async callback(_code, { signal: callbackSignal } = {}) {
if (callbackSignal?.aborted) onAbort()
else if (typeof callbackSignal?.addEventListener === "function") callbackSignal.addEventListener("abort", onAbort, { once: true })
let harvested
try {
harvested = await harvesting.promise
const membership = await retryTransient(
() => studioJson("membership/me", { session: harvested.session, fetchImpl, operation: "会员信息" }),
sleep,
)
const uid = String(membership?.uid ?? "").trim()
if (!uid) throw new Error("AStudio 账号信息里没有 uid,无法确定账号")
const key = await retryTransient(() => exchangeModelToken(harvested.session, fetchImpl), sleep)
return {
type: "success",
key,
accountId: uid,
metadata: {
uid,
method: "web",
source: STUDIO_WEB_URL,
session: harvested.session,
},
}
} catch (error) {
return { type: "failed", error: error?.message ?? String(error) }
} finally {
clearTimeout(cleanup)
signal?.removeEventListener?.("abort", onAbort)
callbackSignal?.removeEventListener?.("abort", onAbort)
if (harvested) {
await harvested.close().catch(() => {})
await harvested.release()
// 会话已收进 metadata.session;浏览器目录是第二份凭据副本,
// 成功失败都不留(否则每次重登都在盘上堆一份)。
await browserModule.removeProfile(harvested.profilePath)
}
}
},
}
},
},
{
// oauth 方式:magpie 不显示 key 输入框,authorize 必须立刻返回
// { url, instructions, method, callback },结果由 callback 交回。
@@ -479,7 +683,9 @@ function createPlugin({ fetchImpl = globalThis.fetch, env = process.env, homedir
const auth = await getAuth()
if (auth?.type !== "api" || !auth.key) return {}
const session = auth.metadata?.session
if (!session?.token) {
// 账号面鉴权只需 ssoSessionId + account_id(2026-11-06 实测,token 可缺);
// account_id 是三种登录方式都有的最小标识。
if (!session?.accountId) {
let res
try {
res = await fetchCatalog(auth.key, fetchImpl)
@@ -523,7 +729,15 @@ function createPlugin({ fetchImpl = globalThis.fetch, env = process.env, homedir
})
}
if (balance && typeof balance.sparkTotalBalance === "number") {
windows.push({ name: "星火积分", balance: balance.sparkTotalBalance, aside: false })
// 星火积分的到期时间 balance 接口不给,从入账流水推(失败不塌方);
// 流水是发放额,到期提示按余额封顶。
const sparkExpiry = await readSparkExpiry(session, balance.sparkTotalBalance).catch(() => null)
windows.push({
name: "星火积分",
balance: balance.sparkTotalBalance,
aside: false,
...(sparkExpiry && balance.sparkTotalBalance > 0 ? sparkExpiry : {}),
})
}
return {
...(membership?.planName ? { plan: membership.planName } : { plan: "AStudio" }),
@@ -533,13 +747,14 @@ function createPlugin({ fetchImpl = globalThis.fetch, env = process.env, homedir
}
},
// 「每日登录积分」:服务端在当天账号会话首次活跃时发放,客户端没有领取
// 接口(DAILY_REWARD_DIALOG 弹窗只做通知)。这里以一组账号面请求代表
// 当天的会话活跃,再用余额差与待通知弹窗观测结果,不谎称已领取。
// 接口(DAILY_REWARD_DIALOG 弹窗只做通知)。先读当日获得流水:已有当日
// GRANT 行就 done、一个写请求都不发;流水为空才复刻桌面端启动的 init-app,
// 再读一次流水(流水读不到才退回余额差 + 弹窗观测)。
async checkin(getAuth) {
const auth = await getAuth()
if (auth?.type !== "api" || !auth.key) return {}
const session = auth.metadata?.session
if (!session?.token) {
if (!session?.accountId) {
return { outcome: "ineligible", message: "该账号只有模型凭据(无网页会话),无法执行每日登录签到" }
}
let config
@@ -552,46 +767,148 @@ function createPlugin({ fetchImpl = globalThis.fetch, env = process.env, homedir
if (config?.dailyLoginEnabled === false) {
return { outcome: "inactive", message: "当前没有每日登录积分活动" }
}
let before
const warnings = []
// 星火 7 天内到期时给签到消息加一句提醒(按北京时间算日历天,不是
// 「剩不到 24 小时」)。余额是还没花掉的量,提示金额不能超过它。
const expiryNote = async (cap) => {
let limit = cap
if (limit === undefined) {
const balance = await readBalance(session).catch(() => null)
limit = balance?.sparkTotalBalance
}
const sparkExpiry = await readSparkExpiry(session, limit).catch(() => null)
if (!sparkExpiry) return ""
const daysLeft = cstDayOf(Date.parse(sparkExpiry.runsOutAt)) - cstDayOf(nowMsImpl())
if (daysLeft > 7) return ""
return `;注意 ${sparkExpiry.runsOut} 星火积分${daysLeft <= 0 ? "今天" : ` ${daysLeft} 天内`}到期`
}
// 1) 流水优先:当日已有「每日登录赠送」GRANT 行 = 已发放。只读,
// 不写 init-app、不碰弹窗(11-06 实测服务端午夜批量先于签到)。
let grant = null
let ledgerError = null
try {
grant = await readDailyGrantLedger(session)
} catch (error) {
if (error?.signIn === "expired") throw error
ledgerError = error
}
if (grant) {
const rawPoints = Number(grant.amount)
const credit = Number.isFinite(rawPoints) && rawPoints > 0 ? rawPoints : 0
return {
outcome: "done",
...(credit > 0 ? { credit } : {}),
message: `每日登录积分 +${credit || 0} 已发放(流水实证,先于签到发生)${await expiryNote()}`,
}
}
// 2) 未发放:复刻桌面端启动的 init-app(签到唯一的写请求),再读一次
// 流水。余额只用于「流水滞后」归因与旧判据兜底。
let before = null
try {
before = await readBalance(session)
} catch (error) {
if (error?.signIn === "expired") throw error
return { outcome: "failed", message: error?.message ?? "积分余额读取失败" }
}
// 旧判据(流水不可用)才需要基线弹窗:签到前就挂着的旧弹窗不能算今天。
let hadDailyBefore = null
let baselineError = null
if (ledgerError) {
try {
const baseline = await readPopups(session)
hadDailyBefore = Array.isArray(baseline) && baseline.some((item) => item?.componentType === "DAILY_REWARD_DIALOG")
} catch (error) {
if (error?.signIn === "expired") throw error
baselineError = error
}
}
const login = await desktopLogin(session)
warnings.push(...login.warnings)
// 会话活跃 touch:与桌面端启动时同类只读请求。
await studioJson("membership/me", { session, fetchImpl, operation: "会员信息" }).catch(() => null)
await studioJson("points/summary", { session, fetchImpl, operation: "积分汇总" }).catch(() => null)
await sleep(2500)
let after
let after = null
try {
after = await readBalance(session)
} catch (error) {
if (error?.signIn === "expired") throw error
return { outcome: "failed", message: error?.message ?? "积分余额读取失败" }
}
if (typeof before?.totalBalance !== "number" || typeof after?.totalBalance !== "number") {
return { outcome: "failed", message: "积分余额读数不完整" }
}
const delta = after.totalBalance - before.totalBalance
if (delta > 0) return { outcome: "claimed", credit: delta, message: `每日登录积分 +${delta}` }
// 服务端把已发放但还没通知的每日奖励挂成待通知弹窗;见到它才算「今日已签到」。
let popups
let grantAfter = null
try {
popups = await studioJson("client-popups/pending", { session, fetchImpl, operation: "每日奖励弹窗" })
grantAfter = await readDailyGrantLedger(session)
} catch (error) {
if (error?.signIn === "expired") throw error
return { outcome: "failed", message: error?.message ?? "每日奖励弹窗读取失败" }
if (!ledgerError) ledgerError = error
}
if (grantAfter) {
const rawPoints = Number(grantAfter.amount)
const credit = Number.isFinite(rawPoints) && rawPoints > 0 ? rawPoints : 0
return {
outcome: "claimed",
...(credit > 0 ? { credit } : {}),
message: `每日登录积分 +${credit || "?"}(流水实证,本次签到触发)${await expiryNote(after?.sparkTotalBalance)}`,
}
}
const delta =
typeof before?.totalBalance === "number" && typeof after?.totalBalance === "number"
? after.totalBalance - before.totalBalance
: null
const warnSuffix = warnings.length ? `(${warnings.join(" / ")})` : ""
if (!ledgerError) {
// 流水通畅但无 GRANT 行:余额涨了说明发放已到账、流水只是滞后;
// 余额没涨才是真的没发。不谎称已签。
if (delta > 0) {
return {
outcome: "claimed",
credit: delta,
message: `每日登录积分 +${delta}(余额上涨,流水尚未入账)${await expiryNote(after?.sparkTotalBalance)}`,
}
}
return { outcome: "inactive", message: `未观测到新发放:当日获得流水无「每日登录赠送」记录${warnSuffix}` }
}
// ---- 流水读失败:退回旧判据(余额差+弹窗,只读)----
if (typeof before?.totalBalance !== "number" || typeof after?.totalBalance !== "number") {
return { outcome: "failed", message: `积分余额读数不完整${warnSuffix}` }
}
let popups = null
let popupError = null
try {
popups = await readPopups(session)
} catch (error) {
if (error?.signIn === "expired") throw error
popupError = error
}
if (delta > 0) {
return {
outcome: "claimed",
credit: delta,
message: `每日登录积分 +${delta}${await expiryNote(after?.sparkTotalBalance)}`,
}
}
// 基线读失败 ⇒ 不知道签到前是否已有弹窗,任何 done 结论都是猜的。
if (hadDailyBefore === null) {
return {
outcome: "failed",
message: `签到前无法读取每日奖励弹窗,不能判定今日是否发放${baselineError?.message ? `:${baselineError.message}` : ""}${warnSuffix}`,
}
}
if (popupError) {
return { outcome: "failed", message: `${popupError?.message ?? "每日奖励弹窗读取失败"}${warnSuffix}` }
}
const daily = Array.isArray(popups) && popups.find((item) => item?.componentType === "DAILY_REWARD_DIALOG")
if (daily) {
const rawPoints = Number(daily.payload?.points)
const credit = Number.isFinite(rawPoints) && rawPoints >= 0 ? rawPoints : 0
// payload 没有日期字段,签到前就挂着的那份无法断定是今天的。
if (hadDailyBefore === true) {
return { outcome: "inactive", message: "余额无变化,且签到前已有未确认的每日奖励弹窗,无法判定今日是否发放" }
}
return { outcome: "done", ...(credit > 0 ? { credit } : {}), message: "每日登录积分已发放(服务端待通知弹窗)" }
}
// 余额没涨、也没有待通知弹窗:发放可能挂靠桌面端登录,本次未观测到。
// done 会渲染成「今日已签到」,是没发生的断言,故记 inactive。
return { outcome: "inactive", message: "未观测到新发放:余额无变化(发放可能挂靠桌面端登录)" }
// 余额没涨、也没有待通知弹窗:这套请求序列没触发发放,不谎称已签。
return { outcome: "inactive", message: `未观测到新发放:余额无变化,也没有今日的每日奖励弹窗${warnSuffix}` }
},
},
@@ -650,12 +967,15 @@ export const _internal = {
registryDataRoots,
buildCookieHeader,
studioJson,
exchangeModelToken,
MODEL_GATEWAY_BASE,
MODEL_MANAGER_URL,
STUDIO_API_BASE,
STUDIO_VERSION,
STUDIO_WEB_URL,
OFFICIAL_SITE,
DESKTOP_WAIT_MS,
WEB_SIGNIN_WAIT_MS,
BOOTSTRAP,
ID,
}
File diff suppressed because it is too large Load Diff
+3 -2
View File
@@ -1,12 +1,13 @@
{
"name": "@magpie-community/opencode-astudio-auth",
"version": "0.1.4",
"description": "AStudio (iFLYTEK Astron Studio) desktop sign-in as an OpenCode/magpie provider: Responses model gateway with live model catalog",
"version": "0.2.0",
"description": "AStudio (iFLYTEK Astron Studio) sign-in as an OpenCode/magpie provider: browser sign-in with one account-pool slot per account, or the desktop sign-in, over the Responses model gateway with live model catalog",
"type": "module",
"main": "./opencode.mjs",
"exports": { ".": "./opencode2.mjs" },
"files": [
"index.mjs",
"browser.mjs",
"opencode.mjs",
"opencode2.mjs",
"README.md",
+3 -3
View File
@@ -189,8 +189,8 @@
],
"community": true,
"summary": {
"en": "Third-party Magpie adapter for dsh-providers-hub (by JetLi): ten providers, each a separate channel you can sign in to, meter and switch off on its own — AStudio (iFlytek), Accio (Alibaba), LobsterAI (Youdao), MagiCrew (letsmagic.cn / magicrew.ai), AutoClaw (international autoglm.ai / China zhipuai.cn), and Loomy (iFlytek), plus MonkeyCode (monkeycode-ai.com China / monkeycode-ai.net international). Channels already in the registry are shipped only with a named difference (#614; see the notes below). Runs without DSH. Its AStudio signs in on a local page (SMS, password or WeChat QR, no desktop app needed) and calls chat/completions; the standalone AStudio plugin (astudio) reuses the desktop sign-in and calls Responses. On one account both share the same daily points pool. Its AutoClaw providers sign in by pasting an accessToken + refreshToken, or by reading an already signed-in AutoClaw desktop client (current Windows user only, off unless clicked) — web OAuth and phone SMS are NOT supported here, use opencode-autoclaw-auth for those. Note: importing rotates the one-time refresh token, which signs the desktop client out; it will ask for sign-in again afterwards. Both plugins read one account's credit balance, so spend in one and the other sees it. Its Loomy adds WeChat QR sign-in (the official iFlytek WeChat OAuth, long-poll for the code) — the standalone Loomy plugin (opencode-loomy-auth) has SMS code + pasted session but no WeChat QR; SMS code sign-in works the same in both (the plugin's local sign-in page offers only WeChat QR and SMS — no pasted-session entry; use opencode-loomy-auth for that), and both read one account's credit balance. Its MonkeyCode providers (new channels, no standalone-package overlap) reach the OhMyAgent gateway over the Anthropic Messages protocol with a per-prompt HMAC signature; sign in through a browser window (the plugin reads the HttpOnly session cookie and exchanges it for gateway credentials) or paste an API key + signing secret; the daily-tier models (monkeycode-basic/pro/ultra/…) draw on the subscription quota and unprefixed models draw on credits, with a Cap proof-of-work daily check-in when a web session is present.",
"zh": "dsh-providers-hub(作者 JetLi)的第三方适配:十条供应商(每渠道一条,可各自登录/看额度/单独关闭)——AStudio(讯飞)、Accio(阿里)、LobsterAI(有道)、超级麦吉/MagiCrew(letsmagic.cn / magicrew.ai)、AutoClaw(autoglm.ai 国际 / zhipuai.cn 国内)、Loomy(讯飞)、MonkeyCode(monkeycode-ai.com 国内 / monkeycode-ai.net 国际)。与 registry 已有渠道重复的,只有写明差别(#614,见下方各渠道说明)才提供。不依赖 DSH 运行。其中 AStudio 在本地登录页用短信、密码或微信扫码登录(不需要桌面端),走 chat/completions;独立的 AStudio 插件(astudio)复用桌面端登录态,走 Responses。同一账号两边共用一个每日积分池。其 AutoClaw 两条渠道的登录方式只有两种:粘贴 accessToken + refreshToken,或读取已登录的 AutoClaw 桌面端(仅当前 Windows 用户、默认关闭、需主动点击);不支持网页 OAuth 与手机验证码,需要请用 opencode-autoclaw-auth。注意:导入会轮换一次性的 refresh_token,桌面客户端会被登出、之后需要重新登录。两个插件读同一账号的积分余额,一边用掉的另一边会同步减少。其 Loomy 新增微信扫码登录(讯飞官方微信 OAuth,长轮询拿 code)——独立的 Loomy 插件(opencode-loomy-auth)只有短信验证码与粘贴 session,没有微信扫码;短信验证码两边同款(本插件登录页只有微信扫码与短信两条路,没有粘贴 session 入口,要粘贴请用独立包),读的也是同一账号的积分余额。 其 MonkeyCode 两条渠道为新渠道(registry 无同渠道独立包),走 OhMyAgent 网关的 Anthropic Messages 协议(按 prompt 文本做 HMAC 签名);登录为浏览器窗口(插件读 HttpOnly 会话 cookie 换网关凭据)或粘贴 API Key + 签名密钥;monkeycode-basic/pro/ultra/ 前缀模型走订阅每日额度、不带前缀走积分,有网页会话时支持 Cap 工作量证明的每日签到。"
"en": "Third-party Magpie adapter for dsh-providers-hub (by JetLi): ten providers, each a separate channel you can sign in to, meter and switch off on its own — AStudio (iFlytek), Accio (Alibaba), LobsterAI (Youdao), MagiCrew (letsmagic.cn / magicrew.ai), AutoClaw (international autoglm.ai / China zhipuai.cn), and Loomy (iFlytek), plus MonkeyCode (monkeycode-ai.com China / monkeycode-ai.net international). Channels already in the registry are shipped only with a named difference (#614; see the notes below). Runs without DSH. Its AStudio signs in on a local page (SMS, password or WeChat QR, no desktop app needed) and calls chat/completions; the standalone AStudio plugin (astudio) signs in through a browser or reuses the desktop sign-in, and calls Responses. On one account both share the same daily points pool. Its AutoClaw providers sign in by pasting an accessToken + refreshToken, or by reading an already signed-in AutoClaw desktop client (current Windows user only, off unless clicked) — web OAuth and phone SMS are NOT supported here, use opencode-autoclaw-auth for those. Note: importing rotates the one-time refresh token, which signs the desktop client out; it will ask for sign-in again afterwards. Both plugins read one account's credit balance, so spend in one and the other sees it. Its Loomy adds WeChat QR sign-in (the official iFlytek WeChat OAuth, long-poll for the code) — the standalone Loomy plugin (opencode-loomy-auth) has SMS code + pasted session but no WeChat QR; SMS code sign-in works the same in both (the plugin's local sign-in page offers only WeChat QR and SMS — no pasted-session entry; use opencode-loomy-auth for that), and both read one account's credit balance. Its MonkeyCode providers (new channels, no standalone-package overlap) reach the OhMyAgent gateway over the Anthropic Messages protocol with a per-prompt HMAC signature; sign in through a browser window (the plugin reads the HttpOnly session cookie and exchanges it for gateway credentials) or paste an API key + signing secret; the daily-tier models (monkeycode-basic/pro/ultra/…) draw on the subscription quota and unprefixed models draw on credits, with a Cap proof-of-work daily check-in when a web session is present.",
"zh": "dsh-providers-hub(作者 JetLi)的第三方适配:十条供应商(每渠道一条,可各自登录/看额度/单独关闭)——AStudio(讯飞)、Accio(阿里)、LobsterAI(有道)、超级麦吉/MagiCrew(letsmagic.cn / magicrew.ai)、AutoClaw(autoglm.ai 国际 / zhipuai.cn 国内)、Loomy(讯飞)、MonkeyCode(monkeycode-ai.com 国内 / monkeycode-ai.net 国际)。与 registry 已有渠道重复的,只有写明差别(#614,见下方各渠道说明)才提供。不依赖 DSH 运行。其中 AStudio 在本地登录页用短信、密码或微信扫码登录(不需要桌面端),走 chat/completions;独立的 AStudio 插件(astudio)可在浏览器里登录(可多账号)或复用桌面端登录态,也可以粘贴模型凭据,走 Responses。同一账号两边共用一个每日积分池。其 AutoClaw 两条渠道的登录方式只有两种:粘贴 accessToken + refreshToken,或读取已登录的 AutoClaw 桌面端(仅当前 Windows 用户、默认关闭、需主动点击);不支持网页 OAuth 与手机验证码,需要请用 opencode-autoclaw-auth。注意:导入会轮换一次性的 refresh_token,桌面客户端会被登出、之后需要重新登录。两个插件读同一账号的积分余额,一边用掉的另一边会同步减少。其 Loomy 新增微信扫码登录(讯飞官方微信 OAuth,长轮询拿 code)——独立的 Loomy 插件(opencode-loomy-auth)只有短信验证码与粘贴 session,没有微信扫码;短信验证码两边同款(本插件登录页只有微信扫码与短信两条路,没有粘贴 session 入口,要粘贴请用独立包),读的也是同一账号的积分余额。 其 MonkeyCode 两条渠道为新渠道(registry 无同渠道独立包),走 OhMyAgent 网关的 Anthropic Messages 协议(按 prompt 文本做 HMAC 签名);登录为浏览器窗口(插件读 HttpOnly 会话 cookie 换网关凭据)或粘贴 API Key + 签名密钥;monkeycode-basic/pro/ultra/ 前缀模型走订阅每日额度、不带前缀走积分,有网页会话时支持 Cap 工作量证明的每日签到。"
}
},
{
@@ -215,7 +215,7 @@
}
},
{ "package": "@magpie-community/opencode-astudio-auth", "name": "AStudio", "providers": ["astudio"], "community": true,
"summary": { "en": "Unofficial AStudio (iFLYTEK Astron Studio desktop): reuse the desktop sign-in to serve its Responses model gateway, with the live model catalog, daily login-points check-in and points balance. Desktop discovery runs on Windows (registry lookup), with a paste-token fallback. Differs from Providers Hub's hub-astudio, which signs in on a local page (SMS, password or WeChat QR) and calls chat/completions; on one account both share the same daily points pool.", "zh": "非官方 AStudio(科大讯飞 Astron Studio 桌面端):复用桌面端登录态接入其模型网关,含实时模型目录、每日登录积分签到与积分余额。桌面端发现仅 Windows(注册表定位),另有粘贴凭据方式。与 Providers Hub 的 hub-astudio 不同:那边在本地登录页用短信、密码或微信扫码登录,走 chat/completions;同一账号两边共用一个每日积分池。" } },
"summary": { "en": "Unofficial AStudio (iFLYTEK Astron Studio): sign in through a browser (each account gets its own pool slot), reuse the desktop sign-in, or paste a token, to serve its Responses model gateway with the live model catalog, daily login-points check-in (read from the credit ledger) and points balance with spark-point expiry. Differs from Providers Hub's hub-astudio, which signs in on a local page (SMS, password or WeChat QR) and calls chat/completions; on one account both share the same daily points pool.", "zh": "非官方 AStudio(科大讯飞 Astron Studio):支持浏览器登录(每个账号占账号池一格)、复用桌面端登录态或粘贴凭据,接入其模型网关,含实时模型目录、每日登录积分签到(按积分流水判定)与积分余额/星火到期时间。与 Providers Hub 的 hub-astudio 不同:那边在本地登录页用短信、密码或微信扫码登录,走 chat/completions;同一账号两边共用一个每日积分池。" } },
{ "package": "@magpie-community/opencode-agnes-code-auth", "name": "Agnes Code", "providers": ["agnes-code"], "community": true,
"summary": { "en": "Unofficial Agnes Code desktop: reuse the desktop sign-in for its OpenAI-compatible gateway, with the live model catalog, daily credit check-in and points balance. Desktop decryption is Windows-only; a paste-token method covers the rest. Differs from opencode-agnes-auth (`agnes`), which signs in to Agnes AI international in Chrome and meters that product's plans and USD balance: this one serves the Agnes Code desktop product and its daily credits.", "zh": "非官方 Agnes Code 桌面端:复用桌面端登录态接入其 OpenAI 兼容网关,含实时模型目录、每日积分签到与余额显示。桌面端解密仅限 Windows,其余平台用粘贴 accessToken。与 opencode-agnes-auth(`agnes`)不同:那边在 Chrome 里登录 Agnes AI 国际版、显示该产品的套餐与美元余额;本包服务 Agnes Code 桌面端产品与它的每日积分。" } },
{ "package": "@magpie-community/opencode-tabbit-auth", "name": "Tabbit", "icon": "https://web.tabbit.com/favicon.ico", "providers": ["tabbit"], "community": true,