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:
Pursuit806
2026-11-02 03:33:26 +08:00
committed by GitHub
parent 1a05a77431
commit 684e4757ad
12 changed files with 1953 additions and 1 deletions
+21
View File
@@ -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.
+67
View File
@@ -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
```
+416
View File
@@ -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,
}
+287
View File
@@ -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)
})
+32
View File
@@ -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"
}
}