astudio, agnes-code 0.1.0: AStudio and Agnes Code desktop provider plugins (#595, jinyue806)
Adds two unofficial provider packages by jinyue806: - packages/astudio (@magpie-community/opencode-astudio-auth 0.1.0, provider `astudio`): iFLYTEK AStudio (Astron Studio) desktop's saved session or a pasted model token; OpenAI Responses at astronstudio-api-volces-prod.xf-yun.com, live catalog, points balance and an observed daily-login check-in from agent.xfyun.cn. - packages/agnes-code (@magpie-community/opencode-agnes-code-auth 0.1.0, provider `agnes-code`): Agnes Code desktop's safeStorage session (Windows, DPAPI via PowerShell) or a pasted JWT; chat completions at api-agnes-code.agnes-ai.com, live catalog, credits balance from api.agnes-ai.com. - README rows and two registry.json entries. Answers the 11-01 review at 36dd528: tests added with injected fetch/fs/DPAPI, registry kept in its style, folders renamed, README ids fixed, paste methods store their inputs, check-in says inactive (not done) when nothing was observed, usage keeps signIn expired, injected homedir honoured, platform checked before any read on Agnes. Run at the reviewed head 9aaff0d on mote: - node --test: astudio 24 pass, agnes-code 17 pass - bun scripts/check.mjs astudio / agnes-code: ok - full bun test with HOME=$(mktemp -d): 4548 pass, 9 skip, 0 fail - Broken by hand, each red then restored: fallback paths ignoring homedir (1 fail), usage swallowing expired (1 fail), Agnes check-in back to "done" (1 fail) - Unauthenticated probe of each host: model-manager 401, Agnes /v1/models and credits-balance 401 "Login expired", agent.xfyun.cn 200 with code 80000 (all map to signIn expired in the code) Hosts: only the vendors' own (xf-yun.com, xfyun.cn, agnes-ai.com). No dependencies, no install scripts. Not tried: a real AStudio or Agnes Code account (no install on our machines), the Windows registry and DPAPI paths on a real Windows desktop. Not on npm yet: served from the dist branch until first published by hand.
This commit is contained in:
@@ -11,6 +11,8 @@ subscription and makes its requests. The packages work in OpenCode and in
|
||||
|
||||
| Package | Signs in to | Provider id |
|
||||
|---|---|---|
|
||||
| [agnes-code](packages/agnes-code) | Agnes AI's Agnes Code desktop, with the desktop's saved session (Windows) or a pasted access token: live models, daily credit check-in and points balance (unofficial) | `agnes-code` |
|
||||
| [astudio](packages/astudio) | iFlytek's AStudio (科大讯飞 Astron Studio desktop), with the desktop's saved credentials or a pasted model token: live model catalog, daily login-points check-in and points balance (unofficial) | `astudio` |
|
||||
| [catpaw](packages/catpaw) | Meituan's 妙手 CatPaw (ai.catpaw.meituan.com), with a browser web sign-in or the desktop client's saved credentials | `catpaw` |
|
||||
| [cline](packages/cline) | Cline (cline.bot): usage-billed models, ClinePass's and Cline's free ones, with Cline's device sign-in or an API key | `cline` |
|
||||
| [codearts](packages/codearts) | Huawei Cloud CodeArts (码道) coding plans (Trial, personal and enterprise credits), with Huawei Cloud OAuth sign-in (unofficial) | `codearts` |
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Pursuit806
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,67 @@
|
||||
# @magpie-community/opencode-agnes-code-auth
|
||||
|
||||
把 **Agnes Code 桌面端** 的账号额度接入 [magpie](https://usemagpie.ai/) 与 [OpenCode](https://opencode.ai/):复用桌面端登录态(会话文件解密),直连云端 OpenAI 兼容网关,agent 以 `agnes-code/<model>` 使用它的模型;支持「每日登录送积分」自动观测与积分余额显示。
|
||||
|
||||
## 登录什么
|
||||
|
||||
两种方式(登录时二选一):
|
||||
|
||||
1. **读取 Agnes Code 桌面端登录态(推荐,仅 Windows)**——本机装有 Agnes Code 桌面版并登录过即可。插件按 Chrome 同款方案解出会话(`Local State` 的 DPAPI 包裹 AES 主密钥 → 解 `code-auth-session.v1` 的 AES-256-GCM),只在本机、当前 Windows 用户下可解,凭据不外传:
|
||||
- 会话目录:`%APPDATA%\AgnesCode\`。macOS/Linux 下桌面端解密不可用,会明确提示改用粘贴方式。
|
||||
- 会话 JWT 过期会提示打开 Agnes Code 重新登录后重试(桌面端负责续期)。
|
||||
2. **粘贴 accessToken**——从桌面端会话里复制 JWT(`eyJ…`);可选填用户名便于区分账号。
|
||||
|
||||
每个账号登录一次即得一个 magpie 账号,可多账号故障切换。凭据保存在 magpie 的 `plugin-auth.json`(权限 600),不上传。
|
||||
|
||||
## 模型
|
||||
|
||||
供应商 id `agnes-code`。目录**按账号实时拉取**(`GET /v1/models`,读取不计费)。2026-11 实测目录:
|
||||
|
||||
| modelId | context | 备注 |
|
||||
| --- | --- | --- |
|
||||
| `agnes-3.0-flash` | 512k | 免费,思考 |
|
||||
| `agnes-2.5-flash` | 512k | 免费,思考 |
|
||||
| `agnes-2.5-pro` | 512k | 免费,思考 |
|
||||
| `gpt-6.1-sol` | 1M | 会员 |
|
||||
| `gpt-6-astra` | 1M | 会员 |
|
||||
| `grok-4.7` | 500k | 会员 |
|
||||
| `claude-opus-5-5` | 1M | 会员 |
|
||||
| `deepseek-v4.1-flash` | 1M | 会员,思考 |
|
||||
| `deepseek-v4-pro` | 1M | 会员,思考 |
|
||||
| `glm-5.3` | 1M | 会员 |
|
||||
| `kimi-k3` | 1M | 会员 |
|
||||
|
||||
带 `thinking_toggle` 的模型标为推理模型;会员专属模型照常列出,免费账号调用会得到上游透明的 403(`subscription_required`),不影响登录态。
|
||||
|
||||
## 每日签到
|
||||
|
||||
免费档「每日登录送 600 积分」由服务端随当日会话自动发放,没有领取接口——插件的 `auth.checkin` 每天做一次账号会话活跃(只读请求)并观测发放前后的余额差:涨了记已领取(+600);没涨**不谎称已签**,如实报「未观测到新发放」(发放可能挂靠桌面端登录)。
|
||||
|
||||
## 用量
|
||||
|
||||
显示真实积分余额(`GET /api/v2/subscription/credits-balance`,读取不计费):积分总额、限时积分、永久积分(有则显示)。401/403 会把账号标记为需要重新登录。
|
||||
|
||||
## 协议与上游
|
||||
|
||||
- 模型调用:`POST https://api-agnes-code.agnes-ai.com/v1/chat/completions`(OpenAI chat 协议,`Authorization: Bearer <accessToken>`,思考在 `reasoning_content`)。
|
||||
- 模型目录:`GET https://api-agnes-code.agnes-ai.com/v1/models`。
|
||||
- 积分:`GET https://api.agnes-ai.com/api/v2/subscription/credits-balance`。
|
||||
|
||||
## 风险提示
|
||||
|
||||
非官方集成,凭据与协议来自桌面客户端逆向,上游随时可能变更;共享登录态的自动化使用可能违反 Agnes Code 服务条款,账号风险自担。请勿用于批量/滥用场景。
|
||||
|
||||
## 安装与开发
|
||||
|
||||
```
|
||||
magpie plugin add @magpie-community/opencode-agnes-code-auth
|
||||
magpie plugin login agnes-code # 选「读取 Agnes Code 桌面端登录态」或「粘贴 accessToken」
|
||||
magpie provider test agnes-code agnes-3.0-flash
|
||||
```
|
||||
|
||||
测试(零依赖,Node ≥18 或 Bun):
|
||||
|
||||
```
|
||||
npm test # = node --test
|
||||
# 或 bun test
|
||||
```
|
||||
@@ -0,0 +1,416 @@
|
||||
// Agnes Code(Agnes 桌面端)for OpenCode and magpie.
|
||||
//
|
||||
// Agnes Code 桌面端登录后把会话写进 Electron safeStorage(Chromium os_crypt,
|
||||
// Chrome 同款方案):
|
||||
// <userData>/Local State — os_crypt.encrypted_key(base64,
|
||||
// 去 5 字节 "DPAPI" 前缀后 DPAPI 解出
|
||||
// AES-256-GCM 主密钥)
|
||||
// <userData>/code-auth-session.v1 — "v10" + 12 字节 nonce + AES-GCM 密文
|
||||
// 明文 = { accessToken(JWT, Bearer 用),
|
||||
// userInfo{username,...}, bffPublicBaseUrl }
|
||||
// 云端(与桌面端同源同凭据):
|
||||
// 模型调用 POST https://api-agnes-code.agnes-ai.com/v1/chat/completions
|
||||
// (OpenAI chat 协议,Authorization: Bearer <accessToken>,
|
||||
// 思考在 reasoning_content 字段)
|
||||
// 模型目录 GET https://api-agnes-code.agnes-ai.com/v1/models
|
||||
// 积分余额 GET https://api.agnes-ai.com/api/v2/subscription/credits-balance
|
||||
//
|
||||
// 本插件复用这份登录态:第一种登录方式在磁盘上解出桌面端会话(同用户同机器的
|
||||
// DPAPI 即可解,无需密钥口令,仅 Windows),第二种让用户手动粘贴 accessToken。
|
||||
// 积分「每日登录送 600」(免费档)由服务端随当日会话发放、无领取接口,
|
||||
// auth.checkin 用发放前后余额差观测:涨了记 claimed,没涨不谎称已签——
|
||||
// 记 inactive 并说明未观测到(宿主把 done 渲染成「今日已签到」,是没发生的断言)。
|
||||
|
||||
import { spawn } from "node:child_process"
|
||||
import { createDecipheriv } from "node:crypto"
|
||||
import { readFileSync } from "node:fs"
|
||||
import { homedir as osHomedir } from "node:os"
|
||||
import { join } from "node:path"
|
||||
|
||||
const ID = "agnes-code"
|
||||
|
||||
// 云端地址(2026-11-01 实测)。
|
||||
const CHAT_GATEWAY_BASE = "https://api-agnes-code.agnes-ai.com/v1"
|
||||
const MODELS_URL = "https://api-agnes-code.agnes-ai.com/v1/models"
|
||||
const POINTS_API_BASE = "https://api.agnes-ai.com"
|
||||
const BALANCE_PATH = "/api/v2/subscription/credits-balance"
|
||||
|
||||
// 模型目录读不到时的启动表(2026-11-01 实测快照;models 钩子会用实时目录覆盖)。
|
||||
const BOOTSTRAP = [
|
||||
{ id: "agnes-3.0-flash", context: 512000, output: 65536, thinking: true },
|
||||
{ id: "agnes-2.5-flash", context: 512000, output: 65536, thinking: true },
|
||||
{ id: "agnes-2.5-pro", context: 512000, output: 65536, thinking: true },
|
||||
{ id: "gpt-6.1-sol", context: 1000000, output: 131072, thinking: false },
|
||||
{ id: "gpt-6-astra", context: 1000000, output: 131072, thinking: false },
|
||||
{ id: "grok-4.7", context: 500000, output: 128000, thinking: false },
|
||||
{ id: "claude-opus-5-5", context: 1000000, output: 128000, thinking: false },
|
||||
{ id: "deepseek-v4.1-flash", context: 1000000, output: 393216, thinking: true },
|
||||
{ id: "deepseek-v4-pro", context: 1000000, output: 393216, thinking: true },
|
||||
{ id: "glm-5.3", context: 1000000, output: 131072, thinking: false },
|
||||
{ id: "kimi-k3", context: 1048576, output: 131072, thinking: false },
|
||||
]
|
||||
|
||||
// rowFromCatalogEntry 把 /v1/models 的一个模型变成 OpenCode 的 Model。
|
||||
// member_only 模型照常列出:免费账号调用会得到上游透明的 403
|
||||
// (subscription_required),magpie 按模型被拒处理,不会误标登录态。
|
||||
function rowFromCatalogEntry(m) {
|
||||
const thinking = !!m?.thinking_toggle
|
||||
return {
|
||||
id: m.id,
|
||||
name: m.id,
|
||||
limit: {
|
||||
context: typeof m?.max_input_tokens === "number" && m.max_input_tokens > 0 ? m.max_input_tokens : 0,
|
||||
output: typeof m?.max_output_tokens === "number" && m.max_output_tokens > 0 ? m.max_output_tokens : 0,
|
||||
},
|
||||
reasoning: thinking,
|
||||
tool_call: true,
|
||||
modalities: { input: ["text"], output: ["text"] },
|
||||
capabilities: {
|
||||
reasoning: thinking,
|
||||
toolcall: true,
|
||||
attachment: false,
|
||||
input: { text: true, image: false },
|
||||
output: { text: true },
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function bootstrapRows() {
|
||||
return Object.fromEntries(
|
||||
BOOTSTRAP.map((m) => [
|
||||
m.id,
|
||||
{
|
||||
id: m.id,
|
||||
name: m.id,
|
||||
limit: { context: m.context, output: m.output },
|
||||
reasoning: m.thinking,
|
||||
tool_call: true,
|
||||
modalities: { input: ["text"], output: ["text"] },
|
||||
capabilities: {
|
||||
reasoning: m.thinking,
|
||||
toolcall: true,
|
||||
attachment: false,
|
||||
input: { text: true, image: false },
|
||||
output: { text: true },
|
||||
},
|
||||
},
|
||||
]),
|
||||
)
|
||||
}
|
||||
|
||||
// parseEncryptedKey 从 Local State 的 os_crypt.encrypted_key(base64)解出
|
||||
// DPAPI 包裹前的形态校验:去 5 字节 "DPAPI" 前缀,返回待 DPAPI 解密的字节。
|
||||
function parseEncryptedKey(b64) {
|
||||
const blob = Buffer.from(b64, "base64")
|
||||
if (blob.subarray(0, 5).toString("latin1") !== "DPAPI") {
|
||||
throw new Error("Local State 的 encrypted_key 不是 DPAPI 形态")
|
||||
}
|
||||
return blob.subarray(5)
|
||||
}
|
||||
|
||||
// decryptSessionWithKey 用主密钥解开 "v10" safeStorage 会话文件。
|
||||
function decryptSessionWithKey(keyBuf, rawBuf) {
|
||||
if (rawBuf.subarray(0, 3).toString("latin1") !== "v10") {
|
||||
throw new Error("会话文件不是 v10 safeStorage 形态")
|
||||
}
|
||||
const nonce = rawBuf.subarray(3, 15)
|
||||
const tagged = rawBuf.subarray(15)
|
||||
if (tagged.length < 28) throw new Error("会话文件内容太短")
|
||||
const decipher = createDecipheriv("aes-256-gcm", keyBuf, nonce)
|
||||
decipher.setAuthTag(tagged.subarray(tagged.length - 16))
|
||||
const plain = Buffer.concat([decipher.update(tagged.subarray(0, tagged.length - 16)), decipher.final()])
|
||||
return JSON.parse(plain.toString("utf8"))
|
||||
}
|
||||
|
||||
// dpapiUnprotect 用当前 Windows 用户的 DPAPI 解出主密钥(经 PowerShell)。
|
||||
async function dpapiUnprotect(blob, spawnImpl = spawn) {
|
||||
if (process.platform !== "win32") {
|
||||
throw new Error("桌面端会话解密目前仅支持 Windows;请改用「粘贴 accessToken」方式")
|
||||
}
|
||||
const b64 = blob.toString("base64")
|
||||
const result = await new Promise((resolve, reject) => {
|
||||
const child = spawnImpl(
|
||||
"powershell",
|
||||
["-NoProfile", "-Command", `Add-Type -AssemblyName System.Security; $k=[Convert]::FromBase64String('${b64}'); [Console]::Out.Write([Convert]::ToBase64String([System.Security.Cryptography.ProtectedData]::Unprotect($k, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)))`],
|
||||
{ windowsHide: true },
|
||||
)
|
||||
let out = ""
|
||||
child.stdout.on("data", (chunk) => (out += chunk))
|
||||
child.on("error", reject)
|
||||
child.on("close", (code) => (code === 0 ? resolve(out.trim()) : reject(new Error(`DPAPI 解密失败(exit ${code})`))))
|
||||
})
|
||||
const key = Buffer.from(result, "base64")
|
||||
if (key.length !== 32) throw new Error("DPAPI 解出的主密钥长度异常")
|
||||
return key
|
||||
}
|
||||
|
||||
function isExpiredJwt(token, nowMs = Date.now()) {
|
||||
const payload = token.split(".")[1]
|
||||
if (!payload) return false
|
||||
try {
|
||||
const claims = JSON.parse(Buffer.from(payload, "base64url").toString("utf8"))
|
||||
return typeof claims.exp === "number" && claims.exp * 1000 < nowMs
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// readDesktopCredential 在磁盘上解出桌面端登录态,返回 { key, accountId, username, source }。
|
||||
async function readDesktopCredential({ homedir = osHomedir(), platform = process.platform, env = process.env, readFileImpl, dpapiImpl, nowMs } = {}) {
|
||||
// 平台检查前置:macOS/Linux 走不到 DPAPI,先在读盘前给出明确指引,
|
||||
// 而不是让 encrypted_key 形状检查抢先把错误说糊。
|
||||
if (platform !== "win32") {
|
||||
throw new Error("桌面端会话解密目前仅支持 Windows;请改用「粘贴 accessToken」方式")
|
||||
}
|
||||
const readFile = readFileImpl ?? ((path) => readFileSync(path))
|
||||
const dataDirs = [join(env.APPDATA ?? join(homedir, "AppData", "Roaming"), "AgnesCode")]
|
||||
|
||||
const problems = []
|
||||
for (const dir of dataDirs) {
|
||||
const statePath = join(dir, "Local State")
|
||||
const sessionPath = join(dir, "code-auth-session.v1")
|
||||
let keyBlob, raw
|
||||
try {
|
||||
const state = JSON.parse(readFile(statePath).toString("utf8"))
|
||||
keyBlob = parseEncryptedKey(state?.os_crypt?.encrypted_key ?? "")
|
||||
raw = readFile(sessionPath)
|
||||
} catch (error) {
|
||||
problems.push(`${dir}(${error?.message ?? "读取失败"})`)
|
||||
continue
|
||||
}
|
||||
let session
|
||||
try {
|
||||
const dpapi = dpapiImpl ?? ((blob) => dpapiUnprotect(blob))
|
||||
const key = await dpapi(keyBlob)
|
||||
session = decryptSessionWithKey(key, raw)
|
||||
} catch (error) {
|
||||
problems.push(`${dir}(解密失败:${error?.message ?? "未知"})`)
|
||||
continue
|
||||
}
|
||||
if (typeof session?.accessToken !== "string" || !session.accessToken.trim()) {
|
||||
problems.push(`${dir}(会话里没有 accessToken)`)
|
||||
continue
|
||||
}
|
||||
if (isExpiredJwt(session.accessToken, nowMs)) {
|
||||
throw new Error("Agnes Code 登录已过期,请打开 Agnes Code 重新登录后重试")
|
||||
}
|
||||
const username = typeof session.userInfo?.username === "string" && session.userInfo.username.trim()
|
||||
? session.userInfo.username.trim()
|
||||
: undefined
|
||||
return { key: session.accessToken.trim(), accountId: username, username, source: sessionPath }
|
||||
}
|
||||
|
||||
const detail = problems.length ? `:${problems.join(";")}` : ""
|
||||
throw new Error(`未找到 Agnes Code 桌面端登录态${detail}。请先启动 Agnes Code 并登录,或改用「粘贴 accessToken」方式。`)
|
||||
}
|
||||
|
||||
async function fetchModels(key, fetchImpl) {
|
||||
return await fetchImpl(MODELS_URL, {
|
||||
headers: { authorization: `Bearer ${key}`, accept: "application/json" },
|
||||
signal: AbortSignal.timeout(15000),
|
||||
redirect: "error",
|
||||
})
|
||||
}
|
||||
|
||||
async function fetchBalance(key, fetchImpl) {
|
||||
return await fetchImpl(POINTS_API_BASE + BALANCE_PATH, {
|
||||
headers: { authorization: `Bearer ${key}`, accept: "application/json" },
|
||||
signal: AbortSignal.timeout(15000),
|
||||
redirect: "error",
|
||||
})
|
||||
}
|
||||
|
||||
function createPlugin({ fetchImpl = globalThis.fetch, readFileImpl, dpapiImpl, homedir = osHomedir(), platform = process.platform, sleepImpl } = {}) {
|
||||
const sleep = sleepImpl ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)))
|
||||
|
||||
async function readBalance(key) {
|
||||
const res = await fetchBalance(key, fetchImpl)
|
||||
if (res.status === 401 || res.status === 403) {
|
||||
throw Object.assign(new Error(`Agnes 拒绝了这份凭据(HTTP ${res.status}),请重新登录 Agnes Code`), { signIn: "expired" })
|
||||
}
|
||||
if (!res.ok) throw new Error(`积分余额读取失败(HTTP ${res.status})`)
|
||||
const body = await res.json()
|
||||
const data = body?.data
|
||||
if (!data || typeof data.total_balance !== "number") throw new Error("积分余额格式异常")
|
||||
return data
|
||||
}
|
||||
|
||||
return {
|
||||
config: async (cfg) => {
|
||||
cfg.provider ??= {}
|
||||
// ??= 保留用户在 plugins.json 里自己配置的同名供应商。
|
||||
cfg.provider[ID] ??= {
|
||||
name: "Agnes",
|
||||
npm: "@ai-sdk/openai-compatible", // OpenAI chat completions;网关在 baseURL 后拼 /chat/completions
|
||||
api: CHAT_GATEWAY_BASE,
|
||||
models: bootstrapRows(),
|
||||
}
|
||||
},
|
||||
|
||||
auth: {
|
||||
provider: ID,
|
||||
methods: [
|
||||
{
|
||||
type: "api",
|
||||
label: "读取 Agnes Code 桌面端登录态",
|
||||
async authorize() {
|
||||
let cred
|
||||
try {
|
||||
cred = await readDesktopCredential({ readFileImpl, dpapiImpl, homedir, platform })
|
||||
} catch (error) {
|
||||
return { type: "failed", error: error?.message ?? "读取 Agnes Code 桌面端登录态失败" }
|
||||
}
|
||||
return {
|
||||
type: "success",
|
||||
key: cred.key,
|
||||
accountId: cred.accountId,
|
||||
metadata: { username: cred.username, source: cred.source, method: "desktop" },
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "api",
|
||||
label: "粘贴 accessToken",
|
||||
prompts: [
|
||||
{
|
||||
type: "password",
|
||||
key: "accessToken",
|
||||
message: "Agnes Code 会话里的 JWT accessToken(eyJ…)",
|
||||
validate: (v) => (v && v.trim() ? undefined : "必填"),
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
key: "username",
|
||||
message: "用户名(可选,用于显示)",
|
||||
},
|
||||
],
|
||||
// username 只作显示名;原先没 authorize,输入会被整体丢弃。
|
||||
async authorize(inputs) {
|
||||
const key = String(inputs?.accessToken ?? "").trim()
|
||||
if (!key) return { type: "failed", error: "accessToken 必填" }
|
||||
const username = String(inputs?.username ?? "").trim() || undefined
|
||||
return {
|
||||
type: "success",
|
||||
key,
|
||||
accountId: username,
|
||||
metadata: { username, source: "paste", method: "paste" },
|
||||
}
|
||||
},
|
||||
},
|
||||
],
|
||||
// @ai-sdk/openai-compatible 把 apiKey 发成 Authorization: Bearer <key>,
|
||||
// 与桌面端对网关的调用完全一致,无需自定义头。
|
||||
async loader(getAuth) {
|
||||
const auth = await getAuth()
|
||||
if (auth?.type !== "api" || !auth.key) return {}
|
||||
return { baseURL: CHAT_GATEWAY_BASE, apiKey: auth.key }
|
||||
},
|
||||
// 免费档「每日登录送 600」由服务端随当日会话发放;这里显示真实积分余额,
|
||||
// 读取不计费。
|
||||
async usage(getAuth) {
|
||||
const auth = await getAuth()
|
||||
if (auth?.type !== "api" || !auth.key) return {}
|
||||
let balance
|
||||
try {
|
||||
balance = await readBalance(auth.key)
|
||||
} catch (error) {
|
||||
if (error?.signIn === "expired") {
|
||||
return { error: error.message, signIn: "expired", windows: [] }
|
||||
}
|
||||
return { error: error?.message ?? "Agnes 积分读取失败", windows: [] }
|
||||
}
|
||||
const windows = [{ name: "积分", balance: balance.total_balance, aside: false }]
|
||||
if (balance.time_sensitive_balance > 0) {
|
||||
windows.push({ name: "限时积分", balance: balance.time_sensitive_balance, aside: true })
|
||||
}
|
||||
if (balance.permanent_balance > 0) {
|
||||
windows.push({ name: "永久积分", balance: balance.permanent_balance, aside: true })
|
||||
}
|
||||
return {
|
||||
plan: balance.level_name || (balance.level ? `Level ${balance.level}` : "Free"),
|
||||
windows,
|
||||
}
|
||||
},
|
||||
// 「每日登录送积分」由服务端随当日会话发放,无领取接口;这里做一次账号
|
||||
// 会话活跃(只读请求)并观测发放前后的余额差:涨了记 claimed,没涨记 done。
|
||||
async checkin(getAuth) {
|
||||
const auth = await getAuth()
|
||||
if (auth?.type !== "api" || !auth.key) return {}
|
||||
let before
|
||||
try {
|
||||
before = await readBalance(auth.key)
|
||||
} catch (error) {
|
||||
if (error?.signIn === "expired") throw error
|
||||
return { outcome: "failed", message: error?.message ?? "积分余额读取失败" }
|
||||
}
|
||||
// 会话活跃 touch:与桌面端启动时同类只读请求。
|
||||
await fetchModels(auth.key, fetchImpl).catch(() => null)
|
||||
await fetchBalance(auth.key, fetchImpl).catch(() => null)
|
||||
await sleep(2500)
|
||||
let after
|
||||
try {
|
||||
after = await readBalance(auth.key)
|
||||
} catch (error) {
|
||||
if (error?.signIn === "expired") throw error
|
||||
return { outcome: "failed", message: error?.message ?? "积分余额读取失败" }
|
||||
}
|
||||
const delta = after.total_balance - before.total_balance
|
||||
if (delta > 0) return { outcome: "claimed", credit: delta, message: `每日登录积分 +${delta}` }
|
||||
// 余额没涨 ≠ 已发放:无领取接口,发放可能挂靠桌面端登录,本次未观测到。
|
||||
// 不能报 done(宿主渲染成「今日已签到」);inactive 是静默结算态,message 仍带实情。
|
||||
return { outcome: "inactive", message: "未观测到新发放:余额无变化(发放可能挂靠桌面端登录)" }
|
||||
},
|
||||
},
|
||||
|
||||
provider: {
|
||||
id: ID,
|
||||
// 按账号实时拉目录(模型增删、thinking 标记可能随时间变)。
|
||||
async models(provider, { auth } = {}) {
|
||||
if (auth?.type !== "api" || !auth.key) return provider.models
|
||||
let res
|
||||
try {
|
||||
res = await fetchModels(auth.key, fetchImpl)
|
||||
} catch {
|
||||
// 网络失败保留原列表,与目录接口非 2xx 同待遇。
|
||||
return provider.models
|
||||
}
|
||||
if (res.status === 401 || res.status === 403) {
|
||||
throw Object.assign(new Error(`Agnes 拒绝了这份凭据(HTTP ${res.status}),请重新登录 Agnes Code`), { signIn: "expired" })
|
||||
}
|
||||
if (!res.ok) return provider.models
|
||||
let body
|
||||
try {
|
||||
body = await res.json()
|
||||
} catch {
|
||||
throw new Error("Agnes 模型目录不是有效 JSON")
|
||||
}
|
||||
const list = body?.data
|
||||
if (!Array.isArray(list) || list.some((m) => typeof m?.id !== "string" || !m.id)) {
|
||||
throw new Error("Agnes 模型目录格式异常")
|
||||
}
|
||||
const rows = Object.fromEntries(list.map((m) => [m.id, rowFromCatalogEntry(m)]))
|
||||
if (!Object.keys(rows).length) throw new Error("Agnes 模型目录为空")
|
||||
return rows
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// 插件是唯一的导出函数;magpie 会把入口导出的每个函数都当插件调用,测试需要的
|
||||
// 内部函数按社区约定放在 _internal 对象上。
|
||||
export const AgnesPlugin = async () => createPlugin()
|
||||
export const _internal = {
|
||||
createPlugin,
|
||||
rowFromCatalogEntry,
|
||||
bootstrapRows,
|
||||
parseEncryptedKey,
|
||||
decryptSessionWithKey,
|
||||
readDesktopCredential,
|
||||
isExpiredJwt,
|
||||
CHAT_GATEWAY_BASE,
|
||||
MODELS_URL,
|
||||
POINTS_API_BASE,
|
||||
BALANCE_PATH,
|
||||
BOOTSTRAP,
|
||||
ID,
|
||||
}
|
||||
@@ -0,0 +1,287 @@
|
||||
import test from "node:test"
|
||||
import assert from "node:assert/strict"
|
||||
import { createCipheriv, randomBytes } from "node:crypto"
|
||||
import { join as pjoin } from "node:path"
|
||||
import { AgnesPlugin, _internal } from "./index.mjs"
|
||||
|
||||
const {
|
||||
createPlugin,
|
||||
rowFromCatalogEntry,
|
||||
bootstrapRows,
|
||||
parseEncryptedKey,
|
||||
decryptSessionWithKey,
|
||||
readDesktopCredential,
|
||||
isExpiredJwt,
|
||||
CHAT_GATEWAY_BASE,
|
||||
MODELS_URL,
|
||||
ID,
|
||||
} = _internal
|
||||
|
||||
const MODEL_ENTRY = {
|
||||
id: "agnes-3.0-flash",
|
||||
object: "model",
|
||||
max_input_tokens: 512000,
|
||||
max_output_tokens: 65536,
|
||||
model_type: "text",
|
||||
is_member_only: false,
|
||||
thinking_toggle: { default_enabled: true },
|
||||
supported_endpoint_types: ["openai"],
|
||||
}
|
||||
|
||||
test("rowFromCatalogEntry maps the agnes catalog shape", () => {
|
||||
const m = rowFromCatalogEntry(MODEL_ENTRY)
|
||||
assert.equal(m.id, "agnes-3.0-flash")
|
||||
assert.deepEqual(m.limit, { context: 512000, output: 65536 })
|
||||
assert.equal(m.reasoning, true)
|
||||
assert.equal(m.tool_call, true)
|
||||
assert.equal(m.capabilities.reasoning, true)
|
||||
assert.equal(m.capabilities.input.image, false)
|
||||
|
||||
const plain = rowFromCatalogEntry({ id: "glm-5.3", max_input_tokens: 1000000, max_output_tokens: 131072 })
|
||||
assert.equal(plain.reasoning, false)
|
||||
assert.deepEqual(plain.limit, { context: 1000000, output: 131072 })
|
||||
})
|
||||
|
||||
test("bootstrap table covers the observed catalog", () => {
|
||||
const rows = bootstrapRows()
|
||||
assert.equal(Object.keys(rows).length, 11)
|
||||
for (const id of ["agnes-3.0-flash", "claude-opus-5-5", "kimi-k3", "deepseek-v4-pro"]) {
|
||||
assert.ok(rows[id], `missing ${id}`)
|
||||
}
|
||||
assert.equal(rows["agnes-3.0-flash"].limit.context, 512000)
|
||||
assert.equal(rows["kimi-k3"].limit.context, 1048576)
|
||||
})
|
||||
|
||||
test("parseEncryptedKey strips the DPAPI prefix and rejects other shapes", () => {
|
||||
const key = randomBytes(32)
|
||||
const blob = Buffer.concat([Buffer.from("DPAPI", "latin1"), key])
|
||||
assert.deepEqual(parseEncryptedKey(blob.toString("base64")), key)
|
||||
assert.throws(() => parseEncryptedKey(Buffer.from("hello").toString("base64")), /DPAPI/)
|
||||
})
|
||||
|
||||
function frame(key, obj) {
|
||||
const nonce = Buffer.alloc(12, 7)
|
||||
const cipher = createCipheriv("aes-256-gcm", key, nonce)
|
||||
const ct = Buffer.concat([cipher.update(JSON.stringify(obj), "utf8"), cipher.final()])
|
||||
return Buffer.concat([Buffer.from("v10", "latin1"), nonce, ct, cipher.getAuthTag()])
|
||||
}
|
||||
|
||||
test("decryptSessionWithKey round-trips the v10 safeStorage frame", () => {
|
||||
const key = randomBytes(32)
|
||||
const session = { accessToken: "jwt.abc", userInfo: { username: "tester" }, bffPublicBaseUrl: "https://x/v1" }
|
||||
const out = decryptSessionWithKey(key, frame(key, session))
|
||||
assert.deepEqual(out, session)
|
||||
|
||||
assert.throws(() => decryptSessionWithKey(key, Buffer.from("v01-not-a-frame")), /v10/)
|
||||
assert.throws(() => decryptSessionWithKey(randomBytes(32), frame(key, session)), /auth|tag|state/i)
|
||||
})
|
||||
|
||||
test("isExpiredJwt reads the exp claim", () => {
|
||||
const make = (claims) => `h.${Buffer.from(JSON.stringify(claims)).toString("base64url")}.s`
|
||||
assert.equal(isExpiredJwt(make({ exp: Math.floor(Date.now() / 1000) - 10 })), true)
|
||||
assert.equal(isExpiredJwt(make({ exp: Math.floor(Date.now() / 1000) + 3600 })), false)
|
||||
assert.equal(isExpiredJwt("not-a-jwt"), false)
|
||||
})
|
||||
|
||||
function fixtureFs(files) {
|
||||
const norm = (x) => pjoin(...x.split(/[\/]+/))
|
||||
const byNorm = new Map(Object.entries(files).map(([k, v]) => [norm(k), v]))
|
||||
return (path) => {
|
||||
if (byNorm.has(norm(path))) return byNorm.get(norm(path))
|
||||
throw Object.assign(new Error("ENOENT"), { code: "ENOENT" })
|
||||
}
|
||||
}
|
||||
|
||||
test("readDesktopCredential decrypts the desktop session and reports the username", async () => {
|
||||
const key = randomBytes(32)
|
||||
const keyBlob = Buffer.concat([Buffer.from("DPAPI", "latin1"), key])
|
||||
const session = { accessToken: "jwt.def", userInfo: { username: "jy960815", id: "uuid-1" }, bffPublicBaseUrl: "https://x/v1" }
|
||||
const cred = await readDesktopCredential({
|
||||
platform: "win32",
|
||||
env: { APPDATA: "/w/Roaming" },
|
||||
homedir: "/home/t",
|
||||
readFileImpl: fixtureFs({
|
||||
[pjoin("/w/Roaming", "AgnesCode", "Local State")]: Buffer.from(JSON.stringify({ os_crypt: { encrypted_key: keyBlob.toString("base64") } })),
|
||||
[pjoin("/w/Roaming", "AgnesCode", "code-auth-session.v1")]: frame(key, session),
|
||||
}),
|
||||
dpapiImpl: async (blob) => blob,
|
||||
})
|
||||
assert.equal(cred.key, "jwt.def")
|
||||
assert.equal(cred.accountId, "jy960815")
|
||||
assert.equal(cred.username, "jy960815")
|
||||
assert.match(cred.source, /code-auth-session\.v1$/)
|
||||
})
|
||||
|
||||
test("readDesktopCredential rejects expired logins with an actionable message", async () => {
|
||||
const key = randomBytes(32)
|
||||
const keyBlob = Buffer.concat([Buffer.from("DPAPI", "latin1"), key])
|
||||
const expired = `h.${Buffer.from(JSON.stringify({ exp: Math.floor(Date.now() / 1000) - 100 })).toString("base64url")}.s`
|
||||
await assert.rejects(
|
||||
readDesktopCredential({
|
||||
platform: "win32",
|
||||
env: { APPDATA: "/w/Roaming" },
|
||||
homedir: "/home/t",
|
||||
readFileImpl: fixtureFs({
|
||||
[pjoin("/w/Roaming", "AgnesCode", "Local State")]: Buffer.from(JSON.stringify({ os_crypt: { encrypted_key: keyBlob.toString("base64") } })),
|
||||
[pjoin("/w/Roaming", "AgnesCode", "code-auth-session.v1")]: frame(key, { accessToken: expired, userInfo: { username: "x" }, bffPublicBaseUrl: "https://x/v1" }),
|
||||
}),
|
||||
dpapiImpl: async (blob) => blob,
|
||||
}),
|
||||
/重新登录/,
|
||||
)
|
||||
})
|
||||
|
||||
test("readDesktopCredential lists what it could not read", async () => {
|
||||
await assert.rejects(
|
||||
readDesktopCredential({ platform: "win32", env: { APPDATA: "/w/Roaming" }, homedir: "/home/t", readFileImpl: fixtureFs({}) }),
|
||||
(e) => /未找到 Agnes Code 桌面端登录态/.test(e.message) && /AgnesCode/.test(e.message),
|
||||
)
|
||||
})
|
||||
|
||||
test("readDesktopCredential refuses non-Windows with a clear pointer before touching disk", async () => {
|
||||
let reads = 0
|
||||
await assert.rejects(
|
||||
readDesktopCredential({
|
||||
platform: "darwin",
|
||||
homedir: "/home/t",
|
||||
readFileImpl: () => {
|
||||
reads += 1
|
||||
return Buffer.from("{}")
|
||||
},
|
||||
}),
|
||||
/仅支持 Windows/,
|
||||
)
|
||||
assert.equal(reads, 0)
|
||||
})
|
||||
|
||||
test("paste login method stores the access token and optional username", async () => {
|
||||
const plugin = createPlugin()
|
||||
const method = plugin.auth.methods[1]
|
||||
assert.match(method.label, /粘贴/)
|
||||
const out = await method.authorize({ accessToken: "jwt.paste", username: "u9" })
|
||||
assert.deepEqual(out, {
|
||||
type: "success",
|
||||
key: "jwt.paste",
|
||||
accountId: "u9",
|
||||
metadata: { username: "u9", source: "paste", method: "paste" },
|
||||
})
|
||||
|
||||
const bare = await method.authorize({ accessToken: "jwt.paste" })
|
||||
assert.equal(bare.type, "success")
|
||||
assert.equal(bare.metadata.username, undefined)
|
||||
|
||||
const missing = await method.authorize({ username: "u9" })
|
||||
assert.equal(missing.type, "failed")
|
||||
assert.match(missing.error, /必填/)
|
||||
})
|
||||
|
||||
test("config hook declares the chat-completions provider without clobbering user config", async () => {
|
||||
const plugin = createPlugin()
|
||||
const cfg = {}
|
||||
await plugin.config(cfg)
|
||||
assert.equal(cfg.provider[ID].npm, "@ai-sdk/openai-compatible")
|
||||
assert.equal(cfg.provider[ID].api, CHAT_GATEWAY_BASE)
|
||||
assert.ok(cfg.provider[ID].models["agnes-3.0-flash"])
|
||||
|
||||
const existing = { provider: { [ID]: { name: "mine" } } }
|
||||
await plugin.config(existing)
|
||||
assert.deepEqual(existing.provider[ID], { name: "mine" })
|
||||
})
|
||||
|
||||
test("loader hands the token to the openai-compatible provider; no auth yields empty", async () => {
|
||||
const plugin = createPlugin()
|
||||
assert.deepEqual(await plugin.auth.loader(async () => undefined), {})
|
||||
assert.deepEqual(await plugin.auth.loader(async () => ({ type: "api", key: "k" })), { baseURL: CHAT_GATEWAY_BASE, apiKey: "k" })
|
||||
})
|
||||
|
||||
const jsonRes = (body, status = 200) => ({ ok: status >= 200 && status < 300, status, json: async () => body })
|
||||
|
||||
test("models hook maps the live catalog and keeps the old list on network failure", async () => {
|
||||
const plugin = createPlugin({
|
||||
fetchImpl: async (url) => {
|
||||
assert.equal(String(url), MODELS_URL)
|
||||
return jsonRes({ data: [MODEL_ENTRY, { id: "kimi-k3", max_input_tokens: 1048576, max_output_tokens: 131072 }] })
|
||||
},
|
||||
})
|
||||
const rows = await plugin.provider.models({ models: {} }, { auth: { type: "api", key: "k" } })
|
||||
assert.deepEqual(Object.keys(rows), ["agnes-3.0-flash", "kimi-k3"])
|
||||
assert.equal(rows["kimi-k3"].reasoning, false)
|
||||
|
||||
const keep = createPlugin({ fetchImpl: async () => { throw new Error("down") } })
|
||||
const previousProvider = { models: { kept: true } }
|
||||
assert.deepEqual(
|
||||
await keep.provider.models(previousProvider, { auth: { type: "api", key: "k" } }),
|
||||
previousProvider.models,
|
||||
)
|
||||
|
||||
const expired = createPlugin({ fetchImpl: async () => jsonRes({}, 401) })
|
||||
await assert.rejects(
|
||||
expired.provider.models({ models: {} }, { auth: { type: "api", key: "k" } }),
|
||||
(e) => e.signIn === "expired",
|
||||
)
|
||||
|
||||
const malformed = createPlugin({ fetchImpl: async () => jsonRes({ data: {} }) })
|
||||
await assert.rejects(malformed.provider.models({ models: {} }, { auth: { type: "api", key: "k" } }))
|
||||
})
|
||||
|
||||
const BALANCE = { total_balance: 600, time_sensitive_balance: 600, permanent_balance: 0, level: 0, level_name: "" }
|
||||
|
||||
test("usage maps the balance into quota windows", async () => {
|
||||
const plugin = createPlugin({ fetchImpl: async (url) => {
|
||||
assert.match(String(url), /credits-balance/)
|
||||
return jsonRes({ code: "000000", message: "success", data: BALANCE })
|
||||
} })
|
||||
const out = await plugin.auth.usage(async () => ({ type: "api", key: "k" }))
|
||||
assert.equal(out.plan, "Free")
|
||||
assert.deepEqual(out.windows[0], { name: "积分", balance: 600, aside: false })
|
||||
assert.deepEqual(out.windows[1], { name: "限时积分", balance: 600, aside: true })
|
||||
|
||||
const named = createPlugin({ fetchImpl: async () => jsonRes({ code: "000000", data: { ...BALANCE, level_name: "Plus", permanent_balance: 50, time_sensitive_balance: 0 } }) })
|
||||
const out2 = await named.auth.usage(async () => ({ type: "api", key: "k" }))
|
||||
assert.equal(out2.plan, "Plus")
|
||||
assert.deepEqual(out2.windows.map((w) => w.name), ["积分", "永久积分"])
|
||||
|
||||
const expired = createPlugin({ fetchImpl: async () => jsonRes({}, 401) })
|
||||
const err = await expired.auth.usage(async () => ({ type: "api", key: "k" }))
|
||||
assert.equal(err.signIn, "expired")
|
||||
})
|
||||
|
||||
const checkinFetch = (balanceSequence) => {
|
||||
let calls = 0
|
||||
return async (input) => {
|
||||
const url = String(input)
|
||||
if (url.includes("credits-balance")) {
|
||||
calls += 1
|
||||
return jsonRes({ code: "000000", data: { ...BALANCE, total_balance: balanceSequence[Math.min(calls - 1, balanceSequence.length - 1)] } })
|
||||
}
|
||||
if (url.includes("/v1/models")) return jsonRes({ data: [] })
|
||||
throw new Error(`unexpected ${url}`)
|
||||
}
|
||||
}
|
||||
|
||||
test("check-in observes the balance delta around the session touch", async () => {
|
||||
const claimed = createPlugin({ fetchImpl: checkinFetch([600, 1200]), sleepImpl: async () => {} })
|
||||
const out = await claimed.auth.checkin(async () => ({ type: "api", key: "k" }))
|
||||
assert.deepEqual(out, { outcome: "claimed", credit: 600, message: "每日登录积分 +600" })
|
||||
|
||||
const unobserved = createPlugin({ fetchImpl: checkinFetch([600, 600]), sleepImpl: async () => {} })
|
||||
const out2 = await unobserved.auth.checkin(async () => ({ type: "api", key: "k" }))
|
||||
// 余额没涨不谎称 done(宿主渲染成「今日已签到」):inactive + 实情 message。
|
||||
assert.equal(out2.outcome, "inactive")
|
||||
assert.match(out2.message, /未观测到新发放/)
|
||||
})
|
||||
|
||||
test("check-in propagates dead sessions as signIn expired", async () => {
|
||||
const dead = createPlugin({ fetchImpl: async () => jsonRes({}, 401), sleepImpl: async () => {} })
|
||||
await assert.rejects(
|
||||
dead.auth.checkin(async () => ({ type: "api", key: "k" })),
|
||||
(e) => e.signIn === "expired",
|
||||
)
|
||||
})
|
||||
|
||||
test("module export is a plugin factory", async () => {
|
||||
const plugin = await AgnesPlugin()
|
||||
assert.equal(typeof plugin.config, "function")
|
||||
assert.equal(typeof plugin.auth.checkin, "function")
|
||||
assert.equal(plugin.auth.methods.length, 2)
|
||||
})
|
||||
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-agnes-code-auth",
|
||||
"version": "0.1.0",
|
||||
"description": "Agnes Code desktop sign-in as an OpenCode/magpie provider: OpenAI-compatible chat gateway, live model catalog, daily check-in and points balance",
|
||||
"type": "module",
|
||||
"main": "./index.mjs",
|
||||
"files": [
|
||||
"index.mjs",
|
||||
"README.md",
|
||||
"LICENSE"
|
||||
],
|
||||
"keywords": [
|
||||
"opencode",
|
||||
"opencode-plugin",
|
||||
"magpie",
|
||||
"agnes",
|
||||
"agnes-code"
|
||||
],
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"test": "node --test"
|
||||
},
|
||||
"magpie": {
|
||||
"icon": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAALDSURBVFhHvZffS5NRGMffP6D6Q7rq3fp9o4F43n4JXQhqXQRdKFpExTISisKKCBJndJGY/YAuJr1nk9jKzCVubsOtSdOoRZFY+1E5F5W4re2Jc9rGds7rrHZ8H/gwON/nvM/3nOfAeCSpJHY2WNfLCu6Ukeo1IHXRoGAQAlITMsIeA1JNpEZpzWIY6627DAqOc5sFIytqzIhwLVdcVnCaTV4zEE4VTWxV7Bv0ODmLjHB0Y41lnUR6zoq6gVSTRB8cK+jHJLmBpIagD0hNSNxilWzfb4Pu3iCcvODlNC2EG7g7FIZC/I0J4QZsT+aKBi72vOB0FuEG0EEHYMcHGLSEYds+G6ezCDdA2NEwDC1HnbB5j5XTWIQbaD/rhsVvKdqCji43p7MINUCu//uPNGQyWWqgse0Zl8MizIBxNwbnZIQWJr/ZXI62gs1jEWbg+q0QLb6QWIbLfdMQjS9xOVoIMdB2xlW89nPX/HD/4VvwBT9zeVpUbeDQMSf8XMrQ4u6pGG1FIPQVhh6953K1qMrA4RPjkMy/eHL1dc122ndiiLSEzdeiooGm9jFurYCp2wfLqV+0eDabg+PnPfQ/YMIXpWsj4x/hjiUM5tuz3N5SKhoYHpmDKzemy9bqWxzw+Pk8LVKIS+Yg1cwDM2XrrqkY1DXZue+WUtGA/+UXyOUAvIE4/ZMZc0cglT91IUpPSPr/5l2SrvcOzHDf02JVAysFMdJ11c/tuXnvFdVbO12cpkVFA32Ds2xdGp5AHBpbR7l8AnkLqXQWDhx5ymlaVDSwZa8VevpD9OpHJz5B/4PX0Nyx8sMkkDas1vdSJKEDyD8iK3hBohOLhqgPqpsYOM0L+mCsx6fy86AaY8W1RlZwhA4mdDRDuFbv0WyTotaUz4fEBMJRLlkw5ORc8UKQKyHjEplYyAtlN/8vf76luknPi9eej986sOvbZw1S8QAAAABJRU5ErkJggg==",
|
||||
"maxConcurrency": 4
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/magpie-community/plugins.git",
|
||||
"directory": "packages/agnes-code"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Pursuit806
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,65 @@
|
||||
# @magpie-community/opencode-astudio-auth
|
||||
|
||||
把 **AStudio(科大讯飞 Astron Studio 桌面端)** 的账号额度接入 [magpie](https://usemagpie.ai/) 与 [OpenCode](https://opencode.ai/):复用桌面端登录态,直连云端模型网关(OpenAI Responses 协议),agent 以 `astudio/<model>` 使用它的模型;支持每日登录积分自动签到与积分余额显示。
|
||||
|
||||
## 登录什么
|
||||
|
||||
两种方式(登录时二选一):
|
||||
|
||||
1. **读取 AStudio 桌面端登录态(推荐)**——本机装有 AStudio 桌面版并登录过即可,插件自动从它的数据目录读出模型凭据与网页会话(积分/签到用)。数据目录按以下顺序查找:
|
||||
- `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 可选)。
|
||||
|
||||
每个 AStudio 账号登录一次即得一个 magpie 账号,可多账号故障切换。凭据保存在 magpie 的 `plugin-auth.json`(权限 600),不上传。
|
||||
|
||||
## 模型
|
||||
|
||||
供应商 id `astudio`。目录**按账号实时拉取**(`GET /api/v1/model-manager/models`,读取不计费),含思考档位与限免标记。2026-11 实测目录:
|
||||
|
||||
| modelId | 名称 | context | 备注 |
|
||||
| --- | --- | --- | --- |
|
||||
| `astronclaw-auto` | Auto | 256k | 智能路由 |
|
||||
| `spark-x2.6` | Spark-X2.6 | 256k | 抢先体验 |
|
||||
| `spark-x2.6-4b` | Spark-X2.6-Lite | 1M | **限免** |
|
||||
| `spark-x2.5` | Spark-X2.5 | 256k | |
|
||||
| `xopglm52` | GLM-5.2 | 1M | |
|
||||
| `xopdeepseekv4pro0813` | DeepSeek-V4-Pro | 1M | |
|
||||
| `xopdsv4flash0731in` | DeepSeek-V4-Flash | 1M | |
|
||||
|
||||
思考档位(none / high / max,随模型)映射为 magpie 的推理档位;上游字段变化以实时目录为准。
|
||||
|
||||
## 每日签到(每日登录积分)
|
||||
|
||||
AStudio 有「每日登录积分」:服务端在当天账号会话首次活跃时发放(体验版 100 分/天,标准版 200,高级/畅享 400;活动期 31 天有效),客户端弹窗只做通知、没有领取接口。插件为此提供 magpie 的 `auth.checkin`:每天替账号做一次会话活跃(只读请求)并观测前后余额差——涨了记为已领取;没涨**不谎称已签**,如实报「未观测到新发放」(发放可能挂靠桌面端登录)。签到需要账号带网页会话(桌面端登录态方式默认有)。
|
||||
|
||||
## 用量
|
||||
|
||||
有网页会话时显示真实数据:会员档(体验版/标准版/高级版/畅享版)、通用积分余额(含最近到期批次与时间)、星火积分余额。所有读取均不计费;模型调用本身才消耗账号额度。401/403/登录异常会把账号标记为需要重新登录。
|
||||
|
||||
## 协议与上游
|
||||
|
||||
- 模型调用:`POST https://astronstudio-api-volces-prod.xf-yun.com/model-gateway/v1/responses`(OpenAI Responses,`Authorization: Bearer`)——与 AStudio 桌面端写进 acode 内核的 `base_url` / `wire_api` 完全一致。
|
||||
- 模型目录:`GET https://astronstudio-api-volces-prod.xf-yun.com/api/v1/model-manager/models`。
|
||||
- 账号面:`https://agent.xfyun.cn/xingchen-studio/`(`points/balance`、`membership/me`、`membership/plan-config`,Cookie 会话鉴权)。
|
||||
|
||||
## 风险提示
|
||||
|
||||
非官方集成,凭据与协议来自桌面客户端逆向,上游随时可能变更;共享登录态的自动化使用可能违反 AStudio 服务条款,账号风险自担。请勿用于批量/滥用场景。
|
||||
|
||||
## 安装与开发
|
||||
|
||||
```
|
||||
magpie plugin add @magpie-community/opencode-astudio-auth
|
||||
magpie plugin login astudio # 选「读取 AStudio 桌面端登录态」或「粘贴 modelBearerToken」
|
||||
magpie provider test astudio spark-x2.6-4b # 限免模型,验收一发
|
||||
```
|
||||
|
||||
测试(零依赖,Node ≥18 或 Bun):
|
||||
|
||||
```
|
||||
npm test # = node --test
|
||||
# 或 bun test
|
||||
```
|
||||
@@ -0,0 +1,556 @@
|
||||
// AStudio(科大讯飞 Astron Studio 桌面端)for OpenCode and magpie.
|
||||
//
|
||||
// AStudio 桌面端登录后,把账号的模型凭据与会话写进它的数据目录(Windows 下
|
||||
// 注册表 HKCU\Software\AStudioStorage 登记 DataRoot):
|
||||
// <DataRoot>/userdata/astron-session.json — modelBearerToken / token / uid
|
||||
// <DataRoot>/runtime/acode-home/config.toml — [model_providers.astron-spark]
|
||||
// experimental_bearer_token = "…"(与 session 的 modelBearerToken 同源)
|
||||
// 两套云端接口:
|
||||
// 模型调用 POST https://astronstudio-api-volces-prod.xf-yun.com/model-gateway/v1/responses
|
||||
// (OpenAI Responses 协议,Authorization: Bearer <modelBearerToken>,
|
||||
// 与桌面端写进 acode 内核的 base_url/wire_api 完全一致)
|
||||
// 模型目录 GET https://astronstudio-api-volces-prod.xf-yun.com/api/v1/model-manager/models
|
||||
// 账号面 https://agent.xfyun.cn/xingchen-studio/…(Cookie 会话鉴权):
|
||||
// points/balance、membership/me、membership/plan-config、points/summary
|
||||
//
|
||||
// 本插件复用这份登录态:第一种登录方式直接从磁盘读取桌面端会话(Raccoon
|
||||
// 「复用桌面端登录态」同款),第二种让用户手动粘贴 modelBearerToken。目录与
|
||||
// 思考档位按账号实时拉取(目录读取不计费)。AStudio 有「每日登录积分」
|
||||
// (服务端在当天账号会话首次活跃时发放,客户端弹窗只做通知,无领取接口),
|
||||
// auth.checkin 用「发放前后余额差」观测:涨了记 claimed,没涨不谎称已签——
|
||||
// 记 inactive 并说明未观测到(宿主把 done 渲染成「今日已签到」,是没发生的断言)。
|
||||
|
||||
import { spawnSync } from "node:child_process"
|
||||
import { readFileSync } from "node:fs"
|
||||
import { homedir as osHomedir } from "node:os"
|
||||
|
||||
const ID = "astudio"
|
||||
|
||||
// 云端地址(来自桌面端 resolveAstronRuntimeProfile 的 production 分支)。
|
||||
const MODEL_GATEWAY_BASE = "https://astronstudio-api-volces-prod.xf-yun.com/model-gateway/v1"
|
||||
const MODEL_MANAGER_URL = "https://astronstudio-api-volces-prod.xf-yun.com/api/v1/model-manager/models"
|
||||
const STUDIO_API_BASE = "https://agent.xfyun.cn/xingchen-studio/"
|
||||
|
||||
const REGISTRY_KEY = "HKCU\\Software\\AStudioStorage"
|
||||
const REGISTRY_PREFIXES = ["Production", "Canary", "Development"]
|
||||
|
||||
// 未登录/拿不到桌面端数据时的兜底目录(桌面端未在注册表登记时也可能落在这些位置)。
|
||||
// 函数吃 homedir 参数(readDesktopCredential 注入,缺省回落真实家目录),测试可重定向。
|
||||
const SESSION_FALLBACKS = [
|
||||
(home = osHomedir()) => join(home, ".acode", "acode", "userdata", "astron-session.json"),
|
||||
]
|
||||
|
||||
const ACODE_CONFIG_FALLBACKS = [
|
||||
(home = osHomedir()) => join(home, ".acode", "acode", "config.toml"),
|
||||
]
|
||||
|
||||
// 模型目录读不到时的启动表(2026-11-01 实测目录快照;models 钩子会用实时目录覆盖)。
|
||||
const BOOTSTRAP = [
|
||||
{ id: "astronclaw-auto", name: "Auto", context: 262144, output: 32768 },
|
||||
{ id: "spark-x2.6", name: "Spark-X2.6", context: 262144, output: 32768, badge: "Preview" },
|
||||
{ id: "spark-x2.6-4b", name: "Spark-X2.6-Lite", context: 1048576, output: 110000, free: true },
|
||||
{ id: "spark-x2.5", name: "Spark-X2.5", context: 262144, output: 32768 },
|
||||
{ id: "xopglm52", name: "GLM-5.2", context: 1048576, output: 32768 },
|
||||
{ id: "xopdeepseekv4pro0813", name: "DeepSeek-V4-Pro", context: 1048576, output: 32768 },
|
||||
{ id: "xopdsv4flash0731in", name: "DeepSeek-V4-Flash", context: 1048576, output: 32768 },
|
||||
]
|
||||
|
||||
function join(...parts) {
|
||||
return parts.join("/")
|
||||
}
|
||||
|
||||
// rowFromCatalogEntry 把 model-manager 的一个模型变成 OpenCode 的 Model。
|
||||
// 套餐不按 token 计费,无 cost;倍率上游未给出,不标。
|
||||
function rowFromCatalogEntry(m) {
|
||||
const image = Array.isArray(m?.input_modalities) && m.input_modalities.includes("image")
|
||||
const efforts = Array.isArray(m?.supported_reasoning_levels)
|
||||
? m.supported_reasoning_levels.filter((l) => typeof l?.effort === "string" && l.effort)
|
||||
: []
|
||||
const reasoning = efforts.some((l) => l.effort !== "none")
|
||||
const variants = reasoning
|
||||
? Object.fromEntries(efforts.map((l) => [l.effort, { reasoningEffort: l.effort }]))
|
||||
: undefined
|
||||
const free = m?.badge?.text?.en === "Free"
|
||||
return {
|
||||
id: m.slug,
|
||||
name: m.display_name ?? m.slug,
|
||||
limit: {
|
||||
context: typeof m?.context_window === "number" && m.context_window > 0 ? m.context_window : 0,
|
||||
output: typeof m?.max_output_tokens === "number" && m.max_output_tokens > 0 ? m.max_output_tokens : 32768,
|
||||
},
|
||||
reasoning,
|
||||
tool_call: true,
|
||||
...(variants ? { variants } : {}),
|
||||
...(free ? { free: true } : {}),
|
||||
modalities: { input: image ? ["text", "image"] : ["text"], output: ["text"] },
|
||||
capabilities: {
|
||||
reasoning,
|
||||
toolcall: true,
|
||||
attachment: image,
|
||||
input: { text: true, image },
|
||||
output: { text: true },
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function bootstrapRows() {
|
||||
return Object.fromEntries(
|
||||
BOOTSTRAP.map((m) => [
|
||||
m.id,
|
||||
{
|
||||
id: m.id,
|
||||
name: m.name,
|
||||
limit: { context: m.context, output: m.output },
|
||||
reasoning: true,
|
||||
tool_call: true,
|
||||
...(m.free ? { free: true } : {}),
|
||||
modalities: { input: ["text"], output: ["text"] },
|
||||
capabilities: {
|
||||
reasoning: true,
|
||||
toolcall: true,
|
||||
attachment: false,
|
||||
input: { text: true, image: false },
|
||||
output: { text: true },
|
||||
},
|
||||
},
|
||||
]),
|
||||
)
|
||||
}
|
||||
|
||||
// registryDataRoots 读注册表里登记的各 profile 数据根目录(Windows)。
|
||||
function registryDataRoots(registryQuery = defaultRegistryQuery) {
|
||||
const roots = []
|
||||
for (const prefix of REGISTRY_PREFIXES) {
|
||||
const value = registryQuery(REGISTRY_KEY, `${prefix}DataRoot`)
|
||||
if (value) roots.push(value)
|
||||
}
|
||||
return roots
|
||||
}
|
||||
|
||||
function defaultRegistryQuery(key, valueName) {
|
||||
if (process.platform !== "win32") return null
|
||||
try {
|
||||
const r = spawnSync("reg", ["query", key, "/v", valueName, "/reg:64"], { timeout: 5000, windowsHide: true })
|
||||
const out = `${r.stdout ?? ""}`
|
||||
const m = out.match(/REG_SZ\s+(\S[^\r\n]*)/)
|
||||
return m ? m[1].trim() : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// readAcodeConfigToken 兜底:从 acode 内核的 config.toml 取凭据。
|
||||
function readAcodeConfigToken(content) {
|
||||
const section = content.match(/^\s*\[\s*model_providers\s*\.\s*astron-spark\s*\]\s*$/m)
|
||||
if (!section) return null
|
||||
const after = content.slice(section.index + section[0].length)
|
||||
const nextSection = after.search(/^\s*\[/m)
|
||||
const body = nextSection >= 0 ? after.slice(0, nextSection) : after
|
||||
const token = body.match(/^\s*experimental_bearer_token\s*=\s*"([^"]+)"\s*$/m)?.[1]
|
||||
const uid = body.match(/^\s*uid\s*=\s*"([^"]+)"\s*$/m)?.[1]
|
||||
return token ? { key: token, uid: uid ?? undefined } : null
|
||||
}
|
||||
|
||||
// readDesktopCredential 找到桌面端登录态并返回 { key, uid, session, source }。
|
||||
// session 是账号面的 Cookie 材料(token/ssoSessionId/accountId),积分与签到用。
|
||||
// 找不到抛错,error message 面向用户。
|
||||
function readDesktopCredential({ env = process.env, homedir = osHomedir(), readFileImpl, registryQuery } = {}) {
|
||||
const readFile = readFileImpl ?? ((path) => readFileSync(path, "utf8"))
|
||||
const sessionPaths = []
|
||||
const configPaths = []
|
||||
const configured = env.ASTUDIO_HOME?.trim() || env.SYNARA_HOME?.trim()
|
||||
if (configured) {
|
||||
sessionPaths.push(join(configured, "userdata", "astron-session.json"))
|
||||
configPaths.push(join(configured, "runtime", "acode-home", "config.toml"))
|
||||
}
|
||||
for (const root of registryDataRoots(registryQuery)) {
|
||||
sessionPaths.push(join(root, "userdata", "astron-session.json"))
|
||||
configPaths.push(join(root, "runtime", "acode-home", "config.toml"))
|
||||
}
|
||||
for (const p of SESSION_FALLBACKS) sessionPaths.push(p(homedir))
|
||||
for (const p of ACODE_CONFIG_FALLBACKS) configPaths.push(p(homedir))
|
||||
|
||||
const problems = []
|
||||
for (const path of sessionPaths) {
|
||||
let raw
|
||||
try {
|
||||
raw = readFile(path)
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
let session
|
||||
try {
|
||||
session = JSON.parse(raw)
|
||||
} catch {
|
||||
problems.push(`${path} 不是有效 JSON`)
|
||||
continue
|
||||
}
|
||||
if (session.banned === true) throw new Error(`AStudio 账号已被封禁(${path})`)
|
||||
const key = typeof session.modelBearerToken === "string" && session.modelBearerToken.trim()
|
||||
? session.modelBearerToken.trim()
|
||||
: typeof session.token === "string" && session.token.trim()
|
||||
? session.token.trim()
|
||||
: null
|
||||
if (!key) {
|
||||
problems.push(`${path} 里没有 modelBearerToken/token`)
|
||||
continue
|
||||
}
|
||||
if (key.length > 4096) {
|
||||
problems.push(`${path} 的凭据异常地长`)
|
||||
continue
|
||||
}
|
||||
const uid = typeof session.uid === "string" && session.uid.trim() ? session.uid.trim() : undefined
|
||||
const cookieSession = typeof session.token === "string" && session.token.trim() && typeof session.accountId === "string" && session.accountId.trim()
|
||||
? { token: session.token.trim(), ssoSessionId: typeof session.ssoSessionId === "string" ? session.ssoSessionId.trim() : undefined, accountId: session.accountId.trim() }
|
||||
: undefined
|
||||
return { key, uid, session: cookieSession, source: path }
|
||||
}
|
||||
|
||||
for (const path of configPaths) {
|
||||
let raw
|
||||
try {
|
||||
raw = readFile(path)
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
const parsed = readAcodeConfigToken(raw)
|
||||
if (parsed) return { ...parsed, session: undefined, source: path }
|
||||
problems.push(`${path} 里没有 astron-spark 凭据`)
|
||||
}
|
||||
|
||||
const detail = problems.length ? `:${problems.join(";")}` : ""
|
||||
throw new Error(`未找到 AStudio 桌面端登录态${detail}。请先启动 AStudio 并登录,或改用「粘贴 modelBearerToken」方式。`)
|
||||
}
|
||||
|
||||
// 桌面端 buildAstronCookieHeader 的等价实现(agent.xfyun.cn 的 Cookie 会话)。
|
||||
function buildCookieHeader(session) {
|
||||
const parts = []
|
||||
if (session?.ssoSessionId) parts.push(`ssoSessionId=${session.ssoSessionId}`, `sso_sessionid=${session.ssoSessionId}`)
|
||||
if (session?.accountId) parts.push(`account_id=${session.accountId}`)
|
||||
if (session?.token) parts.push(`token=${session.token}`)
|
||||
return parts.join("; ")
|
||||
}
|
||||
|
||||
// studioJson 调账号面接口;信封 flag:true&&code:0 视为成功并返回 data,
|
||||
// 401/403(含 code 80000 登录异常)抛带 signIn:"expired" 的错。
|
||||
async function studioJson(path, { session, fetchImpl, method = "GET", body, operation = path }) {
|
||||
let res
|
||||
try {
|
||||
res = await fetchImpl(new URL(path, STUDIO_API_BASE), {
|
||||
method,
|
||||
headers: {
|
||||
accept: "application/json",
|
||||
...(body !== undefined ? { "content-type": "application/json" } : {}),
|
||||
cookie: buildCookieHeader(session),
|
||||
},
|
||||
...(body !== undefined ? { body: JSON.stringify(body) } : {}),
|
||||
signal: AbortSignal.timeout(15000),
|
||||
redirect: "error",
|
||||
})
|
||||
} catch (error) {
|
||||
throw new Error(`${operation} 网络失败:${error?.cause?.code || error?.message || "未知错误"}`)
|
||||
}
|
||||
if (res.status === 401 || res.status === 403) {
|
||||
throw Object.assign(new Error(`AStudio 会话已失效(HTTP ${res.status}),请重新登录 AStudio`), { signIn: "expired" })
|
||||
}
|
||||
let payload
|
||||
try {
|
||||
payload = await res.json()
|
||||
} catch {
|
||||
throw new Error(`${operation} 返回的不是 JSON(HTTP ${res.status})`)
|
||||
}
|
||||
const envelope = payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {}
|
||||
if (!res.ok || (envelope.flag === false || (envelope.code !== undefined && envelope.code !== 0))) {
|
||||
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}` : ""})`)
|
||||
}
|
||||
return envelope.data
|
||||
}
|
||||
|
||||
async function fetchCatalog(key, fetchImpl) {
|
||||
return await fetchImpl(MODEL_MANAGER_URL, {
|
||||
headers: { authorization: `Bearer ${key}`, accept: "application/json" },
|
||||
signal: AbortSignal.timeout(15000),
|
||||
redirect: "error",
|
||||
})
|
||||
}
|
||||
|
||||
function createPlugin({ fetchImpl = globalThis.fetch, env = process.env, homedir = osHomedir(), registryQuery, readFileImpl, sleepImpl } = {}) {
|
||||
const sleep = sleepImpl ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)))
|
||||
|
||||
async function readBalance(session) {
|
||||
return await studioJson("points/balance", { session, fetchImpl, operation: "积分余额" })
|
||||
}
|
||||
|
||||
return {
|
||||
config: async (cfg) => {
|
||||
cfg.provider ??= {}
|
||||
// ??= 保留用户在 plugins.json 里自己配置的同名供应商。
|
||||
cfg.provider[ID] ??= {
|
||||
name: "AStudio",
|
||||
npm: "@ai-sdk/openai", // OpenAI Responses;网关在 baseURL 后拼 /responses
|
||||
api: MODEL_GATEWAY_BASE,
|
||||
models: bootstrapRows(),
|
||||
}
|
||||
},
|
||||
|
||||
auth: {
|
||||
provider: ID,
|
||||
methods: [
|
||||
{
|
||||
type: "api",
|
||||
label: "读取 AStudio 桌面端登录态",
|
||||
// 不用输入框:authorize 自己从磁盘读桌面端会话。
|
||||
async authorize() {
|
||||
let cred
|
||||
try {
|
||||
cred = readDesktopCredential({ env, homedir, registryQuery, readFileImpl })
|
||||
} catch (error) {
|
||||
return { type: "failed", error: error?.message ?? "读取 AStudio 桌面端登录态失败" }
|
||||
}
|
||||
return {
|
||||
type: "success",
|
||||
key: cred.key,
|
||||
accountId: cred.uid,
|
||||
metadata: {
|
||||
uid: cred.uid,
|
||||
source: cred.source,
|
||||
method: "desktop",
|
||||
// Cookie 会话材料:积分余额、会员信息与每日签到用。
|
||||
session: cred.session,
|
||||
},
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "api",
|
||||
label: "粘贴 modelBearerToken",
|
||||
prompts: [
|
||||
{
|
||||
type: "password",
|
||||
key: "modelBearerToken",
|
||||
message: "modelBearerToken(astron-session.json 或 acode config.toml 里的值)",
|
||||
validate: (v) => (v && v.trim() ? undefined : "必填"),
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
key: "uid",
|
||||
message: "账号 uid(可选,用于显示,如 18800000000)",
|
||||
},
|
||||
{
|
||||
type: "password",
|
||||
key: "sessionToken",
|
||||
message: "网页会话 token(astron-session.json 的 token 字段;用于积分余额与每日签到)",
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
key: "accountId",
|
||||
message: "账号面 accountId(与 sessionToken 一起填,积分余额与签到才可用)",
|
||||
},
|
||||
{
|
||||
type: "password",
|
||||
key: "ssoSessionId",
|
||||
message: "ssoSessionId(可选,Cookie 会话补充材料)",
|
||||
},
|
||||
],
|
||||
// 粘贴路径此前只问不存(没有 authorize,输入全部丢弃)。现在按桌面端
|
||||
// 成功返回的同一形状落库;token+accountId 齐才组得出 Cookie 会话。
|
||||
async authorize(inputs) {
|
||||
const key = String(inputs?.modelBearerToken ?? "").trim()
|
||||
if (!key) return { type: "failed", error: "modelBearerToken 必填" }
|
||||
if (key.length > 4096) return { type: "failed", error: "凭据异常地长" }
|
||||
const token = String(inputs?.sessionToken ?? "").trim()
|
||||
const accountId = String(inputs?.accountId ?? "").trim()
|
||||
const ssoSessionId = String(inputs?.ssoSessionId ?? "").trim()
|
||||
const uid = String(inputs?.uid ?? "").trim() || undefined
|
||||
const session = token && accountId
|
||||
? { token, accountId, ...(ssoSessionId ? { ssoSessionId } : {}) }
|
||||
: undefined
|
||||
return {
|
||||
type: "success",
|
||||
key,
|
||||
accountId: accountId || uid,
|
||||
metadata: {
|
||||
uid,
|
||||
source: "paste",
|
||||
method: "paste",
|
||||
...(session ? { session } : {}),
|
||||
},
|
||||
}
|
||||
},
|
||||
},
|
||||
],
|
||||
// @ai-sdk/openai 把 apiKey 发成 Authorization: Bearer <key>,与桌面端内核
|
||||
// 对 model-gateway 的调用完全一致,无需自定义头。
|
||||
async loader(getAuth) {
|
||||
const auth = await getAuth()
|
||||
if (auth?.type !== "api" || !auth.key) return {}
|
||||
return { baseURL: MODEL_GATEWAY_BASE, apiKey: auth.key }
|
||||
},
|
||||
// 有 Cookie 会话时显示真实积分余额与会员档;只有模型凭据时退回目录
|
||||
// 连通性检查。读取均不计费。
|
||||
async usage(getAuth) {
|
||||
const auth = await getAuth()
|
||||
if (auth?.type !== "api" || !auth.key) return {}
|
||||
const session = auth.metadata?.session
|
||||
if (!session?.token) {
|
||||
let res
|
||||
try {
|
||||
res = await fetchCatalog(auth.key, fetchImpl)
|
||||
} catch (error) {
|
||||
return { error: `AStudio 不可达:${error?.cause?.code || error?.message || "网络错误"}`, windows: [] }
|
||||
}
|
||||
if (res.status === 401 || res.status === 403) {
|
||||
return { error: `AStudio 拒绝了这份凭据(HTTP ${res.status}),请重新登录`, signIn: "expired", windows: [] }
|
||||
}
|
||||
if (!res.ok) return { error: `AStudio 返回 HTTP ${res.status}`, windows: [] }
|
||||
return { plan: "AStudio", windows: [] }
|
||||
}
|
||||
// 单项失败不塌方(一边挂了另一边还能显示),但登录态过期必须透传,
|
||||
// 不能折叠成「账号信息读取失败」。
|
||||
const tolerate = (promise) =>
|
||||
promise.catch((error) => {
|
||||
if (error?.signIn === "expired") throw error
|
||||
return null
|
||||
})
|
||||
let balance, membership
|
||||
try {
|
||||
;[balance, membership] = await Promise.all([
|
||||
tolerate(readBalance(session)),
|
||||
tolerate(studioJson("membership/me", { session, fetchImpl, operation: "会员信息" })),
|
||||
])
|
||||
} catch (error) {
|
||||
return { error: error?.message ?? "AStudio 账号信息读取失败", signIn: "expired", windows: [] }
|
||||
}
|
||||
if (!balance && !membership) {
|
||||
return { error: "AStudio 账号信息读取失败", windows: [] }
|
||||
}
|
||||
const windows = []
|
||||
if (balance && typeof balance.totalBalance === "number") {
|
||||
windows.push({
|
||||
name: "通用积分",
|
||||
balance: balance.totalBalance,
|
||||
aside: false,
|
||||
...(balance.activityNextExpireTime && balance.activityBalance > 0
|
||||
? { runsOutAt: balance.activityNextExpireTime, runsOut: balance.activityBalance }
|
||||
: {}),
|
||||
})
|
||||
}
|
||||
if (balance && typeof balance.sparkTotalBalance === "number") {
|
||||
windows.push({ name: "星火积分", balance: balance.sparkTotalBalance, aside: false })
|
||||
}
|
||||
return {
|
||||
...(membership?.planName ? { plan: membership.planName } : { plan: "AStudio" }),
|
||||
...(membership?.uid != null ? { user: String(membership.uid) } : {}),
|
||||
...(membership?.endTime ? { until: membership.endTime } : {}),
|
||||
windows,
|
||||
}
|
||||
},
|
||||
// 「每日登录积分」:服务端在当天账号会话首次活跃时发放,客户端没有领取
|
||||
// 接口(弹窗只做通知)。这里以一组账号面请求代表当天的会话活跃,并用
|
||||
// 发放前后的余额差观测结果:涨了是 claimed,没涨是 done。
|
||||
async checkin(getAuth) {
|
||||
const auth = await getAuth()
|
||||
if (auth?.type !== "api" || !auth.key) return {}
|
||||
const session = auth.metadata?.session
|
||||
if (!session?.token) {
|
||||
return { outcome: "ineligible", message: "该账号只有模型凭据(无网页会话),无法执行每日登录签到" }
|
||||
}
|
||||
let config
|
||||
try {
|
||||
config = await studioJson("membership/plan-config", { session, fetchImpl, operation: "签到配置" })
|
||||
} catch (error) {
|
||||
if (error?.signIn === "expired") throw error
|
||||
return { outcome: "failed", message: error?.message ?? "签到配置读取失败" }
|
||||
}
|
||||
if (config?.dailyLoginEnabled === false) {
|
||||
return { outcome: "inactive", message: "当前没有每日登录积分活动" }
|
||||
}
|
||||
let before
|
||||
try {
|
||||
before = await readBalance(session)
|
||||
} catch (error) {
|
||||
if (error?.signIn === "expired") throw error
|
||||
return { outcome: "failed", message: error?.message ?? "积分余额读取失败" }
|
||||
}
|
||||
// 会话活跃 touch:与桌面端启动时同类只读请求。
|
||||
await studioJson("membership/me", { session, fetchImpl, operation: "会员信息" }).catch(() => null)
|
||||
await studioJson("points/summary", { session, fetchImpl, operation: "积分汇总" }).catch(() => null)
|
||||
await sleep(2500)
|
||||
let after
|
||||
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}` }
|
||||
// 余额没涨 ≠ 已发放:无领取接口,发放可能挂靠桌面端登录,本次未观测到。
|
||||
// 不能报 done(宿主渲染成「今日已签到」,是没发生的断言);inactive 是
|
||||
// 静默结算态,message 仍会把实情带给用户。
|
||||
return { outcome: "inactive", message: "未观测到新发放:余额无变化(发放可能挂靠桌面端登录)" }
|
||||
},
|
||||
},
|
||||
|
||||
provider: {
|
||||
id: ID,
|
||||
// 按账号实时拉目录(模型、思考档位、限免标记都可能随账号/时间变)。
|
||||
async models(provider, { auth } = {}) {
|
||||
if (auth?.type !== "api" || !auth.key) return provider.models
|
||||
let res
|
||||
try {
|
||||
res = await fetchCatalog(auth.key, fetchImpl)
|
||||
} catch {
|
||||
// 网络失败保留原列表,与目录接口非 2xx 同待遇。
|
||||
return provider.models
|
||||
}
|
||||
if (res.status === 401 || res.status === 403) {
|
||||
throw Object.assign(new Error(`AStudio 拒绝了这份凭据(HTTP ${res.status}),请重新登录`), { signIn: "expired" })
|
||||
}
|
||||
if (!res.ok) return provider.models
|
||||
let body
|
||||
try {
|
||||
body = await res.json()
|
||||
} catch {
|
||||
throw new Error("AStudio 模型目录不是有效 JSON")
|
||||
}
|
||||
const list = body?.data?.models
|
||||
if (!Array.isArray(list) || list.some((m) => typeof m?.slug !== "string" || !m.slug)) {
|
||||
throw new Error("AStudio 模型目录格式异常")
|
||||
}
|
||||
const rows = Object.fromEntries(
|
||||
list
|
||||
.filter((m) => m.visibility !== "hidden" && m.supported_in_api !== false)
|
||||
.map((m) => [m.slug, rowFromCatalogEntry(m)]),
|
||||
)
|
||||
if (!Object.keys(rows).length) throw new Error("AStudio 模型目录为空")
|
||||
return rows
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// 插件是唯一的导出函数;magpie 会把入口导出的每个函数都当插件调用,测试需要的
|
||||
// 内部函数按社区约定放在 _internal 对象上。
|
||||
export const AStudioPlugin = async () => createPlugin()
|
||||
export const _internal = {
|
||||
createPlugin,
|
||||
rowFromCatalogEntry,
|
||||
bootstrapRows,
|
||||
readDesktopCredential,
|
||||
readAcodeConfigToken,
|
||||
registryDataRoots,
|
||||
buildCookieHeader,
|
||||
studioJson,
|
||||
MODEL_GATEWAY_BASE,
|
||||
MODEL_MANAGER_URL,
|
||||
STUDIO_API_BASE,
|
||||
BOOTSTRAP,
|
||||
ID,
|
||||
}
|
||||
@@ -0,0 +1,447 @@
|
||||
import test from "node:test"
|
||||
import assert from "node:assert/strict"
|
||||
import { AStudioPlugin, _internal } from "./index.mjs"
|
||||
|
||||
const {
|
||||
createPlugin,
|
||||
rowFromCatalogEntry,
|
||||
bootstrapRows,
|
||||
readDesktopCredential,
|
||||
readAcodeConfigToken,
|
||||
registryDataRoots,
|
||||
buildCookieHeader,
|
||||
studioJson,
|
||||
MODEL_GATEWAY_BASE,
|
||||
MODEL_MANAGER_URL,
|
||||
STUDIO_API_BASE,
|
||||
ID,
|
||||
} = _internal
|
||||
|
||||
const CATALOG_ENTRY = {
|
||||
slug: "spark-x2.6-4b",
|
||||
badge: { text: { en: "Free", "zh-CN": "限免" } },
|
||||
visibility: "list",
|
||||
display_name: "Spark-X2.6-Lite",
|
||||
description: "Spark-X2.6-Lite 文本模型。",
|
||||
context_window: 1048576,
|
||||
max_context_window: 1048576,
|
||||
max_output_tokens: 110000,
|
||||
input_modalities: ["text"],
|
||||
supported_in_api: true,
|
||||
default_reasoning_level: "high",
|
||||
supported_reasoning_levels: [
|
||||
{ effort: "none", description: "关闭思考" },
|
||||
{ effort: "high", description: "高强度思考" },
|
||||
{ effort: "max", description: "最大强度思考" },
|
||||
],
|
||||
supports_parallel_tool_calls: true,
|
||||
}
|
||||
|
||||
test("rowFromCatalogEntry maps the live catalog shape", () => {
|
||||
const m = rowFromCatalogEntry(CATALOG_ENTRY)
|
||||
assert.equal(m.id, "spark-x2.6-4b")
|
||||
assert.equal(m.name, "Spark-X2.6-Lite")
|
||||
assert.deepEqual(m.limit, { context: 1048576, output: 110000 })
|
||||
assert.equal(m.reasoning, true)
|
||||
assert.equal(m.tool_call, true)
|
||||
assert.equal(m.free, true)
|
||||
assert.deepEqual(m.variants, {
|
||||
none: { reasoningEffort: "none" },
|
||||
high: { reasoningEffort: "high" },
|
||||
max: { reasoningEffort: "max" },
|
||||
})
|
||||
assert.equal(m.capabilities.input.image, false)
|
||||
})
|
||||
|
||||
test("rowFromCatalogEntry degrades safely on sparse entries", () => {
|
||||
const m = rowFromCatalogEntry({ slug: "m1", display_name: "M1", input_modalities: ["text", "image"] })
|
||||
assert.deepEqual(m.limit, { context: 0, output: 32768 })
|
||||
assert.equal(m.reasoning, false)
|
||||
assert.equal("variants" in m, false)
|
||||
assert.equal(m.capabilities.attachment, true)
|
||||
assert.equal(m.capabilities.input.image, true)
|
||||
|
||||
const none = rowFromCatalogEntry({
|
||||
slug: "m2",
|
||||
supported_reasoning_levels: [{ effort: "none" }],
|
||||
})
|
||||
assert.equal(none.reasoning, false)
|
||||
assert.equal("variants" in none, false)
|
||||
})
|
||||
|
||||
test("bootstrap table covers the observed catalog", () => {
|
||||
const rows = bootstrapRows()
|
||||
assert.equal(Object.keys(rows).length, 7)
|
||||
for (const id of ["astronclaw-auto", "spark-x2.6", "spark-x2.6-4b", "xopglm52", "xopdeepseekv4pro0813"]) {
|
||||
assert.ok(rows[id], `missing ${id}`)
|
||||
}
|
||||
assert.equal(rows["spark-x2.6-4b"].free, true)
|
||||
assert.equal(rows["xopglm52"].limit.context, 1048576)
|
||||
})
|
||||
|
||||
test("readAcodeConfigToken parses the astron-spark section", () => {
|
||||
const toml = `
|
||||
[features]
|
||||
hooks = true
|
||||
|
||||
[model_providers.astron-spark]
|
||||
name = "Astron Spark"
|
||||
experimental_bearer_token = "tok-abc"
|
||||
uid = "18800000000"
|
||||
|
||||
[marketplaces.x]
|
||||
last_updated = "2026-10-31T16:27:14Z"
|
||||
`
|
||||
assert.deepEqual(readAcodeConfigToken(toml), { key: "tok-abc", uid: "18800000000" })
|
||||
assert.equal(readAcodeConfigToken("[other]\nkey = \"x\""), null)
|
||||
assert.equal(readAcodeConfigToken("[model_providers.astron-spark]\nname = \"Astron Spark\""), null)
|
||||
})
|
||||
|
||||
function fakeFs(files) {
|
||||
return (path) => {
|
||||
if (path in files) return files[path]
|
||||
throw Object.assign(new Error("ENOENT"), { code: "ENOENT" })
|
||||
}
|
||||
}
|
||||
|
||||
test("readDesktopCredential reads the desktop session via ASTUDIO_HOME", () => {
|
||||
const cred = readDesktopCredential({
|
||||
env: { ASTUDIO_HOME: "F:\\AStudio Data" },
|
||||
readFileImpl: fakeFs({
|
||||
"F:\\AStudio Data/userdata/astron-session.json": JSON.stringify({
|
||||
uid: "18800000000", accountId: "18800000000", banned: false,
|
||||
modelBearerToken: "tok-65", token: "tok-36", loginMethod: "wechat",
|
||||
}),
|
||||
}),
|
||||
})
|
||||
assert.deepEqual(cred, {
|
||||
key: "tok-65",
|
||||
uid: "18800000000",
|
||||
session: { token: "tok-36", ssoSessionId: undefined, accountId: "18800000000" },
|
||||
source: "F:\\AStudio Data/userdata/astron-session.json",
|
||||
})
|
||||
})
|
||||
|
||||
test("readDesktopCredential falls back to token and to the acode config", () => {
|
||||
const cred = readDesktopCredential({
|
||||
env: { ASTUDIO_HOME: "D:\\astudio" },
|
||||
readFileImpl: fakeFs({
|
||||
"D:\\astudio/userdata/astron-session.json": JSON.stringify({ uid: "u1", token: "tok-36" }),
|
||||
}),
|
||||
})
|
||||
assert.deepEqual(cred, { key: "tok-36", uid: "u1", session: undefined, source: "D:\\astudio/userdata/astron-session.json" })
|
||||
|
||||
const cred2 = readDesktopCredential({
|
||||
env: { ASTUDIO_HOME: "D:\\astudio" },
|
||||
readFileImpl: fakeFs({
|
||||
"D:\\astudio/runtime/acode-home/config.toml": '[model_providers.astron-spark]\nexperimental_bearer_token = "tok-cfg"\nuid = "u2"\n',
|
||||
}),
|
||||
})
|
||||
assert.deepEqual(cred2, { key: "tok-cfg", uid: "u2", session: undefined, source: "D:\\astudio/runtime/acode-home/config.toml" })
|
||||
})
|
||||
|
||||
test("readDesktopCredential uses registry roots and rejects banned accounts", () => {
|
||||
const cred = readDesktopCredential({
|
||||
env: {},
|
||||
registryQuery: (key, name) => (name === "ProductionDataRoot" ? "F:\\AStudio Data" : null),
|
||||
readFileImpl: fakeFs({
|
||||
"F:\\AStudio Data/userdata/astron-session.json": JSON.stringify({ uid: "u3", modelBearerToken: "tok-reg" }),
|
||||
}),
|
||||
})
|
||||
assert.equal(cred.key, "tok-reg")
|
||||
|
||||
assert.throws(
|
||||
() => readDesktopCredential({
|
||||
env: { ASTUDIO_HOME: "D:\\astudio" },
|
||||
readFileImpl: fakeFs({
|
||||
"D:\\astudio/userdata/astron-session.json": JSON.stringify({ banned: true, modelBearerToken: "x" }),
|
||||
}),
|
||||
}),
|
||||
/封禁/,
|
||||
)
|
||||
|
||||
assert.throws(
|
||||
() => readDesktopCredential({ env: {}, readFileImpl: fakeFs({}) }),
|
||||
/未找到 AStudio 桌面端登录态/,
|
||||
)
|
||||
})
|
||||
|
||||
test("registryDataRoots queries each profile prefix", () => {
|
||||
const seen = []
|
||||
const roots = registryDataRoots((key, name) => {
|
||||
seen.push(`${key}|${name}`)
|
||||
return name === "ProductionDataRoot" ? "C:\\data" : null
|
||||
})
|
||||
assert.deepEqual(roots, ["C:\\data"])
|
||||
assert.ok(seen.includes("HKCU\\Software\\AStudioStorage|ProductionDataRoot"))
|
||||
assert.ok(seen.includes("HKCU\\Software\\AStudioStorage|CanaryDataRoot"))
|
||||
})
|
||||
|
||||
test("config hook declares the Responses provider without clobbering user config", async () => {
|
||||
const plugin = createPlugin()
|
||||
const cfg = {}
|
||||
await plugin.config(cfg)
|
||||
assert.equal(cfg.provider[ID].npm, "@ai-sdk/openai")
|
||||
assert.equal(cfg.provider[ID].api, MODEL_GATEWAY_BASE)
|
||||
assert.ok(cfg.provider[ID].models["astronclaw-auto"])
|
||||
|
||||
const existing = { provider: { [ID]: { name: "mine" } } }
|
||||
await plugin.config(existing)
|
||||
assert.deepEqual(existing.provider[ID], { name: "mine" })
|
||||
})
|
||||
|
||||
test("loader hands the key to the OpenAI provider; no auth yields empty", async () => {
|
||||
const plugin = createPlugin()
|
||||
assert.deepEqual(await plugin.auth.loader(async () => undefined), {})
|
||||
const out = await plugin.auth.loader(async () => ({ type: "api", key: "k" }))
|
||||
assert.deepEqual(out, { baseURL: MODEL_GATEWAY_BASE, apiKey: "k" })
|
||||
})
|
||||
|
||||
const okRes = (body, status = 200) => ({ ok: status >= 200 && status < 300, status, json: async () => body })
|
||||
|
||||
test("models hook maps the live catalog and keeps the old list on network failure", async () => {
|
||||
const plugin = createPlugin({
|
||||
fetchImpl: async (url) => {
|
||||
assert.equal(url, MODEL_MANAGER_URL)
|
||||
return okRes({ code: 0, data: { models: [CATALOG_ENTRY, { slug: "xopglm52", display_name: "GLM-5.2", context_window: 1048576, max_output_tokens: 32768, input_modalities: ["text"], visibility: "list", supported_in_api: true, supported_reasoning_levels: [{ effort: "high" }] }] } })
|
||||
},
|
||||
})
|
||||
const rows = await plugin.provider.models({ models: {} }, { auth: { type: "api", key: "k" } })
|
||||
assert.deepEqual(Object.keys(rows), ["spark-x2.6-4b", "xopglm52"])
|
||||
assert.equal(rows["spark-x2.6-4b"].free, true)
|
||||
|
||||
const keep = createPlugin({ fetchImpl: async () => { throw new Error("down") } })
|
||||
const previousProvider = { models: { kept: true } }
|
||||
assert.deepEqual(
|
||||
await keep.provider.models(previousProvider, { auth: { type: "api", key: "k" } }),
|
||||
previousProvider.models,
|
||||
)
|
||||
|
||||
const expired = createPlugin({ fetchImpl: async () => okRes({}, 401) })
|
||||
await assert.rejects(
|
||||
expired.provider.models({ models: {} }, { auth: { type: "api", key: "k" } }),
|
||||
(e) => e.signIn === "expired",
|
||||
)
|
||||
|
||||
const malformed = createPlugin({ fetchImpl: async () => okRes({ data: {} }) })
|
||||
await assert.rejects(malformed.provider.models({ models: {} }, { auth: { type: "api", key: "k" } }))
|
||||
})
|
||||
|
||||
test("usage hook checks the credential without burning quota", async () => {
|
||||
const ok = createPlugin({ fetchImpl: async () => okRes({ code: 0, data: { models: [] } }) })
|
||||
assert.deepEqual(await ok.auth.usage(async () => ({ type: "api", key: "k" })), { plan: "AStudio", windows: [] })
|
||||
|
||||
const expired = createPlugin({ fetchImpl: async () => okRes({}, 403) })
|
||||
const out = await expired.auth.usage(async () => ({ type: "api", key: "k" }))
|
||||
assert.equal(out.signIn, "expired")
|
||||
|
||||
const down = createPlugin({ fetchImpl: async () => { throw new Error("no route") } })
|
||||
const err = await down.auth.usage(async () => ({ type: "api", key: "k" }))
|
||||
assert.match(err.error, /不可达/)
|
||||
|
||||
assert.deepEqual(await ok.auth.usage(async () => undefined), {})
|
||||
})
|
||||
|
||||
test("desktop login method reads real files through authorize", async () => {
|
||||
const plugin = createPlugin({
|
||||
env: { ASTUDIO_HOME: "D:\\astudio" },
|
||||
readFileImpl: fakeFs({
|
||||
"D:\\astudio/userdata/astron-session.json": JSON.stringify({ uid: "u9", modelBearerToken: "tok-9" }),
|
||||
}),
|
||||
})
|
||||
const method = plugin.auth.methods[0]
|
||||
assert.match(method.label, /桌面端/)
|
||||
const out = await method.authorize({})
|
||||
assert.deepEqual(out, {
|
||||
type: "success",
|
||||
key: "tok-9",
|
||||
accountId: "u9",
|
||||
metadata: { uid: "u9", source: "D:\\astudio/userdata/astron-session.json", method: "desktop", session: undefined },
|
||||
})
|
||||
|
||||
const failing = createPlugin({ env: {}, readFileImpl: fakeFs({}) })
|
||||
const failed = await failing.auth.methods[0].authorize({})
|
||||
assert.equal(failed.type, "failed")
|
||||
assert.match(failed.error, /未找到/)
|
||||
})
|
||||
|
||||
test("desktop credential carries the cookie session for points and check-in", () => {
|
||||
const cred = readDesktopCredential({
|
||||
env: { ASTUDIO_HOME: "D:\\astudio" },
|
||||
readFileImpl: fakeFs({
|
||||
"D:\\astudio/userdata/astron-session.json": JSON.stringify({
|
||||
uid: "18800000000", accountId: "18800000000", token: "tok-36", ssoSessionId: "sso-36", modelBearerToken: "tok-65",
|
||||
}),
|
||||
}),
|
||||
})
|
||||
assert.deepEqual(cred.session, { token: "tok-36", ssoSessionId: "sso-36", accountId: "18800000000" })
|
||||
})
|
||||
|
||||
test("buildCookieHeader mirrors the desktop client", () => {
|
||||
assert.equal(
|
||||
buildCookieHeader({ token: "T", ssoSessionId: "S", accountId: "A" }),
|
||||
"ssoSessionId=S; sso_sessionid=S; account_id=A; token=T",
|
||||
)
|
||||
assert.equal(buildCookieHeader({ token: "T", accountId: "A" }), "account_id=A; token=T")
|
||||
assert.equal(buildCookieHeader(undefined), "")
|
||||
})
|
||||
|
||||
const jsonRes = (body, status = 200) => ({ ok: status >= 200 && status < 300, status, json: async () => body })
|
||||
|
||||
test("studioJson unwraps the envelope and flags dead sessions", async () => {
|
||||
const session = { token: "T", ssoSessionId: "S", accountId: "A" }
|
||||
const data = await studioJson("points/balance", {
|
||||
session,
|
||||
operation: "测试",
|
||||
fetchImpl: async (input, init) => {
|
||||
assert.equal(String(input), STUDIO_API_BASE + "points/balance")
|
||||
assert.match(init.headers.cookie, /sso_sessionid=S/)
|
||||
return jsonRes({ flag: true, code: 0, desc: "成功", data: { totalBalance: 1 } })
|
||||
},
|
||||
})
|
||||
assert.deepEqual(data, { totalBalance: 1 })
|
||||
|
||||
await assert.rejects(
|
||||
studioJson("points/balance", { session, operation: "测试", fetchImpl: async () => jsonRes({ flag: false, code: 80000, desc: "登录异常,请重新登录" }) }),
|
||||
(e) => e.signIn === "expired",
|
||||
)
|
||||
await assert.rejects(
|
||||
studioJson("points/balance", { session, operation: "测试", fetchImpl: async () => jsonRes({}, 401) }),
|
||||
(e) => e.signIn === "expired",
|
||||
)
|
||||
await assert.rejects(
|
||||
studioJson("points/balance", { session, operation: "测试", fetchImpl: async () => jsonRes({ flag: true, code: 500, desc: "boom" }) }),
|
||||
/boom/,
|
||||
)
|
||||
})
|
||||
|
||||
test("studioJson via usage: balance and membership map to quota windows", async () => {
|
||||
const session = { token: "T", ssoSessionId: "S", accountId: "A" }
|
||||
const plugin = createPlugin({
|
||||
fetchImpl: async (input) => {
|
||||
const url = String(input)
|
||||
if (url.includes("points/balance")) {
|
||||
return jsonRes({ flag: true, code: 0, data: { totalBalance: 7900, activityBalance: 7900, activityNextExpireTime: "2026-11-03T06:11:12", sparkTotalBalance: 35000, sparkActivityBalance: 35000 } })
|
||||
}
|
||||
if (url.includes("membership/me")) {
|
||||
return jsonRes({ flag: true, code: 0, data: { uid: 18800000000, active: true, planCode: "TRIAL", planName: "体验版" } })
|
||||
}
|
||||
throw new Error(`unexpected ${url}`)
|
||||
},
|
||||
})
|
||||
const out = await plugin.auth.usage(async () => ({ type: "api", key: "k", metadata: { session } }))
|
||||
assert.equal(out.plan, "体验版")
|
||||
assert.equal(out.user, "18800000000")
|
||||
assert.deepEqual(out.windows[0], { name: "通用积分", balance: 7900, aside: false, runsOutAt: "2026-11-03T06:11:12", runsOut: 7900 })
|
||||
assert.deepEqual(out.windows[1], { name: "星火积分", balance: 35000, aside: false })
|
||||
})
|
||||
|
||||
const checkinFetch = (balanceSequence) => {
|
||||
let balanceCalls = 0
|
||||
return async (input) => {
|
||||
const url = String(input)
|
||||
if (url.includes("membership/plan-config")) {
|
||||
return jsonRes({ flag: true, code: 0, data: { dailyLoginEnabled: true, dailyLoginValidDays: 31, plans: [{ planCode: "TRIAL", dailyLoginPoints: 100 }] } })
|
||||
}
|
||||
if (url.includes("points/balance")) {
|
||||
balanceCalls += 1
|
||||
const total = balanceSequence[Math.min(balanceCalls - 1, balanceSequence.length - 1)]
|
||||
return jsonRes({ flag: true, code: 0, data: { totalBalance: total, activityBalance: total } })
|
||||
}
|
||||
if (url.includes("membership/me") || url.includes("points/summary")) {
|
||||
return jsonRes({ flag: true, code: 0, data: {} })
|
||||
}
|
||||
throw new Error(`unexpected ${url}`)
|
||||
}
|
||||
}
|
||||
|
||||
const checkinAuth = { type: "api", key: "k", metadata: { session: { token: "T", ssoSessionId: "S", accountId: "A" } } }
|
||||
|
||||
test("check-in observes the balance delta around the session touch", async () => {
|
||||
const claimed = createPlugin({ fetchImpl: checkinFetch([7900, 8000]), sleepImpl: async () => {} })
|
||||
const out = await claimed.auth.checkin(async () => checkinAuth)
|
||||
assert.deepEqual(out, { outcome: "claimed", credit: 100, message: "每日登录积分 +100" })
|
||||
|
||||
const unobserved = createPlugin({ fetchImpl: checkinFetch([7900, 7900]), sleepImpl: async () => {} })
|
||||
const out2 = await unobserved.auth.checkin(async () => checkinAuth)
|
||||
// 余额没涨不谎称 done(宿主渲染成「今日已签到」):inactive + 实情 message。
|
||||
assert.equal(out2.outcome, "inactive")
|
||||
assert.match(out2.message, /未观测到新发放/)
|
||||
})
|
||||
|
||||
test("check-in reports ineligible without a session and inactive without the campaign", async () => {
|
||||
const noSession = createPlugin()
|
||||
const out = await noSession.auth.checkin(async () => ({ type: "api", key: "k", metadata: {} }))
|
||||
assert.equal(out.outcome, "ineligible")
|
||||
|
||||
const inactive = createPlugin({
|
||||
fetchImpl: async () => jsonRes({ flag: true, code: 0, data: { dailyLoginEnabled: false, dailyLoginValidDays: 0, plans: [] } }),
|
||||
sleepImpl: async () => {},
|
||||
})
|
||||
const out2 = await inactive.auth.checkin(async () => checkinAuth)
|
||||
assert.equal(out2.outcome, "inactive")
|
||||
})
|
||||
|
||||
test("check-in propagates dead sessions as signIn expired", async () => {
|
||||
const dead = createPlugin({
|
||||
fetchImpl: async () => jsonRes({ flag: false, code: 80000, desc: "登录异常,请重新登录" }, 200),
|
||||
sleepImpl: async () => {},
|
||||
})
|
||||
await assert.rejects(
|
||||
dead.auth.checkin(async () => checkinAuth),
|
||||
(e) => e.signIn === "expired",
|
||||
)
|
||||
})
|
||||
|
||||
test("paste login method stores key plus cookie session inputs", async () => {
|
||||
const plugin = createPlugin()
|
||||
const method = plugin.auth.methods[1]
|
||||
assert.match(method.label, /粘贴/)
|
||||
const out = await method.authorize({ modelBearerToken: "tok-p", uid: "u7", sessionToken: "tok-36", accountId: "A7", ssoSessionId: "sso-7" })
|
||||
assert.deepEqual(out, {
|
||||
type: "success",
|
||||
key: "tok-p",
|
||||
accountId: "A7",
|
||||
metadata: { uid: "u7", source: "paste", method: "paste", session: { token: "tok-36", accountId: "A7", ssoSessionId: "sso-7" } },
|
||||
})
|
||||
|
||||
// 只有模型凭据也放行(无 Cookie 会话,积分/签到不可用),但缺失 key 拒绝。
|
||||
const bare = await method.authorize({ modelBearerToken: "tok-p" })
|
||||
assert.equal(bare.type, "success")
|
||||
assert.equal(bare.metadata.session, undefined)
|
||||
|
||||
const missing = await method.authorize({})
|
||||
assert.equal(missing.type, "failed")
|
||||
assert.match(missing.error, /必填/)
|
||||
})
|
||||
|
||||
test("fallback discovery honors the injected homedir", () => {
|
||||
const cred = readDesktopCredential({
|
||||
env: {},
|
||||
registryQuery: () => null,
|
||||
homedir: "/home/t",
|
||||
readFileImpl: fakeFs({
|
||||
"/home/t/.acode/acode/userdata/astron-session.json": JSON.stringify({ uid: "u8", modelBearerToken: "tok-8" }),
|
||||
}),
|
||||
})
|
||||
assert.equal(cred.key, "tok-8")
|
||||
assert.equal(cred.source, "/home/t/.acode/acode/userdata/astron-session.json")
|
||||
})
|
||||
|
||||
test("usage keeps signIn expired when the cookie session dies mid-read", async () => {
|
||||
const plugin = createPlugin({ fetchImpl: async () => jsonRes({}, 401) })
|
||||
const out = await plugin.auth.usage(async () => ({
|
||||
type: "api",
|
||||
key: "k",
|
||||
metadata: { session: { token: "T", accountId: "A" } },
|
||||
}))
|
||||
assert.equal(out.signIn, "expired")
|
||||
assert.match(out.error, /会话已失效/)
|
||||
})
|
||||
|
||||
test("module export is a plugin factory", async () => {
|
||||
const plugin = await AStudioPlugin()
|
||||
assert.equal(typeof plugin.config, "function")
|
||||
assert.equal(typeof plugin.auth.loader, "function")
|
||||
assert.equal(plugin.auth.methods.length, 2)
|
||||
})
|
||||
@@ -0,0 +1,34 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-astudio-auth",
|
||||
"version": "0.1.0",
|
||||
"description": "AStudio (iFLYTEK Astron Studio) desktop sign-in as an OpenCode/magpie provider: Responses model gateway with live model catalog",
|
||||
"type": "module",
|
||||
"main": "./index.mjs",
|
||||
"files": [
|
||||
"index.mjs",
|
||||
"README.md",
|
||||
"LICENSE"
|
||||
],
|
||||
"keywords": [
|
||||
"opencode",
|
||||
"opencode-plugin",
|
||||
"magpie",
|
||||
"astudio",
|
||||
"astron",
|
||||
"iflytek",
|
||||
"xfyun"
|
||||
],
|
||||
"license": "MIT",
|
||||
"scripts": {
|
||||
"test": "node --test"
|
||||
},
|
||||
"magpie": {
|
||||
"icon": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACAAAAAgCAYAAABzenr0AAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAVJSURBVFhHxVdrUxVHEDX55v9J/At5fNcqK6n4xcSUmqiJ8QUaUHmphEdQQQV8IBqFlFYZISDRxBAwEUIQDFoiivhAEAXuzuzudO9J9T5guZcraDSZqq69d3e2z+k+PTO9CxbEBoA34v9fx5gTQym1iJnXOI6TKaa13vpvTfyIT9d1FyXj+UNYAVjoOM5xvOYRYiycykRWVtabctVa18oErbVRShm5vkqLfIYYtXHsBZZlvSUPbNt2tdastZZJXmjye05TSq7Kv8Z/J/lhwRAswZySQCn1JQCZJAReGFgpNQVohZZEIk5ECHi2bX8xRUAKJSQgaQpeCB37zsVJ6DS6NxVpDFyunlFgE7+XYiKDYG2NE8iM9J+KPnQYRDkTNJ5meW5ZGo6tYFkKDVcJLV0mJJBCwg8yxMpMRyAAnZFeuWdD2yqwmPMI/Om4xpk2wqr9HjYeBkaf2bBty38+SwZSCIgEMwjEJVCThPFhxtMhg8kRFyoxTUZARp7auNTNqG4m5J8mlJ1jTEyKHys5A3ECMyRIIaAsKaYg2olRwmAnob+ZMdDkYaDVw70exsiQwdiYixtDhLY+g8YOg8MXCOeukF8bIolkIC7h/AmE6VXawuQzB3fbGDfqCddOMH4/Trhc6+GXOg+tjR462xnXehldN0V/xl+3DdhI9AGBmatCzY9AQCJcBbbCyN+EvjpGZy3j12OM5mrG2UOMkxWMYwcYNYcZdfUeGi4w2v8kDD5wfBlcR8G4ItVLZEDSKFIorZAYs3GridFew7h4lHG+ilF/kFFTzjhQxigu9pBbyMguJGSXMgoqGYfOMBrbCD39LsbGbZ/MvDIwnS6NhFSxsqAdhaFeRtsJD03VhLOVHk5WeKjex9j7LWNPMWNHIWFzAWFNDuHjbMJHWYRlOxmrShgbKz1cv2OD3DkIzARXMI6FZxMafUMG/fcIXU2MHyoZdQcZx/ZL9ITiEg953xC27Tb4Kp+wOoexfDvjgyzCexsIi1YT3skg9N7RskmlJ6D8DIRaKdnRLPQ/cNBwlfFTF6Fn0MXNXkJDjYfackLVPkJZKWN3EWP7HsKmAsLaXMaKHYQlWwjvricsyzc40uTg0ZOgFiw1Rw1E4LZWaLxqkHvKQ0UD+0vrSp/BrSGD35oZR/czyssIRSWB9pm7DNbnEz7dTliaQdhQZtDYbmN8Uklovv6yGrSeIwOydmXy6cuEJQXA8lJG3inC0RbCjx2Ezn6D3uuE7454KC1h7CpiZIfRr95J+LyA0N4dFBy8IJBEYp7LMCLgOArHLzJWlAEr93nYVuOh/Dzj+1bGpW5C9wDhQrOH4hJGTiH50Yv2yzIYFfVy2Fk+aBLw/JahTBLWkwmNwWEbAw9tDDxwMDjs4P6Ig0ejDp5M2Lh91+BAtYevdxE25hPW5hGWbibUtThgDt5PcyClJxAvQiEhRUOhGSeQRu6Lua5Cy8+ErXsY63INVuYQFm9iXOqw/dQnEinAcxNIXoZRcxFtpZH5J6Bj4eGwjaIq9rVfvt1gcQah55aGRyrYP1LB0xJIOY6fZ8EeH2SouZXwWR7jw22ED7IJ9x/L9muFFT+rzXocpzYkaSxKa9AHWHg8aiOvirF4C+GT3QaTibBfmD0DaRuS1JbsORZIIWlWIKPQ8ofB+xs8rNtrwCRNSFr9xYTAzJbsRZvSyHlUrOMTGrXNBh19NoyJeoCU99I3pS/TlseLVUhI5UszGt2fBVh+p7bl0ceBUuqlP0yU0iZhaSP7fPKz6TnTHyaCFcf+fz/Nkofrum+7rvvffpxGIy2rVziSMf4B2dvP/4LPzYQAAAAASUVORK5CYII=",
|
||||
"maxConcurrency": 4
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/magpie-community/plugins.git",
|
||||
"directory": "packages/astudio"
|
||||
}
|
||||
}
|
||||
+5
-1
@@ -170,6 +170,10 @@
|
||||
"en": "Use your terminal Agent CLIs right inside magpie, by chat. Runs a local service on 127.0.0.1 that starts when the page opens and stops with magpie; only its own page gets the token. First install ~46 MB; Claude Code isn't bundled, so install the `claude` CLI yourself.",
|
||||
"zh": "把终端里的 Agent CLI 搬进 magpie 窗口,直接对话使用。会在本机 127.0.0.1 跑一个后台服务,打开页面才启动,随 magpie 退出;令牌只交给自己的页面。首次安装约 46 MB;不自带 Claude Code,要用请自己装 `claude` CLI。"
|
||||
}
|
||||
}
|
||||
},
|
||||
{ "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.", "zh": "非官方 AStudio(科大讯飞 Astron Studio 桌面端):复用桌面端登录态接入其模型网关,含实时模型目录、每日登录积分签到与积分余额。桌面端发现仅 Windows(注册表定位),另有粘贴凭据方式。" } },
|
||||
{ "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.", "zh": "非官方 Agnes Code 桌面端:复用桌面端登录态接入其 OpenAI 兼容网关,含实时模型目录、每日积分签到与余额显示。桌面端解密仅限 Windows,其余平台用粘贴 accessToken。" } }
|
||||
]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user