From 72ca16e006c9d634879eac92a86584cbe58bd378 Mon Sep 17 00:00:00 2001 From: kshu06537-bot Date: Wed, 18 Nov 2026 18:31:08 +0800 Subject: [PATCH 1/7] quwork 0.1.0: unofficial QuWork provider (browser SMS sign-in, desktop session, points) --- packages/quwork/LICENSE | 21 + packages/quwork/README.md | 96 +++++ packages/quwork/index.mjs | 670 ++++++++++++++++++++++++++++++++ packages/quwork/opencode.mjs | 3 + packages/quwork/opencode2.mjs | 620 +++++++++++++++++++++++++++++ packages/quwork/package.json | 54 +++ packages/quwork/page/app.js | 36 ++ packages/quwork/page/balance.js | 3 + packages/quwork/page/index.html | 50 +++ packages/quwork/page/style.css | 62 +++ packages/quwork/test.mjs | 38 ++ registry.json | 4 +- 12 files changed, 1656 insertions(+), 1 deletion(-) create mode 100644 packages/quwork/LICENSE create mode 100644 packages/quwork/README.md create mode 100644 packages/quwork/index.mjs create mode 100644 packages/quwork/opencode.mjs create mode 100644 packages/quwork/opencode2.mjs create mode 100644 packages/quwork/package.json create mode 100644 packages/quwork/page/app.js create mode 100644 packages/quwork/page/balance.js create mode 100644 packages/quwork/page/index.html create mode 100644 packages/quwork/page/style.css create mode 100644 packages/quwork/test.mjs diff --git a/packages/quwork/LICENSE b/packages/quwork/LICENSE new file mode 100644 index 000000000..91b497d62 --- /dev/null +++ b/packages/quwork/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 kshu06537-bot + +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. diff --git a/packages/quwork/README.md b/packages/quwork/README.md new file mode 100644 index 000000000..8fb680c62 --- /dev/null +++ b/packages/quwork/README.md @@ -0,0 +1,96 @@ +# @magpie-community/opencode-quwork-auth + +**非官方** QuWork(Clawork,微服)接入:[magpie](https://usemagpie.ai/) 与 [OpenCode](https://opencode.ai/) 的模型供应商 `quwork`。支持浏览器手机验证码登录(不需要 QuWork 桌面客户端)、复用桌面端登录态,或粘贴 `sk-` 令牌;显示实时模型与积分余额。 + +> Unofficial. QuWork publishes no developer API for other clients. This package uses the account and endpoints the QuWork desktop client uses; read the risk section before using or sharing it. + +## 登录方式 + +登录菜单有三项,任选其一: + +1. **浏览器登录 QuWork(手机验证码,无需客户端)** —— magpie 在本机 `127.0.0.1` 启动一次性登录页(随机路径、仅本机可访问、10 分钟超时),你在页面里输入手机号、完成 QuWork 的阿里云验证码、填入短信验证码,插件用 QuWork 的 `/api/user/client/login` 换取账号令牌。登录成功后页面提示完成,magpie 自动接管。 +2. **读取 QuWork 本机登录态** —— 本机装过 QuWork 桌面端并登录过时,读取它的 `llm_token`(`sk-` 开头);不启动、不修改桌面端。Windows 读 `%APPDATA%\qurwork-desktop\qurwork-desktop.sqlite`(含 WAL),macOS 读对应的 Application Support 目录。 +3. **粘贴 QuWork 令牌** —— 直接粘贴 `sk-` 令牌;只够调用模型,读不到积分余额(余额接口要账号 access token)。 + +每个登录是一个 magpie 账号,可多账号故障切换。凭据保存在 magpie 的 `plugin-auth.json`(权限 600),不上传;插件不记录请求内容或令牌。 + +## 模型 + +供应商 id `quwork`,走 OpenAI Chat Completions 协议: + +`https://llm.quwork.cn/v1/chat/completions` + +内置 10 个常用模型(目录随 QuWork 配置变化时以插件声明为准): + +| model | context | output | 备注 | +| --- | --- | --- | --- | +| `deepseek-flash` | 1M | 384k | 识图,思考 off/low/high/max | +| `deepseek-v4-pro` | 1M | 384k | 思考 off/low/high/max | +| `qwen3.8-max` | 1M | 128k | | +| `qwen3.8-flash` | 1M | 128k | 识图 | +| `qwen3.7-plus` | 1M | 128k | 识图 | +| `glm-5.3-flash` | 1M | 128k | 识图 | +| `glm-5.2` | 1M | 128k | | +| `kimi-k2.7-code` | 1M | 128k | | +| `kimi-k2.6` | 1M | 256k | 识图 | +| `MiniMax-M2.5` | 1M | 32k | | + +在 agent 里用 `quwork/`。 + +## 积分余额 + +- 侧边栏 **「QuWork 接入」** 页顶部显示积分余额(登录后自动缓存最新值)。 +- magpie 的 **Quota(额度)** 页,或: + +```powershell +magpie quota quwork +magpie quota quwork --json +``` + +余额来自 `GET https://llm.rrzu.com/api/user/self` 的 `data.points_entitlement`,读取不计费;60 秒内复用缓存。401/403 会把账号标为需要重新登录。**浏览器登录**与**读取本机登录态**能读余额;**粘贴 `sk-` 令牌**不能,因为账号接口只认 access token。 + +## 上游与协议 + +- 模型:`https://llm.quwork.cn/v1`(OpenAI Chat Completions,`Authorization: Bearer `,另带 `X-QurWork-Env: prod`、`X-QurWork-Version`)。 +- 账号:`https://llm.rrzu.com`,登录 `/api/user/client/login`,短信 `/api/sendVerifyCode`(需阿里云验证码 `aliyun_captcha`),资料 `/api/user/self`。 +- 验证码 SDK:阿里云官方 `https://o.alicdn.com/captcha-frontend/aliyunCaptcha/AliyunCaptcha.js`,`region=cn`、`prefix=1hms8d`、`SceneId=10vzkucv`(与 QuWork 客户端一致)。 + +## 安全与隐私 + +- 登录页只监听 `127.0.0.1`,使用每次登录随机的 URL 路径;POST 检查 `Origin`,不匹配直接 403;页面禁止被嵌入(`X-Frame-Options: DENY`)、`Referrer-Policy: no-referrer`、`Cache-Control: no-store`。 +- 浏览器登录的设备标识保存在系统临时目录的 `magpie-quwork-device.json`(稳定设备 id,降低频繁换设备的风控概率),不是账号令牌。 +- 不打印、不上传令牌;错误信息不含令牌。 + +## 风险提示(重要) + +- **非官方集成。** QuWork 没有公开的开发者 API / API Key;本插件复刻的是桌面客户端的登录与模型接口。QuWork 的服务条款可能限制在官方客户端之外使用账号与额度。 +- **有账号风险。** 第三方客户端访问可能被上游识别,导致验证码加强、限流、额度冻结、警告或封号;无法保证不会发生。浏览器登录的设备标识已保持稳定,但仍不是官方客户端。 +- **请只用你自己的账号。** 不要共享令牌、不要多账号批量/滥用、不要转售或对外提供网关;这些行为显著提高封号与法律风险。 +- 上游接口、模型和积分规则随时可能变更;变更后插件可能失效。发布前请阅读 QuWork 客户端内的《Clawork 软件许可及服务协议》。 +- 本项目按 MIT 发布,不附带任何担保;使用风险自担。 + +## 安装与开发 + +```powershell +magpie plugin add @magpie-community/opencode-quwork-auth +magpie plugin login quwork # 选第 1 项:浏览器登录 +magpie provider test quwork +``` + +从本仓库开发: + +```powershell +magpie plugin add ./packages/quwork +bun scripts/check.mjs quwork +npm test +``` + +OpenCode: + +```json +{ "plugin": ["@magpie-community/opencode-quwork-auth"] } +``` + +## 页面 + +安装后侧边栏出现 **「QuWork 接入」**:显示供应商是否已出现、积分余额(缓存)、登录步骤和两种备选登录方式。页面只读取 `providers:list`,不读取账号或请求内容。 diff --git a/packages/quwork/index.mjs b/packages/quwork/index.mjs new file mode 100644 index 000000000..dbfe76aaa --- /dev/null +++ b/packages/quwork/index.mjs @@ -0,0 +1,670 @@ +import { createServer } from "node:http" +import { randomUUID } from "node:crypto" +import { copyFileSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs" +import { homedir, tmpdir } from "node:os" +import { dirname, join } from "node:path" +import { fileURLToPath } from "node:url" + +const PROVIDER = "quwork" +const LLM_BASE = "https://llm.quwork.cn/v1" +const ACCOUNT_BASE = "https://llm.rrzu.com" +const TOKEN_ENV = "QUWORK_LLM_TOKEN" +const FALLBACK_VERSION = "1.7.5" +const CAPTCHA_SDK = "https://o.alicdn.com/captcha-frontend/aliyunCaptcha/AliyunCaptcha.js" +const CAPTCHA_REGION = "cn" +const CAPTCHA_PREFIX = "1hms8d" +const CAPTCHA_SCENE_ID = "10vzkucv" +const PLUGIN_DIR = dirname(fileURLToPath(import.meta.url)) +const BALANCE_FILE = join(PLUGIN_DIR, "page", "balance.js") +const DEVICE_FILE = join(tmpdir(), "magpie-quwork-device.json") +const BALANCE_TTL_MS = 60_000 + +const balanceCache = new Map() + +const MODELS = [ + { + id: "deepseek-flash", + name: "DeepSeek-V4.1-Flash", + limit: { context: 1000000, output: 384000 }, + reasoning: true, + tool_call: true, + modalities: { input: ["text", "image"] }, + variants: { off: {}, low: {}, high: {}, max: {} }, + }, + { + id: "deepseek-v4-pro", + name: "DeepSeek-V4-Pro", + limit: { context: 1000000, output: 384000 }, + reasoning: true, + tool_call: true, + variants: { off: {}, low: {}, high: {}, max: {} }, + }, + { id: "qwen3.8-max", name: "Qwen3.8-Max", limit: { context: 1000000, output: 128000 }, tool_call: true }, + { id: "qwen3.8-flash", name: "Qwen3.8-Flash", limit: { context: 1000000, output: 128000 }, tool_call: true, modalities: { input: ["text", "image"] } }, + { id: "qwen3.7-plus", name: "Qwen3.7-Plus", limit: { context: 1000000, output: 128000 }, tool_call: true, modalities: { input: ["text", "image"] } }, + { id: "glm-5.3-flash", name: "GLM-5.3 Flash", limit: { context: 1000000, output: 128000 }, tool_call: true, modalities: { input: ["text", "image"] } }, + { id: "glm-5.2", name: "GLM-5.2", limit: { context: 1000000, output: 128000 }, tool_call: true }, + { id: "kimi-k2.7-code", name: "Kimi-K2.7-Code", limit: { context: 1000000, output: 128000 }, tool_call: true }, + { id: "kimi-k2.6", name: "Kimi-K2.6", limit: { context: 1000000, output: 262144 }, tool_call: true, modalities: { input: ["text", "image"] } }, + { id: "MiniMax-M2.5", name: "MiniMax-M2.5", limit: { context: 1000000, output: 32768 }, tool_call: true }, +] + +const LOGIN_PAGE = ` + + + + +QuWork 登录 · magpie + + + +
+

QuWork 登录

+

用手机号 + 短信验证码登录 QuWork。登录成功后这个页面会提示完成,magpie 会自动接管,不需要安装 QuWork 客户端。

