From a48f39692a3a059a337346fe47d2790f3c2bdf2d Mon Sep 17 00:00:00 2001 From: Pursuit806 <35015883+jinyue806@users.noreply.github.com> Date: Tue, 3 Nov 2026 15:36:30 +0800 Subject: [PATCH] astudio 0.1.3, agnes-code 0.1.2: the desktop sign-in links the official site and waits instead of showing a key box (#658) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The desktop sign-in of astudio and agnes-code is now an oauth method, so magpie shows no empty key box. When the desktop session is on disk it finishes at once; when it isn't, it links the official site and polls every 2s for up to 5 minutes, ending on cancel (the host's signal). Missing, unreadable (with the reason, read errors other than ENOENT kept), expired and banned are told apart; banned and non-Windows agnes-code throw so the host shows the reason. agnes-code decrypts the DPAPI master key once per sign-in (re-decrypted if the session frame no longer opens with it) and kills a PowerShell stuck past 15s. agnes-code's README and registry summary say how it differs from the `agnes` entry. By jinyue806. Reviewed at 3a6bb97 (base 17e5ef7; main since then only changed packages/workbuddy). Run at 3a6bb97: - mote, bun 1.4.2, HOME=$(mktemp -d) bun test: 4921 pass, 0 fail (374 files); bun scripts/check.mjs ok; node --test on both packages 62 pass. - xiaomi-gpu (Windows 11, node 22): node --test on both packages 62 pass. - Raw bytes of astudio/index.test.mjs: 0 single-backslash "D:\a", 22 "D:\\astudio". - magpie's plugin host (host.js from magpie origin/main e41ef6288, run by bun on mote, sandbox HOME): astudio authorize with nothing on disk gave the official URL and method auto; writing a session file 3s into the callback finished it in 4.0s and saved key + metadata to auth.json; with the file present the url was empty; banned came back as the error message; an aborted callback was dropped; agnes-code on macOS came back with "仅支持 Windows" and no poll. - Broken by hand: dropping the master-key cache's set reds "decrypted once per sign-in"; dropping the banned throw reds "refuses banned accounts". Not tried: a real DPAPI decrypt (Protect over ssh is "Access is denied", no interactive logon there), real AStudio or Agnes Code desktops. Left for a follow-up the author offered: a DPAPI failure itself is not remembered, so each 2s poll can spawn PowerShell again (bounded by the 5-minute wait). --- packages/agnes-code/README.md | 21 ++- packages/agnes-code/index.mjs | 165 +++++++++++++++++--- packages/agnes-code/index.test.mjs | 243 ++++++++++++++++++++++++++++- packages/agnes-code/package.json | 2 +- packages/astudio/README.md | 2 +- packages/astudio/index.mjs | 151 ++++++++++++++---- packages/astudio/index.test.mjs | 168 +++++++++++++++++++- packages/astudio/package.json | 2 +- registry.json | 2 +- 9 files changed, 686 insertions(+), 70 deletions(-) diff --git a/packages/agnes-code/README.md b/packages/agnes-code/README.md index 38e906a..ae5b673 100644 --- a/packages/agnes-code/README.md +++ b/packages/agnes-code/README.md @@ -2,11 +2,30 @@ 把 **Agnes Code 桌面端** 的账号额度接入 [magpie](https://usemagpie.ai/) 与 [OpenCode](https://opencode.ai/):复用桌面端登录态(会话文件解密),直连云端 OpenAI 兼容网关,agent 以 `agnes-code/` 使用它的模型;支持「每日登录送积分」自动观测与积分余额显示。 +## 与 `agnes`(Agnes AI 国际版)的区别 + +Agnes 在 registry 里有两个入口,都保留([#614](https://github.com/magpie-community/plugins/issues/614)): + +| | 本包(`agnes-code`) | [agnes](packages/agnes)(`agnes`) | +| --- | --- | --- | +| 登录 | 读 Agnes **Code 桌面端**已保存的会话(Windows,DPAPI + safeStorage),或粘贴 `accessToken` | 在 Chrome 里登录 Agnes AI 国际版网页(agnes-ai.com),不需要桌面端 | +| 服务 | Agnes Code 编码产品:`api-agnes-code.agnes-ai.com/v1`(chat completions,编码模型目录) | Agnes AI 国际版的文本模型、Token/Agent Plan 用量与美元余额 | +| 每日额度 | 本产品的每日积分(`api/v2/subscription/credits-balance`) | 该产品自己的套餐与余额读数 | +| 平台 | 桌面端解密仅 Windows,其余平台走粘贴 | 有 Chrome 即可 | + +两者是 Agnes 同一个账号体系下的**两个不同产品**:各自读各自产品的余额读数,装的模型与端点也不同,装两个不会重复也不会互相替代。 + +English: two entries serve Agnes. This one reuses the Agnes Code desktop's +saved session (Windows) or a pasted `accessToken` and calls the Agnes Code +gateway; the `agnes` entry signs in to Agnes AI international in Chrome and +meters that product's plans and USD balance. Same account system, different +products: neither entry replaces the other. + ## 登录什么 两种方式(登录时二选一): -1. **读取 Agnes Code 桌面端登录态(推荐,仅 Windows)**——本机装有 Agnes Code 桌面版并登录过即可。插件按 Chrome 同款方案解出会话(`Local State` 的 DPAPI 包裹 AES 主密钥 → 解 `code-auth-session.v1` 的 AES-256-GCM),只在本机、当前 Windows 用户下可解,凭据不外传: +1. **读取 Agnes Code 桌面端登录态(推荐,仅 Windows)**——本机装有 Agnes Code 桌面版并登录过即可,不用填任何东西。没装/没登录时这一步会给出 [Agnes Code 官网页](https://agnes-ai.com/agnescode) 链接并自动等待:装好登录后自动完成,不用回来点按钮。本机已有数据但读不出来(登录已过期、DPAPI 解不开、会话里没有 accessToken)会直接说明原因,打开桌面端登录或修好后同样自动完成。插件按 Chrome 同款方案解出会话(`Local State` 的 DPAPI 包裹 AES 主密钥 → 解 `code-auth-session.v1` 的 AES-256-GCM),只在本机、当前 Windows 用户下可解,凭据不外传: - 会话目录:`%APPDATA%\AgnesCode\`。macOS/Linux 下桌面端解密不可用,会明确提示改用粘贴方式。 - 会话 JWT 过期会提示打开 Agnes Code 重新登录后重试(桌面端负责续期)。 2. **粘贴 accessToken**——从桌面端会话里复制 JWT(`eyJ…`);可选填用户名便于区分账号。 diff --git a/packages/agnes-code/index.mjs b/packages/agnes-code/index.mjs index 2aca33f..41d6ab1 100644 --- a/packages/agnes-code/index.mjs +++ b/packages/agnes-code/index.mjs @@ -16,7 +16,8 @@ // 积分余额 GET https://api.agnes-ai.com/api/v2/subscription/credits-balance // // 本插件复用这份登录态:第一种登录方式在磁盘上解出桌面端会话(同用户同机器的 -// DPAPI 即可解,无需密钥口令,仅 Windows),第二种让用户手动粘贴 accessToken。 +// DPAPI 即可解,无需密钥口令,仅 Windows;magpie 的 oauth 方式,没解到时给出 +// 官网链接并轮询,等用户去装/重开桌面端),第二种让用户手动粘贴 accessToken。 // 积分「每日登录送 600」(免费档)由服务端随当日会话发放、无领取接口, // auth.checkin 用发放前后余额差观测:涨了记 claimed,没涨不谎称已签—— // 记 inactive 并说明未观测到(宿主把 done 渲染成「今日已签到」,是没发生的断言)。 @@ -35,6 +36,14 @@ 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" +// 读取桌面端登录态失败时展示的跳转页:Agnes Code 官网页(含桌面端下载)。 +const OFFICIAL_SITE = "https://agnes-ai.com/agnescode" +// PowerShell 解 DPAPI 的超时:它卡住时 read() 不返回,5 分钟的截止时间根本检查不到。 +const DPAPI_TIMEOUT_MS = 15000 +// 等待「用户去装/重开桌面端并登录」的窗口与轮询间隔。 +const DESKTOP_POLL_MS = 2000 +const DESKTOP_WAIT_MS = 5 * 60 * 1000 + // 模型目录读不到时的启动表(2026-11-01 实测快照;models 钩子会用实时目录覆盖)。 const BOOTSTRAP = [ { id: "agnes-3.0-flash", context: 512000, output: 65536, thinking: true }, @@ -123,8 +132,8 @@ function decryptSessionWithKey(keyBuf, rawBuf) { } // dpapiUnprotect 用当前 Windows 用户的 DPAPI 解出主密钥(经 PowerShell)。 -async function dpapiUnprotect(blob, spawnImpl = spawn) { - if (process.platform !== "win32") { +async function dpapiUnprotect(blob, spawnImpl = spawn, { timeoutMs = DPAPI_TIMEOUT_MS, platform = process.platform } = {}) { + if (platform !== "win32") { throw new Error("桌面端会话解密目前仅支持 Windows;请改用「粘贴 accessToken」方式") } const b64 = blob.toString("base64") @@ -135,9 +144,24 @@ async function dpapiUnprotect(blob, spawnImpl = spawn) { { windowsHide: true }, ) let out = "" + let settled = false + const finish = (settle, value) => { + if (settled) return + settled = true + clearTimeout(timer) + settle(value) + } + // PowerShell 卡住时不能无限等:到点杀掉子进程,让这次 read() 带原因返回。 + const timer = setTimeout(() => { + // 先落定再 kill:kill 会同步触发 close,顺序反了就会把「失败 exit」当成结果。 + finish(reject, new Error(`DPAPI 解密超时(PowerShell 超过 ${Math.round(timeoutMs / 1000)}s 没有响应)`)) + try { + child.kill() + } catch {} + }, timeoutMs) 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})`)))) + child.on("error", (error) => finish(reject, error)) + child.on("close", (code) => finish(code === 0 ? resolve : reject, code === 0 ? out.trim() : new Error(`DPAPI 解密失败(exit ${code})`))) }) const key = Buffer.from(result, "base64") if (key.length !== 32) throw new Error("DPAPI 解出的主密钥长度异常") @@ -156,7 +180,7 @@ function isExpiredJwt(token, nowMs = Date.now()) { } // readDesktopCredential 在磁盘上解出桌面端登录态,返回 { key, accountId, username, source }。 -async function readDesktopCredential({ homedir = osHomedir(), platform = process.platform, env = process.env, readFileImpl, dpapiImpl, nowMs } = {}) { +async function readDesktopCredential({ homedir = osHomedir(), platform = process.platform, env = process.env, readFileImpl, dpapiImpl, nowMs, keyCache } = {}) { // 平台检查前置:macOS/Linux 走不到 DPAPI,先在读盘前给出明确指引, // 而不是让 encrypted_key 形状检查抢先把错误说糊。 if (platform !== "win32") { @@ -175,15 +199,28 @@ async function readDesktopCredential({ homedir = osHomedir(), platform = process keyBlob = parseEncryptedKey(state?.os_crypt?.encrypted_key ?? "") raw = readFile(sessionPath) } catch (error) { - problems.push(`${dir}(${error?.message ?? "读取失败"})`) + // ENOENT = 这台机器上没有 Agnes Code;其它读盘错误要留痕。 + if (error?.code !== "ENOENT") problems.push(`${dir}(${error?.message ?? "读取失败"})`) continue } + // 同一次登录里主密钥解出一次就缓存:轮询时不必每 2 秒再起一次 PowerShell。 + let key = keyCache?.get(statePath) + if (!key) { + try { + const dpapi = dpapiImpl ?? ((blob) => dpapiUnprotect(blob)) + key = await dpapi(keyBlob) + keyCache?.set(statePath, key) + } 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) { + // 缓存的主密钥解不开这份帧(文件被别的用户/实例重写过):丢掉缓存下次重解。 + keyCache?.delete(statePath) problems.push(`${dir}(解密失败:${error?.message ?? "未知"})`) continue } @@ -192,7 +229,7 @@ async function readDesktopCredential({ homedir = osHomedir(), platform = process continue } if (isExpiredJwt(session.accessToken, nowMs)) { - throw new Error("Agnes Code 登录已过期,请打开 Agnes Code 重新登录后重试") + throw Object.assign(new Error("Agnes Code 登录已过期,请打开 Agnes Code 重新登录后重试"), { code: "expired" }) } const username = typeof session.userInfo?.username === "string" && session.userInfo.username.trim() ? session.userInfo.username.trim() @@ -201,7 +238,15 @@ async function readDesktopCredential({ homedir = osHomedir(), platform = process } const detail = problems.length ? `:${problems.join(";")}` : "" - throw new Error(`未找到 Agnes Code 桌面端登录态${detail}。请先启动 Agnes Code 并登录,或改用「粘贴 accessToken」方式。`) + // 「什么都没找到」与「有数据但读不出来」分开说:后者的用户多半已经装好了。 + const message = problems.length + ? `Agnes Code 桌面端登录态读不出来${detail}。请先启动 Agnes Code 并登录,或改用「粘贴 accessToken」方式。` + : "未找到 Agnes Code 桌面端登录态。请先启动 Agnes Code 并登录,或改用「粘贴 accessToken」方式。" + throw Object.assign( + new Error(message), + // problems 为空 = 这些路径上什么都没有(新机器);非空 = 有 Agnes Code 的数据但用不了。 + { code: problems.length ? "unreadable" : "missing" }, + ) } async function fetchModels(key, fetchImpl) { @@ -220,7 +265,48 @@ async function fetchBalance(key, fetchImpl) { }) } -function createPlugin({ fetchImpl = globalThis.fetch, readFileImpl, dpapiImpl, homedir = osHomedir(), platform = process.platform, sleepImpl } = {}) { +// authResult 把解出的桌面端会话变成 magpie 的登录结果:带 key 会被存成 API key, +// metadata 整份留给 loader / usage / checkin。 +function authResult(cred) { + return { + type: "success", + key: cred.key, + accountId: cred.accountId, + metadata: { username: cred.username, source: cred.source, method: "desktop" }, + } +} + +// probeDesktopCredential 解一次桌面端会话,把「没解到」变成返回值而不是异常。 +async function probeDesktopCredential(deps) { + try { + return { cred: await readDesktopCredential(deps) } + } catch (error) { + return { error } + } +} + +// waitForDesktopCredential 轮询磁盘,等用户装好/重开桌面端并登录。返回 +// {status:"ready", result} / {status:"timeout", error} / {status:"aborted"}。 +async function waitForDesktopCredential({ read, sleep, now, signal, waitMs = DESKTOP_WAIT_MS, stepMs = DESKTOP_POLL_MS }) { + const deadline = now() + waitMs + for (;;) { + // magpie 取消登录时会 abort 这个 signal,别再空转剩下的几分钟。 + if (signal?.aborted) return { status: "aborted" } + const trial = await read() + if (trial.cred) return { status: "ready", result: authResult(trial.cred) } + if (now() >= deadline) return { status: "timeout", error: trial.error } + await sleep(stepMs) + } +} + +// reasonOf 把读盘失败压成一句给用户看的话(超时失败时带上最后一次的原因)。 +function reasonOf(error) { + return ["unreadable", "expired", "unsupported"].includes(error?.code) + ? error.message + : "本机没有读到 Agnes Code 桌面端登录态" +} + +function createPlugin({ fetchImpl = globalThis.fetch, env = process.env, readFileImpl, dpapiImpl, homedir = osHomedir(), platform = process.platform, sleepImpl, nowMsImpl = () => Date.now() } = {}) { const sleep = sleepImpl ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))) async function readBalance(key) { @@ -251,20 +337,45 @@ function createPlugin({ fetchImpl = globalThis.fetch, readFileImpl, dpapiImpl, h provider: ID, methods: [ { - type: "api", + // oauth 方式:magpie 不显示 key 输入框,authorize 必须立刻返回 + // { url, instructions, method, callback },结果由 callback 交回。 + // 解得出就立刻完成(url 留空);解不出就给出官网链接,边等边让用户去装。 + type: "oauth", 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 桌面端登录态失败" } + async authorize(_inputs, { signal } = {}) { + // 非 Windows 解不了 DPAPI:抛错(宿主把 message 原样当失败原因), + // 别把用户丢进一个注定等不到的轮询里。 + if (platform !== "win32") { + throw new Error("桌面端会话解密仅支持 Windows;本机请改用「粘贴 accessToken」方式") + } + // 主密钥在同一次登录里只解一次(轮询不再每 2 秒起一次 PowerShell)。 + const keyCache = new Map() + const read = () => probeDesktopCredential({ readFileImpl, dpapiImpl, homedir, platform, env, nowMs: nowMsImpl(), keyCache }) + const probe = await read() + if (probe.cred) { + return { + url: "", + instructions: `已读取本机 Agnes Code 登录态(${probe.cred.username ?? probe.cred.accountId}),正在完成登录…`, + method: "auto", + callback: async () => authResult(probe.cred), + } } return { - type: "success", - key: cred.key, - accountId: cred.accountId, - metadata: { username: cred.username, source: cred.source, method: "desktop" }, + url: OFFICIAL_SITE, + instructions: + probe.error?.code === "unreadable" || probe.error?.code === "expired" + ? `${probe.error.message}(上方链接是官网;打开 Agnes Code 登录或修好后,这一步会自动完成。)` + : "本机没有读到 Agnes Code 桌面端登录态。装上或打开 Agnes Code 桌面端并登录就好——上方链接是官网,可下载;登录后这一步会自动完成。已有 token 的话,也可以改用「粘贴 accessToken」。", + method: "auto", + callback: async (_code, { signal: callbackSignal } = {}) => { + const waited = await waitForDesktopCredential({ read, sleep, now: nowMsImpl, signal: callbackSignal ?? signal }) + if (waited.status === "ready") return waited.result + if (waited.status === "aborted") return { type: "failed", error: "登录已取消" } + return { + type: "failed", + error: `仍未读到 Agnes Code 桌面端登录态(最后一次:${reasonOf(waited.error)})。登录 Agnes Code 后,重新点一次「读取 Agnes Code 桌面端登录态」即可。`, + } + }, } }, }, @@ -405,12 +516,20 @@ export const _internal = { bootstrapRows, parseEncryptedKey, decryptSessionWithKey, + dpapiUnprotect, readDesktopCredential, + probeDesktopCredential, + waitForDesktopCredential, + reasonOf, + authResult, isExpiredJwt, CHAT_GATEWAY_BASE, MODELS_URL, POINTS_API_BASE, BALANCE_PATH, + OFFICIAL_SITE, + DESKTOP_WAIT_MS, + DPAPI_TIMEOUT_MS, BOOTSTRAP, ID, } diff --git a/packages/agnes-code/index.test.mjs b/packages/agnes-code/index.test.mjs index 3eeeb8c..9110f6c 100644 --- a/packages/agnes-code/index.test.mjs +++ b/packages/agnes-code/index.test.mjs @@ -12,6 +12,9 @@ const { decryptSessionWithKey, readDesktopCredential, isExpiredJwt, + dpapiUnprotect, + OFFICIAL_SITE, + DESKTOP_WAIT_MS, CHAT_GATEWAY_BASE, MODELS_URL, ID, @@ -131,10 +134,21 @@ test("readDesktopCredential rejects expired logins with an actionable message", ) }) -test("readDesktopCredential lists what it could not read", async () => { +test("readDesktopCredential tells an empty machine from an unreadable one", async () => { + // 什么都没有 = missing(新机器),不该把「这台机器上没有」说成读不出来 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), + (e) => e.code === "missing" && !/AgnesCode(/.test(e.message), + ) + // 有文件但读不出来 = unreadable,原因要留在 message 里给用户看 + await assert.rejects( + readDesktopCredential({ + platform: "win32", + env: { APPDATA: "/w/Roaming" }, + homedir: "/home/t", + readFileImpl: fixtureFs({ [pjoin("/w/Roaming", "AgnesCode", "Local State")]: Buffer.from("{ 不是 JSON") }), + }), + (e) => e.code === "unreadable" && /不是有效|Unexpected|JSON/i.test(e.message), ) }) @@ -175,6 +189,231 @@ test("paste login method stores the access token and optional username", async ( assert.match(missing.error, /必填/) }) +const WIN_ENV = { APPDATA: "D:/AgnesTest" } + +function winFiles(key, session) { + const keyBlob = Buffer.concat([Buffer.from("DPAPI", "latin1"), key]) + return { + [pjoin(WIN_ENV.APPDATA, "AgnesCode", "Local State")]: Buffer.from( + JSON.stringify({ os_crypt: { encrypted_key: keyBlob.toString("base64") } }), + ), + [pjoin(WIN_ENV.APPDATA, "AgnesCode", "code-auth-session.v1")]: frame(key, session), + } +} + +test("desktop login method is oauth, so magpie shows no key input box", async () => { + const plugin = await AgnesPlugin() + // type:"api" 在 magpie 里就是一个 key 输入框 —— 本方法自己解磁盘,不该要用户输入。 + assert.equal(plugin.auth.methods[0].type, "oauth") + assert.equal(plugin.auth.methods[0].prompts, undefined) +}) + +test("desktop login method decrypts the session and finishes right away", async () => { + const key = randomBytes(32) + const plugin = createPlugin({ + platform: "win32", + env: WIN_ENV, + dpapiImpl: async (blob) => blob, + readFileImpl: fixtureFs(winFiles(key, { accessToken: "jwt.desk", userInfo: { username: "tester", id: "uuid-1" } })), + }) + const out = await plugin.auth.methods[0].authorize() + assert.equal(out.url, "") + assert.match(out.instructions, /已读取本机 Agnes Code 登录态(tester)/) + const result = await out.callback() + assert.equal(result.type, "success") + assert.equal(result.key, "jwt.desk") + assert.equal(result.accountId, "tester") + assert.equal(result.metadata.username, "tester") + assert.match(result.metadata.source, /code-auth-session\.v1$/) +}) + +test("desktop login method points at the official site and waits when the session is missing", async () => { + let clock = 0 + const slept = [] + const plugin = createPlugin({ + platform: "win32", + env: WIN_ENV, + dpapiImpl: async (blob) => blob, + readFileImpl: fixtureFs({}), + sleepImpl: async (ms) => { + slept.push(ms) + if (slept.length > 400) throw new Error("轮询没有封顶") + clock += ms + }, + nowMsImpl: () => clock, + }) + const out = await plugin.auth.methods[0].authorize() + assert.equal(out.url, OFFICIAL_SITE) + assert.equal(out.method, "auto") + assert.match(out.instructions, /没有读到 Agnes Code 桌面端登录态/) + // 等不到就是 failed,并告诉他登录后重试 + const failed = await out.callback() + assert.equal(failed.type, "failed") + assert.match(failed.error, /重新点一次/) + // 轮询被 DESKTOP_WAIT_MS 封顶,不会无限等下去 + assert.equal(slept.length, DESKTOP_WAIT_MS / 2000) +}) + +test("desktop login method completes on its own once the desktop logs in", async () => { + const key = randomBytes(32) + const base = fixtureFs(winFiles(key, { accessToken: "jwt.late", userInfo: { username: "late" } })) + const sessionPath = pjoin(WIN_ENV.APPDATA, "AgnesCode", "code-auth-session.v1") + let sessionReads = 0 + const plugin = createPlugin({ + platform: "win32", + env: WIN_ENV, + dpapiImpl: async (blob) => blob, + sleepImpl: async () => {}, + readFileImpl: (path) => { + if (pjoin(path) === pjoin(sessionPath)) { + sessionReads += 1 + if (sessionReads < 3) throw Object.assign(new Error("ENOENT"), { code: "ENOENT" }) + } + return base(path) + }, + }) + const out = await plugin.auth.methods[0].authorize() + assert.equal(out.url, OFFICIAL_SITE) + assert.equal((await out.callback()).key, "jwt.late") + assert.equal(sessionReads, 3) +}) + +test("desktop login method refuses to poll on non-Windows", async () => { + const plugin = createPlugin({ platform: "linux", homedir: "/home/t", readFileImpl: fixtureFs({}) }) + // 宿主 host.js 不看 oauth authorize 结果里的 type,只看抛出的 message / callback; + // 抛错在任何宿主版本上都把原因原样交给用户。 + await assert.rejects(() => plugin.auth.methods[0].authorize({}, {}), /粘贴 accessToken/) +}) + +test("readDesktopCredential keeps a read error instead of calling the machine empty", async () => { + await assert.rejects( + readDesktopCredential({ + platform: "win32", + env: WIN_ENV, + readFileImpl: () => { + throw Object.assign(new Error("EACCES: permission denied"), { code: "EACCES" }) + }, + }), + (e) => e.code === "unreadable" && /读取失败|EACCES/.test(e.message), + ) +}) + +test("desktop login method explains an expired or unreadable session", async () => { + const key = randomBytes(32) + const expired = `h.${Buffer.from(JSON.stringify({ exp: Math.floor(Date.now() / 1000) - 60 })).toString("base64url")}.s` + const plugin = createPlugin({ + platform: "win32", + env: WIN_ENV, + dpapiImpl: async (blob) => blob, + readFileImpl: fixtureFs(winFiles(key, { accessToken: expired, userInfo: { username: "tester" } })), + }) + const out = await plugin.auth.methods[0].authorize({}, {}) + assert.equal(out.url, OFFICIAL_SITE) + assert.match(out.instructions, /登录已过期/) + assert.doesNotMatch(out.instructions, /本机没有读到/) +}) + +test("desktop login method reports the last reason when it times out", async () => { + const key = randomBytes(32) + // 假时钟从「现在」起步:JWT 才算过期,deadline 也还能走到 + let clock = Date.now() + const slept = [] + const expired = `h.${Buffer.from(JSON.stringify({ exp: Math.floor(clock / 1000) - 60 })).toString("base64url")}.s` + const plugin = createPlugin({ + platform: "win32", + env: WIN_ENV, + dpapiImpl: async (blob) => blob, + readFileImpl: fixtureFs(winFiles(key, { accessToken: expired, userInfo: { username: "t" } })), + sleepImpl: async (ms) => { + slept.push(ms) + if (slept.length > 400) throw new Error("轮询没有封顶") + clock += ms + }, + nowMsImpl: () => clock, + }) + const out = await plugin.auth.methods[0].authorize({}, {}) + const failed = await out.callback(undefined, {}) + assert.equal(failed.type, "failed") + assert.match(failed.error, /登录已过期/) +}) + +test("desktop login method stops polling when the sign-in is cancelled", async () => { + let clock = 0 + const slept = [] + const controller = new AbortController() + const plugin = createPlugin({ + platform: "win32", + env: WIN_ENV, + dpapiImpl: async (blob) => blob, + readFileImpl: fixtureFs({}), + sleepImpl: async (ms) => { + slept.push(ms) + clock += ms + controller.abort() + }, + nowMsImpl: () => clock, + }) + const out = await plugin.auth.methods[0].authorize({}, { signal: controller.signal }) + const failed = await out.callback(undefined, { signal: controller.signal }) + assert.equal(failed.type, "failed") + assert.match(failed.error, /取消/) + assert.equal(slept.length, 1) +}) + +test("the desktop master key is decrypted once per sign-in, not once per poll", async () => { + const key = randomBytes(32) + // 会话读得出来、但 JWT 已过期 ⇒ 每次轮询都会走到解密那一步,缓存与不缓存能分开 + let clock = Date.now() + const slept = [] + const expired = `h.${Buffer.from(JSON.stringify({ exp: Math.floor(clock / 1000) - 60 })).toString("base64url")}.s` + let dpapiCalls = 0 + const plugin = createPlugin({ + platform: "win32", + env: WIN_ENV, + dpapiImpl: async (blob) => { + dpapiCalls += 1 + return blob + }, + sleepImpl: async (ms) => { + slept.push(ms) + if (slept.length > 400) throw new Error("轮询没有封顶") + clock += ms + }, + nowMsImpl: () => clock, + readFileImpl: fixtureFs(winFiles(key, { accessToken: expired, userInfo: { username: "late" } })), + }) + const out = await plugin.auth.methods[0].authorize({}, {}) + assert.equal((await out.callback(undefined, {})).type, "failed") + assert.ok(slept.length > 1, "应该轮询了不止一次") + assert.equal(dpapiCalls, 1) // 轮询再多次,主密钥也只解一次 +}) + +test("dpapiUnprotect kills a stuck PowerShell instead of waiting forever", async () => { + const { EventEmitter } = await import("node:events") + const fakeSpawn = () => { + const child = new EventEmitter() + child.stdout = new EventEmitter() + child.kill = () => child.emit("close", null) + return child + } + const plugin = createPlugin({ platform: "win32" }) + // 万一超时保护被删掉,这里也不能挂死:guard 先报红 + const guard = new Promise((_, reject) => setTimeout(() => reject(new Error("dpapiUnprotect 挂住了:子进程没被杀掉")), 300)) + // platform 显式传 win32:这条测的是超时,不该跟着跑测试的机器变 + await assert.rejects(Promise.race([dpapiUnprotect(Buffer.from("blob"), fakeSpawn, { timeoutMs: 0, platform: "win32" }), guard]), /DPAPI 解密超时/) + assert.equal(plugin.auth.provider, ID) // 顺手确认插件实例仍然可建 +}) + +test("dpapiUnprotect refuses a machine that is not Windows, before spawning anything", async () => { + let spawned = 0 + const spawnImpl = () => { + spawned += 1 + throw new Error("不该起子进程") + } + await assert.rejects(dpapiUnprotect(Buffer.from("blob"), spawnImpl, { platform: "darwin" }), /仅支持 Windows/) + assert.equal(spawned, 0) +}) + test("config hook declares the chat-completions provider without clobbering user config", async () => { const plugin = createPlugin() const cfg = {} diff --git a/packages/agnes-code/package.json b/packages/agnes-code/package.json index fbfb0fe..b5d13d6 100644 --- a/packages/agnes-code/package.json +++ b/packages/agnes-code/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-agnes-code-auth", - "version": "0.1.1", + "version": "0.1.2", "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": "./opencode.mjs", diff --git a/packages/astudio/README.md b/packages/astudio/README.md index a457b67..32c1e1a 100644 --- a/packages/astudio/README.md +++ b/packages/astudio/README.md @@ -25,7 +25,7 @@ same daily points balance. 两种方式(登录时二选一): -1. **读取 AStudio 桌面端登录态(推荐)**——本机装有 AStudio 桌面版并登录过即可,插件自动从它的数据目录读出模型凭据与网页会话(积分/签到用)。数据目录按以下顺序查找: +1. **读取 AStudio 桌面端登录态(推荐)**——本机装有 AStudio 桌面版并登录过即可,插件自动从它的数据目录读出模型凭据与网页会话(积分/签到用),不用填任何东西。没装/没登录时这一步会给出 [AStudio 官网](https://agent.xfyun.cn/) 链接并自动等待:装好登录后自动完成,不用回来点按钮。本机已有数据但读不出来(会话不是有效 JSON、没有凭据、账号被封禁)会直接说明原因,登录/修好后同样自动完成。数据目录按以下顺序查找: - `ASTUDIO_HOME`(或 `SYNARA_HOME`)环境变量指定的目录; - Windows 注册表 `HKCU\Software\AStudioStorage` 的 `Production/Canary/DevelopmentDataRoot`; - 兜底 `~/.acode/acode/`。 diff --git a/packages/astudio/index.mjs b/packages/astudio/index.mjs index 7481a4b..b0567d1 100644 --- a/packages/astudio/index.mjs +++ b/packages/astudio/index.mjs @@ -14,7 +14,8 @@ // points/balance、membership/me、membership/plan-config、points/summary // // 本插件复用这份登录态:第一种登录方式直接从磁盘读取桌面端会话(Raccoon -// 「复用桌面端登录态」同款),第二种让用户手动粘贴 modelBearerToken。目录与 +// 「复用桌面端登录态」同款;magpie 的 oauth 方式,读不到时给出官网链接并轮询, +// 等用户装好桌面端登录),第二种让用户手动粘贴 modelBearerToken。目录与 // 思考档位按账号实时拉取(目录读取不计费)。AStudio 有「每日登录积分」 // (服务端在当天账号会话首次活跃时发放,客户端弹窗只做通知,无领取接口), // auth.checkin 用「发放前后余额差」观测:涨了记 claimed,没涨不谎称已签—— @@ -31,6 +32,12 @@ const MODEL_GATEWAY_BASE = "https://astronstudio-api-volces-prod.xf-yun.com/mode 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/" +// 读取桌面端登录态失败时展示的跳转页:AStudio 官网(含桌面端下载)。 +const OFFICIAL_SITE = "https://agent.xfyun.cn/" +// 等待「用户去装桌面端并登录」的窗口与轮询间隔。 +const DESKTOP_POLL_MS = 2000 +const DESKTOP_WAIT_MS = 5 * 60 * 1000 + const REGISTRY_KEY = "HKCU\\Software\\AStudioStorage" const REGISTRY_PREFIXES = ["Production", "Canary", "Development"] @@ -172,12 +179,8 @@ function readDesktopCredential({ env = process.env, homedir = osHomedir(), readF const problems = [] for (const path of sessionPaths) { - let raw - try { - raw = readFile(path) - } catch { - continue - } + const raw = readFileOrNull(path, readFile, problems) + if (raw === null) continue let session try { session = JSON.parse(raw) @@ -185,7 +188,7 @@ function readDesktopCredential({ env = process.env, homedir = osHomedir(), readF problems.push(`${path} 不是有效 JSON`) continue } - if (session.banned === true) throw new Error(`AStudio 账号已被封禁(${path})`) + if (session.banned === true) throw Object.assign(new Error(`AStudio 账号已被封禁(${path})`), { code: "banned" }) const key = typeof session.modelBearerToken === "string" && session.modelBearerToken.trim() ? session.modelBearerToken.trim() : typeof session.token === "string" && session.token.trim() @@ -207,19 +210,34 @@ function readDesktopCredential({ env = process.env, homedir = osHomedir(), readF } for (const path of configPaths) { - let raw - try { - raw = readFile(path) - } catch { - continue - } + const raw = readFileOrNull(path, readFile, problems) + if (raw === null) 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」方式。`) + // 「什么都没找到」与「有数据但读不出来」分开说:后者的用户多半已经装好了。 + const message = problems.length + ? `AStudio 桌面端登录态读不出来${detail}。请先启动 AStudio 并登录,或改用「粘贴 modelBearerToken」方式。` + : "未找到 AStudio 桌面端登录态。请先启动 AStudio 并登录,或改用「粘贴 modelBearerToken」方式。" + throw Object.assign( + new Error(message), + // problems 为空 = 这些路径上什么都没有(新机器);非空 = 有 AStudio 的数据但用不了。 + { code: problems.length ? "unreadable" : "missing" }, + ) +} + +// readFileOrNull 读一个候选文件:不存在(ENOENT)算「这台机器上没有」,别的读盘 +// 错误(权限、I/O)要留进 problems,否则用户只会看到「没装」而看不出是读不了。 +function readFileOrNull(path, readFile, problems) { + try { + return readFile(path) + } catch (error) { + if (error?.code !== "ENOENT") problems.push(`${path} 读取失败(${error?.message ?? "未知错误"})`) + return null + } } // 桌面端 buildAstronCookieHeader 的等价实现(agent.xfyun.cn 的 Cookie 会话)。 @@ -277,7 +295,53 @@ async function fetchCatalog(key, fetchImpl) { }) } -function createPlugin({ fetchImpl = globalThis.fetch, env = process.env, homedir = osHomedir(), registryQuery, readFileImpl, sleepImpl } = {}) { +// authResult 把读到的桌面端凭据变成 magpie 的登录结果:带 key 会被存成 API key, +// metadata 整份留给 loader / usage / checkin(session 是账号面的 Cookie 材料)。 +function authResult(cred) { + return { + type: "success", + key: cred.key, + accountId: cred.uid, + metadata: { + uid: cred.uid, + source: cred.source, + method: "desktop", + session: cred.session, + }, + } +} + +// probeDesktopCredential 读一次桌面端登录态,把「没找到」变成返回值而不是异常。 +function probeDesktopCredential(deps = {}) { + try { + return { cred: readDesktopCredential(deps) } + } catch (error) { + return { error } + } +} + +// waitForDesktopCredential 轮询磁盘,等用户在本机装好并登录桌面端。返回 +// {status:"ready", result} / {status:"timeout", error} / {status:"aborted"}。 +async function waitForDesktopCredential({ read, sleep, now, signal, waitMs = DESKTOP_WAIT_MS, stepMs = DESKTOP_POLL_MS }) { + const deadline = now() + waitMs + for (;;) { + // magpie 取消登录时会 abort 这个 signal,别再空转剩下的几分钟。 + if (signal?.aborted) return { status: "aborted" } + const trial = read() + if (trial.cred) return { status: "ready", result: authResult(trial.cred) } + if (now() >= deadline) return { status: "timeout", error: trial.error } + await sleep(stepMs) + } +} + +// reasonOf 把读盘失败压成一句给用户看的话(超时失败时带上最后一次的原因)。 +function reasonOf(error) { + return error?.code === "unreadable" || error?.code === "banned" + ? error.message + : "本机没有 AStudio 桌面端登录态" +} + +function createPlugin({ fetchImpl = globalThis.fetch, env = process.env, homedir = osHomedir(), registryQuery, readFileImpl, sleepImpl, nowMsImpl = () => Date.now() } = {}) { const sleep = sleepImpl ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))) async function readBalance(session) { @@ -300,26 +364,40 @@ function createPlugin({ fetchImpl = globalThis.fetch, env = process.env, homedir provider: ID, methods: [ { - type: "api", + // oauth 方式:magpie 不显示 key 输入框,authorize 必须立刻返回 + // { url, instructions, method, callback },结果由 callback 交回。 + // 读得到就立刻完成(url 留空);读不到就给出官网链接,边等边让用户去装。 + type: "oauth", label: "读取 AStudio 桌面端登录态", - // 不用输入框:authorize 自己从磁盘读桌面端会话。 - async authorize() { - let cred - try { - cred = readDesktopCredential({ env, homedir, registryQuery, readFileImpl }) - } catch (error) { - return { type: "failed", error: error?.message ?? "读取 AStudio 桌面端登录态失败" } + async authorize(_inputs, { signal } = {}) { + const read = () => probeDesktopCredential({ env, homedir, registryQuery, readFileImpl }) + const probe = read() + if (probe.cred) { + return { + url: "", + instructions: `已读取本机 AStudio 登录态(${probe.cred.uid}),正在完成登录…`, + method: "auto", + callback: async () => authResult(probe.cred), + } } + // 硬失败:抛错让宿主把原因原样当登录失败显示(0.1.2810 也认 {type:"failed"}, + // 但抛错在任何宿主版本上都成立),不能落到下面那条「装上吧」的说明里。 + if (probe.error?.code === "banned") throw new Error(probe.error.message) return { - type: "success", - key: cred.key, - accountId: cred.uid, - metadata: { - uid: cred.uid, - source: cred.source, - method: "desktop", - // Cookie 会话材料:积分余额、会员信息与每日签到用。 - session: cred.session, + url: OFFICIAL_SITE, + instructions: + probe.error?.code === "unreadable" + ? `${probe.error.message}(上方链接是官网;在 AStudio 里登录或修好后,这一步会自动完成。)` + : "本机没有找到 AStudio 桌面端登录态。装上并登录 AStudio 桌面端就好——上方链接是官网,可下载;登录后这一步会自动完成。已有 token 的话,也可以改用「粘贴 modelBearerToken」。", + method: "auto", + callback: async (_code, { signal: callbackSignal } = {}) => { + const waited = await waitForDesktopCredential({ read, sleep, now: nowMsImpl, signal: callbackSignal ?? signal }) + if (waited.status === "ready") return waited.result + if (waited.status === "aborted") return { type: "failed", error: "登录已取消" } + return { + type: "failed", + error: `仍未检测到 AStudio 桌面端登录态(最后一次:${reasonOf(waited.error)})。装上或登录 AStudio 后,重新点一次「读取 AStudio 桌面端登录态」即可。`, + } }, } }, @@ -544,6 +622,11 @@ export const _internal = { rowFromCatalogEntry, bootstrapRows, readDesktopCredential, + probeDesktopCredential, + waitForDesktopCredential, + readFileOrNull, + reasonOf, + authResult, readAcodeConfigToken, registryDataRoots, buildCookieHeader, @@ -551,6 +634,8 @@ export const _internal = { MODEL_GATEWAY_BASE, MODEL_MANAGER_URL, STUDIO_API_BASE, + OFFICIAL_SITE, + DESKTOP_WAIT_MS, BOOTSTRAP, ID, } diff --git a/packages/astudio/index.test.mjs b/packages/astudio/index.test.mjs index bb8232e..056aa41 100644 --- a/packages/astudio/index.test.mjs +++ b/packages/astudio/index.test.mjs @@ -7,6 +7,7 @@ const { rowFromCatalogEntry, bootstrapRows, readDesktopCredential, + waitForDesktopCredential, readAcodeConfigToken, registryDataRoots, buildCookieHeader, @@ -14,6 +15,8 @@ const { MODEL_GATEWAY_BASE, MODEL_MANAGER_URL, STUDIO_API_BASE, + OFFICIAL_SITE, + DESKTOP_WAIT_MS, ID, } = _internal @@ -242,27 +245,178 @@ test("usage hook checks the credential without burning quota", async () => { assert.deepEqual(await ok.auth.usage(async () => undefined), {}) }) +test("desktop login method is oauth, so magpie shows no key input box", () => { + const plugin = createPlugin({ env: {}, registryQuery: () => null, readFileImpl: fakeFs({}) }) + const method = plugin.auth.methods[0] + // type:"api" 在 magpie 里就是一个 key 输入框 —— 本方法自己读磁盘,不该要用户输入。 + assert.equal(method.type, "oauth") + assert.match(method.label, /桌面端/) + assert.equal(method.prompts, undefined) +}) + test("desktop login method reads real files through authorize", async () => { const plugin = createPlugin({ env: { ASTUDIO_HOME: "D:\\astudio" }, + registryQuery: () => null, 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, { + const out = await plugin.auth.methods[0].authorize({}) + assert.equal(out.url, "") + assert.match(out.instructions, /已读取本机 AStudio 登录态(u9)/) + assert.equal(out.method, "auto") + assert.deepEqual(await out.callback(), { 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({}) +test("desktop login method points at the official site and waits when nothing is on disk", async () => { + let clock = 0 + const slept = [] + const plugin = createPlugin({ + env: {}, + registryQuery: () => null, + readFileImpl: fakeFs({}), + sleepImpl: async (ms) => { + slept.push(ms) + // 变异把 deadline 判断删掉时这里立刻报红,而不是让假 sleep 把事件循环占死。 + if (slept.length > 400) throw new Error("轮询没有封顶") + clock += ms + }, + nowMsImpl: () => clock, + }) + const out = await plugin.auth.methods[0].authorize({}) + assert.equal(out.url, OFFICIAL_SITE) + assert.equal(out.method, "auto") + assert.match(out.instructions, /没有找到 AStudio 桌面端登录态/) + // 用户去装桌面端:等不到就是 failed,并告诉他装好后重试 + const failed = await out.callback() assert.equal(failed.type, "failed") - assert.match(failed.error, /未找到/) + assert.match(failed.error, /重新点一次/) + // 轮询被 DESKTOP_WAIT_MS 封顶,不会无限等下去 + assert.equal(slept.length, DESKTOP_WAIT_MS / 2000) +}) + +test("desktop login method completes on its own once the desktop signs in", async () => { + const session = JSON.stringify({ uid: "u7", modelBearerToken: "tok-7" }) + let reads = 0 + const plugin = createPlugin({ + env: { ASTUDIO_HOME: "D:\\astudio" }, + registryQuery: () => null, + sleepImpl: async () => {}, + readFileImpl: (path) => { + if (path !== "D:\\astudio/userdata/astron-session.json") throw Object.assign(new Error("ENOENT"), { code: "ENOENT" }) + reads += 1 + if (reads < 3) throw Object.assign(new Error("ENOENT"), { code: "ENOENT" }) + return session + }, + }) + const out = await plugin.auth.methods[0].authorize({}) + assert.equal(out.url, OFFICIAL_SITE) + assert.equal(reads, 1) // authorize 读一次 + assert.equal((await out.callback()).key, "tok-7") + assert.equal(reads, 3) +}) + +test("waitForDesktopCredential stops at the deadline", async () => { + let clock = 0 + const slept = [] + const result = await waitForDesktopCredential({ + read: () => ({ error: new Error("没找到") }), + sleep: async (ms) => { + slept.push(ms) + clock += ms + }, + now: () => clock, + waitMs: 5000, + stepMs: 2000, + }) + assert.equal(result.status, "timeout") + assert.equal(result.error.message, "没找到") // 超时要把最后一次的原因带出来 + assert.deepEqual(slept, [2000, 2000, 2000]) +}) + +test("desktop login method refuses banned accounts instead of offering the site", async () => { + const plugin = createPlugin({ + env: { ASTUDIO_HOME: "D:\\astudio" }, + registryQuery: () => null, + readFileImpl: fakeFs({ + "D:\\astudio/userdata/astron-session.json": JSON.stringify({ banned: true, modelBearerToken: "tok" }), + }), + }) + // 宿主 host.js 不看 oauth authorize 结果里的 type,只看它抛出的 message 或 callback; + // 抛错在任何宿主版本上都把原因原样交给用户。 + await assert.rejects(() => plugin.auth.methods[0].authorize({}, {}), /封禁/) +}) + +test("desktop login method explains an unreadable session instead of pointing at install", async () => { + const plugin = createPlugin({ + env: { ASTUDIO_HOME: "D:\\astudio" }, + registryQuery: () => null, + readFileImpl: fakeFs({ "D:\\astudio/userdata/astron-session.json": "{ 不是 JSON" }), + }) + const out = await plugin.auth.methods[0].authorize({}, {}) + assert.equal(out.url, OFFICIAL_SITE) + assert.match(out.instructions, /不是有效 JSON/) + assert.doesNotMatch(out.instructions, /本机没有找到/) +}) + +test("desktop login method keeps a read error instead of calling the machine empty", async () => { + const plugin = createPlugin({ + env: { ASTUDIO_HOME: "D:\\astudio" }, + registryQuery: () => null, + readFileImpl: () => { + throw Object.assign(new Error("EACCES: permission denied"), { code: "EACCES" }) + }, + }) + const out = await plugin.auth.methods[0].authorize({}, {}) + assert.match(out.instructions, /读取失败.*EACCES/s) // 读不了 ≠ 没装 +}) + +test("desktop login method reports the last reason when it times out", async () => { + let clock = 0 + const slept = [] + const plugin = createPlugin({ + env: { ASTUDIO_HOME: "D:\\astudio" }, + registryQuery: () => null, + readFileImpl: fakeFs({ "D:\\astudio/userdata/astron-session.json": "{}" }), + sleepImpl: async (ms) => { + slept.push(ms) + if (slept.length > 400) throw new Error("轮询没有封顶") + clock += ms + }, + nowMsImpl: () => clock, + }) + const out = await plugin.auth.methods[0].authorize({}, {}) + const failed = await out.callback(undefined, {}) + assert.equal(failed.type, "failed") + assert.match(failed.error, /没有 modelBearerToken.token/) +}) + +test("desktop login method stops polling when the sign-in is cancelled", async () => { + let clock = 0 + const slept = [] + const controller = new AbortController() + const plugin = createPlugin({ + env: {}, + registryQuery: () => null, + readFileImpl: fakeFs({}), + sleepImpl: async (ms) => { + slept.push(ms) + clock += ms + controller.abort() + }, + nowMsImpl: () => clock, + }) + const out = await plugin.auth.methods[0].authorize({}, { signal: controller.signal }) + const failed = await out.callback(undefined, { signal: controller.signal }) + assert.equal(failed.type, "failed") + assert.match(failed.error, /取消/) + assert.equal(slept.length, 1) // 取消后不再空转 }) test("desktop credential carries the cookie session for points and check-in", () => { diff --git a/packages/astudio/package.json b/packages/astudio/package.json index 7fcc92c..bf71e88 100644 --- a/packages/astudio/package.json +++ b/packages/astudio/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-astudio-auth", - "version": "0.1.2", + "version": "0.1.3", "description": "AStudio (iFLYTEK Astron Studio) desktop sign-in as an OpenCode/magpie provider: Responses model gateway with live model catalog", "type": "module", "main": "./opencode.mjs", diff --git a/registry.json b/registry.json index 5d41dac..dc142d6 100644 --- a/registry.json +++ b/registry.json @@ -194,6 +194,6 @@ { "package": "@magpie-community/opencode-astudio-auth", "name": "AStudio", "providers": ["astudio"], "community": true, "summary": { "en": "Unofficial AStudio (iFLYTEK Astron Studio desktop): reuse the desktop sign-in to serve its Responses model gateway, with the live model catalog, daily login-points check-in and points balance. Desktop discovery runs on Windows (registry lookup), with a paste-token fallback. Differs from Providers Hub's hub-astudio, which signs in on a local page (SMS, password or WeChat QR) and calls chat/completions; on one account both share the same daily points pool.", "zh": "非官方 AStudio(科大讯飞 Astron Studio 桌面端):复用桌面端登录态接入其模型网关,含实时模型目录、每日登录积分签到与积分余额。桌面端发现仅 Windows(注册表定位),另有粘贴凭据方式。与 Providers Hub 的 hub-astudio 不同:那边在本地登录页用短信、密码或微信扫码登录,走 chat/completions;同一账号两边共用一个每日积分池。" } }, { "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。" } } + "summary": { "en": "Unofficial Agnes Code desktop: reuse the desktop sign-in for its OpenAI-compatible gateway, with the live model catalog, daily credit check-in and points balance. Desktop decryption is Windows-only; a paste-token method covers the rest. Differs from opencode-agnes-auth (`agnes`), which signs in to Agnes AI international in Chrome and meters that product's plans and USD balance: this one serves the Agnes Code desktop product and its daily credits.", "zh": "非官方 Agnes Code 桌面端:复用桌面端登录态接入其 OpenAI 兼容网关,含实时模型目录、每日积分签到与余额显示。桌面端解密仅限 Windows,其余平台用粘贴 accessToken。与 opencode-agnes-auth(`agnes`)不同:那边在 Chrome 里登录 Agnes AI 国际版、显示该产品的套餐与美元余额;本包服务 Agnes Code 桌面端产品与它的每日积分。" } } ] }