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..0e1e74939 --- /dev/null +++ b/packages/quwork/README.md @@ -0,0 +1,41 @@ +# QuWork for Magpie + +社区供应商 `quwork`。插件会打开专用 Chrome/Edge 窗口,在 QuWork 官网完成登录;也会读取官网登录态中的账号 token,并尝试取得模型凭据。插件内置 10 个模型条目,实际可用模型由 QuWork 和账号权益决定。 + +## 安装与使用 + +在 Magpie 的「插件 → 添加插件」选择本地插件目录,或在社区仓库根目录运行 `magpie plugin add ./packages/quwork`。 + +1. 在「供应商 → QuWork → 登录」选择「官网浏览器登录(自动读取登录态)」。 +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 的适配层不提供签到。 + +## 降低账号风险 + +任何第三方客户端、自动签到或代调用都无法保证账号不会被限制。插件能做的只是把请求量压到最低: + +- 自动签到默认关闭;建议先在官网手动签到一次,确认账号和入口正常,再决定是否打开自动签到。 +- 登录失效、429 限流、网络错误或上游未明确确认时,插件本次不自动重试,避免 Magpie 每 30 分钟反复请求;请稍后手动签到并在官网核对。 +- 只使用自己的单账号;不要共享、出租、代签、批量注册,不要用代理轮换地区,也不要在多个客户端同时高频使用同一账号。 +- 如果 QuWork 协议或客服没有明确允许第三方客户端/自动签到,最保守的做法是只用 `sk-` 模型密钥调用模型,积分和签到都在官网手动完成。 + +## 积分余额 + +模型密钥用于模型调用,个人账号积分请在 QuWork 官方入口查看。已有有效旧版积分凭据的账号仍可在 Magpie 的「额度(Quota)」页查看总余额、限时积分和永久积分,具体字段以上游返回为准。也可运行 `magpie quota 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 许可。 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 new file mode 100644 index 000000000..1b02b6f88 --- /dev/null +++ b/packages/quwork/index.mjs @@ -0,0 +1,559 @@ +import { createHash } from "node:crypto" +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 +const OFFICIAL_LOGIN = "https://quwork.cn/" + +const CLIENT_HEADERS = { "x-qurwork-env": "prod", "x-qurwork-version": FALLBACK_VERSION } + +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 }, +] + +function authKey(auth) { + const key = auth?.type === "api" ? auth.key : auth?.access + return typeof key === "string" && key.trim().length >= 4 && key.trim().length <= 4096 ? key.trim() : "" +} + +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) { + 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 (/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 "" +} + +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) { + last = result + continue + } + return { ...result, kind: "http" } + } catch (error) { + return { status: 0, ok: false, payload: null, text: "", error, 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: "ineligible", message: "QuWork 登录已过期,请重新在官网登录后再签到。" } + } + if (result.kind === "network") { + return { outcome: "inactive", message: "暂时无法连接 QuWork 签到服务;本次不自动重试,请稍后手动签到。" } + } + if (result.status === 429) { + return { outcome: "inactive", 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") { + return { outcome: "inactive", message: message || `暂时无法读取 QuWork 签到状态(HTTP ${result.status});请稍后手动签到。` } + } + if (result.kind === "ok") return { claim: true } + return { outcome: "inactive", message: "QuWork 未返回可识别的签到状态;请到官网核对。" } +} + +async function interpretCheckinClaim(result, accessToken, fetchImpl, now = Date.now()) { + if (result.kind === "auth") { + return { outcome: "ineligible", message: "QuWork 登录已过期,请重新在官网登录后再签到。" } + } + if (result.kind === "network") { + return { outcome: "inactive", message: "暂时无法连接 QuWork 签到服务;本次不自动重试,请稍后手动签到。" } + } + if (result.status === 429) { + return { outcome: "inactive", 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 + } + 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: "inactive", 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`, { + headers: { ...CLIENT_HEADERS, authorization: `Bearer ${accessToken}` }, + redirect: "error", + signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS), + }) + if (!response.ok) { + await response.body?.cancel().catch(() => {}) + 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})。`) + } + const payload = await response.json() + const entitlement = payload?.data?.points_entitlement + const total = pointsNumber(entitlement?.total_points) + if (payload?.success !== true || total === null) return usageError("QuWork 未返回有效的积分余额。") + const limited = pointsNumber(entitlement.limited_points) + const permanent = pointsNumber(entitlement.permanent_points) + const plan = entitlement.active_subscription?.plan_name + const parts = [] + if (limited !== null) parts.push(`限时 ${limited}`) + if (permanent !== null) parts.push(`永久 ${permanent}`) + const detail = parts.length ? `(${parts.join(" · ")})` : "" + return { plan: typeof plan === "string" && plan.trim() ? plan.trim() : "积分", balance: `${total} 积分${detail}`, windows: [] } + } catch { + return usageError("暂时无法读取 QuWork 积分,请稍后查看。") + } +} + +async function checkKey(key, fetchImpl, signal) { + try { + const timeout = AbortSignal.timeout(UPSTREAM_TIMEOUT_MS) + const response = await fetchImpl(`${LLM_BASE}/models`, { + headers: { ...CLIENT_HEADERS, authorization: `Bearer ${key}` }, + redirect: "error", + signal: signal ? AbortSignal.any([signal, timeout]) : timeout, + }) + await response.body?.cancel().catch(() => {}) + return response.ok ? null : `QuWork 未接受模型密钥(HTTP ${response.status})。` + } catch { + return signal?.aborted ? "QuWork 登录已取消。" : "连接 QuWork 模型服务失败,请稍后查看。" + } +} + +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()) { + 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 ??= {} + config.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: "官网浏览器登录(自动读取登录态)", + authorize: browserAuthorize, + }, + { + type: "api", + label: "填写已获授权的 QuWork 模型密钥", + prompts: [{ type: "password", key: "key", message: "QuWork 授权用于第三方接入的模型密钥", placeholder: "sk-…" }], + async authorize(inputs, { signal } = {}) { + 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" } } + }, + }, + ], + async loader(getAuth) { + 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, + async fetch(input, init) { + const isRequest = input instanceof Request + const target = new URL(isRequest ? input.url : String(input)) + if (!target.href.startsWith(`${LLM_BASE}/`)) { + throw new Error("QuWork 模型密钥仅用于 QuWork 模型网关。") + } + const key = authKey(await getAuth()) + 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) + return fetchImpl(isRequest ? input : target.href, { ...init, headers, redirect: "error" }) + }, + } + }, + async usage(getAuth) { + const auth = await getAuth() + 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("当前为模型密钥接入。请在 QuWork 官方入口查看账号积分。") + } + const now = Date.now() + for (const [cacheKey, entry] of balanceCache) { + if (entry.until <= now) balanceCache.delete(cacheKey) + } + const cacheKey = createHash("sha256").update(accessToken).digest("hex") + const cached = balanceCache.get(cacheKey) + if (cached) return cached.result + const entry = { until: Infinity, result: null } + entry.result = fetchUsage(accessToken, fetchImpl).finally(() => { + entry.until = Date.now() + BALANCE_TTL_MS + }) + 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 + }, + }, + } +} + +export const QuWorkProvider = async () => createPlugin() +export const _internal = { createPlugin } diff --git a/packages/quwork/index.test.mjs b/packages/quwork/index.test.mjs new file mode 100644 index 000000000..85e3052b6 --- /dev/null +++ b/packages/quwork/index.test.mjs @@ -0,0 +1,332 @@ +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 +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({}) + 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("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), ["oauth", "api"]) + assert.match(page, /href="https:\/\/quwork\.cn\/" target="_self"/) + assert.match(page, /每日签到/) + 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) => { + calls.push({ url, init }) + return Response.json({ data: [] }) + } }) + let auth = { type: "api", key: "sk-test" } + const options = await hooks.auth.loader(async () => auth) + assert.equal(options.apiKey, "quwork") + assert.equal(options.baseURL, "https://llm.quwork.cn/v1") + await assert.rejects( + () => options.fetch("https://example.com/v1/models"), + /仅用于 QuWork 模型网关/, + ) + assert.equal(calls.length, 0) + auth = { type: "api", key: "sk-test-updated" } + await options.fetch(`${options.baseURL}/models`) + assert.equal(calls[0].init.headers.get("authorization"), "Bearer sk-test-updated") + assert.equal(calls[0].init.redirect, "error") +}) + +test("key setup validates only the model key with a read-only request", async () => { + const calls = [] + const hooks = createPlugin({ + fetchImpl: async (url, init) => { + calls.push({ url, method: init.method ?? "GET", authorization: init.headers.authorization }) + return Response.json({ data: [] }) + }, + }) + 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 " }), { + 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 legacy accounts and deduplicates concurrent reads", async () => { + const calls = [] + const hooks = createPlugin({ fetchImpl: async (_url, init) => { + const authorization = init.headers.authorization + calls.push(authorization) + 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-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)") + 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" }, "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-test", metadata: { source: "browser", accessToken: "fixture-access" }, + })) + assert.equal(result.balance, undefined) + assert.equal(result.signIn, signIn) + assert.match(result.error, message) + 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: "ineligible", + 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", "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/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..dca790959 --- /dev/null +++ b/packages/quwork/package.json @@ -0,0 +1,57 @@ +{ + "name": "@magpie-community/opencode-quwork-auth", + "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", + "exports": { + ".": "./opencode2.mjs" + }, + "files": [ + "index.mjs", + "browser.mjs", + "opencode.mjs", + "opencode2.mjs", + "README.md", + "LICENSE", + "page/index.html", + "page/app.js", + "page/style.css" + ], + "keywords": [ + "opencode", + "opencode-plugin", + "magpie", + "quwork", + "qurwork", + "clawork" + ], + "license": "MIT", + "scripts": { + "test": "node --test" + }, + "magpie": { + "name": "QuWork", + "summary": { + "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": { + "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..4f2724393 --- /dev/null +++ b/packages/quwork/page/app.js @@ -0,0 +1,30 @@ +;(async () => { + const status = document.getElementById("status") + + async function refresh() { + try { + 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.className = "ok" + } else { + status.textContent = "请在供应商页查看 QuWork。首次安装后可重启 Magpie 再查看。" + status.className = "missing" + } + } catch { + status.textContent = "请在 Magpie 供应商页查看 QuWork 状态。" + status.className = "missing" + } + } + + try { + await magpie.ready + await refresh() + magpie.onVisibility?.((visible) => { + if (visible) refresh() + }) + } catch { + status.textContent = "在 Magpie 内打开此页即可查看供应商状态。" + } +})() diff --git a/packages/quwork/page/index.html b/packages/quwork/page/index.html new file mode 100644 index 000000000..1f552e84f --- /dev/null +++ b/packages/quwork/page/index.html @@ -0,0 +1,48 @@ + + + + + +QuWork 接入 + + + + + +
+

QuWork 接入

+

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

+ +
+

官网登录

+

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

+ 在 Magpie 内打开官网 +

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

+
+ +
+

积分余额

+

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

+
+ +
+

每日签到

+

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

+

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

+

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

+

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

+
+ +
+

供应商状态

+

正在读取…

+
+ +
+

接入 Magpie

+

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

+

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

+
+
+ + diff --git a/packages/quwork/page/style.css b/packages/quwork/page/style.css new file mode 100644 index 000000000..283240cc6 --- /dev/null +++ b/packages/quwork/page/style.css @@ -0,0 +1,57 @@ +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; +} + +.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 { + 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)); +} + +#status.ok { color: #16a34a; } +#status.missing { color: #dc2626; } diff --git a/registry.json b/registry.json index 8237e459e..9637c201f 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": "QuWork community integration with official website sign-in, daily check-in and authorized model key setup.", "zh": "QuWork 社区接入,提供官网登录、每日签到和授权模型密钥配置。" } } ] }