+ + +
+ + + + + +
+
验证码由 QuWork 发送,登录态只保存在本机 magpie。若验证码加载失败,可改用 magpie 里的「读取 QuWork 本机登录态」或「粘贴令牌」。
+
+ + + +` + +function appDataDirs() { + const dirs = [] + if (process.env.APPDATA) dirs.push(process.env.APPDATA) + if (process.platform === "darwin") dirs.push(join(homedir(), "Library", "Application Support")) + else dirs.push(join(homedir(), ".config")) + return dirs +} + +function harnessRoots() { + const roots = [] + if (process.env.QURWORK_DSH_HOME) roots.push(process.env.QURWORK_DSH_HOME) + roots.push(join(homedir(), ".qurwork-desktop-dsh", ".dsh")) + roots.push(join(homedir(), ".quwork-desktop-dsh", ".dsh")) + return roots +} + +function tokenFromCredentials(file) { + try { + if (!existsSync(file)) return "" + const raw = readFileSync(file, "utf8") + const match = raw.match(/QURIVS_LLM_API_KEY\s*:\s*([^\s,}]+)/) + return match ? match[1].replace(/^["']|["']$/g, "").trim() : "" + } catch { + return "" + } +} + +function tokensFromWal(walFile) { + try { + if (!existsSync(walFile)) return {} + const text = readFileSync(walFile).toString("latin1") + const start = text.indexOf('"accessToken"') + if (start < 0) return {} + const chunk = text.slice(start, start + 1600) + return { + llmToken: chunk.match(/"llmToken":"([^"]+)"/)?.[1] ?? "", + accessToken: chunk.match(/"accessToken":"([^"]+)"/)?.[1] ?? "", + } + } catch { + return {} + } +} + +async function readDesktopSession(file) { + const walFile = `${file}-wal` + const shmFile = `${file}-shm` + try { + const { Database } = await import("bun:sqlite") + const db = new Database(file, { readonly: true }) + try { + const row = db.query("select session_json from auth_session where id = 1").get() + if (row?.session_json) return JSON.parse(row.session_json) + } finally { + db.close() + } + } catch { + // The desktop app may hold the database open; use a copy below. + } + + try { + const dir = mkdtempSync(join(tmpdir(), "quwork-session-")) + try { + const copy = join(dir, "db.sqlite") + copyFileSync(file, copy) + if (existsSync(walFile)) copyFileSync(walFile, `${copy}-wal`) + if (existsSync(shmFile)) copyFileSync(shmFile, `${copy}-shm`) + const { Database } = await import("bun:sqlite") + const db = new Database(copy, { readonly: true }) + try { + const row = db.query("select session_json from auth_session where id = 1").get() + if (row?.session_json) return JSON.parse(row.session_json) + } finally { + db.close() + } + } finally { + rmSync(dir, { recursive: true, force: true }) + } + } catch { + // Fall through to the WAL scan. + } + return null +} + +async function tokenFromDesktopDb() { + for (const base of appDataDirs()) { + const file = join(base, "qurwork-desktop", "qurwork-desktop.sqlite") + const walFile = `${file}-wal` + if (!existsSync(file) && !existsSync(walFile)) continue + const session = existsSync(file) ? await readDesktopSession(file) : null + if (session?.llmToken) return String(session.llmToken).trim() + const tokens = tokensFromWal(walFile) + if (tokens.llmToken) return tokens.llmToken + } + return "" +} + +async function findLocalToken() { + const fromEnv = (process.env[TOKEN_ENV] ?? "").trim() + if (fromEnv) return { key: fromEnv, source: "env" } + for (const root of harnessRoots()) { + const key = tokenFromCredentials(join(root, ".credentials.yaml")) + if (key) return { key, source: "credentials" } + } + const key = await tokenFromDesktopDb() + if (key) return { key, source: "desktop-db" } + return { key: "", source: "" } +} + +async function findAccessToken() { + for (const base of appDataDirs()) { + const file = join(base, "qurwork-desktop", "qurwork-desktop.sqlite") + const walFile = `${file}-wal` + if (!existsSync(file) && !existsSync(walFile)) continue + const session = existsSync(file) ? await readDesktopSession(file) : null + if (session?.accessToken) return String(session.accessToken).trim() + const tokens = tokensFromWal(walFile) + if (tokens.accessToken) return tokens.accessToken + } + return "" +} + +function quworkVersion() { + for (const root of harnessRoots()) { + try { + const file = join(root, "profiles", "web", "cordis.patch.yml") + if (!existsSync(file)) continue + const match = readFileSync(file, "utf8").match(/X-QurWork-Version\s*:\s*([0-9][^\s,}]*)/) + if (match) return match[1].trim() + } catch { + continue + } + } + return FALLBACK_VERSION +} + +function deviceIdentifier() { + try { + if (existsSync(DEVICE_FILE)) { + const data = JSON.parse(readFileSync(DEVICE_FILE, "utf8")) + if (typeof data?.deviceId === "string" && data.deviceId) return data.deviceId + } + } catch { + // Generate a new id below. + } + const deviceId = randomUUID() + try { + writeFileSync(DEVICE_FILE, JSON.stringify({ deviceId }), "utf8") + } catch { + // A read-only temp folder is fine; the id is then only stable for this process. + } + return deviceId +} + +function numberOrZero(value) { + const number = Number(value) + return Number.isFinite(number) ? number : 0 +} + +async function readPoints(accessToken, { force = false } = {}) { + if (!accessToken) return null + const cached = balanceCache.get(accessToken) + if (!force && cached && Date.now() - cached.at < BALANCE_TTL_MS) return cached.points + const res = await fetch(`${ACCOUNT_BASE}/api/user/self`, { + headers: { authorization: `Bearer ${accessToken}`, "x-qurwork-env": "prod", "x-qurwork-version": quworkVersion() }, + }) + if (res.status === 401 || res.status === 403) { + throw Object.assign(new Error(`QuWork 拒绝了这份凭据(HTTP ${res.status}),请重新登录 QuWork`), { status: res.status, signIn: "expired" }) + } + if (!res.ok) throw new Error(`QuWork 返回 ${res.status}`) + const payload = await res.json() + const entitlement = payload?.data?.points_entitlement + if (!payload?.success || !entitlement) { + throw new Error(payload?.message || "QuWork 积分接口没有返回可用数据") + } + const points = { + total: numberOrZero(entitlement.total_points), + limited: numberOrZero(entitlement.limited_points), + permanent: numberOrZero(entitlement.permanent_points), + plan: entitlement.active_subscription?.plan_name ?? "积分", + } + balanceCache.set(accessToken, { points, at: Date.now() }) + return points +} + +function pointsText(points) { + if (!points) return "" + return `${points.total} 积分` +} + +function writeBalanceCache(points) { + try { + const value = points ? pointsText(points) : "" + const detail = points + ? { + total: points.total, + limited: points.limited, + permanent: points.permanent, + plan: points.plan, + updatedAt: new Date().toISOString(), + } + : null + writeFileSync( + BALANCE_FILE, + `window.__QUWORK_BALANCE__ = ${JSON.stringify(value)};\nwindow.__QUWORK_BALANCE_DETAIL__ = ${JSON.stringify(detail)};\n`, + "utf8", + ) + } catch { + // The page is a convenience; a read-only folder must not break the provider. + } +} + +async function checkKey(key) { + try { + const res = await fetch(`${LLM_BASE}/models`, { + headers: { authorization: `Bearer ${key}`, "x-qurwork-env": "prod", "x-qurwork-version": quworkVersion() }, + }) + if (res.ok) return { ok: true } + const detail = (await res.text()).slice(0, 200) + return { ok: false, error: `QuWork 返回 ${res.status}${detail ? `:${detail}` : ""}` } + } catch (error) { + return { ok: false, error: `连不上 QuWork:${error instanceof Error ? error.message : String(error)}` } + } +} + +function readJsonBody(req) { + return new Promise((resolve, reject) => { + let size = 0 + const chunks = [] + req.on("data", (chunk) => { + size += chunk.length + if (size > 1_000_000) { + reject(new Error("请求体过大")) + req.destroy() + return + } + chunks.push(chunk) + }) + req.on("end", () => { + try { + resolve(chunks.length ? JSON.parse(Buffer.concat(chunks).toString("utf8")) : {}) + } catch { + reject(new Error("请求格式无效")) + } + }) + req.on("error", reject) + }) +} + +function sendJson(res, status, body) { + res.writeHead(status, { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" }) + res.end(JSON.stringify(body)) +} + +async function startBrowserLogin() { + const state = { result: null, closed: false } + const secret = randomUUID() + const server = createServer(async (req, res) => { + const url = new URL(req.url ?? "/", "http://127.0.0.1") + const prefix = `/${secret}` + const host = req.headers.host ?? "" + const origin = req.headers.origin + if (req.method === "POST" && origin && origin !== `http://${host}`) { + return sendJson(res, 403, { success: false, message: "forbidden" }) + } + if (req.method === "GET" && url.pathname === `${prefix}/`) { + res.writeHead(200, { + "content-type": "text/html; charset=utf-8", + "cache-control": "no-store", + "x-frame-options": "DENY", + "referrer-policy": "no-referrer", + "x-content-type-options": "nosniff", + }) + res.end(LOGIN_PAGE) + return + } + if (req.method === "POST" && url.pathname === `${prefix}/api/send-code`) { + try { + const body = await readJsonBody(req) + const phone = String(body.phone ?? "").trim() + const captcha = String(body.captcha ?? "").trim() + if (!/^1[3-9]\d{9}$/.test(phone)) return sendJson(res, 400, { success: false, message: "手机号格式不正确" }) + if (!captcha) return sendJson(res, 400, { success: false, message: "缺少验证码参数" }) + const query = `?${new URLSearchParams({ aliyun_captcha: captcha }).toString()}` + const upstream = await fetch(`${ACCOUNT_BASE}/api/sendVerifyCode${query}`, { + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded", "x-qurwork-env": "prod", "x-qurwork-version": quworkVersion() }, + body: new URLSearchParams({ phone, type: "login" }).toString(), + }) + const payload = await upstream.json().catch(() => ({ success: false, message: `QuWork 返回 ${upstream.status}` })) + return sendJson(res, upstream.ok ? 200 : upstream.status, payload) + } catch (error) { + return sendJson(res, 500, { success: false, message: error instanceof Error ? error.message : String(error) }) + } + } + if (req.method === "POST" && url.pathname === `${prefix}/api/login`) { + try { + const body = await readJsonBody(req) + const phone = String(body.phone ?? "").trim() + const code = String(body.code ?? "").trim() + if (!/^1[3-9]\d{9}$/.test(phone)) return sendJson(res, 400, { success: false, message: "手机号格式不正确" }) + if (!/^\d{4,6}$/.test(code)) return sendJson(res, 400, { success: false, message: "验证码格式不正确" }) + const upstream = await fetch(`${ACCOUNT_BASE}/api/user/client/login`, { + method: "POST", + headers: { "content-type": "application/json", "x-qurwork-env": "prod", "x-qurwork-version": quworkVersion() }, + body: JSON.stringify({ + phone, + verification_code: code, + platform: "qurvis", + device_identifier: deviceIdentifier(), + device_uuid: "", + }), + }) + const payload = await upstream.json().catch(() => ({ success: false, message: `QuWork 返回 ${upstream.status}` })) + if (upstream.ok && payload?.success && payload?.data?.token) { + state.result = { + key: String(payload.data.llm_token ?? "").trim() || String(payload.data.token ?? "").trim(), + accessToken: String(payload.data.token ?? "").trim(), + user: payload.data.user ?? null, + } + return sendJson(res, 200, { success: true }) + } + return sendJson(res, upstream.ok ? 200 : upstream.status, payload) + } catch (error) { + return sendJson(res, 500, { success: false, message: error instanceof Error ? error.message : String(error) }) + } + } + res.writeHead(404, { "content-type": "text/plain; charset=utf-8" }) + res.end("not found") + }) + + await new Promise((resolve, reject) => { + server.once("error", reject) + server.listen(0, "127.0.0.1", resolve) + }) + + const address = server.address() + const port = typeof address === "object" && address ? address.port : 0 + return { + url: `http://127.0.0.1:${port}/${secret}/`, + state, + close() { + state.closed = true + try { + server.close() + } catch { + // already closed + } + }, + } +} + +async function waitForBrowserLogin(session, timeoutMs = 10 * 60_000) { + const startedAt = Date.now() + try { + while (!session.state.closed && Date.now() - startedAt < timeoutMs) { + if (session.state.result) return session.state.result + await new Promise((resolve) => setTimeout(resolve, 1000)) + } + return null + } finally { + session.close() + } +} + +export const QuWorkProvider = async () => ({ + config: async (cfg) => { + cfg.provider ??= {} + cfg.provider[PROVIDER] ??= { + name: "QuWork", + npm: "@ai-sdk/openai-compatible", + api: LLM_BASE, + models: Object.fromEntries(MODELS.map((model) => [model.id, model])), + } + }, + + auth: { + provider: PROVIDER, + methods: [ + { + type: "oauth", + label: "浏览器登录 QuWork(手机验证码,无需客户端)", + async authorize(_inputs, options = {}) { + const session = await startBrowserLogin() + if (options.signal) options.signal.addEventListener("abort", () => session.close(), { once: true }) + return { + url: session.url, + instructions: "在打开的页面里输入手机号,完成阿里云验证码后获取短信验证码,再点「登录并接入 magpie」。", + method: "auto", + close: () => session.close(), + async callback() { + const result = await waitForBrowserLogin(session) + if (!result?.key) return { type: "failed", error: "登录超时或未完成,请重试。" } + const checked = await checkKey(result.key) + if (!checked.ok) return { type: "failed", error: checked.error } + return { + type: "success", + key: result.key, + metadata: { source: "browser", accessToken: result.accessToken, user: result.user }, + } + }, + } + }, + }, + { + type: "api", + label: "读取 QuWork 本机登录态", + async authorize() { + const found = await findLocalToken() + if (!found.key) { + return { type: "failed", error: "没有找到 QuWork 登录态:先用上面的「浏览器登录」,或在下一个方法里粘贴 sk- 令牌。" } + } + const checked = await checkKey(found.key) + if (!checked.ok) return { type: "failed", error: checked.error } + return { type: "success", key: found.key, metadata: { source: found.source } } + }, + }, + { + type: "api", + label: "粘贴 QuWork 令牌", + placeholder: "sk-…", + async authorize(inputs) { + const key = String(inputs?.key ?? inputs?.apiKey ?? inputs?.api_key ?? inputs?.value ?? "").trim() + if (!key) return { type: "failed", error: "没有收到令牌。请在输入框里粘贴 sk-…;或使用「浏览器登录 QuWork」。" } + const checked = await checkKey(key) + if (!checked.ok) return { type: "failed", error: checked.error } + return { type: "success", key, metadata: { source: "pasted" } } + }, + }, + ], + async loader(getAuth) { + const auth = await getAuth() + if (!auth) return {} + const key = auth.type === "api" ? auth.key : auth.access + if (!key) return {} + return { + baseURL: LLM_BASE, + async fetch(input, init) { + const headers = new Headers(init?.headers) + headers.set("authorization", `Bearer ${key}`) + headers.set("x-qurwork-env", "prod") + headers.set("x-qurwork-version", quworkVersion()) + return fetch(input, { ...init, headers }) + }, + } + }, + async usage(getAuth) { + const auth = await getAuth() + if (!auth) return { error: "QuWork 未登录", windows: [] } + try { + const accessToken = auth?.metadata?.accessToken || (await findAccessToken()) + if (!accessToken) return { error: "没有 QuWork 账号令牌;用「浏览器登录 QuWork」重新登录后就能显示积分。", windows: [] } + const points = await readPoints(accessToken) + if (!points) return { error: "QuWork 积分接口没有返回可用数据。", windows: [] } + writeBalanceCache(points) + const suffix = points.limited > 0 ? `(限时 ${points.limited} + 永久 ${points.permanent})` : "" + return { + plan: points.plan, + balance: `${pointsText(points)}${suffix}`, + windows: [], + } + } catch (error) { + if (error?.signIn === "expired") { + return { error: error.message, signIn: "expired", windows: [] } + } + return { error: `读 QuWork 余额失败:${error instanceof Error ? error.message : String(error)}`, windows: [] } + } + }, + }, + + provider: { + id: PROVIDER, + async models(provider, { auth } = {}) { + try { + const accessToken = auth?.metadata?.accessToken || (await findAccessToken()) + const points = await readPoints(accessToken) + if (points) writeBalanceCache(points) + } catch (error) { + if (error?.signIn === "expired") throw error + // Balance display is best-effort. + } + return provider.models + }, + }, +}) + +export const _internal = { + MODELS, + PLUGIN_DIR, + startBrowserLogin, + readPoints, + writeBalanceCache, + deviceIdentifier, + quworkVersion, +} diff --git a/packages/quwork/opencode.mjs b/packages/quwork/opencode.mjs new file mode 100644 index 000000000..5159b39e4 --- /dev/null +++ b/packages/quwork/opencode.mjs @@ -0,0 +1,3 @@ +// The package's OpenCode 1.x plugin: magpie's host and OpenCode 1.x take every +// function export as a plugin. OpenCode 2.x loads opencode2.mjs, which runs this. +export { QuWorkProvider } from "./index.mjs" diff --git a/packages/quwork/opencode2.mjs b/packages/quwork/opencode2.mjs new file mode 100644 index 000000000..b9393085e --- /dev/null +++ b/packages/quwork/opencode2.mjs @@ -0,0 +1,620 @@ +// The OpenCode 2.x face of a package whose plugins are written for +// OpenCode 1.x (and magpie's plugin host). +// +// OpenCode 2.x loads a package's `exports["."]` and wants its default to be +// {id, setup(ctx)}; it has no fallback for a 1.x plugin's named functions +// (plugins#657). This file is that default. It runs each 1.x plugin the +// package's opencode.mjs exports and hands 2.x what the plugin's hooks say: +// +// auth.methods → the integration's sign-in methods +// config() → the provider, its package, base URL and models +// provider.models → the signed-in account's own model list +// auth.loader → each request's base URL, key, headers and fetch +// +// What 2.x has no place for is left out: chat.headers and chat.params +// (2.x's sdk hook doesn't carry the session), magpie's usage and checkin, +// tools and events. +// +// scripts/opencode2.mjs is the one copy that is edited. Every package that +// has it carries the same bytes as packages//opencode2.mjs, and +// scripts/check.mjs fails when a copy differs. + +import { readFileSync } from "node:fs" +import * as v1 from "./opencode.mjs" + +const pkg = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8")) + +// The key the SDK is made with: the account's own goes on each request in +// its place (see wrapFetch), so a key read when the SDK was made can't go +// out after the account changed. +const PLACEHOLDER = "opencode2-v1-key" + +// The SDK package a 1.x npm name runs as on 2.x. A version keeps 2.x from +// swapping @ai-sdk/* for its native providers, which never call the sdk +// hook below; openai-compatible's is the one 2.x ships, the others are AI +// SDK v6's dist-tag, the line 2.x's bridge runs. +export function packageOf(npm) { + const name = npm || "@ai-sdk/openai-compatible" + if (name === "@ai-sdk/openai-compatible") return "aisdk:@ai-sdk/openai-compatible@2.0.41" + if (/^@ai-sdk\/[^/@]+$/.test(name)) return `aisdk:${name}@ai-v6` + return `aisdk:${name}` +} + +// The plugins a 1.x module exports, as magpie's host and OpenCode 1.x read +// them: a default {server} is the one plugin, else every function export +// and every {server} object. +export function pluginsOf(mod) { + const d = mod?.default + if (d && typeof d === "object" && ("server" in d || "id" in d || "tui" in d)) + return typeof d.server === "function" ? [d.server] : [] + const out = [] + for (const value of Object.values(mod ?? {})) { + const fn = typeof value === "function" ? value : value && typeof value === "object" && typeof value.server === "function" ? value.server : null + if (fn && !out.includes(fn)) out.push(fn) + } + return out +} + +const int = (n, fallback = 0) => { + const v = Math.trunc(Number(n)) + return Number.isFinite(v) && v >= 0 ? v : fallback +} +const money = (n) => (Number.isFinite(Number(n)) && Number(n) >= 0 ? Number(n) : 0) +const record = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : {}) +const json = (v) => { + try { + return JSON.parse(JSON.stringify(v ?? null)) + } catch { + return null + } +} +const strings = (v) => Object.fromEntries(Object.entries(record(v)).filter(([, s]) => typeof s === "string")) +const nonEmpty = (o) => (Object.keys(o).length ? o : undefined) + +// connKey names a connection the way 2.x does. +const connKey = (c) => (!c ? "" : c.type === "credential" ? `credential:${c.id}` : `env:${c.name}`) + +// ---- sign-in ------------------------------------------------------------ + +// fields is a 1.x method's prompts as a 2.x form. +export function fieldsOf(prompts) { + const out = [] + for (const p of prompts ?? []) { + if (!p?.key) continue + const f = { key: String(p.key), type: "string", title: String(p.message ?? p.key) } + if (p.placeholder) f.placeholder = String(p.placeholder) + if (p.type === "select" && Array.isArray(p.options)) + f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) + // a prompt shown only when another answer says so can't be required, and + // neither can one whose own validate() accepts an empty answer (the + // browser sign-in's optional API key) + if (!p.condition && p.required !== false) f.required = true + out.push(f) + } + return out.length ? out : undefined +} + +// v1Saved is what a 1.x sign-in's success is saved as, the way 1.x writes +// auth.json: the result without its type and provider. +function v1Saved(r) { + const { type: _t, provider: _p, ...rest } = r + if ("key" in r) return { type: "api", ...rest } + return { type: "oauth", ...rest } +} + +// credentialOf is a 1.x sign-in's success as a 2.x credential: OAuth for +// both kinds, the 1.x auth kept whole in its metadata. No refresh is +// registered, so 2.x hands the credential over as it is and the plugin's +// own loader renews it, as it does on 1.x. +export function credentialOf(methodID, r) { + if (!r || r.type !== "success") throw new Error(r?.error || r?.message || "the sign-in failed") + const saved = json(v1Saved(r)) + if (saved.type === "api") + return { type: "oauth", methodID, access: String(saved.key ?? ""), refresh: "", expires: 0, metadata: { v1: saved } } + return { + type: "oauth", + methodID, + access: String(saved.access ?? ""), + refresh: String(saved.refresh ?? ""), + expires: int(saved.expires), + metadata: { v1: saved }, + } +} + +// authOfValue is the 1.x auth a 2.x credential stands for. +export function authOfValue(value) { + if (!value) return null + if (value.type === "oauth") { + const v1 = record(value.metadata).v1 + if (v1 && typeof v1 === "object") return v1 + return { type: "oauth", access: value.access, refresh: value.refresh, expires: value.expires } + } + if (value.type === "key") { + const meta = value.metadata && Object.keys(value.metadata).length ? { metadata: value.metadata } : {} + return { type: "api", key: value.key, ...meta } + } + return null +} + +const fingerprint = (a) => JSON.stringify([a?.type, a?.access ?? a?.key ?? "", a?.refresh ?? ""]) + +// ---- models ------------------------------------------------------------- + +const MODALITIES = ["text", "audio", "image", "video", "pdf"] + +// internalOf is a config model as 1.x hands it to provider.models: what +// fromModelsDevModel makes of it, with the config's own variants. +export function internalOf(providerID, conf, key, m) { + const mods = record(m.modalities) + const has = (list, k) => Array.isArray(list) && list.includes(k) + const cost = record(m.cost) + return { + ...m, + id: key, + providerID, + name: m.name ?? key, + api: { id: m.id ?? key, url: m.provider?.api ?? conf.api ?? conf.options?.baseURL ?? "", npm: m.provider?.npm ?? conf.npm ?? "@ai-sdk/openai-compatible" }, + status: m.status ?? "active", + headers: m.headers ?? {}, + options: m.options ?? {}, + cost: { input: money(cost.input), output: money(cost.output), cache: { read: money(cost.cache_read), write: money(cost.cache_write) } }, + limit: { context: int(m.limit?.context), input: m.limit?.input, output: int(m.limit?.output) }, + capabilities: { + temperature: m.temperature ?? false, + reasoning: m.reasoning ?? false, + attachment: m.attachment ?? false, + toolcall: m.tool_call ?? true, + input: Object.fromEntries(MODALITIES.map((k) => [k, mods.input ? has(mods.input, k) : k === "text"])), + output: Object.fromEntries(MODALITIES.map((k) => [k, mods.output ? has(mods.output, k) : k === "text"])), + interleaved: m.interleaved ?? false, + }, + release_date: m.release_date ?? "", + variants: record(m.variants), + } +} + +// modelOf is a 1.x model, in config or internal form, as a 2.x Model.Info. +export function modelOf(providerID, provider, key, m) { + const caps = record(m.capabilities) + const listFrom = (obj, list) => { + if (obj && typeof obj === "object") return MODALITIES.filter((k) => obj[k]) + if (Array.isArray(list)) return list.map(String) + return ["text"] + } + const input = listFrom(caps.input, m.modalities?.input) + const output = listFrom(caps.output, m.modalities?.output) + const c = record(m.cost) + const cache = record(c.cache) + const npm = m.api?.npm ?? m.provider?.npm + const url = m.api?.url ?? m.provider?.api + const settings = { ...record(json(m.options)) } + if (url && url !== provider.baseURL) settings.baseURL = url + const variants = Object.entries(record(m.variants)) + .filter(([, v]) => !record(v).disabled) + .map(([id, v]) => { + const { disabled: _d, ...rest } = record(json(v)) + return nonEmpty(rest) ? { id, settings: rest } : { id } + }) + const status = ["alpha", "beta", "deprecated", "active"].includes(m.status) ? m.status : "active" + const out = { + id: key, + modelID: String(m.api?.id ?? m.id ?? key), + providerID, + name: String(m.name ?? key), + capabilities: { + tools: caps.toolcall ?? m.tool_call ?? true, + input: input.length ? input : ["text"], + output: output.length ? output : ["text"], + ...(typeof (caps.temperature ?? m.temperature) === "boolean" ? { temperature: caps.temperature ?? m.temperature } : {}), + }, + variants, + time: { released: Date.parse(m.release_date ?? "") || 0 }, + cost: [{ input: money(c.input), output: money(c.output), cache: { read: money(cache.read ?? c.cache_read), write: money(cache.write ?? c.cache_write) } }], + status, + enabled: true, + limit: { context: int(m.limit?.context, 128000) || 128000, output: int(m.limit?.output, 8192) || 8192 }, + } + if (m.limit?.input) out.limit.input = int(m.limit.input) + if (npm && npm !== provider.npm) out.package = packageOf(npm) + if (nonEmpty(settings)) out.settings = settings + const headers = strings(m.headers) + if (nonEmpty(headers)) out.headers = headers + return out +} + +// ---- requests ----------------------------------------------------------- + +const urlOf = (input) => (typeof input === "string" ? input : input instanceof URL ? input.href : input?.url ?? String(input)) + +// wrapFetch sends a request the SDK made from the provider's settings the +// way 1.x would have sent it with the loader's options: the loader's base +// URL in place of the configured one, the account's key in place of the +// placeholder, the loader's headers added, through the loader's fetch. +export function wrapFetch(next, base, options) { + return async (input, init = {}) => { + const o = await options() + let url = urlOf(input) + const from = String(base ?? "").replace(/\/+$/, "") + const to = o.baseURL ? String(o.baseURL).replace(/\/+$/, "") : "" + if (from && to && from !== to && url.startsWith(from)) url = to + url.slice(from.length) + const req = input instanceof Request ? input : null + const headers = new Headers(init.headers ?? req?.headers ?? undefined) + for (const [k, v] of [...headers.entries()]) { + if (!v.includes(PLACEHOLDER)) continue + if (o.key) headers.set(k, v.replaceAll(PLACEHOLDER, o.key)) + else headers.delete(k) + } + for (const [k, v] of Object.entries(strings(o.headers))) headers.set(k, v) + const send = typeof o.fetch === "function" ? o.fetch : next ?? fetch + if (req && init.body === undefined) { + const body = req.method === "GET" || req.method === "HEAD" ? undefined : await req.text() + return send(url, { method: req.method, headers, body, signal: init.signal ?? req.signal }) + } + return send(url, { ...init, headers }) + } +} + +// ---- one plugin --------------------------------------------------------- + +async function setupPlugin(ctx, fn, live) { + const directory = ctx?.location?.directory ?? process.cwd() + // the active account each provider was last read for, and the renewed + // auth a plugin saved for it (2.x has no way for a plugin to write a + // credential back, so it is kept in the plugin's storage, under the + // credential it renews and the token it was renewed from) + const current = new Map() + const saved = new Map() + const signingIn = new Map() + const storeKey = (id, key) => `v1auth/${id}/${key}` + + const client = { + auth: { + async set(arg) { + const id = arg?.path?.id + const body = json(arg?.body) + const cur = id && current.get(id) + // a sign-in's own saves belong to the credential it is about to + // make, not the one that was active when it started + if (!cur || !body || signingIn.get(id) > 0) return { data: true } + const entry = { fp: cur.fp, auth: body } + saved.set(storeKey(id, cur.key), entry) + await Promise.resolve() + .then(() => ctx.storage?.set?.(storeKey(id, cur.key), entry)) + .catch(() => {}) + return { data: true } + }, + async get() { + return { data: undefined } + }, + }, + app: { log: async () => ({ data: true }) }, + } + + const hooks = (await fn({ client, directory, worktree: directory, project: {}, serverUrl: undefined, $: undefined }, {})) ?? {} + const cfg = { provider: {} } + try { + await hooks.config?.(cfg) + } catch {} + const auth = hooks.auth + const authID = auth?.provider ? String(auth.provider) : undefined + const providers = record(cfg.provider) + + // getAuth reads the active account: the credential 2.x holds, or what the + // plugin last saved renewing it. + const getAuth = async (id) => { + const connection = await ctx.integration.connection.active(id).catch(() => undefined) + if (!connection) { + current.delete(id) + return undefined + } + const value = await ctx.integration.connection.resolve(connection).catch(() => undefined) + const base = authOfValue(value) + if (!base) { + current.delete(id) + return undefined + } + const key = connKey(connection) + const fp = fingerprint(base) + // ours: a credential one of this plugin's own sign-ins made + const ours = value?.type === "oauth" && !!record(value.metadata).v1 + current.set(id, { key, fp, ours }) + const sk = storeKey(id, key) + let entry = saved.get(sk) + if (!entry) { + entry = await Promise.resolve() + .then(() => ctx.storage?.get?.(sk)) + .catch(() => undefined) + if (entry) saved.set(sk, entry) + } + return entry && entry.fp === fp && entry.auth ? entry.auth : base + } + + // the sign-in methods + if (authID && Array.isArray(auth.methods) && auth.methods.length) { + const label = (c) => { + const a = authOfValue(c) + const name = a?.name ?? a?.email ?? a?.metadata?.name ?? a?.metadata?.email ?? a?.account + return typeof name === "string" && name ? name : undefined + } + const begin = () => signingIn.set(authID, (signingIn.get(authID) ?? 0) + 1) + const end = () => signingIn.set(authID, Math.max(0, (signingIn.get(authID) ?? 1) - 1)) + const title = record(providers[authID]).name + // 2.x runs a transform again on every reload, from nothing + await ctx.integration.transform((editor) => { + let keyed = false + // the integration 2.x makes for an id it doesn't know is named by the + // id; the provider's own name reads better in the sign-in list + if (typeof title === "string" && title) + try { + editor.update?.(authID, (i) => { + if (i && (!i.name || i.name === authID)) i.name = title + }) + } catch {} + auth.methods.forEach((m, i) => { + if (!m) return + const methodID = `v1-${i}` + const form = fieldsOf(m.prompts) + if (m.type === "api" && typeof m.authorize !== "function") { + if (keyed) return + keyed = true + editor.method.update({ integrationID: authID, method: { type: "key", label: String(m.label ?? "API key"), ...(form ? { form } : {}) } }) + return + } + if (typeof m.authorize !== "function") return + editor.method.update({ + integrationID: authID, + method: { id: methodID, type: "oauth", label: String(m.label ?? authID), ...(form ? { form } : {}) }, + async authorize(answer) { + begin() + let ended = false + const done = () => { + if (!ended) end() + ended = true + } + try { + const inputs = Object.fromEntries(Object.entries(record(answer)).map(([k, v]) => [k, String(v)])) + const r = await m.authorize(inputs) + if (m.type === "api") { + done() + return { url: "", instructions: "", mode: "auto", callback: Promise.resolve().then(() => credentialOf(methodID, r)) } + } + if (r?.method === "code") + return { + url: String(r.url ?? ""), + instructions: String(r.instructions ?? ""), + mode: "code", + callback: async (code) => { + try { + return credentialOf(methodID, await r.callback(code)) + } finally { + done() + } + }, + } + const callback = Promise.resolve() + .then(() => r.callback()) + .then((res) => credentialOf(methodID, res)) + .finally(done) + callback.catch(() => {}) + return { url: String(r?.url ?? ""), instructions: String(r?.instructions ?? ""), mode: "auto", callback } + } catch (e) { + done() + throw e + } + }, + label, + }) + }) + }) + } + + // the loader's options for the account signed in now, read again when + // the account changes + let loaded = null + const loaderOptions = async (id) => { + if (id !== authID || typeof auth?.loader !== "function") { + const a = authID === id ? await getAuth(id) : undefined + return { key: a?.type === "api" ? a.key : undefined } + } + const a = await getAuth(id) + if (!a) return {} + const fp = current.get(id)?.key + "\0" + fingerprint(a) + if (loaded?.fp !== fp) { + const p = Promise.resolve() + .then(() => auth.loader(() => getAuth(id), providerOf(id))) + .then((o) => record(o)) + loaded = { fp, p } + p.catch(() => { + if (loaded?.fp === fp) loaded = null + }) + } + const o = await loaded.p + const key = typeof o.apiKey === "string" && o.apiKey ? o.apiKey : a.type === "api" ? a.key : undefined + return { baseURL: o.baseURL, key, headers: o.headers, fetch: o.fetch } + } + + // the providers, with the list the account's own read last gave each + const source = new Map() + // providerOf is a provider as 1.x hands it to provider.models and + // auth.loader + const providerOf = (id) => { + const conf = record(providers[id]) + const models = Object.fromEntries(Object.entries(record(conf.models)).map(([k, m]) => [k, internalOf(id, conf, k, record(m))])) + return { id, name: conf.name ?? id, source: "config", env: [], options: record(conf.options), models } + } + const listed = new Set() + for (const [id, conf0] of Object.entries(providers)) { + const conf = record(conf0) + // a provider entry that only names the sign-in (no package, no models) + // is not a provider of models + if (!conf.npm && !Object.keys(record(conf.models)).length) continue + const options = record(conf.options) + const { apiKey: _k, baseURL: _b, fetch: _f, headers: optHeaders, ...rest } = options + // with no base URL the config leaves it to the loader: a name that + // can't resolve stands in for it, and each request swaps in the + // loader's (wrapFetch) + const baseURL = options.baseURL ?? conf.api ?? `https://${id.replace(/[^a-z0-9-]/gi, "-")}.opencode2-v1.invalid` + const npm = conf.npm ?? "@ai-sdk/openai-compatible" + const info = { + id, + ...(id === authID ? { integrationID: id } : {}), + name: String(conf.name ?? id), + activation: "auto", + package: packageOf(npm), + settings: { ...record(json(rest)), ...(baseURL ? { baseURL: String(baseURL) } : {}) }, + } + const headers = { ...strings(conf.headers), ...strings(optHeaders) } + if (nonEmpty(headers)) info.headers = headers + const prov = { baseURL, npm } + const fromConfig = () => + Object.entries(record(conf.models)).map(([key, m]) => modelOf(id, prov, key, internalOf(id, conf, key, record(m)))) + listed.add(id) + await ctx.provider.transform((editor) => { + const s = source.get(id) + editor.add({ info, models: s?.models ?? fromConfig(), sourceConnection: s?.connection }) + }) + source.set(id, { conf, prov, models: null, connection: undefined }) + } + + // each request: the placeholder key, and the fetch that swaps in the + // account's. A provider the package doesn't list (one 2.x has built in + // that the plugin only signs in to) is left to 2.x unless the plugin's + // loader serves it and one of the plugin's own sign-ins is active. + const own = authID && !listed.has(authID) && typeof auth?.loader === "function" ? [authID] : [] + for (const id of new Set([...listed, ...own])) { + const base = source.get(id)?.prov.baseURL + await ctx.aisdk.hook( + "sdk", + async (evt) => { + const opts = evt.options + if (!opts || opts.__opencode2) return + if (!listed.has(id)) { + await getAuth(id) + if (!current.get(id)?.ours) return + } + opts.__opencode2 = true + opts.apiKey = PLACEHOLDER + opts.fetch = wrapFetch(opts.fetch, opts.baseURL ?? base, () => loaderOptions(id)) + }, + { providerID: id }, + ) + } + + // refresh reads the account's own list after a sign-in or a switch + const listID = hooks.provider?.id ? String(hooks.provider.id) : undefined + let refreshing = null + let again = false + // the account the list was last read for: a credential.updated that + // leaves it as it was reads nothing again + let readFor = null + const stateOf = async () => { + const c = await ctx.integration.connection.active(authID).catch(() => undefined) + const a = c ? await getAuth(authID) : undefined + return connKey(c) + "\0" + (a ? fingerprint(a) : "") + } + const refresh = () => { + if (refreshing) { + again = true + return refreshing + } + refreshing = (async () => { + try { + if (!authID || !source.has(authID)) return + const s = source.get(authID) + const connection = await ctx.integration.connection.active(authID).catch(() => undefined) + const a = connection ? await getAuth(authID) : undefined + readFor = connKey(connection) + "\0" + (a ? fingerprint(a) : "") + if (!a || listID !== authID || typeof hooks.provider?.models !== "function") { + if (s.connection || s.models) { + s.connection = undefined + s.models = null + await ctx.provider.reload() + } + return + } + const provider = providerOf(authID) + let got + try { + got = await hooks.provider.models(provider, { auth: a }) + } catch { + got = null + } + if (connKey(await ctx.integration.connection.active(authID).catch(() => undefined)) !== connKey(connection)) { + again = true + return + } + s.connection = connection + s.models = got && typeof got === "object" ? Object.entries(got).map(([k, m]) => modelOf(authID, s.prov, k, record(m))) : null + await ctx.provider.reload() + await ctx.model?.reload?.() + } finally { + refreshing = null + if (again && live.on) { + again = false + void refresh() + } + } + })() + return refreshing + } + + if (authID && ctx.event?.subscribe) + void (async () => { + try { + // a switch names the integration; an update (a sign-in, a removal) + // names nothing, so it reads again only when this account changed + const types = ["credential.switched", "credential.updated"] + for await (const event of ctx.event.subscribe({ types })) { + if (!live.on) return + if (event?.type === "credential.switched" && event?.data?.integrationID === authID) { + loaded = null + await refresh() + } else if (event?.type === "credential.updated" && (await stateOf()) !== readFor) { + await refresh() + } + } + } catch {} + })() + // A plugin still reading its list in the background when the first read + // returned (agy-cli: `agy models` and a session probe take seconds, and + // the first read gets its static list) says so through + // provider.warming(): the list is read once more when that ends, once, + // and no later than a minute on. + const warmed = async () => { + let w + try { + w = typeof hooks.provider?.warming === "function" ? hooks.provider.warming() : null + } catch { + return + } + if (!w || typeof w.then !== "function") return + let timer + await Promise.race([ + Promise.resolve(w).catch(() => {}), + new Promise((r) => { + timer = setTimeout(r, 60_000) + timer.unref?.() + }), + ]) + clearTimeout(timer) + if (live.on) await refresh() + } + void refresh().then(warmed, () => {}) +} + +export async function setup(ctx, mod = v1) { + const live = { on: true } + for (const fn of pluginsOf(mod)) { + try { + await setupPlugin(ctx, fn, live) + } catch (e) { + // one plugin failing to start leaves the package's others working + console.error(`${pkg.name}: ${e?.message ?? e}`) + } + } + return () => { + live.on = false + } +} + +export default { id: pkg.name, setup: (ctx) => setup(ctx) } diff --git a/packages/quwork/package.json b/packages/quwork/package.json new file mode 100644 index 000000000..0a02aa529 --- /dev/null +++ b/packages/quwork/package.json @@ -0,0 +1,54 @@ +{ + "name": "@magpie-community/opencode-quwork-auth", + "version": "0.1.0", + "description": "Unofficial QuWork (Clawork) provider for OpenCode and magpie: browser phone+SMS sign-in with Aliyun captcha, or the desktop client's saved session, with live models, points balance and a setup page", + "type": "module", + "main": "./opencode.mjs", + "exports": { + ".": "./opencode2.mjs" + }, + "files": [ + "index.mjs", + "opencode.mjs", + "opencode2.mjs", + "README.md", + "LICENSE", + "page" + ], + "keywords": [ + "opencode", + "opencode-plugin", + "magpie", + "quwork", + "qurwork", + "clawork" + ], + "license": "MIT", + "scripts": { + "test": "node --test" + }, + "magpie": { + "name": "QuWork", + "summary": { + "en": "Unofficial QuWork (Clawork) access: browser sign-in with phone and SMS (Aliyun captcha), or the desktop client's saved session; live models, points balance and a setup page.", + "zh": "非官方 QuWork(Clawork)接入:浏览器手机验证码登录(阿里云验证码),或复用桌面端登录态;动态模型、积分余额与接入页。" + }, + "icon": "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA2NCA2NCI+PHJlY3Qgd2lkdGg9IjY0IiBoZWlnaHQ9IjY0IiByeD0iMTQiIGZpbGw9IiMyZjZmZWQiLz48dGV4dCB4PSIzMiIgeT0iNDUiIGZvbnQtZmFtaWx5PSJBcmlhbCxIZWx2ZXRpY2Esc2Fucy1zZXJpZiIgZm9udC1zaXplPSIzOCIgZm9udC13ZWlnaHQ9IjcwMCIgdGV4dC1hbmNob3I9Im1pZGRsZSIgZmlsbD0iI2ZmZmZmZiI+UTwvdGV4dD48L3N2Zz4=", + "page": { + "title": "QuWork 接入", + "file": "page/index.html", + "titles": { + "zh": "QuWork 接入", + "en": "QuWork setup" + } + }, + "permissions": [ + "providers:list" + ] + }, + "repository": { + "type": "git", + "url": "git+https://github.com/magpie-community/plugins.git", + "directory": "packages/quwork" + } +} diff --git a/packages/quwork/page/app.js b/packages/quwork/page/app.js new file mode 100644 index 000000000..6463f0533 --- /dev/null +++ b/packages/quwork/page/app.js @@ -0,0 +1,36 @@ +;(async () => { + await magpie.ready + + const status = document.getElementById("status") + const balance = document.getElementById("balance") + const balanceMeta = document.getElementById("balance-meta") + + if (window.__QUWORK_BALANCE__) { + balance.textContent = window.__QUWORK_BALANCE__ + const detail = window.__QUWORK_BALANCE_DETAIL__ + if (detail?.updatedAt) { + const when = new Date(detail.updatedAt) + const parts = [`更新于 ${when.toLocaleString()}`] + if (detail.limited > 0) parts.push(`限时 ${detail.limited}`, `永久 ${detail.permanent}`) + balanceMeta.textContent = parts.join(" · ") + } + } else { + balance.textContent = "—" + } + + try { + const providers = await magpie.read("providers:list") + const list = Array.isArray(providers) ? providers : [] + const quwork = list.find((provider) => provider?.id === "quwork") + if (quwork) { + status.textContent = `已找到供应商:${quwork.name || "QuWork"}。现在到 Providers 页面点登录即可。` + status.className = "ok" + } else { + status.textContent = "供应商列表里还没有 QuWork:确认插件是 On,必要时重启 magpie。" + status.className = "missing" + } + } catch (error) { + status.textContent = `读取供应商列表失败:${error instanceof Error ? error.message : String(error)}` + status.className = "missing" + } +})() diff --git a/packages/quwork/page/balance.js b/packages/quwork/page/balance.js new file mode 100644 index 000000000..0ac2735e6 --- /dev/null +++ b/packages/quwork/page/balance.js @@ -0,0 +1,3 @@ +window.__QUWORK_BALANCE__ = "" +window.__QUWORK_BALANCE_DETAIL__ = null + diff --git a/packages/quwork/page/index.html b/packages/quwork/page/index.html new file mode 100644 index 000000000..1a01b8ea9 --- /dev/null +++ b/packages/quwork/page/index.html @@ -0,0 +1,50 @@ + + + + + +QuWork 接入 + + + + + + +
+

QuWork 接入

+

把 QuWork 的积分模型接进 magpie。支持浏览器手机验证码登录,不需要 QuWork 桌面客户端。

+ +
+

积分余额

+

—

+

登录后打开一次 magpie 的 Quota(额度)页,这里会显示最新积分。

+
+ +
+

供应商状态

+

正在读取…

+
+ +
+

登录步骤

+
    +
  1. 打开 magpie 的 Providers(供应商) 页面。
  2. +
  3. 找到 QuWork,点登录按钮。
  4. +
  5. 选 「浏览器登录 QuWork(手机验证码,无需客户端)」。
  6. +
  7. 在打开的页面里输入手机号,完成阿里云验证码,填入短信验证码。
  8. +
  9. 页面提示成功后关闭它,magpie 会自动完成登录。
  10. +
+

如果供应商列表里还没有 QuWork,先到 Plugins(插件)→ Installed(已安装) 确认本插件是 On;必要时重启 magpie。

+
+ +
+

没有浏览器登录条件?

+

登录菜单里还有两种方式:

+
    +
  • 读取 QuWork 本机登录态:本机装过 QuWork 并登录过时可用。
  • +
  • 粘贴 QuWork 令牌:直接粘贴 sk- 开头的令牌。
  • +
+
+
+ + diff --git a/packages/quwork/page/style.css b/packages/quwork/page/style.css new file mode 100644 index 000000000..4f4d9a797 --- /dev/null +++ b/packages/quwork/page/style.css @@ -0,0 +1,62 @@ +body { + margin: 0; + padding: 28px 32px 48px; +} + +main { + max-width: 680px; +} + +h1 { + margin: 0 0 6px; + font-size: 24px; +} + +.lead { + margin: 0 0 22px; + color: var(--magpie-fg-muted, #6b7280); + line-height: 1.7; +} + +.card { + border: 1px solid var(--magpie-border, rgba(127, 127, 127, 0.25)); + border-radius: 14px; + padding: 18px 20px; + margin-bottom: 16px; +} + +h2 { + margin: 0 0 10px; + font-size: 15px; +} + +ol, ul { + margin: 0; + padding-left: 22px; + line-height: 1.9; +} + +.hint { + margin: 12px 0 0; + color: var(--magpie-fg-muted, #6b7280); + font-size: 13px; + line-height: 1.7; +} + +code { + font-family: ui-monospace, SFMono-Regular, Consolas, monospace; + font-size: 0.92em; + padding: 1px 5px; + border-radius: 5px; + background: var(--magpie-code-bg, rgba(127, 127, 127, 0.15)); +} + +.balance { + margin: 0; + font-size: 30px; + font-weight: 700; + letter-spacing: -0.02em; +} + +#status.ok { color: #16a34a; } +#status.missing { color: #dc2626; } diff --git a/packages/quwork/test.mjs b/packages/quwork/test.mjs new file mode 100644 index 000000000..675a0e942 --- /dev/null +++ b/packages/quwork/test.mjs @@ -0,0 +1,38 @@ +import test from "node:test" +import assert from "node:assert/strict" +import { QuWorkProvider } from "./index.mjs" + +test("config declares the QuWork provider and models", async () => { + const hooks = await QuWorkProvider({}) + const cfg = { provider: {} } + await hooks.config(cfg) + assert.equal(cfg.provider.quwork.npm, "@ai-sdk/openai-compatible") + assert.equal(cfg.provider.quwork.api, "https://llm.quwork.cn/v1") + assert.ok(Object.keys(cfg.provider.quwork.models).length >= 10) +}) + +test("three sign-in methods, a loader and usage", async () => { + const hooks = await QuWorkProvider({}) + assert.equal(hooks.auth.provider, "quwork") + assert.equal(hooks.auth.methods.length, 3) + assert.equal(hooks.auth.methods[0].type, "oauth") + assert.ok(hooks.auth.methods[0].label.includes("浏览器登录")) + assert.equal(typeof hooks.auth.methods[0].authorize, "function") + assert.equal(typeof hooks.auth.loader, "function") + assert.equal(typeof hooks.auth.usage, "function") +}) + +test("the browser login page is served under a secret path", async () => { + const hooks = await QuWorkProvider({}) + const desc = await hooks.auth.methods[0].authorize(undefined, {}) + try { + assert.match(desc.url, /^http:\/\/127\.0\.0\.1:\d+\/[0-9a-f-]{36}\/$/) + const res = await fetch(desc.url) + assert.equal(res.status, 200) + const html = await res.text() + assert.ok(html.includes("QuWork 登录")) + assert.ok(html.includes("api/send-code")) + } finally { + desc.close?.() + } +}) diff --git a/registry.json b/registry.json index 8237e459e..6a3850344 100644 --- a/registry.json +++ b/registry.json @@ -304,6 +304,8 @@ "summary": { "en": "A guide page for DaFeiYu, a desktop pet that lights a bulb per request and shows quota percentages and API balances. The pet is a separate Windows/macOS app you download yourself; this page does not install or start it. Artwork from PC2005-cloud/dsh-pet, non-commercial use only.", "zh": "蓝色大肥鱼桌宠的使用指南页:几个请求亮几盏灯,订阅显示额度百分比,API 钱包显示余额。桌宠是需要另外下载的 Windows/macOS 独立 App,本页不会安装或启动它。角色素材来自 PC2005-cloud/dsh-pet,仅限非商用。" } }, { "package": "@magpie-community/agent-pine", "name": "Pine", "kind": "agent", "community": true, "icon": "https://raw.githubusercontent.com/pmndre/pine/next/docs/images/logo-light.svg", - "summary": { "en": "Pine (pmndre/pine, the event-driven agent harness on pi's SDK) on magpie's Agents page: pick one of magpie's models and magpie writes its gateway and catalog into ~/.pine/models.json and the model into pine.json, so new conversations start on it. Restart Pine after a change; unofficial.", "zh": "把 Pine(pmndre/pine,跑在 pi SDK 上的事件驱动 Agent 框架)加到 magpie 的 Agent 页:选一个 magpie 的模型,magpie 把网关和模型目录写进 ~/.pine/models.json、把起始模型写进 pine.json,新对话就用它。换完模型要重启 Pine;非官方适配。" } } + "summary": { "en": "Pine (pmndre/pine, the event-driven agent harness on pi's SDK) on magpie's Agents page: pick one of magpie's models and magpie writes its gateway and catalog into ~/.pine/models.json and the model into pine.json, so new conversations start on it. Restart Pine after a change; unofficial.", "zh": "把 Pine(pmndre/pine,跑在 pi SDK 上的事件驱动 Agent 框架)加到 magpie 的 Agent 页:选一个 magpie 的模型,magpie 把网关和模型目录写进 ~/.pine/models.json、把起始模型写进 pine.json,新对话就用它。换完模型要重启 Pine;非官方适配。" } }, + { "package": "@magpie-community/opencode-quwork-auth", "name": "QuWork", "providers": ["quwork"], "community": true, + "summary": { "en": "Unofficial QuWork (Clawork) access: browser sign-in with phone and SMS (Aliyun captcha), or the desktop client's saved session; live models, points balance and a setup page.", "zh": "非官方 QuWork(Clawork)接入:浏览器手机验证码登录(阿里云验证码),或复用桌面端登录态;动态模型、积分余额与接入页。" } } ] } From 0b360ed4edea3d82b7fe4c75fbc3c8ee7188e08e Mon Sep 17 00:00:00 2001 From: kshu06537-bot Date: Wed, 18 Nov 2026 19:09:39 +0800 Subject: [PATCH 2/7] quwork 0.1.1: harden sign-in and keep points in Magpie Quota --- packages/quwork/README.md | 96 +--- packages/quwork/index.mjs | 764 +++++++++++++------------------- packages/quwork/index.test.mjs | 179 ++++++++ packages/quwork/package.json | 12 +- packages/quwork/page/app.js | 48 +- packages/quwork/page/balance.js | 3 - packages/quwork/page/index.html | 26 +- packages/quwork/page/style.css | 7 - packages/quwork/test.mjs | 38 -- registry.json | 2 +- 10 files changed, 540 insertions(+), 635 deletions(-) create mode 100644 packages/quwork/index.test.mjs delete mode 100644 packages/quwork/page/balance.js delete mode 100644 packages/quwork/test.mjs diff --git a/packages/quwork/README.md b/packages/quwork/README.md index 8fb680c62..f4c3db080 100644 --- a/packages/quwork/README.md +++ b/packages/quwork/README.md @@ -1,96 +1,30 @@ -# @magpie-community/opencode-quwork-auth +# QuWork for Magpie -**非官方** QuWork(Clawork,微服)接入:[magpie](https://usemagpie.ai/) 与 [OpenCode](https://opencode.ai/) 的模型供应商 `quwork`。支持浏览器手机验证码登录(不需要 QuWork 桌面客户端)、复用桌面端登录态,或粘贴 `sk-` 令牌;显示实时模型与积分余额。 +实验性社区供应商 `quwork`,支持在本机浏览器手动完成手机号、人机验证和短信验证码验证。登录无需安装 QuWork 桌面客户端。插件内置 10 个模型条目,实际可用模型由 QuWork 和账号权益决定。 -> Unofficial. QuWork publishes no developer API for other clients. This package uses the account and endpoints the QuWork desktop client uses; read the risk section before using or sharing it. +## 账号风险 -## 登录方式 +浏览器接入使用 QuWork 非公开客户端接口。尚未查到 QuWork 允许第三方客户端消耗个人账号积分的授权。官方协议第 2.3.2 条规定未明示授权的权利需另获书面许可,第 8.1 条限制逆向工程,第 8.2 条允许对违规行为暂停或终止服务。个人账号也存在风险,重要账号建议使用官方入口。阅读 [Clawork 软件许可及服务协议](https://llm.rrzu.com/claw-agreement)。 -登录菜单有三项,任选其一: +## 安装与使用 -1. **浏览器登录 QuWork(手机验证码,无需客户端)** —— magpie 在本机 `127.0.0.1` 启动一次性登录页(随机路径、仅本机可访问、10 分钟超时),你在页面里输入手机号、完成 QuWork 的阿里云验证码、填入短信验证码,插件用 QuWork 的 `/api/user/client/login` 换取账号令牌。登录成功后页面提示完成,magpie 自动接管。 -2. **读取 QuWork 本机登录态** —— 本机装过 QuWork 桌面端并登录过时,读取它的 `llm_token`(`sk-` 开头);不启动、不修改桌面端。Windows 读 `%APPDATA%\qurwork-desktop\qurwork-desktop.sqlite`(含 WAL),macOS 读对应的 Application Support 目录。 -3. **粘贴 QuWork 令牌** —— 直接粘贴 `sk-` 令牌;只够调用模型,读不到积分余额(余额接口要账号 access token)。 +在 Magpie 的「插件 → 添加插件」选择本地插件目录,或在社区仓库根目录运行 `magpie plugin add ./packages/quwork`。启用后,前往「供应商 → QuWork → 登录」并选择「浏览器登录 QuWork(实验性)」。本机页面提示短信验证通过后,回到 Magpie 确认登录状态。 -每个登录是一个 magpie 账号,可多账号故障切换。凭据保存在 magpie 的 `plugin-auth.json`(权限 600),不上传;插件不记录请求内容或令牌。 +已从 QuWork 获得第三方接入授权的用户可在登录菜单单独填写模型密钥。模型密钥的权限限于模型调用,查询积分需要账号授权。 -## 模型 - -供应商 id `quwork`,走 OpenAI Chat Completions 协议: - -`https://llm.quwork.cn/v1/chat/completions` - -内置 10 个常用模型(目录随 QuWork 配置变化时以插件声明为准): - -| model | context | output | 备注 | -| --- | --- | --- | --- | -| `deepseek-flash` | 1M | 384k | 识图,思考 off/low/high/max | -| `deepseek-v4-pro` | 1M | 384k | 思考 off/low/high/max | -| `qwen3.8-max` | 1M | 128k | | -| `qwen3.8-flash` | 1M | 128k | 识图 | -| `qwen3.7-plus` | 1M | 128k | 识图 | -| `glm-5.3-flash` | 1M | 128k | 识图 | -| `glm-5.2` | 1M | 128k | | -| `kimi-k2.7-code` | 1M | 128k | | -| `kimi-k2.6` | 1M | 256k | 识图 | -| `MiniMax-M2.5` | 1M | 32k | | - -在 agent 里用 `quwork/`。 - -## 积分余额 - -- 侧边栏 **「QuWork 接入」** 页顶部显示积分余额(登录后自动缓存最新值)。 -- magpie 的 **Quota(额度)** 页,或: +在 Magpie 的「额度(Quota)」页查看 QuWork 账号的积分总余额。上游提供限时或永久积分字段时会一并显示。查询失败会显示原因,余额为零只在上游确实返回零时显示。命令行也可查询: ```powershell magpie quota quwork -magpie quota quwork --json ``` -余额来自 `GET https://llm.rrzu.com/api/user/self` 的 `data.points_entitlement`,读取不计费;60 秒内复用缓存。401/403 会把账号标为需要重新登录。**浏览器登录**与**读取本机登录态**能读余额;**粘贴 `sk-` 令牌**不能,因为账号接口只认 access token。 - -## 上游与协议 - -- 模型:`https://llm.quwork.cn/v1`(OpenAI Chat Completions,`Authorization: Bearer `,另带 `X-QurWork-Env: prod`、`X-QurWork-Version`)。 -- 账号:`https://llm.rrzu.com`,登录 `/api/user/client/login`,短信 `/api/sendVerifyCode`(需阿里云验证码 `aliyun_captcha`),资料 `/api/user/self`。 -- 验证码 SDK:阿里云官方 `https://o.alicdn.com/captcha-frontend/aliyunCaptcha/AliyunCaptcha.js`,`region=cn`、`prefix=1hms8d`、`SceneId=10vzkucv`(与 QuWork 客户端一致)。 - -## 安全与隐私 - -- 登录页只监听 `127.0.0.1`,使用每次登录随机的 URL 路径;POST 检查 `Origin`,不匹配直接 403;页面禁止被嵌入(`X-Frame-Options: DENY`)、`Referrer-Policy: no-referrer`、`Cache-Control: no-store`。 -- 浏览器登录的设备标识保存在系统临时目录的 `magpie-quwork-device.json`(稳定设备 id,降低频繁换设备的风控概率),不是账号令牌。 -- 不打印、不上传令牌;错误信息不含令牌。 - -## 风险提示(重要) +## 凭据与查询 -- **非官方集成。** QuWork 没有公开的开发者 API / API Key;本插件复刻的是桌面客户端的登录与模型接口。QuWork 的服务条款可能限制在官方客户端之外使用账号与额度。 -- **有账号风险。** 第三方客户端访问可能被上游识别,导致验证码加强、限流、额度冻结、警告或封号;无法保证不会发生。浏览器登录的设备标识已保持稳定,但仍不是官方客户端。 -- **请只用你自己的账号。** 不要共享令牌、不要多账号批量/滥用、不要转售或对外提供网关;这些行为显著提高封号与法律风险。 -- 上游接口、模型和积分规则随时可能变更;变更后插件可能失效。发布前请阅读 QuWork 客户端内的《Clawork 软件许可及服务协议》。 -- 本项目按 MIT 发布,不附带任何担保;使用风险自担。 - -## 安装与开发 - -```powershell -magpie plugin add @magpie-community/opencode-quwork-auth -magpie plugin login quwork # 选第 1 项:浏览器登录 -magpie provider test quwork -``` - -从本仓库开发: - -```powershell -magpie plugin add ./packages/quwork -bun scripts/check.mjs quwork -npm test -``` - -OpenCode: - -```json -{ "plugin": ["@magpie-community/opencode-quwork-auth"] } -``` +- 登录页仅在 `127.0.0.1` 提供一次性地址,校验请求来源。发送短信有冷却时间,登录会话有尝试次数与时限。 +- 浏览器完成验证后,Magpie 保存模型密钥与查询积分用的账号凭据。请只在自己的账号上使用,并保管好 Magpie 的账号配置。 +- 模型密钥发送到指定的 QuWork 模型网关。积分来自 QuWork,短时间内的重复查询使用按凭据隔离的内存结果。 +- 现有的桌面登录态导入方式已移除。此前导入的账号可使用曾保存的模型密钥,查询积分需要独立登录。 -## 页面 +## 开发验证 -安装后侧边栏出现 **「QuWork 接入」**:显示供应商是否已出现、积分余额(缓存)、登录步骤和两种备选登录方式。页面只读取 `providers:list`,不读取账号或请求内容。 +在插件目录运行 `node --test index.test.mjs`。模拟测试覆盖本机登录与额度显示,使用测试数据。社区仓库从根目录运行 `bun scripts/check.mjs quwork`。社区代码采用 MIT 许可。 diff --git a/packages/quwork/index.mjs b/packages/quwork/index.mjs index dbfe76aaa..e6a934179 100644 --- a/packages/quwork/index.mjs +++ b/packages/quwork/index.mjs @@ -1,25 +1,25 @@ import { createServer } from "node:http" -import { randomUUID } from "node:crypto" -import { copyFileSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs" -import { homedir, tmpdir } from "node:os" -import { dirname, join } from "node:path" -import { fileURLToPath } from "node:url" +import { createHash, randomUUID } from "node:crypto" +import { readFileSync, writeFileSync } from "node:fs" +import { tmpdir } from "node:os" +import { join } from "node:path" const PROVIDER = "quwork" const LLM_BASE = "https://llm.quwork.cn/v1" const ACCOUNT_BASE = "https://llm.rrzu.com" -const TOKEN_ENV = "QUWORK_LLM_TOKEN" const FALLBACK_VERSION = "1.7.5" const CAPTCHA_SDK = "https://o.alicdn.com/captcha-frontend/aliyunCaptcha/AliyunCaptcha.js" const CAPTCHA_REGION = "cn" const CAPTCHA_PREFIX = "1hms8d" const CAPTCHA_SCENE_ID = "10vzkucv" -const PLUGIN_DIR = dirname(fileURLToPath(import.meta.url)) -const BALANCE_FILE = join(PLUGIN_DIR, "page", "balance.js") const DEVICE_FILE = join(tmpdir(), "magpie-quwork-device.json") const BALANCE_TTL_MS = 60_000 +const LOGIN_TTL_MS = 10 * 60_000 +const UPSTREAM_TIMEOUT_MS = 15_000 +const RESEND_COOLDOWN_MS = 60_000 +const MAX_LOGIN_ATTEMPTS = 5 -const balanceCache = new Map() +const CLIENT_HEADERS = { "x-qurwork-env": "prod", "x-qurwork-version": FALLBACK_VERSION } const MODELS = [ { @@ -79,18 +79,22 @@ const LOGIN_PAGE = `

QuWork 登录

-

用手机号 + 短信验证码登录 QuWork。登录成功后这个页面会提示完成,magpie 会自动接管,不需要安装 QuWork 客户端。

+

在此本机页面用手机号和短信验证码接入 Magpie。请只登录本人获授权使用的账号。

+

实验性社区接入,使用非公开接口。QuWork 可能限制或暂停账号服务。重要账号建议使用官方入口。查看服务协议

- +
-
-
验证码由 QuWork 发送,登录态只保存在本机 magpie。若验证码加载失败,可改用 magpie 里的「读取 QuWork 本机登录态」或「粘贴令牌」。
+
+
请在浏览器中手动完成阿里云人机验证。有 QuWork 明确授权用于第三方接入的模型密钥时,可在 Magpie 中单独填写。
+ -

QuWork 接入

-

把 QuWork 的积分模型接进 magpie。支持浏览器手机验证码登录,不需要 QuWork 桌面客户端。

+

在本机浏览器完成手机号验证后,可在 Magpie 使用 QuWork 模型。

+

实验性社区接入。该方式使用 QuWork 非公开接口,账号可能被限流或暂停服务。查看 QuWork 服务协议

-

积分余额

-

—

-

登录后打开一次 magpie 的 Quota(额度)页,这里会显示最新积分。

+

查看积分余额

+

浏览器登录后,在 Magpie 的 额度(Quota) 页找到 QuWork 账号,即可查看总余额,以及 QuWork 返回的限时与永久积分。

+

命令行可运行 magpie quota quwork。

供应商状态

-

正在读取…

+

正在读取…

@@ -30,20 +30,16 @@

登录步骤

  1. 打开 magpie 的 Providers(供应商) 页面。
  2. 找到 QuWork,点登录按钮。
  3. -
  4. 选 「浏览器登录 QuWork(手机验证码,无需客户端)」。
  5. +
  6. 选 「浏览器登录 QuWork(实验性)」。
  7. 在打开的页面里输入手机号,完成阿里云验证码,填入短信验证码。
  8. -
  9. 页面提示成功后关闭它,magpie 会自动完成登录。
  10. +
  11. 短信验证后回到 Magpie 确认供应商登录状态。
-

如果供应商列表里还没有 QuWork,先到 Plugins(插件)→ Installed(已安装) 确认本插件是 On;必要时重启 magpie。

+

如果供应商列表里还没有 QuWork,在 插件 → 已安装 启用此插件。必要时重启 Magpie。

-

没有浏览器登录条件?

-

登录菜单里还有两种方式:

-
    -
  • 读取 QuWork 本机登录态:本机装过 QuWork 并登录过时可用。
  • -
  • 粘贴 QuWork 令牌:直接粘贴 sk- 开头的令牌。
  • -
+

已获授权的模型密钥

+

如果 QuWork 已向你提供第三方接入密钥,可以在登录菜单填写该密钥。该方式可调用模型,积分请在官方入口查看。

diff --git a/packages/quwork/page/style.css b/packages/quwork/page/style.css index 4f4d9a797..57610ddb6 100644 --- a/packages/quwork/page/style.css +++ b/packages/quwork/page/style.css @@ -51,12 +51,5 @@ code { background: var(--magpie-code-bg, rgba(127, 127, 127, 0.15)); } -.balance { - margin: 0; - font-size: 30px; - font-weight: 700; - letter-spacing: -0.02em; -} - #status.ok { color: #16a34a; } #status.missing { color: #dc2626; } diff --git a/packages/quwork/test.mjs b/packages/quwork/test.mjs deleted file mode 100644 index 675a0e942..000000000 --- a/packages/quwork/test.mjs +++ /dev/null @@ -1,38 +0,0 @@ -import test from "node:test" -import assert from "node:assert/strict" -import { QuWorkProvider } from "./index.mjs" - -test("config declares the QuWork provider and models", async () => { - const hooks = await QuWorkProvider({}) - const cfg = { provider: {} } - await hooks.config(cfg) - assert.equal(cfg.provider.quwork.npm, "@ai-sdk/openai-compatible") - assert.equal(cfg.provider.quwork.api, "https://llm.quwork.cn/v1") - assert.ok(Object.keys(cfg.provider.quwork.models).length >= 10) -}) - -test("three sign-in methods, a loader and usage", async () => { - const hooks = await QuWorkProvider({}) - assert.equal(hooks.auth.provider, "quwork") - assert.equal(hooks.auth.methods.length, 3) - assert.equal(hooks.auth.methods[0].type, "oauth") - assert.ok(hooks.auth.methods[0].label.includes("浏览器登录")) - assert.equal(typeof hooks.auth.methods[0].authorize, "function") - assert.equal(typeof hooks.auth.loader, "function") - assert.equal(typeof hooks.auth.usage, "function") -}) - -test("the browser login page is served under a secret path", async () => { - const hooks = await QuWorkProvider({}) - const desc = await hooks.auth.methods[0].authorize(undefined, {}) - try { - assert.match(desc.url, /^http:\/\/127\.0\.0\.1:\d+\/[0-9a-f-]{36}\/$/) - const res = await fetch(desc.url) - assert.equal(res.status, 200) - const html = await res.text() - assert.ok(html.includes("QuWork 登录")) - assert.ok(html.includes("api/send-code")) - } finally { - desc.close?.() - } -}) diff --git a/registry.json b/registry.json index 6a3850344..357078982 100644 --- a/registry.json +++ b/registry.json @@ -306,6 +306,6 @@ "icon": "https://raw.githubusercontent.com/pmndre/pine/next/docs/images/logo-light.svg", "summary": { "en": "Pine (pmndre/pine, the event-driven agent harness on pi's SDK) on magpie's Agents page: pick one of magpie's models and magpie writes its gateway and catalog into ~/.pine/models.json and the model into pine.json, so new conversations start on it. Restart Pine after a change; unofficial.", "zh": "把 Pine(pmndre/pine,跑在 pi SDK 上的事件驱动 Agent 框架)加到 magpie 的 Agent 页:选一个 magpie 的模型,magpie 把网关和模型目录写进 ~/.pine/models.json、把起始模型写进 pine.json,新对话就用它。换完模型要重启 Pine;非官方适配。" } }, { "package": "@magpie-community/opencode-quwork-auth", "name": "QuWork", "providers": ["quwork"], "community": true, - "summary": { "en": "Unofficial QuWork (Clawork) access: browser sign-in with phone and SMS (Aliyun captcha), or the desktop client's saved session; live models, points balance and a setup page.", "zh": "非官方 QuWork(Clawork)接入:浏览器手机验证码登录(阿里云验证码),或复用桌面端登录态;动态模型、积分余额与接入页。" } } + "summary": { "en": "Experimental community integration for QuWork, with interactive browser sign-in and points in Magpie Quota.", "zh": "实验性 QuWork 社区接入。浏览器手动验证,积分在 Magpie 额度页显示。" } } ] } From 8dd217f7d78a05d60499216e7da2b004abf9d1b6 Mon Sep 17 00:00:00 2001 From: kshu06537-bot Date: Wed, 18 Nov 2026 19:35:33 +0800 Subject: [PATCH 3/7] quwork 0.1.2: official website login shortcut and key-only setup --- packages/quwork/README.md | 27 +-- packages/quwork/index.mjs | 361 +------------------------------- packages/quwork/index.test.mjs | 126 +++-------- packages/quwork/package.json | 8 +- packages/quwork/page/app.js | 2 +- packages/quwork/page/index.html | 30 ++- packages/quwork/page/style.css | 10 +- registry.json | 2 +- 8 files changed, 68 insertions(+), 498 deletions(-) diff --git a/packages/quwork/README.md b/packages/quwork/README.md index f4c3db080..fc231e8cd 100644 --- a/packages/quwork/README.md +++ b/packages/quwork/README.md @@ -1,30 +1,21 @@ # QuWork for Magpie -实验性社区供应商 `quwork`,支持在本机浏览器手动完成手机号、人机验证和短信验证码验证。登录无需安装 QuWork 桌面客户端。插件内置 10 个模型条目,实际可用模型由 QuWork 和账号权益决定。 - -## 账号风险 - -浏览器接入使用 QuWork 非公开客户端接口。尚未查到 QuWork 允许第三方客户端消耗个人账号积分的授权。官方协议第 2.3.2 条规定未明示授权的权利需另获书面许可,第 8.1 条限制逆向工程,第 8.2 条允许对违规行为暂停或终止服务。个人账号也存在风险,重要账号建议使用官方入口。阅读 [Clawork 软件许可及服务协议](https://llm.rrzu.com/claw-agreement)。 +社区供应商 `quwork`。账号登录在 QuWork 官网完成,Magpie 可使用 QuWork 授权用于第三方接入的模型密钥。插件内置 10 个模型条目,实际可用模型由 QuWork 和账号权益决定。 ## 安装与使用 -在 Magpie 的「插件 → 添加插件」选择本地插件目录,或在社区仓库根目录运行 `magpie plugin add ./packages/quwork`。启用后,前往「供应商 → QuWork → 登录」并选择「浏览器登录 QuWork(实验性)」。本机页面提示短信验证通过后,回到 Magpie 确认登录状态。 - -已从 QuWork 获得第三方接入授权的用户可在登录菜单单独填写模型密钥。模型密钥的权限限于模型调用,查询积分需要账号授权。 +在 Magpie 的「插件 → 添加插件」选择本地插件目录,或在社区仓库根目录运行 `magpie plugin add ./packages/quwork`。 -在 Magpie 的「额度(Quota)」页查看 QuWork 账号的积分总余额。上游提供限时或永久积分字段时会一并显示。查询失败会显示原因,余额为零只在上游确实返回零时显示。命令行也可查询: +1. 在侧栏「QuWork 接入」点「打开 QuWork 官网」,或在浏览器打开 [QuWork 官网](https://quwork.cn/)。 +2. 在官网点「注册 / 登录」,选择短信验证码或微信登录。手机号和验证码请在官网页面填写。 +3. 获得 QuWork 授权用于第三方接入的模型密钥后,在「供应商 → QuWork → 登录」填写。官网账号与 Magpie 的自动关联需要 QuWork 提供第三方授权接口,目前尚未查到该接口。 -```powershell -magpie quota quwork -``` +## 积分余额 -## 凭据与查询 +模型密钥用于模型调用,个人账号积分请在 QuWork 官方入口查看。已有有效旧版积分凭据的账号仍可在 Magpie 的「额度(Quota)」页查看总余额、限时积分和永久积分,具体字段以上游返回为准。也可运行 `magpie quota quwork`。 -- 登录页仅在 `127.0.0.1` 提供一次性地址,校验请求来源。发送短信有冷却时间,登录会话有尝试次数与时限。 -- 浏览器完成验证后,Magpie 保存模型密钥与查询积分用的账号凭据。请只在自己的账号上使用,并保管好 Magpie 的账号配置。 -- 模型密钥发送到指定的 QuWork 模型网关。积分来自 QuWork,短时间内的重复查询使用按凭据隔离的内存结果。 -- 现有的桌面登录态导入方式已移除。此前导入的账号可使用曾保存的模型密钥,查询积分需要独立登录。 +旧版积分查询使用非公开接口,受 QuWork 使用规则约束。官方协议第 2.3.2 条规定未明示授权的权利需另获书面许可,第 8.2 条允许对违规行为暂停或终止服务。[Clawork 软件许可及服务协议](https://llm.rrzu.com/claw-agreement) ## 开发验证 -在插件目录运行 `node --test index.test.mjs`。模拟测试覆盖本机登录与额度显示,使用测试数据。社区仓库从根目录运行 `bun scripts/check.mjs quwork`。社区代码采用 MIT 许可。 +在插件目录运行 `node --test index.test.mjs`。测试覆盖官网入口、模型密钥校验和旧版余额兼容,使用模拟凭据。社区仓库从根目录运行 `bun scripts/check.mjs quwork`。社区代码采用 MIT 许可。 diff --git a/packages/quwork/index.mjs b/packages/quwork/index.mjs index e6a934179..2aa640167 100644 --- a/packages/quwork/index.mjs +++ b/packages/quwork/index.mjs @@ -1,23 +1,11 @@ -import { createServer } from "node:http" -import { createHash, randomUUID } from "node:crypto" -import { readFileSync, writeFileSync } from "node:fs" -import { tmpdir } from "node:os" -import { join } from "node:path" +import { createHash } from "node:crypto" const PROVIDER = "quwork" const LLM_BASE = "https://llm.quwork.cn/v1" const ACCOUNT_BASE = "https://llm.rrzu.com" const FALLBACK_VERSION = "1.7.5" -const CAPTCHA_SDK = "https://o.alicdn.com/captcha-frontend/aliyunCaptcha/AliyunCaptcha.js" -const CAPTCHA_REGION = "cn" -const CAPTCHA_PREFIX = "1hms8d" -const CAPTCHA_SCENE_ID = "10vzkucv" -const DEVICE_FILE = join(tmpdir(), "magpie-quwork-device.json") const BALANCE_TTL_MS = 60_000 -const LOGIN_TTL_MS = 10 * 60_000 const UPSTREAM_TIMEOUT_MS = 15_000 -const RESEND_COOLDOWN_MS = 60_000 -const MAX_LOGIN_ATTEMPTS = 5 const CLIENT_HEADERS = { "x-qurwork-env": "prod", "x-qurwork-version": FALLBACK_VERSION } @@ -49,177 +37,19 @@ const MODELS = [ { id: "MiniMax-M2.5", name: "MiniMax-M2.5", limit: { context: 1000000, output: 32768 }, tool_call: true }, ] -const LOGIN_PAGE = ` - - - - -QuWork 登录 · magpie - - - -
-

QuWork 登录

-

在此本机页面用手机号和短信验证码接入 Magpie。请只登录本人获授权使用的账号。

-

实验性社区接入,使用非公开接口。QuWork 可能限制或暂停账号服务。重要账号建议使用官方入口。查看服务协议

- - -
- - - - - -
-
请在浏览器中手动完成阿里云人机验证。有 QuWork 明确授权用于第三方接入的模型密钥时,可在 Magpie 中单独填写。
-
- - - - -` - function authKey(auth) { const key = auth?.type === "api" ? auth.key : auth?.access return typeof key === "string" && /^sk-[A-Za-z0-9_-]{1,512}$/.test(key.trim()) ? key.trim() : "" } -function deviceIdentifier() { - try { - const data = JSON.parse(readFileSync(DEVICE_FILE, "utf8")) - if (typeof data?.deviceId === "string" && data.deviceId) return data.deviceId - } catch {} - const deviceId = randomUUID() - try { - writeFileSync(DEVICE_FILE, JSON.stringify({ deviceId }), { encoding: "utf8", mode: 0o600 }) - } catch { - // A read-only temp folder is fine; the id is then only stable for this process. - } - return deviceId -} - function pointsNumber(value) { if (typeof value !== "number" && !(typeof value === "string" && /^\d+(\.\d+)?$/.test(value.trim()))) return null const amount = Number(value) return Number.isFinite(amount) && amount >= 0 ? amount : null } -function usageError(error, signIn = "kept") { - return { error, signIn, windows: [] } +function usageError(error) { + return { error, signIn: "kept", windows: [] } } async function fetchUsage(accessToken, fetchImpl) { @@ -231,7 +61,7 @@ async function fetchUsage(accessToken, fetchImpl) { }) if (!response.ok) { await response.body?.cancel().catch(() => {}) - if (response.status === 401) return usageError("QuWork 余额凭据已失效,请重新登录后查看积分。", "expired") + if (response.status === 401) return usageError("旧版积分凭据已失效。请在 QuWork 官方入口查看积分。") if (response.status === 403) return usageError("QuWork 拒绝查询积分,请在官方入口核对账号状态。") if (response.status === 429) return usageError("QuWork 限制了积分查询,请稍后查看。") return usageError(`暂时无法查询 QuWork 积分(HTTP ${response.status})。`) @@ -268,148 +98,7 @@ async function checkKey(key, fetchImpl, signal) { } } -async function readJsonBody(request) { - let size = 0 - const chunks = [] - for await (const chunk of request) { - size += chunk.length - if (size > 16 * 1024) throw new Error("请求体过大") - chunks.push(chunk) - } - const body = JSON.parse(Buffer.concat(chunks).toString("utf8")) - if (!body || typeof body !== "object" || Array.isArray(body)) throw new Error("请求格式无效") - return body -} - -function sendJson(res, status, body) { - res.writeHead(status, { - "content-type": "application/json; charset=utf-8", - "cache-control": "no-store", - "referrer-policy": "no-referrer", - "x-content-type-options": "nosniff", - }) - res.end(JSON.stringify(body)) -} - -async function startBrowserLogin(fetchImpl, getDeviceIdentifier, signal) { - signal?.throwIfAborted() - const controller = new AbortController() - const prefix = `/${randomUUID()}/` - const sendPath = `${prefix}api/send-code` - const loginPath = `${prefix}api/login` - let port = 0 - let busy = false - let accepted = false - let sentTo = "" - let nextSendAt = 0 - let loginAttempts = 0 - let finish - const result = new Promise((resolve) => { finish = resolve }) - const server = createServer({ requestTimeout: 30_000, headersTimeout: 15_000 }, async (req, res) => { - const host = `127.0.0.1:${port}` - const fail = (status, message) => sendJson(res, status, { success: false, message }) - if (req.headers.host !== host) return fail(403, "请求来源无效") - if (req.method === "GET" && req.url === prefix) { - res.writeHead(200, { - "content-type": "text/html; charset=utf-8", - "cache-control": "no-store", - "x-frame-options": "DENY", - "referrer-policy": "no-referrer", - "x-content-type-options": "nosniff", - "content-security-policy": "frame-ancestors 'none'; base-uri 'none'; form-action 'none'; object-src 'none'", - }) - res.end(LOGIN_PAGE) - return - } - if (req.method !== "POST" || (req.url !== sendPath && req.url !== loginPath)) return fail(404, "登录页面不存在") - const contentType = req.headers["content-type"]?.split(";")[0].trim().toLowerCase() - if (req.headers.origin !== `http://${host}` || contentType !== "application/json") return fail(403, "请求来源无效") - if (accepted || controller.signal.aborted) return fail(410, "登录页面已关闭") - if (busy) return fail(409, "上一请求仍在处理") - - busy = true - try { - const body = await readJsonBody(req).catch(() => null) - if (!body) return fail(400, "请求格式无效") - const phone = typeof body.phone === "string" ? body.phone.trim() : "" - if (!/^1[3-9]\d{9}$/.test(phone)) return fail(400, "手机号格式不正确") - const upstreamSignal = AbortSignal.any([controller.signal, AbortSignal.timeout(UPSTREAM_TIMEOUT_MS)]) - if (req.url === sendPath) { - if (Date.now() < nextSendAt) return fail(429, `请 ${Math.ceil((nextSendAt - Date.now()) / 1000)} 秒后再发送`) - const captcha = typeof body.captcha === "string" ? body.captcha.trim() : "" - if (!captcha) return fail(400, "请先完成人机验证") - const query = new URLSearchParams({ aliyun_captcha: captcha }) - nextSendAt = Date.now() + RESEND_COOLDOWN_MS - const response = await fetchImpl(`${ACCOUNT_BASE}/api/sendVerifyCode?${query}`, { - method: "POST", - headers: { ...CLIENT_HEADERS, "content-type": "application/x-www-form-urlencoded" }, - body: new URLSearchParams({ phone, type: "login" }), - redirect: "error", - signal: upstreamSignal, - }) - const payload = await response.json().catch(() => null) - if (response.ok && payload?.success === true) { - sentTo = phone - return sendJson(res, 200, { success: true }) - } - return fail(response.status === 429 ? 429 : 400, "QuWork 未发送验证码。请稍后再试或到官方入口核对账号状态。") - } - const code = typeof body.code === "string" ? body.code.trim() : "" - if (phone !== sentTo || !/^\d{4,6}$/.test(code)) return fail(400, "请先为该手机号获取并填写短信验证码") - if (loginAttempts >= MAX_LOGIN_ATTEMPTS) return fail(429, "本次登录尝试次数已用完。请到 QuWork 官方入口核对账号状态。") - loginAttempts += 1 - const response = await fetchImpl(`${ACCOUNT_BASE}/api/user/client/login`, { - method: "POST", - headers: { ...CLIENT_HEADERS, "content-type": "application/json" }, - body: JSON.stringify({ - phone, - verification_code: code, - platform: "qurvis", - device_identifier: getDeviceIdentifier(), - device_uuid: "", - }), - redirect: "error", - signal: upstreamSignal, - }) - const payload = await response.json().catch(() => null) - if (!response.ok || payload?.success !== true) { - if (response.status === 403 || response.status === 429) loginAttempts = MAX_LOGIN_ATTEMPTS - return fail(response.status === 429 ? 429 : 400, "QuWork 未接受登录。请检查验证码或到官方入口核对账号状态。") - } - const key = authKey({ type: "api", key: payload.data?.llm_token }) - const accessToken = payload.data?.token - if (!key || typeof accessToken !== "string" || !accessToken.trim()) return fail(502, "QuWork 未返回完整的登录凭据") - if (controller.signal.aborted) return fail(410, "登录页面已关闭") - accepted = true - sendJson(res, 200, { success: true }) - finish({ key, accessToken: accessToken.trim() }) - } catch { - if (!res.destroyed) fail(502, "连接 QuWork 失败,请稍后查看。") - } finally { - busy = false - } - }) - - await new Promise((resolve, reject) => { - server.once("error", reject) - server.listen(0, "127.0.0.1", resolve) - }) - port = server.address().port - const timer = setTimeout(close, LOGIN_TTL_MS) - function close() { - if (controller.signal.aborted) return - clearTimeout(timer) - signal?.removeEventListener("abort", close) - controller.abort() - server.close() - finish(null) - } - if (signal?.aborted) close() - else signal?.addEventListener("abort", close, { once: true }) - return { url: `http://127.0.0.1:${port}${prefix}`, result, close } -} - -function createPlugin({ fetchImpl = globalThis.fetch, getDeviceIdentifier = deviceIdentifier } = {}) { +function createPlugin({ fetchImpl = globalThis.fetch } = {}) { const balanceCache = new Map() return { async config(config) { @@ -424,42 +113,10 @@ function createPlugin({ fetchImpl = globalThis.fetch, getDeviceIdentifier = devi auth: { provider: PROVIDER, methods: [ - { - type: "oauth", - label: "浏览器登录 QuWork(实验性)", - async authorize(_inputs, { signal } = {}) { - const session = await startBrowserLogin(fetchImpl, getDeviceIdentifier, signal) - return { - url: session.url, - instructions: "在本机浏览器阅读风险提示,手动完成人机验证和短信验证。", - method: "auto", - close: session.close, - async callback(_code, { signal: callbackSignal } = {}) { - const callbackAbort = callbackSignal ?? signal - if (callbackAbort?.aborted) session.close() - else callbackAbort?.addEventListener("abort", session.close, { once: true }) - try { - const credentials = await session.result - if (!credentials || callbackAbort?.aborted) return { type: "failed", error: "QuWork 登录已取消或超时。" } - const error = await checkKey(credentials.key, fetchImpl, callbackAbort) - if (error) return { type: "failed", error } - return { - type: "success", - key: credentials.key, - metadata: { source: "browser", accessToken: credentials.accessToken }, - } - } finally { - callbackAbort?.removeEventListener("abort", session.close) - session.close() - } - }, - } - }, - }, { type: "api", label: "填写已获授权的 QuWork 模型密钥", - placeholder: "sk-…", + prompts: [{ type: "password", key: "key", message: "QuWork 授权用于第三方接入的模型密钥", placeholder: "sk-…" }], async authorize(inputs, { signal } = {}) { const key = authKey({ type: "api", key: inputs?.key ?? inputs?.apiKey ?? inputs?.api_key ?? inputs?.value }) if (!key) return { type: "failed", error: "请填写 QuWork 授权用于第三方接入的模型密钥。" } @@ -481,7 +138,7 @@ function createPlugin({ fetchImpl = globalThis.fetch, getDeviceIdentifier = devi throw new Error("QuWork 模型密钥仅用于 QuWork 模型网关。") } const key = authKey(await getAuth()) - if (!key) throw new Error("请在 Magpie 中登录 QuWork。") + if (!key) throw new Error("请在 Magpie 中配置 QuWork 模型密钥。") const headers = new Headers(init?.headers ?? (isRequest ? input.headers : undefined)) headers.set("authorization", `Bearer ${key}`) for (const [name, value] of Object.entries(CLIENT_HEADERS)) headers.set(name, value) @@ -491,10 +148,10 @@ function createPlugin({ fetchImpl = globalThis.fetch, getDeviceIdentifier = devi }, async usage(getAuth) { const auth = await getAuth() - if (!authKey(auth)) return usageError("请先在 Magpie 中登录 QuWork。") + if (!authKey(auth)) return usageError("请先在 Magpie 中配置 QuWork 模型密钥。") const accessToken = auth.metadata?.source === "browser" ? auth.metadata.accessToken : null if (typeof accessToken !== "string" || !accessToken.trim()) { - return usageError("当前仅有模型密钥。积分查询需要浏览器登录获得的账号凭据。") + return usageError("当前为模型密钥接入。请在 QuWork 官方入口查看账号积分。") } const now = Date.now() for (const [cacheKey, entry] of balanceCache) { diff --git a/packages/quwork/index.test.mjs b/packages/quwork/index.test.mjs index e56502e78..6258051e1 100644 --- a/packages/quwork/index.test.mjs +++ b/packages/quwork/index.test.mjs @@ -1,17 +1,10 @@ import test from "node:test" import assert from "node:assert/strict" +import { readFileSync } from "node:fs" import { QuWorkProvider, _internal } from "./index.mjs" const { createPlugin } = _internal -function submit(session, path, body, origin = new URL(session.url).origin) { - return fetch(new URL(`api/${path}`, session.url), { - method: "POST", - headers: { origin, "content-type": "application/json" }, - body: JSON.stringify(body), - }) -} - test("config declares the QuWork provider and models", async () => { const hooks = await QuWorkProvider({}) const cfg = { provider: {} } @@ -21,12 +14,14 @@ test("config declares the QuWork provider and models", async () => { assert.ok(Object.keys(cfg.provider.quwork.models).length >= 10) }) -test("interactive sign-in and authorized keys are the only methods", async () => { +test("the setup page links to QuWork and only the model key method is registered", async () => { const hooks = await QuWorkProvider({}) + const page = readFileSync(new URL("./page/index.html", import.meta.url), "utf8") assert.equal(hooks.auth.provider, "quwork") - assert.deepEqual(hooks.auth.methods.map((method) => method.type), ["oauth", "api"]) - assert.ok(hooks.auth.methods[0].label.includes("浏览器登录")) - assert.equal(typeof hooks.auth.methods[0].authorize, "function") + assert.deepEqual(hooks.auth.methods.map((method) => method.type), ["api"]) + assert.match(page, /href="https:\/\/quwork\.cn\/" target="_blank" rel="noopener noreferrer"/) + assert.doesNotMatch(page, / { - const hooks = await QuWorkProvider({}) - const desc = await hooks.auth.methods[0].authorize(undefined, {}) - try { - assert.match(desc.url, /^http:\/\/127\.0\.0\.1:\d+\/[0-9a-f-]{36}\/$/) - const res = await fetch(desc.url) - assert.equal(res.status, 200) - assert.match(res.headers.get("content-security-policy") ?? "", /frame-ancestors 'none'/) - const html = await res.text() - assert.ok(html.includes("QuWork 登录")) - assert.ok(html.includes("api/send-code")) - } finally { - desc.close?.() - } -}) - -test("the local login API rejects a request without the page origin", async () => { - let calls = 0 - const hooks = createPlugin({ fetchImpl: async () => { calls += 1; throw new Error("unexpected request") } }) - const desc = await hooks.auth.methods[0].authorize(undefined, {}) - try { - const endpoint = new URL("api/send-code", desc.url) - const res = await fetch(endpoint, { - method: "POST", - headers: { "content-type": "application/json" }, - body: JSON.stringify({ phone: "13800000000", captcha: "test" }), - }) - assert.equal(res.status, 403) - assert.equal((await submit(desc, "send-code", {}, "https://example.com")).status, 403) - assert.equal(calls, 0) - } finally { - desc.close?.() - } -}) - -test("browser sign-in enforces the SMS flow and keeps credentials out of browser responses", async () => { +test("key setup validates only the model key with a read-only request", async () => { const calls = [] const hooks = createPlugin({ - getDeviceIdentifier: () => "fixture-device", - fetchImpl: async (url) => { - const target = new URL(url) - calls.push(target.pathname) - if (target.pathname.endsWith("/sendVerifyCode")) return Response.json({ success: true, data: { token: "not-for-browser" } }) - if (target.pathname.endsWith("/client/login")) { - return Response.json({ success: true, data: { token: "fixture-access", llm_token: "sk-fixture", user: { phone: "private" } } }) - } - if (target.pathname.endsWith("/models")) return Response.json({ data: [] }) - throw new Error("unexpected request") + fetchImpl: async (url, init) => { + calls.push({ url, method: init.method ?? "GET", authorization: init.headers.authorization }) + return Response.json({ data: [] }) }, }) - const session = await hooks.auth.methods[0].authorize() - const phone = "13800000000" - try { - assert.equal((await submit(session, "login", { phone, code: "123456" })).status, 400) - assert.equal(calls.length, 0) - const response = await submit(session, "send-code", { phone, captcha: "fixture" }) - assert.deepEqual(await response.json(), { success: true }) - assert.equal((await submit(session, "send-code", { phone, captcha: "fixture" })).status, 429) - const login = await submit(session, "login", { phone, code: "123456" }) - assert.deepEqual(await login.json(), { success: true }) - assert.equal((await submit(session, "login", { phone, code: "123456" })).status, 410) - assert.deepEqual(await session.callback(), { - type: "success", - key: "sk-fixture", - metadata: { source: "browser", accessToken: "fixture-access" }, - }) - assert.equal(calls.length, 3) - } finally { - session.close() - } -}) - -test("cancelling the sign-in callback closes the local page", async () => { - const hooks = await QuWorkProvider({}) - const session = await hooks.auth.methods[0].authorize() - try { - const page = await fetch(session.url) - assert.equal(page.status, 200) - await page.text() - const controller = new AbortController() - const pending = session.callback(undefined, { signal: controller.signal }) - controller.abort() - assert.equal((await pending).type, "failed") - await assert.rejects(() => fetch(session.url)) - } finally { - session.close() - } + const method = hooks.auth.methods[0] + assert.equal((await method.authorize({ key: "000000" })).type, "failed") + assert.equal(calls.length, 0) + assert.deepEqual(await method.authorize({ key: " sk-test " }), { + type: "success", + key: "sk-test", + metadata: { source: "pasted" }, + }) + assert.deepEqual(calls, [{ url: "https://llm.quwork.cn/v1/models", method: "GET", authorization: "Bearer sk-test" }]) }) -test("quota is scoped to browser accounts and deduplicates concurrent reads", async () => { +test("quota is scoped to legacy accounts and deduplicates concurrent reads", async () => { const calls = [] const hooks = createPlugin({ fetchImpl: async (_url, init) => { const authorization = init.headers.authorization @@ -149,27 +74,28 @@ test("quota is scoped to browser accounts and deduplicates concurrent reads", as const points = authorization === "Bearer first-access" ? "42.5" : 0 return Response.json({ success: true, data: { points_entitlement: { total_points: points, limited_points: 0 } } }) } }) - const forAccount = (accessToken) => async () => ({ type: "api", key: "sk-fixture", metadata: { source: "browser", accessToken } }) + const forAccount = (accessToken) => async () => ({ type: "api", key: "sk-test", metadata: { source: "browser", accessToken } }) const first = forAccount("first-access") assert.deepEqual((await Promise.all([hooks.auth.usage(first), hooks.auth.usage(first)])).map((value) => value.balance), [ "42.5 积分(限时 0)", "42.5 积分(限时 0)", ]) assert.equal((await hooks.auth.usage(forAccount("second-access"))).balance, "0 积分(限时 0)") - assert.match((await hooks.auth.usage(async () => ({ type: "api", key: "sk-fixture" }))).error, /仅有模型密钥/) + const keyOnly = await hooks.auth.usage(async () => ({ type: "api", key: "sk-test", metadata: { source: "pasted" } })) + assert.match(keyOnly.error, /官方入口查看账号积分/) assert.deepEqual(calls, ["Bearer first-access", "Bearer second-access"]) }) test("quota treats missing data, expired credentials and refusals as distinct states", async () => { const fixtures = [ [200, { success: true, data: { points_entitlement: { total_points: null } } }, "kept", /有效的积分/], - [401, { token: "not-for-display" }, "expired", /凭据已失效/], + [401, { token: "not-for-display" }, "kept", /旧版积分凭据已失效/], [403, { error: "not-for-display" }, "kept", /拒绝查询/], [429, { error: "not-for-display" }, "kept", /限制了积分查询/], ] for (const [status, payload, signIn, message] of fixtures) { const hooks = createPlugin({ fetchImpl: async () => Response.json(payload, { status }) }) const result = await hooks.auth.usage(async () => ({ - type: "api", key: "sk-fixture", metadata: { source: "browser", accessToken: "fixture-access" }, + type: "api", key: "sk-test", metadata: { source: "browser", accessToken: "fixture-access" }, })) assert.equal(result.balance, undefined) assert.equal(result.signIn, signIn) diff --git a/packages/quwork/package.json b/packages/quwork/package.json index 896436677..88c29578a 100644 --- a/packages/quwork/package.json +++ b/packages/quwork/package.json @@ -1,7 +1,7 @@ { "name": "@magpie-community/opencode-quwork-auth", - "version": "0.1.1", - "description": "Experimental QuWork (Clawork) provider for OpenCode and Magpie with interactive browser sign-in and account points in Magpie Quota", + "version": "0.1.2", + "description": "QuWork (Clawork) provider for OpenCode and Magpie with an official website shortcut and authorized model key setup", "type": "module", "main": "./opencode.mjs", "exports": { @@ -32,8 +32,8 @@ "magpie": { "name": "QuWork", "summary": { - "en": "Experimental community integration for QuWork, with interactive browser sign-in and points in Magpie Quota.", - "zh": "实验性 QuWork 社区接入。浏览器手动验证,积分在 Magpie 额度页显示。" + "en": "QuWork community integration with an official website shortcut and authorized model key setup.", + "zh": "QuWork 社区接入,提供官网登录入口和授权模型密钥配置。" }, "icon": "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA2NCA2NCI+PHJlY3Qgd2lkdGg9IjY0IiBoZWlnaHQ9IjY0IiByeD0iMTQiIGZpbGw9IiMyZjZmZWQiLz48dGV4dCB4PSIzMiIgeT0iNDUiIGZvbnQtZmFtaWx5PSJBcmlhbCxIZWx2ZXRpY2Esc2Fucy1zZXJpZiIgZm9udC1zaXplPSIzOCIgZm9udC13ZWlnaHQ9IjcwMCIgdGV4dC1hbmNob3I9Im1pZGRsZSIgZmlsbD0iI2ZmZmZmZiI+UTwvdGV4dD48L3N2Zz4=", "page": { diff --git a/packages/quwork/page/app.js b/packages/quwork/page/app.js index 32d028c87..4f2724393 100644 --- a/packages/quwork/page/app.js +++ b/packages/quwork/page/app.js @@ -6,7 +6,7 @@ const providers = await magpie.read("providers:list") const list = Array.isArray(providers) ? providers : providers?.providers if (Array.isArray(list) && list.some((provider) => provider?.id === "quwork")) { - status.textContent = "已找到 QuWork,可以在供应商页管理登录。" + status.textContent = "已找到 QuWork,可以在供应商页管理模型密钥。" status.className = "ok" } else { status.textContent = "请在供应商页查看 QuWork。首次安装后可重启 Magpie 再查看。" diff --git a/packages/quwork/page/index.html b/packages/quwork/page/index.html index dd84c0b0c..edf91fd3c 100644 --- a/packages/quwork/page/index.html +++ b/packages/quwork/page/index.html @@ -11,35 +11,29 @@

QuWork 接入

-

在本机浏览器完成手机号验证后,可在 Magpie 使用 QuWork 模型。

-

实验性社区接入。该方式使用 QuWork 非公开接口,账号可能被限流或暂停服务。查看 QuWork 服务协议

+

请在 QuWork 官网登录账号。Magpie 的模型调用需要 QuWork 授权用于第三方接入的模型密钥。

-

查看积分余额

-

浏览器登录后,在 Magpie 的 额度(Quota) 页找到 QuWork 账号,即可查看总余额,以及 QuWork 返回的限时与永久积分。

-

命令行可运行 magpie quota quwork。

+

官网登录

+

在官网右上角点「注册 / 登录」,选择短信验证码或微信登录。

+ 打开 QuWork 官网 +

官网地址 https://quwork.cn/

-

供应商状态

-

正在读取…

+

积分余额

+

持有有效旧版积分凭据的账号可在 Magpie 额度(Quota)→ QuWork 查看余额。通过模型密钥接入的账号请在 QuWork 官方入口查看积分。

-

登录步骤

-
    -
  1. 打开 magpie 的 Providers(供应商) 页面。
  2. -
  3. 找到 QuWork,点登录按钮。
  4. -
  5. 选 「浏览器登录 QuWork(实验性)」。
  6. -
  7. 在打开的页面里输入手机号,完成阿里云验证码,填入短信验证码。
  8. -
  9. 短信验证后回到 Magpie 确认供应商登录状态。
  10. -
-

如果供应商列表里还没有 QuWork,在 插件 → 已安装 启用此插件。必要时重启 Magpie。

+

供应商状态

+

正在读取…

-

已获授权的模型密钥

-

如果 QuWork 已向你提供第三方接入密钥,可以在登录菜单填写该密钥。该方式可调用模型,积分请在官方入口查看。

+

接入 Magpie

+

获得 QuWork 授权的模型密钥后,前往 供应商 → QuWork → 登录 填写密钥。自动关联官网账号需要 QuWork 提供面向 Magpie 的授权接口。

+

如果供应商列表里还没有 QuWork,在 插件 → 已安装 启用此插件。必要时重启 Magpie。

diff --git a/packages/quwork/page/style.css b/packages/quwork/page/style.css index 57610ddb6..283240cc6 100644 --- a/packages/quwork/page/style.css +++ b/packages/quwork/page/style.css @@ -30,10 +30,12 @@ h2 { font-size: 15px; } -ol, ul { - margin: 0; - padding-left: 22px; - line-height: 1.9; +.official-link { + display: inline-block; + padding: 8px 14px; + border: 1px solid var(--magpie-border, rgba(127, 127, 127, 0.3)); + border-radius: 8px; + font-weight: 600; } .hint { diff --git a/registry.json b/registry.json index 357078982..289eb3ce0 100644 --- a/registry.json +++ b/registry.json @@ -306,6 +306,6 @@ "icon": "https://raw.githubusercontent.com/pmndre/pine/next/docs/images/logo-light.svg", "summary": { "en": "Pine (pmndre/pine, the event-driven agent harness on pi's SDK) on magpie's Agents page: pick one of magpie's models and magpie writes its gateway and catalog into ~/.pine/models.json and the model into pine.json, so new conversations start on it. Restart Pine after a change; unofficial.", "zh": "把 Pine(pmndre/pine,跑在 pi SDK 上的事件驱动 Agent 框架)加到 magpie 的 Agent 页:选一个 magpie 的模型,magpie 把网关和模型目录写进 ~/.pine/models.json、把起始模型写进 pine.json,新对话就用它。换完模型要重启 Pine;非官方适配。" } }, { "package": "@magpie-community/opencode-quwork-auth", "name": "QuWork", "providers": ["quwork"], "community": true, - "summary": { "en": "Experimental community integration for QuWork, with interactive browser sign-in and points in Magpie Quota.", "zh": "实验性 QuWork 社区接入。浏览器手动验证,积分在 Magpie 额度页显示。" } } + "summary": { "en": "QuWork community integration with an official website shortcut and authorized model key setup.", "zh": "QuWork 社区接入,提供官网登录入口和授权模型密钥配置。" } } ] } From 3b5899ddba589239881db8435afdfba52d284182 Mon Sep 17 00:00:00 2001 From: kshu06537-bot Date: Wed, 18 Nov 2026 20:09:28 +0800 Subject: [PATCH 4/7] quwork 0.1.3: make official website link navigate inside Magpie --- packages/quwork/index.test.mjs | 2 +- packages/quwork/package.json | 2 +- packages/quwork/page/index.html | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/quwork/index.test.mjs b/packages/quwork/index.test.mjs index 6258051e1..3ae100af2 100644 --- a/packages/quwork/index.test.mjs +++ b/packages/quwork/index.test.mjs @@ -19,7 +19,7 @@ test("the setup page links to QuWork and only the model key method is registered const page = readFileSync(new URL("./page/index.html", import.meta.url), "utf8") assert.equal(hooks.auth.provider, "quwork") assert.deepEqual(hooks.auth.methods.map((method) => method.type), ["api"]) - assert.match(page, /href="https:\/\/quwork\.cn\/" target="_blank" rel="noopener noreferrer"/) + assert.match(page, /href="https:\/\/quwork\.cn\/" target="_self"/) assert.doesNotMatch(page, /QuWork 接入

官网登录

在官网右上角点「注册 / 登录」,选择短信验证码或微信登录。

- 打开 QuWork 官网 -

官网地址 https://quwork.cn/

+ 在 Magpie 内打开官网 +

如果页面没有跳转,请复制 https://quwork.cn/ 到系统浏览器打开。

From fb6cbf4586ed341616c99d126601d0b919e59c42 Mon Sep 17 00:00:00 2001 From: kshu06537-bot Date: Wed, 18 Nov 2026 20:23:41 +0800 Subject: [PATCH 5/7] quwork 0.1.4: read official website sign-in in a dedicated browser --- packages/quwork/README.md | 10 +- packages/quwork/browser.mjs | 267 ++++++++++++++++++++++++++++++++ packages/quwork/index.mjs | 105 ++++++++++++- packages/quwork/index.test.mjs | 34 +++- packages/quwork/package.json | 3 +- packages/quwork/page/index.html | 8 +- 6 files changed, 408 insertions(+), 19 deletions(-) create mode 100644 packages/quwork/browser.mjs diff --git a/packages/quwork/README.md b/packages/quwork/README.md index fc231e8cd..cc0c2662d 100644 --- a/packages/quwork/README.md +++ b/packages/quwork/README.md @@ -1,20 +1,20 @@ # QuWork for Magpie -社区供应商 `quwork`。账号登录在 QuWork 官网完成,Magpie 可使用 QuWork 授权用于第三方接入的模型密钥。插件内置 10 个模型条目,实际可用模型由 QuWork 和账号权益决定。 +社区供应商 `quwork`。插件会打开专用 Chrome/Edge 窗口,在 QuWork 官网完成登录;也会读取官网登录态中的账号 token,并尝试取得模型凭据。插件内置 10 个模型条目,实际可用模型由 QuWork 和账号权益决定。 ## 安装与使用 在 Magpie 的「插件 → 添加插件」选择本地插件目录,或在社区仓库根目录运行 `magpie plugin add ./packages/quwork`。 -1. 在侧栏「QuWork 接入」点「打开 QuWork 官网」,或在浏览器打开 [QuWork 官网](https://quwork.cn/)。 -2. 在官网点「注册 / 登录」,选择短信验证码或微信登录。手机号和验证码请在官网页面填写。 -3. 获得 QuWork 授权用于第三方接入的模型密钥后,在「供应商 → QuWork → 登录」填写。官网账号与 Magpie 的自动关联需要 QuWork 提供第三方授权接口,目前尚未查到该接口。 +1. 在「供应商 → QuWork → 登录」选择「官网浏览器登录(自动读取登录态)」。 +2. 在弹出的专用浏览器窗口里打开 QuWork 官网,点「注册 / 登录」,选择短信验证码或微信登录。手机号和验证码只在官网页面填写。 +3. 登录成功后,Magpie 会读取官网 localStorage 中的 `quwork_web_token`,并尝试从登录响应中取得 `llm_token`。如果上游没有返回模型凭据,登录菜单里仍可填写 QuWork 授权用于第三方接入的 `sk-` 模型密钥。 ## 积分余额 模型密钥用于模型调用,个人账号积分请在 QuWork 官方入口查看。已有有效旧版积分凭据的账号仍可在 Magpie 的「额度(Quota)」页查看总余额、限时积分和永久积分,具体字段以上游返回为准。也可运行 `magpie quota quwork`。 -旧版积分查询使用非公开接口,受 QuWork 使用规则约束。官方协议第 2.3.2 条规定未明示授权的权利需另获书面许可,第 8.2 条允许对违规行为暂停或终止服务。[Clawork 软件许可及服务协议](https://llm.rrzu.com/claw-agreement) +官网登录读取的是 QuWork 官网自己写入的登录态;积分查询和模型调用仍受 QuWork 使用规则约束。官方协议第 2.3.2 条规定未明示授权的权利需另获书面许可,第 8.2 条允许对违规行为暂停或终止服务。[Clawork 软件许可及服务协议](https://llm.rrzu.com/claw-agreement) ## 开发验证 diff --git a/packages/quwork/browser.mjs b/packages/quwork/browser.mjs new file mode 100644 index 000000000..6f2678324 --- /dev/null +++ b/packages/quwork/browser.mjs @@ -0,0 +1,267 @@ +import { spawn } from "node:child_process" +import { chmodSync, existsSync, mkdirSync, mkdtempSync, rmSync } from "node:fs" +import { createServer } from "node:net" +import { tmpdir } from "node:os" +import { join } from "node:path" + +const activeBrowsers = new Set() +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) + +process.once("exit", () => { + for (const child of activeBrowsers) { + try { + child.kill("SIGKILL") + } catch {} + } +}) + +export function findBrowser(platform = process.platform, env = process.env) { + if (env.QUWORK_BROWSER && existsSync(env.QUWORK_BROWSER)) return env.QUWORK_BROWSER + const candidates = + platform === "darwin" + ? [ + "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", + "/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge", + "/Applications/Chromium.app/Contents/MacOS/Chromium", + ] + : platform === "win32" + ? [ + join(env.PROGRAMFILES || "", "Google/Chrome/Application/chrome.exe"), + join(env["PROGRAMFILES(X86)"] || "", "Google/Chrome/Application/chrome.exe"), + join(env.LOCALAPPDATA || "", "Google/Chrome/Application/chrome.exe"), + join(env.PROGRAMFILES || "", "Microsoft/Edge/Application/msedge.exe"), + join(env["PROGRAMFILES(X86)"] || "", "Microsoft/Edge/Application/msedge.exe"), + ] + : [ + "/usr/bin/google-chrome", + "/usr/bin/google-chrome-stable", + "/usr/bin/chromium", + "/usr/bin/chromium-browser", + "/usr/bin/microsoft-edge", + ] + return candidates.find((candidate) => candidate && existsSync(candidate)) ?? "" +} + +function browserArgs(profile, port, url) { + return [ + `--user-data-dir=${profile}`, + `--remote-debugging-port=${port}`, + "--remote-debugging-address=127.0.0.1", + "--no-first-run", + "--no-default-browser-check", + "--disable-sync", + "--disable-default-apps", + "--disable-background-mode", + "--new-window", + url, + ] +} + +function freePort() { + return new Promise((resolve, reject) => { + const server = createServer() + server.once("error", reject) + server.listen(0, "127.0.0.1", () => { + const port = server.address().port + server.close(() => resolve(port)) + }) + }) +} + +function waitForExit(child, timeoutMs) { + if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve() + return new Promise((resolve) => { + const timer = setTimeout(resolve, timeoutMs) + child.once("exit", () => { + clearTimeout(timer) + resolve() + }) + }) +} + +async function cdpTarget(port, targetPrefix) { + const deadline = Date.now() + 15_000 + while (Date.now() < deadline) { + try { + const response = await fetch(`http://127.0.0.1:${port}/json/list`, { signal: AbortSignal.timeout(1200) }) + const list = await response.json() + const target = list.find( + (item) => + item?.type === "page" && + typeof item.url === "string" && + item.url.startsWith(targetPrefix) && + item.webSocketDebuggerUrl, + ) + if (target) return target + } catch {} + await sleep(200) + } + return null +} + +class CDP { + constructor(webSocketUrl) { + this.socket = new WebSocket(webSocketUrl) + this.nextId = 1 + this.pending = new Map() + this.listeners = new Map() + this.closed = false + this.opened = new Promise((resolve, reject) => { + this.socket.onopen = resolve + this.socket.onerror = () => reject(new Error("无法连接浏览器调试接口")) + }) + this.socket.onmessage = (event) => { + let message + try { + message = JSON.parse(String(event.data)) + } catch { + return + } + if (message.id) { + const pending = this.pending.get(message.id) + if (!pending) return + this.pending.delete(message.id) + if (message.error) pending.reject(new Error(message.error.message || "浏览器命令失败")) + else pending.resolve(message.result ?? {}) + return + } + for (const listener of this.listeners.get(message.method) ?? []) { + listener(message.params ?? {}) + } + } + this.socket.onclose = () => { + this.closed = true + for (const pending of this.pending.values()) pending.reject(new Error("浏览器调试连接已关闭")) + this.pending.clear() + } + } + + async send(method, params = {}) { + await this.opened + if (this.closed) throw new Error("浏览器调试连接已关闭") + const id = this.nextId++ + return new Promise((resolve, reject) => { + this.pending.set(id, { resolve, reject }) + this.socket.send(JSON.stringify({ id, method, params })) + }) + } + + on(method, listener) { + const listeners = this.listeners.get(method) ?? [] + listeners.push(listener) + this.listeners.set(method, listeners) + } + + close() { + try { + this.socket.close() + } catch {} + } +} + +function captureLoginResponses(client) { + const captured = { webToken: "", llmToken: "" } + const pending = new Set() + client.on("Network.responseReceived", ({ requestId, response }) => { + if (typeof response?.url !== "string") return + if (/\/api\/user\/client\/login|\/api\/oauth\/wechat\/share\/exchange/.test(response.url)) { + pending.add(requestId) + } + }) + client.on("Network.loadingFinished", async ({ requestId }) => { + if (!pending.delete(requestId)) return + try { + const body = await client.send("Network.getResponseBody", { requestId }) + const text = body.base64Encoded + ? Buffer.from(body.body, "base64").toString("utf8") + : body.body + const payload = JSON.parse(text) + const data = payload?.data ?? payload + if (typeof data?.token === "string" && data.token.trim()) captured.webToken = data.token.trim() + if (typeof data?.llm_token === "string" && data.llm_token.trim()) captured.llmToken = data.llm_token.trim() + } catch {} + }) + return captured +} + +export async function openChromeSession(url, { targetPrefix = "https://quwork.cn/" } = {}) { + const browser = findBrowser() + if (!browser) throw new Error("没有找到 Chrome 或 Edge;请安装浏览器后重试") + const profile = mkdtempSync(join(tmpdir(), "magpie-quwork-browser-")) + mkdirSync(profile, { recursive: true, mode: 0o700 }) + try { + chmodSync(profile, 0o700) + } catch {} + const port = await freePort() + const child = spawn(browser, browserArgs(profile, port, url), { stdio: "ignore", detached: false }) + activeBrowsers.add(child) + let spawnError = "" + child.once("error", (error) => { + spawnError = String(error?.message ?? error) + }) + + const target = await cdpTarget(port, targetPrefix) + if (!target) { + child.kill("SIGKILL") + rmSync(profile, { recursive: true, force: true }) + throw new Error("浏览器没有打开 QuWork 官网") + } + const client = new CDP(target.webSocketDebuggerUrl) + await client.send("Network.enable").catch(() => {}) + const captured = captureLoginResponses(client) + let closed = false + let closing = null + + async function evaluate(expression) { + const result = await client.send("Runtime.evaluate", { + expression, + returnByValue: true, + }) + if (result.exceptionDetails) throw new Error("无法读取 QuWork 官网登录态") + return result.result?.value + } + + async function credentials(timeoutMs) { + const deadline = Date.now() + timeoutMs + let webSeenAt = 0 + while (Date.now() < deadline && !closed) { + if (spawnError) throw new Error(`浏览器无法启动:${spawnError}`) + if (!captured.webToken) { + try { + const value = await evaluate('localStorage.getItem("quwork_web_token")') + if (typeof value === "string" && value.trim()) captured.webToken = value.trim() + } catch {} + } + if (captured.webToken && !webSeenAt) webSeenAt = Date.now() + if (captured.llmToken) return { ...captured } + if (captured.webToken && Date.now() - webSeenAt > 3000) return { ...captured } + await sleep(500) + } + return captured.webToken ? { ...captured } : null + } + + function close() { + if (closing) return closing + closed = true + closing = (async () => { + activeBrowsers.delete(child) + client.close() + if (child.exitCode === null && child.signalCode === null) { + try { + child.kill("SIGTERM") + } catch {} + await waitForExit(child, 2000) + } + if (child.exitCode === null && child.signalCode === null) { + try { + child.kill("SIGKILL") + } catch {} + await waitForExit(child, 1000) + } + rmSync(profile, { recursive: true, force: true }) + })() + return closing + } + + return { evaluate, credentials, close } +} diff --git a/packages/quwork/index.mjs b/packages/quwork/index.mjs index 2aa640167..423a1e348 100644 --- a/packages/quwork/index.mjs +++ b/packages/quwork/index.mjs @@ -1,4 +1,5 @@ import { createHash } from "node:crypto" +import { findBrowser, openChromeSession } from "./browser.mjs" const PROVIDER = "quwork" const LLM_BASE = "https://llm.quwork.cn/v1" @@ -6,6 +7,7 @@ const ACCOUNT_BASE = "https://llm.rrzu.com" const FALLBACK_VERSION = "1.7.5" const BALANCE_TTL_MS = 60_000 const UPSTREAM_TIMEOUT_MS = 15_000 +const OFFICIAL_LOGIN = "https://quwork.cn/" const CLIENT_HEADERS = { "x-qurwork-env": "prod", "x-qurwork-version": FALLBACK_VERSION } @@ -39,7 +41,7 @@ const MODELS = [ function authKey(auth) { const key = auth?.type === "api" ? auth.key : auth?.access - return typeof key === "string" && /^sk-[A-Za-z0-9_-]{1,512}$/.test(key.trim()) ? key.trim() : "" + return typeof key === "string" && key.trim().length >= 4 && key.trim().length <= 4096 ? key.trim() : "" } function pointsNumber(value) { @@ -98,8 +100,84 @@ async function checkKey(key, fetchImpl, signal) { } } -function createPlugin({ fetchImpl = globalThis.fetch } = {}) { +function createPlugin({ fetchImpl = globalThis.fetch, browser = { find: findBrowser, open: openChromeSession } } = {}) { const balanceCache = new Map() + + async function browserAuthorize(_inputs, { signal } = {}) { + if (!browser.find()) { + return { type: "failed", error: "没有找到 Chrome 或 Edge;请安装浏览器,或改用模型密钥登录。" } + } + let session + try { + session = await browser.open(OFFICIAL_LOGIN) + } catch (error) { + return { type: "failed", error: error?.message ?? String(error) } + } + let closed = false + const close = () => { + if (closed) return + closed = true + return session.close() + } + if (signal?.aborted) { + await close() + return { type: "failed", error: "QuWork 登录已取消。" } + } + return { + url: "", + opened: true, + instructions: "已打开专用浏览器窗口:请在 QuWork 官网完成登录。登录成功后,Magpie 会自动继续。", + method: "auto", + close, + async callback(_code, { signal } = {}) { + const abort = () => close() + if (signal?.aborted) abort() + else signal?.addEventListener("abort", abort, { once: true }) + try { + const found = await session.credentials(5 * 60 * 1000) + if (!found?.webToken && !found?.llmToken) { + return { type: "failed", error: "QuWork 官网登录超时,请重试。" } + } + const accessToken = found.webToken || "" + const candidates = [found.llmToken, accessToken].filter(Boolean) + let key = "" + for (const candidate of candidates) { + if (!(await checkKey(candidate, fetchImpl, signal))) { + key = candidate + break + } + } + if (!key && accessToken) { + const points = await fetchUsage(accessToken, fetchImpl) + if (points.balance) { + return { + type: "success", + key: accessToken, + metadata: { source: "browser", accessToken, modelKey: false }, + } + } + } + if (!key) { + return { + type: "failed", + error: "官网登录成功,但 QuWork 没有返回可用于第三方模型的凭据。请在官网控制台创建模型密钥后重试。", + } + } + return { + type: "success", + key, + metadata: { source: "browser", accessToken, modelKey: true }, + } + } catch (error) { + return { type: "failed", error: error?.message ?? String(error) } + } finally { + signal?.removeEventListener("abort", abort) + await close() + } + }, + } + } + return { async config(config) { config.provider ??= {} @@ -113,13 +191,21 @@ function createPlugin({ fetchImpl = globalThis.fetch } = {}) { auth: { provider: PROVIDER, methods: [ + { + type: "oauth", + label: "官网浏览器登录(自动读取登录态)", + authorize: browserAuthorize, + }, { type: "api", label: "填写已获授权的 QuWork 模型密钥", prompts: [{ type: "password", key: "key", message: "QuWork 授权用于第三方接入的模型密钥", placeholder: "sk-…" }], async authorize(inputs, { signal } = {}) { - const key = authKey({ type: "api", key: inputs?.key ?? inputs?.apiKey ?? inputs?.api_key ?? inputs?.value }) - if (!key) return { type: "failed", error: "请填写 QuWork 授权用于第三方接入的模型密钥。" } + const raw = inputs?.key ?? inputs?.apiKey ?? inputs?.api_key ?? inputs?.value + const key = typeof raw === "string" ? raw.trim() : "" + if (!/^sk-[A-Za-z0-9_-]{1,512}$/.test(key)) { + return { type: "failed", error: "请填写 sk- 开头的 QuWork 授权模型密钥。" } + } const error = await checkKey(key, fetchImpl, signal) if (error) return { type: "failed", error } return { type: "success", key, metadata: { source: "pasted" } } @@ -127,7 +213,16 @@ function createPlugin({ fetchImpl = globalThis.fetch } = {}) { }, ], async loader(getAuth) { - if (!authKey(await getAuth())) return {} + const auth = await getAuth() + if (!authKey(auth)) return {} + if (auth.metadata?.modelKey === false) { + return { + baseURL: LLM_BASE, + async fetch() { + throw new Error("官网登录成功,但 QuWork 没有返回模型密钥。请在 QuWork 官网创建模型密钥后重新登录。") + }, + } + } return { baseURL: LLM_BASE, apiKey: PROVIDER, diff --git a/packages/quwork/index.test.mjs b/packages/quwork/index.test.mjs index 3ae100af2..2bf49a778 100644 --- a/packages/quwork/index.test.mjs +++ b/packages/quwork/index.test.mjs @@ -14,18 +14,44 @@ test("config declares the QuWork provider and models", async () => { assert.ok(Object.keys(cfg.provider.quwork.models).length >= 10) }) -test("the setup page links to QuWork and only the model key method is registered", async () => { +test("the setup page links to QuWork and both official sign-in and model key methods are registered", async () => { const hooks = await QuWorkProvider({}) const page = readFileSync(new URL("./page/index.html", import.meta.url), "utf8") assert.equal(hooks.auth.provider, "quwork") - assert.deepEqual(hooks.auth.methods.map((method) => method.type), ["api"]) + assert.deepEqual(hooks.auth.methods.map((method) => method.type), ["oauth", "api"]) assert.match(page, /href="https:\/\/quwork\.cn\/" target="_self"/) assert.doesNotMatch(page, / { + const calls = [] + const hooks = createPlugin({ + fetchImpl: async (url, init) => { + calls.push({ url, authorization: init.headers.authorization }) + return Response.json({ data: [] }) + }, + browser: { + find: () => true, + open: async () => ({ + credentials: async () => ({ webToken: "web-token", llmToken: "sk-browser" }), + close: async () => {}, + }), + }, + }) + const desc = await hooks.auth.methods[0].authorize() + assert.equal(desc.opened, true) + assert.equal(desc.method, "auto") + assert.deepEqual(await desc.callback(), { + type: "success", + key: "sk-browser", + metadata: { source: "browser", accessToken: "web-token", modelKey: true }, + }) + assert.deepEqual(calls, [{ url: "https://llm.quwork.cn/v1/models", authorization: "Bearer sk-browser" }]) +}) + test("the loader sends the active key only to the model gateway and rejects redirects", async () => { const calls = [] const hooks = createPlugin({ fetchImpl: async (url, init) => { @@ -55,7 +81,7 @@ test("key setup validates only the model key with a read-only request", async () return Response.json({ data: [] }) }, }) - const method = hooks.auth.methods[0] + const method = hooks.auth.methods[1] assert.equal((await method.authorize({ key: "000000" })).type, "failed") assert.equal(calls.length, 0) assert.deepEqual(await method.authorize({ key: " sk-test " }), { diff --git a/packages/quwork/package.json b/packages/quwork/package.json index 6bedfb651..e861bf1d8 100644 --- a/packages/quwork/package.json +++ b/packages/quwork/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-quwork-auth", - "version": "0.1.3", + "version": "0.1.4", "description": "QuWork (Clawork) provider for OpenCode and Magpie with an official website shortcut and authorized model key setup", "type": "module", "main": "./opencode.mjs", @@ -9,6 +9,7 @@ }, "files": [ "index.mjs", + "browser.mjs", "opencode.mjs", "opencode2.mjs", "README.md", diff --git a/packages/quwork/page/index.html b/packages/quwork/page/index.html index 4bef8a9a4..496c9495d 100644 --- a/packages/quwork/page/index.html +++ b/packages/quwork/page/index.html @@ -11,18 +11,18 @@

QuWork 接入

-

请在 QuWork 官网登录账号。Magpie 的模型调用需要 QuWork 授权用于第三方接入的模型密钥。

+

登录时选择「官网浏览器登录」,插件会打开专用浏览器窗口,在 QuWork 官网完成登录并自动读取登录态。

官网登录

-

在官网右上角点「注册 / 登录」,选择短信验证码或微信登录。

+

在官网右上角点「注册 / 登录」,选择短信验证码或微信登录;也可以直接使用 Magpie 的官网浏览器登录。

在 Magpie 内打开官网

如果页面没有跳转,请复制 https://quwork.cn/ 到系统浏览器打开。

积分余额

-

持有有效旧版积分凭据的账号可在 Magpie 额度(Quota)→ QuWork 查看余额。通过模型密钥接入的账号请在 QuWork 官方入口查看积分。

+

官网登录成功后,Magpie 会读取账号 token;如果 QuWork 同时返回模型凭据,额度页会显示积分并可直接调用模型。

@@ -32,7 +32,7 @@

供应商状态

接入 Magpie

-

获得 QuWork 授权的模型密钥后,前往 供应商 → QuWork → 登录 填写密钥。自动关联官网账号需要 QuWork 提供面向 Magpie 的授权接口。

+

如果官网登录没有返回模型凭据,获得 QuWork 授权的模型密钥后,前往 供应商 → QuWork → 登录 填写 sk- 密钥。

如果供应商列表里还没有 QuWork,在 插件 → 已安装 启用此插件。必要时重启 Magpie。

From 6758749d3c3f1645193f12946c04a81db1f8c543 Mon Sep 17 00:00:00 2001 From: kshu06537-bot Date: Wed, 18 Nov 2026 20:55:09 +0800 Subject: [PATCH 6/7] quwork 0.1.5: add native daily check-in --- packages/quwork/README.md | 11 ++ packages/quwork/index.mjs | 284 ++++++++++++++++++++++++++++++++ packages/quwork/index.test.mjs | 179 ++++++++++++++++++++ packages/quwork/package.json | 8 +- packages/quwork/page/index.html | 7 + registry.json | 2 +- 6 files changed, 486 insertions(+), 5 deletions(-) diff --git a/packages/quwork/README.md b/packages/quwork/README.md index cc0c2662d..68015bc9d 100644 --- a/packages/quwork/README.md +++ b/packages/quwork/README.md @@ -10,6 +10,17 @@ 2. 在弹出的专用浏览器窗口里打开 QuWork 官网,点「注册 / 登录」,选择短信验证码或微信登录。手机号和验证码只在官网页面填写。 3. 登录成功后,Magpie 会读取官网 localStorage 中的 `quwork_web_token`,并尝试从登录响应中取得 `llm_token`。如果上游没有返回模型凭据,登录菜单里仍可填写 QuWork 授权用于第三方接入的 `sk-` 模型密钥。 +## 每日签到 + +插件实现了 Magpie 的 `auth.checkin` 钩子,签到由 Magpie 原生调度,不会在插件后台自行循环请求。 + +1. **自动签到**:打开 **设置 → 用量 → 插件 → QuWork → 每日签到**(该开关默认关闭)。Magpie 会按北京时间每天检查一次;失败后会在当天稍后重试。 +2. **手动签到**:在 **供应商 → QuWork → 账号用量卡片** 点「立即签到」。签到成功会显示获得的积分;今日已签到会显示完成状态。 +3. 签到使用官网浏览器登录保存的账号 token。只填写 `sk-` 模型密钥的账号不能签到,需要先重新用「官网浏览器登录」建立账号凭据。 +4. 插件不会伪造签到结果:上游未确认时会返回失败或未签到状态,请以 QuWork 官网记录为准。 + +签到钩子只在 Magpie 中生效;OpenCode 2.x 的适配层不提供签到。 + ## 积分余额 模型密钥用于模型调用,个人账号积分请在 QuWork 官方入口查看。已有有效旧版积分凭据的账号仍可在 Magpie 的「额度(Quota)」页查看总余额、限时积分和永久积分,具体字段以上游返回为准。也可运行 `magpie quota quwork`。 diff --git a/packages/quwork/index.mjs b/packages/quwork/index.mjs index 423a1e348..f51df8fce 100644 --- a/packages/quwork/index.mjs +++ b/packages/quwork/index.mjs @@ -4,6 +4,8 @@ import { findBrowser, openChromeSession } from "./browser.mjs" const PROVIDER = "quwork" const LLM_BASE = "https://llm.quwork.cn/v1" const ACCOUNT_BASE = "https://llm.rrzu.com" +const ACCOUNT_BASES = [ACCOUNT_BASE, "https://qurwork-llm.rrzu.com"] +const CHECKIN_PATH = "/api/user/checkin" const FALLBACK_VERSION = "1.7.5" const BALANCE_TTL_MS = 60_000 const UPSTREAM_TIMEOUT_MS = 15_000 @@ -54,6 +56,264 @@ function usageError(error) { return { error, signIn: "kept", windows: [] } } +function accountAccessToken(auth) { + const token = auth?.metadata?.accessToken + if (typeof token === "string" && token.trim()) return token.trim() + if (auth?.metadata?.source === "browser" && typeof auth?.access === "string" && auth.access.trim()) { + return auth.access.trim() + } + return "" +} + +function booleanValue(value) { + if (typeof value === "boolean") return value + if (value === 1 || value === "1" || value === "true") return true + if (value === 0 || value === "0" || value === "false") return false + return null +} + +function checkinData(payload) { + const data = payload && typeof payload === "object" && payload.data !== undefined ? payload.data : payload + return data && typeof data === "object" && !Array.isArray(data) ? data : {} +} + +function checkinMessage(payload, data) { + const value = payload?.message ?? data?.message ?? data?.msg + return typeof value === "string" ? value.replace(/\s+/g, " ").trim().slice(0, 200) : "" +} + +function beijingDate(now = Date.now()) { + const stamp = now instanceof Date ? now.getTime() : Number(now) + return new Date((Number.isFinite(stamp) ? stamp : Date.now()) + 8 * 60 * 60 * 1000).toISOString().slice(0, 10) +} + +function dateOnly(value) { + const match = String(value ?? "").match(/(\d{4})[-/](\d{1,2})[-/](\d{1,2})/) + return match ? `${match[1]}-${match[2].padStart(2, "0")}-${match[3].padStart(2, "0")}` : "" +} + +function checkinRecords(data) { + for (const candidate of [data?.records, data?.stats?.records, data?.history, data?.stats?.history]) { + if (Array.isArray(candidate)) return candidate + } + return [] +} + +function todayRecord(data, now = Date.now()) { + const today = beijingDate(now) + return checkinRecords(data).find((record) => dateOnly(record?.checkin_date ?? record?.date) === today) ?? null +} + +function checkedToday(data, now = Date.now()) { + const stats = data?.stats ?? {} + const flags = [ + data?.checked_in_today, + data?.checkedInToday, + data?.today_checked, + data?.is_checked_in, + data?.checked_in, + stats?.checked_in_today, + stats?.checkedInToday, + stats?.today_checked, + stats?.is_checked_in, + ] + let sawFalse = false + for (const value of flags) { + const answer = booleanValue(value) + if (answer === true) return true + if (answer === false) sawFalse = true + } + if (todayRecord(data, now)) return true + const dates = [ + data?.checkin_date, + data?.last_checkin_date, + data?.lastCheckinDate, + stats?.checkin_date, + stats?.last_checkin_date, + stats?.lastCheckinDate, + ] + if (dates.some((value) => dateOnly(value) === beijingDate(now))) return true + if (sawFalse) return false + return null +} + +function creditOf(data) { + for (const value of [ + data?.quota_awarded, + data?.reward_points, + data?.points_awarded, + data?.awarded_points, + data?.credit, + data?.reward, + data?.points, + data?.stats?.today_quota, + data?.stats?.today_points, + ]) { + const amount = pointsNumber(value) + if (amount !== null) return amount + } + return null +} + +function todayCreditOf(data, now = Date.now()) { + const record = todayRecord(data, now) + if (record) { + const amount = creditOf(record) + if (amount !== null) return amount + } + for (const value of [data?.today_quota, data?.today_points, data?.stats?.today_quota, data?.stats?.today_points]) { + const amount = pointsNumber(value) + if (amount !== null) return amount + } + return null +} + +function streakOf(data) { + for (const value of [ + data?.streak, + data?.continuous_days, + data?.checkin_streak, + data?.consecutive_days, + data?.stats?.streak, + data?.stats?.continuous_days, + data?.stats?.checkin_streak, + ]) { + const amount = pointsNumber(value) + if (amount !== null) return Math.round(amount) + } + return null +} + +function outcomeFromMessage(message) { + if (/已签到|已经签到|今日已签|重复签到|already\s*(?:checked|signed)/i.test(message)) return "done" + if (/未启用|未开启|未开放|disabled|not\s*enabled/i.test(message)) return "inactive" + if (/captcha|验证码|人机|turnstile|challenge/i.test(message)) return "captcha" + return "" +} + +async function checkinHttp(method, accessToken, fetchImpl) { + let last = null + for (const base of ACCOUNT_BASES) { + try { + const response = await fetchImpl(`${base}${CHECKIN_PATH}`, { + method, + headers: { + ...CLIENT_HEADERS, + authorization: `Bearer ${accessToken}`, + ...(method === "POST" ? { "content-type": "application/json" } : {}), + }, + ...(method === "POST" ? { body: "{}" } : {}), + redirect: "error", + signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS), + }) + const text = await response.text().catch(() => "") + let payload = null + try { + payload = text ? JSON.parse(text) : null + } catch {} + const result = { status: response.status, ok: response.ok, payload, text } + if (response.status === 401 || response.status === 403) return { ...result, kind: "auth" } + if (response.ok) return { ...result, kind: "ok" } + if (response.status >= 500 && payload && typeof payload === "object" && payload.success === false) { + if (outcomeFromMessage(checkinMessage(payload, checkinData(payload)))) { + return { ...result, kind: "http" } + } + } + if (response.status === 404 || response.status === 405 || response.status === 501 || response.status >= 500) { + last = result + continue + } + return { ...result, kind: "http" } + } catch (error) { + last = { status: 0, ok: false, payload: null, text: "", error } + } + } + return last ? { ...last, kind: last.status ? "http" : "network" } : { status: 0, ok: false, payload: null, text: "", kind: "network" } +} + +function interpretCheckinStatus(result, now = Date.now()) { + if (result.kind === "auth") { + return { outcome: "failed", message: "QuWork 登录已过期,请重新在官网登录。" } + } + if (result.kind === "network") { + return { outcome: "failed", message: "暂时无法连接 QuWork 签到服务,请稍后再试。" } + } + const payload = result.payload + const data = checkinData(payload) + const message = checkinMessage(payload, data) + if (payload && typeof payload === "object" && payload.success === false) { + const outcome = outcomeFromMessage(message) + if (outcome) return { outcome, message: message || (outcome === "done" ? "今日已签到。" : "当前无法签到。") } + return { outcome: "failed", message: message || `QuWork 未确认签到状态(HTTP ${result.status})。` } + } + if (booleanValue(data.enabled) === false) { + return { outcome: "inactive", message: message || "QuWork 当前未开放每日签到。" } + } + const checked = checkedToday(data, now) + if (checked === true) { + const answer = { outcome: "done", message: message || "今日已签到。" } + const credit = todayCreditOf(data, now) + if (credit !== null) answer.credit = credit + return answer + } + if (checked === false) return { claim: true } + if (result.kind === "http") { + if (result.status === 429) return { outcome: "failed", message: "QuWork 限制了签到请求,请稍后再试。" } + return { outcome: "failed", message: message || `暂时无法读取 QuWork 签到状态(HTTP ${result.status})。` } + } + if (result.kind === "ok") return { claim: true } + return { outcome: "failed", message: "QuWork 未返回可识别的签到状态。" } +} + +async function interpretCheckinClaim(result, accessToken, fetchImpl, now = Date.now()) { + if (result.kind === "auth") { + return { outcome: "failed", message: "QuWork 登录已过期,请重新在官网登录。" } + } + if (result.kind === "network") { + return { outcome: "failed", message: "暂时无法连接 QuWork 签到服务,请稍后再试。" } + } + const payload = result.payload + const data = checkinData(payload) + const message = checkinMessage(payload, data) + if (payload && typeof payload === "object" && payload.success === false) { + const outcome = outcomeFromMessage(message) + if (outcome === "done") return { outcome, message: message || "今日已签到。" } + if (outcome === "inactive" || outcome === "captcha") { + return { outcome, message: message || (outcome === "captcha" ? "QuWork 要求人工验证,请在官网完成签到。" : "QuWork 当前未开放每日签到。") } + } + return { outcome: "failed", message: message || `QuWork 未确认签到结果(HTTP ${result.status})。` } + } + if (result.kind === "ok") { + const credit = creditOf(data) + const streak = streakOf(data) + const answer = { + outcome: "claimed", + message: message || (credit !== null ? `已签到 +${credit}` : "签到成功。"), + } + if (credit !== null) answer.credit = credit + if (streak !== null) answer.streak = streak + return answer + } + if (result.status === 429) return { outcome: "failed", message: "QuWork 限制了签到请求,请稍后再试。" } + const after = interpretCheckinStatus(await checkinHttp("GET", accessToken, fetchImpl), now) + if (after.outcome === "done") { + const answer = { outcome: "claimed", message: after.message || message || "签到成功。" } + if (after.credit !== undefined) answer.credit = after.credit + if (after.streak !== undefined) answer.streak = after.streak + return answer + } + if (after.outcome === "inactive" || after.outcome === "captcha") return after + return { outcome: "failed", message: message || "QuWork 未明确确认签到结果,请在官网核对。" } +} + +async function runCheckin(accessToken, fetchImpl) { + const now = Date.now() + const status = interpretCheckinStatus(await checkinHttp("GET", accessToken, fetchImpl), now) + if (status.outcome) return status + if (!status.claim) return { outcome: "failed", message: "QuWork 未返回可识别的签到状态。" } + return interpretCheckinClaim(await checkinHttp("POST", accessToken, fetchImpl), accessToken, fetchImpl, now) +} + async function fetchUsage(accessToken, fetchImpl) { try { const response = await fetchImpl(`${ACCOUNT_BASE}/api/user/self`, { @@ -102,6 +362,7 @@ async function checkKey(key, fetchImpl, signal) { function createPlugin({ fetchImpl = globalThis.fetch, browser = { find: findBrowser, open: openChromeSession } } = {}) { const balanceCache = new Map() + const checkinInFlight = new Map() async function browserAuthorize(_inputs, { signal } = {}) { if (!browser.find()) { @@ -262,6 +523,29 @@ function createPlugin({ fetchImpl = globalThis.fetch, browser = { find: findBrow balanceCache.set(cacheKey, entry) return entry.result }, + async checkin(getAuth) { + let auth + try { + auth = await getAuth() + } catch { + return { outcome: "failed", message: "无法读取 QuWork 登录信息,请重新登录。" } + } + const accessToken = accountAccessToken(auth) + if (!accessToken) { + return { + outcome: "ineligible", + message: "签到需要官网浏览器登录的账号凭据;仅 sk- 模型密钥不能签到。", + } + } + const cacheKey = createHash("sha256").update(accessToken).digest("hex") + const running = checkinInFlight.get(cacheKey) + if (running) return running + const task = runCheckin(accessToken, fetchImpl) + .catch(() => ({ outcome: "failed", message: "签到失败,请稍后再试。" })) + .finally(() => checkinInFlight.delete(cacheKey)) + checkinInFlight.set(cacheKey, task) + return task + }, }, } } diff --git a/packages/quwork/index.test.mjs b/packages/quwork/index.test.mjs index 2bf49a778..5b2441673 100644 --- a/packages/quwork/index.test.mjs +++ b/packages/quwork/index.test.mjs @@ -4,6 +4,12 @@ import { readFileSync } from "node:fs" import { QuWorkProvider, _internal } from "./index.mjs" const { createPlugin } = _internal +const today = () => new Date(Date.now() + 8 * 60 * 60 * 1000).toISOString().slice(0, 10) +const browserAccount = (accessToken = "web-token") => async () => ({ + type: "api", + key: "sk-test", + metadata: { source: "browser", accessToken, modelKey: true }, +}) test("config declares the QuWork provider and models", async () => { const hooks = await QuWorkProvider({}) @@ -20,10 +26,12 @@ test("the setup page links to QuWork and both official sign-in and model key met assert.equal(hooks.auth.provider, "quwork") assert.deepEqual(hooks.auth.methods.map((method) => method.type), ["oauth", "api"]) assert.match(page, /href="https:\/\/quwork\.cn\/" target="_self"/) + assert.match(page, /每日签到/) assert.doesNotMatch(page, / { @@ -129,3 +137,174 @@ test("quota treats missing data, expired credentials and refusals as distinct st assert.doesNotMatch(result.error, /not-for-display/) } }) + +test("checkin reports done when the account already checked in today", async () => { + const calls = [] + const hooks = createPlugin({ + fetchImpl: async (url, init) => { + calls.push({ url, method: init.method ?? "GET" }) + return Response.json({ + success: true, + data: { + enabled: true, + stats: { + checked_in_today: true, + records: [{ checkin_date: today(), quota_awarded: 100 }], + }, + }, + }) + }, + }) + assert.deepEqual(await hooks.auth.checkin(browserAccount()), { + outcome: "done", + credit: 100, + message: "今日已签到。", + }) + assert.deepEqual(calls, [{ url: "https://llm.rrzu.com/api/user/checkin", method: "GET" }]) +}) + +test("checkin claims once and returns the awarded points", async () => { + const calls = [] + const hooks = createPlugin({ + fetchImpl: async (url, init) => { + calls.push({ url, method: init.method ?? "GET", headers: init.headers, body: init.body }) + if (init.method === "POST") { + return Response.json({ + success: true, + message: "签到成功", + data: { quota_awarded: 100, checkin_date: today() }, + }) + } + return Response.json({ + success: true, + data: { enabled: true, stats: { checked_in_today: false } }, + }) + }, + }) + assert.deepEqual(await hooks.auth.checkin(browserAccount()), { + outcome: "claimed", + credit: 100, + message: "签到成功", + }) + assert.deepEqual(calls.map((call) => call.method), ["GET", "POST"]) + assert.equal(calls[1].headers.authorization, "Bearer web-token") + assert.equal(calls[1].headers["content-type"], "application/json") + assert.equal(calls[1].body, "{}") +}) + +test("checkin treats an already-completed claim as done", async () => { + const hooks = createPlugin({ + fetchImpl: async (_url, init) => { + if (init.method === "POST") return Response.json({ success: false, message: "今日已签到" }) + return Response.json({ + success: true, + data: { enabled: true, stats: { checked_in_today: false } }, + }) + }, + }) + assert.deepEqual(await hooks.auth.checkin(browserAccount()), { + outcome: "done", + message: "今日已签到", + }) +}) + +test("checkin is ineligible for a pasted model key and makes no request", async () => { + let called = false + const hooks = createPlugin({ + fetchImpl: async () => { + called = true + throw new Error("unexpected request") + }, + }) + const result = await hooks.auth.checkin(async () => ({ + type: "api", + key: "sk-test", + metadata: { source: "pasted" }, + })) + assert.equal(result.outcome, "ineligible") + assert.match(result.message, /官网浏览器登录/) + assert.equal(called, false) +}) + +test("checkin reports an expired website session without trying to claim", async () => { + const calls = [] + const hooks = createPlugin({ + fetchImpl: async (_url, init) => { + calls.push(init.method ?? "GET") + return Response.json({ success: false, message: "unauthorized" }, { status: 401 }) + }, + }) + assert.deepEqual(await hooks.auth.checkin(browserAccount()), { + outcome: "failed", + message: "QuWork 登录已过期,请重新在官网登录。", + }) + assert.deepEqual(calls, ["GET"]) +}) + +test("checkin falls back to the secondary account host", async () => { + const calls = [] + const hooks = createPlugin({ + fetchImpl: async (url) => { + calls.push(url) + if (url.startsWith("https://llm.rrzu.com/")) return new Response("", { status: 404 }) + return Response.json({ + success: true, + data: { enabled: true, stats: { checked_in_today: true } }, + }) + }, + }) + assert.deepEqual(await hooks.auth.checkin(browserAccount()), { + outcome: "done", + message: "今日已签到。", + }) + assert.deepEqual(calls, [ + "https://llm.rrzu.com/api/user/checkin", + "https://qurwork-llm.rrzu.com/api/user/checkin", + ]) +}) + +test("checkin treats a disabled upstream feature as inactive", async () => { + const hooks = createPlugin({ + fetchImpl: async () => Response.json({ success: false, message: "签到功能未启用" }), + }) + assert.deepEqual(await hooks.auth.checkin(browserAccount()), { + outcome: "inactive", + message: "签到功能未启用", + }) +}) + +test("checkin verifies an ambiguous claim by re-reading the status", async () => { + const calls = [] + const hooks = createPlugin({ + fetchImpl: async (url, init) => { + calls.push({ url, method: init.method ?? "GET" }) + if (init.method === "POST") { + return url.startsWith("https://llm.rrzu.com/") + ? new Response("", { status: 500 }) + : new Response("", { status: 404 }) + } + if (calls.length === 1) { + return Response.json({ + success: true, + data: { enabled: true, stats: { checked_in_today: false } }, + }) + } + return Response.json({ + success: true, + data: { + enabled: true, + stats: { + checked_in_today: true, + records: [{ checkin_date: today(), quota_awarded: 100 }], + }, + }, + }) + }, + }) + assert.deepEqual(await hooks.auth.checkin(browserAccount()), { + outcome: "claimed", + credit: 100, + message: "今日已签到。", + }) + assert.deepEqual(calls.map((call) => call.method), ["GET", "POST", "POST", "GET"]) +}) diff --git a/packages/quwork/package.json b/packages/quwork/package.json index e861bf1d8..64d475dba 100644 --- a/packages/quwork/package.json +++ b/packages/quwork/package.json @@ -1,7 +1,7 @@ { "name": "@magpie-community/opencode-quwork-auth", - "version": "0.1.4", - "description": "QuWork (Clawork) provider for OpenCode and Magpie with an official website shortcut and authorized model key setup", + "version": "0.1.5", + "description": "QuWork (Clawork) provider for OpenCode and Magpie with official website sign-in, daily check-in and authorized model key setup", "type": "module", "main": "./opencode.mjs", "exports": { @@ -33,8 +33,8 @@ "magpie": { "name": "QuWork", "summary": { - "en": "QuWork community integration with an official website shortcut and authorized model key setup.", - "zh": "QuWork 社区接入,提供官网登录入口和授权模型密钥配置。" + "en": "QuWork community integration with official website sign-in, daily check-in and authorized model key setup.", + "zh": "QuWork 社区接入,提供官网登录、每日签到和授权模型密钥配置。" }, "icon": "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA2NCA2NCI+PHJlY3Qgd2lkdGg9IjY0IiBoZWlnaHQ9IjY0IiByeD0iMTQiIGZpbGw9IiMyZjZmZWQiLz48dGV4dCB4PSIzMiIgeT0iNDUiIGZvbnQtZmFtaWx5PSJBcmlhbCxIZWx2ZXRpY2Esc2Fucy1zZXJpZiIgZm9udC1zaXplPSIzOCIgZm9udC13ZWlnaHQ9IjcwMCIgdGV4dC1hbmNob3I9Im1pZGRsZSIgZmlsbD0iI2ZmZmZmZiI+UTwvdGV4dD48L3N2Zz4=", "page": { diff --git a/packages/quwork/page/index.html b/packages/quwork/page/index.html index 496c9495d..e23d64ad5 100644 --- a/packages/quwork/page/index.html +++ b/packages/quwork/page/index.html @@ -25,6 +25,13 @@

积分余额

官网登录成功后,Magpie 会读取账号 token;如果 QuWork 同时返回模型凭据,额度页会显示积分并可直接调用模型。

+
+

每日签到

+

自动签到:在 设置 → 用量 → 插件 → QuWork 打开「每日签到」(默认关闭)。

+

手动签到:在 供应商 → QuWork → 账号用量卡片 点「立即签到」。

+

签到需要官网浏览器登录保存的账号 token;只填写 sk- 模型密钥的账号不能签到。

+
+

供应商状态

正在读取…

diff --git a/registry.json b/registry.json index 289eb3ce0..9637c201f 100644 --- a/registry.json +++ b/registry.json @@ -306,6 +306,6 @@ "icon": "https://raw.githubusercontent.com/pmndre/pine/next/docs/images/logo-light.svg", "summary": { "en": "Pine (pmndre/pine, the event-driven agent harness on pi's SDK) on magpie's Agents page: pick one of magpie's models and magpie writes its gateway and catalog into ~/.pine/models.json and the model into pine.json, so new conversations start on it. Restart Pine after a change; unofficial.", "zh": "把 Pine(pmndre/pine,跑在 pi SDK 上的事件驱动 Agent 框架)加到 magpie 的 Agent 页:选一个 magpie 的模型,magpie 把网关和模型目录写进 ~/.pine/models.json、把起始模型写进 pine.json,新对话就用它。换完模型要重启 Pine;非官方适配。" } }, { "package": "@magpie-community/opencode-quwork-auth", "name": "QuWork", "providers": ["quwork"], "community": true, - "summary": { "en": "QuWork community integration with an official website shortcut and authorized model key setup.", "zh": "QuWork 社区接入,提供官网登录入口和授权模型密钥配置。" } } + "summary": { "en": "QuWork community integration with official website sign-in, daily check-in and authorized model key setup.", "zh": "QuWork 社区接入,提供官网登录、每日签到和授权模型密钥配置。" } } ] } From 95789558337e04d0c7308a8bb4409d94aa4674d2 Mon Sep 17 00:00:00 2001 From: kshu06537-bot Date: Wed, 18 Nov 2026 21:04:15 +0800 Subject: [PATCH 7/7] quwork 0.1.6: use conservative check-in retries --- packages/quwork/README.md | 9 +++++++++ packages/quwork/index.mjs | 29 +++++++++++++++++------------ packages/quwork/index.test.mjs | 28 +++++++++++++++++++++++++--- packages/quwork/package.json | 2 +- packages/quwork/page/index.html | 1 + 5 files changed, 53 insertions(+), 16 deletions(-) diff --git a/packages/quwork/README.md b/packages/quwork/README.md index 68015bc9d..0e1e74939 100644 --- a/packages/quwork/README.md +++ b/packages/quwork/README.md @@ -21,6 +21,15 @@ 签到钩子只在 Magpie 中生效;OpenCode 2.x 的适配层不提供签到。 +## 降低账号风险 + +任何第三方客户端、自动签到或代调用都无法保证账号不会被限制。插件能做的只是把请求量压到最低: + +- 自动签到默认关闭;建议先在官网手动签到一次,确认账号和入口正常,再决定是否打开自动签到。 +- 登录失效、429 限流、网络错误或上游未明确确认时,插件本次不自动重试,避免 Magpie 每 30 分钟反复请求;请稍后手动签到并在官网核对。 +- 只使用自己的单账号;不要共享、出租、代签、批量注册,不要用代理轮换地区,也不要在多个客户端同时高频使用同一账号。 +- 如果 QuWork 协议或客服没有明确允许第三方客户端/自动签到,最保守的做法是只用 `sk-` 模型密钥调用模型,积分和签到都在官网手动完成。 + ## 积分余额 模型密钥用于模型调用,个人账号积分请在 QuWork 官方入口查看。已有有效旧版积分凭据的账号仍可在 Magpie 的「额度(Quota)」页查看总余额、限时积分和永久积分,具体字段以上游返回为准。也可运行 `magpie quota quwork`。 diff --git a/packages/quwork/index.mjs b/packages/quwork/index.mjs index f51df8fce..1b02b6f88 100644 --- a/packages/quwork/index.mjs +++ b/packages/quwork/index.mjs @@ -186,6 +186,7 @@ function streakOf(data) { function outcomeFromMessage(message) { if (/已签到|已经签到|今日已签|重复签到|already\s*(?:checked|signed)/i.test(message)) return "done" + if (/too\s*many|rate.?limit|请求过于频繁|操作频繁|频繁/i.test(message)) return "inactive" if (/未启用|未开启|未开放|disabled|not\s*enabled/i.test(message)) return "inactive" if (/captcha|验证码|人机|turnstile|challenge/i.test(message)) return "captcha" return "" @@ -219,24 +220,27 @@ async function checkinHttp(method, accessToken, fetchImpl) { return { ...result, kind: "http" } } } - if (response.status === 404 || response.status === 405 || response.status === 501 || response.status >= 500) { + if (response.status === 404 || response.status === 405 || response.status === 501) { last = result continue } return { ...result, kind: "http" } } catch (error) { - last = { status: 0, ok: false, payload: null, text: "", error } + return { status: 0, ok: false, payload: null, text: "", error, kind: "network" } } } - return last ? { ...last, kind: last.status ? "http" : "network" } : { status: 0, ok: false, payload: null, text: "", kind: "network" } + return last ? { ...last, kind: "http" } : { status: 0, ok: false, payload: null, text: "", kind: "network" } } function interpretCheckinStatus(result, now = Date.now()) { if (result.kind === "auth") { - return { outcome: "failed", message: "QuWork 登录已过期,请重新在官网登录。" } + return { outcome: "ineligible", message: "QuWork 登录已过期,请重新在官网登录后再签到。" } } if (result.kind === "network") { - return { outcome: "failed", message: "暂时无法连接 QuWork 签到服务,请稍后再试。" } + return { outcome: "inactive", message: "暂时无法连接 QuWork 签到服务;本次不自动重试,请稍后手动签到。" } + } + if (result.status === 429) { + return { outcome: "inactive", message: "QuWork 限制了签到请求;本次不自动重试,请稍后手动签到。" } } const payload = result.payload const data = checkinData(payload) @@ -258,19 +262,21 @@ function interpretCheckinStatus(result, now = Date.now()) { } if (checked === false) return { claim: true } if (result.kind === "http") { - if (result.status === 429) return { outcome: "failed", message: "QuWork 限制了签到请求,请稍后再试。" } - return { outcome: "failed", message: message || `暂时无法读取 QuWork 签到状态(HTTP ${result.status})。` } + return { outcome: "inactive", message: message || `暂时无法读取 QuWork 签到状态(HTTP ${result.status});请稍后手动签到。` } } if (result.kind === "ok") return { claim: true } - return { outcome: "failed", message: "QuWork 未返回可识别的签到状态。" } + return { outcome: "inactive", message: "QuWork 未返回可识别的签到状态;请到官网核对。" } } async function interpretCheckinClaim(result, accessToken, fetchImpl, now = Date.now()) { if (result.kind === "auth") { - return { outcome: "failed", message: "QuWork 登录已过期,请重新在官网登录。" } + return { outcome: "ineligible", message: "QuWork 登录已过期,请重新在官网登录后再签到。" } } if (result.kind === "network") { - return { outcome: "failed", message: "暂时无法连接 QuWork 签到服务,请稍后再试。" } + return { outcome: "inactive", message: "暂时无法连接 QuWork 签到服务;本次不自动重试,请稍后手动签到。" } + } + if (result.status === 429) { + return { outcome: "inactive", message: "QuWork 限制了签到请求;本次不自动重试,请稍后手动签到。" } } const payload = result.payload const data = checkinData(payload) @@ -294,7 +300,6 @@ async function interpretCheckinClaim(result, accessToken, fetchImpl, now = Date. if (streak !== null) answer.streak = streak return answer } - if (result.status === 429) return { outcome: "failed", message: "QuWork 限制了签到请求,请稍后再试。" } const after = interpretCheckinStatus(await checkinHttp("GET", accessToken, fetchImpl), now) if (after.outcome === "done") { const answer = { outcome: "claimed", message: after.message || message || "签到成功。" } @@ -303,7 +308,7 @@ async function interpretCheckinClaim(result, accessToken, fetchImpl, now = Date. return answer } if (after.outcome === "inactive" || after.outcome === "captcha") return after - return { outcome: "failed", message: message || "QuWork 未明确确认签到结果,请在官网核对。" } + return { outcome: "inactive", message: message || "QuWork 未明确确认签到结果;本次不自动重试,请到官网核对。" } } async function runCheckin(accessToken, fetchImpl) { diff --git a/packages/quwork/index.test.mjs b/packages/quwork/index.test.mjs index 5b2441673..85e3052b6 100644 --- a/packages/quwork/index.test.mjs +++ b/packages/quwork/index.test.mjs @@ -235,8 +235,8 @@ test("checkin reports an expired website session without trying to claim", async }, }) assert.deepEqual(await hooks.auth.checkin(browserAccount()), { - outcome: "failed", - message: "QuWork 登录已过期,请重新在官网登录。", + outcome: "ineligible", + message: "QuWork 登录已过期,请重新在官网登录后再签到。", }) assert.deepEqual(calls, ["GET"]) }) @@ -306,5 +306,27 @@ test("checkin verifies an ambiguous claim by re-reading the status", async () => credit: 100, message: "今日已签到。", }) - assert.deepEqual(calls.map((call) => call.method), ["GET", "POST", "POST", "GET"]) + assert.deepEqual(calls.map((call) => call.method), ["GET", "POST", "GET"]) +}) + +test("checkin stops automatic retries on a rate limit", async () => { + const hooks = createPlugin({ + fetchImpl: async () => Response.json({ success: false, message: "too many requests" }, { status: 429 }), + }) + assert.deepEqual(await hooks.auth.checkin(browserAccount()), { + outcome: "inactive", + message: "QuWork 限制了签到请求;本次不自动重试,请稍后手动签到。", + }) +}) + +test("checkin stops automatic retries when the network is unavailable", async () => { + const hooks = createPlugin({ + fetchImpl: async () => { + throw new Error("offline") + }, + }) + assert.deepEqual(await hooks.auth.checkin(browserAccount()), { + outcome: "inactive", + message: "暂时无法连接 QuWork 签到服务;本次不自动重试,请稍后手动签到。", + }) }) diff --git a/packages/quwork/package.json b/packages/quwork/package.json index 64d475dba..dca790959 100644 --- a/packages/quwork/package.json +++ b/packages/quwork/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-quwork-auth", - "version": "0.1.5", + "version": "0.1.6", "description": "QuWork (Clawork) provider for OpenCode and Magpie with official website sign-in, daily check-in and authorized model key setup", "type": "module", "main": "./opencode.mjs", diff --git a/packages/quwork/page/index.html b/packages/quwork/page/index.html index e23d64ad5..1f552e84f 100644 --- a/packages/quwork/page/index.html +++ b/packages/quwork/page/index.html @@ -30,6 +30,7 @@

每日签到

自动签到:在 设置 → 用量 → 插件 → QuWork 打开「每日签到」(默认关闭)。

手动签到:在 供应商 → QuWork → 账号用量卡片 点「立即签到」。

签到需要官网浏览器登录保存的账号 token;只填写 sk- 模型密钥的账号不能签到。

+

无法保证账号不被限制;建议先确认 QuWork 官方条款,并保持单账号、低频、失败不自动重试。