diff --git a/packages/doubao-work/doubao-work.test.mjs b/packages/doubao-work/doubao-work.test.mjs index 0223a05..8df66e7 100644 --- a/packages/doubao-work/doubao-work.test.mjs +++ b/packages/doubao-work/doubao-work.test.mjs @@ -3,7 +3,7 @@ import fs from "node:fs" import os from "node:os" import path from "node:path" import { App, Page, copies } from "./cdp.mjs" -import { Doubao, NEW_TASK, CLOUD, MENU, READ, STATE, MODELS, idFor, tableFrom, APPS, binary, choose, dataDir, installedAt, hintsWin, hintsMac, owns, isChat, usageOf } from "./doubao.mjs" +import { Doubao, NEW_TASK, CLOUD, MENU, READ, STATE, MODELS, idFor, tableFrom, APPS, binary, choose, dataDir, installedAt, hintsWin, hintsMac, owns, isChat, usageOf, QUOTA, quotaOf, rateOf } from "./doubao.mjs" import { Streamer, sse, completion } from "./openai.mjs" import { flatten, parse, heldFrom } from "./prompt.mjs" import { _internal as I } from "./index.mjs" @@ -339,6 +339,7 @@ function fakePage(reads, { signedIn = true, steps = {} } = {}) { if (expr === NEW_TASK) return steps.newTask ?? "" if (expr === CLOUD) return steps.cloud ?? "" if (expr === MENU) return steps.menu ?? { rows: [] } + if (expr === QUOTA) return steps.quota ?? { error: "no quota step" } if (expr === READ) return reads.length > 1 ? reads.shift() : reads[0] if (expr.includes("chat_input_action_model")) return steps.model ?? "" if (expr.includes("insertContent")) return 10 @@ -696,3 +697,52 @@ test("picking a model from the full list presses that row in the app", async () expect(page.calls.some((c) => c.includes('"Kimi K3.1 Pro 高速"'))).toBe(true) fs.rmSync(dir, { recursive: true, force: true }) }) + +// quota/summary as the app's page answered it for a 标准套餐 account +const SUMMARY = { status: 200, body: { data: { current_subscription: { display: { product_name: "个人订阅", short_name: "标准套餐" } }, window_limit_section: { entitlement_count: 1, usage_exhausted: false, window_limit_groups: [{ feature_group: "general", window_limits: [{ end_time: 0, item_type: 0, less_than_one_percent: false, start_time: 0, used_percent: 0, window_type: 2 }] }] } }, code: 0 } } + +test("the plugin tells the plan's allowance from quota/summary instead of 暂无额度数据", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "doubao-quota-")) + const page = fakePage([], { steps: { quota: SUMMARY } }) + const d = new Doubao({ app: { start: async () => 1, dataDir: dir }, openPage: async () => page, poll: 1 }) + const p = I.createPlugin({ doubao: d }) + const u = await p.auth.usage(async () => ({})) + expect(u).toEqual({ plan: "标准套餐", windows: [{ name: "额度", used: 0 }] }) + // a window with times is named by its span and says when it resets + const w = quotaOf({ body: { data: { window_limit_section: { window_limit_groups: [{ window_limits: [ + { start_time: 1000, end_time: 1000 + 5 * 3600000, used_percent: 42.5 }, + { start_time: 1000, end_time: 1000 + 7 * 86400000, used_percent: 8 }] }] } } } }) + expect(w.windows).toEqual([{ name: "5 小时", used: 42.5, resetsAt: 1000 + 5 * 3600000 }, { name: "每周", used: 8, resetsAt: 1000 + 7 * 86400000 }]) + // an exhausted plan reads 100% + expect(quotaOf({ body: { data: { window_limit_section: { usage_exhausted: true, window_limit_groups: [{ window_limits: [{ used_percent: 99 }] }] } } } }).windows[0].used).toBe(100) + fs.rmSync(dir, { recursive: true, force: true }) +}) + +test("a quota that can't be read says why and keeps the sign-in", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "doubao-quota-")) + const mk = (quota, dataDir = dir) => I.createPlugin({ doubao: new Doubao({ app: { start: async () => 1, dataDir }, openPage: async () => fakePage([], { steps: { quota } }), poll: 1 }) }) + for (const [quota, want] of [[{ status: 401, body: null }, "过期"], [{ status: 200, body: {} }, "没有额度数据"], [{ error: "Failed to fetch" }, "Failed to fetch"]]) { + const u = await mk(quota).auth.usage(async () => ({})) + expect(u.signIn).toBe("kept") + expect(u.error).toContain(want) + } + // an app the plugin never started is not opened for a usage read + const u = await mk(SUMMARY, path.join(dir, "none")).auth.usage(async () => ({})) + expect(u.error).toContain("还没有登录") + fs.rmSync(dir, { recursive: true, force: true }) +}) + +test("a model's multiple is read from its menu row and given as rate", () => { + expect(rateOf(["2x 额度"])).toBe(2) + expect(rateOf(["×0.5"])).toBe(0.5) + expect(rateOf(["消耗 1.5 倍"])).toBe(1.5) + expect(rateOf(["256K 上下文", "V4.1"])).toBe(0) + expect(rateOf([])).toBe(0) + const table = tableFrom([{ label: "自动" }, { label: "Kimi K3.1 Pro", lines: ["x2"] }, { label: "GLM 5.3", lines: ["0.5倍额度"] }, { label: "DeepSeek V4 Pro", lines: ["推理强度"] }]) + expect(table.auto.rate).toBeUndefined() + expect(table["kimi-k3.1-pro"].rate).toBe(2) + expect(table["glm-5.3"].rate).toBe(0.5) + const out = I.models(table) + expect(out["kimi-k3.1-pro"].rate).toBe(2) + expect("rate" in out["deepseek-v4-pro"]).toBe(false) +}) diff --git a/packages/doubao-work/doubao.mjs b/packages/doubao-work/doubao.mjs index eec4ce5..5597780 100644 --- a/packages/doubao-work/doubao.mjs +++ b/packages/doubao-work/doubao.mjs @@ -55,6 +55,19 @@ export function idFor(label) { return id } +// rateOf reads the multiple a menu row says it costs from the lines under +// the model's name ("2x 额度", "×0.5", "消耗 1.5 倍"); 0 when it says none. +// Version numbers and context sizes ("V4.1", "256K") are not multiples. +export function rateOf(lines) { + for (const line of lines ?? []) { + const t = String(line ?? "") + const m = t.match(/(?:^|[^\w.])[x×]\s*(\d+(?:\.\d+)?)(?![\w.])/i) || t.match(/(\d+(?:\.\d+)?)\s*(?:[x×]|倍)(?![a-z])/i) + const n = m ? Number(m[1]) : 0 + if (n > 0) return n + } + return 0 +} + // tableFrom builds the model table ({ id: {label, name} }) from the rows // read off the menu. Nothing read means the fallback stays. export function tableFrom(rows) { @@ -68,6 +81,8 @@ export function tableFrom(rows) { // Chinese suffix) must not become one model for (let n = 2; out[id]; n++) id = idFor(label) + "-" + n out[id] = { label, name: label } + const rate = Number(r?.rate) || rateOf(r?.lines) + if (Number.isFinite(rate) && rate > 0) out[id].rate = rate } if (!Object.keys(out).length) return { ...MODELS } if (out.auto) out.auto = { ...MODELS.auto } @@ -332,7 +347,7 @@ export const MENU = js(` await wait(250); const rows = $$("[role=menuitem]", menu) .filter((e) => e.getAttribute("aria-haspopup") !== "menu") - .map((e) => ({ label: e.innerText.split("\\n")[0].trim(), upgrade: e.innerText.includes("升级") })) + .map((e) => { const l = e.innerText.split("\\n").map((x) => x.trim()).filter(Boolean); return { label: l[0] || "", lines: l.slice(1), upgrade: e.innerText.includes("升级") }; }) .filter((r) => r.label); document.body.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); return { rows }; @@ -369,6 +384,44 @@ export const READ = js(` usage: ext.context_window_usage || "", error: r.error_details ? JSON.stringify(r.error_details) : "" }; `) +// QUOTA asks the app's own page for the plan's allowance, the way the +// page's 订阅 view does (its cookies sign the call). +export const QUOTA = js(` + try { + const r = await fetch("https://www.doubao.com/alice/commerce/sale/subscription/quota/summary/", { method: "POST", credentials: "include", headers: { "content-type": "application/json" }, body: "{}" }); + const t = await r.text(); + let j = null; + try { j = JSON.parse(t); } catch {} + return { status: r.status, body: j }; + } catch (e) { return { error: String(e && e.message || e) }; } +`) + +const HOUR = 3600000 +// quotaOf turns quota/summary into magpie's usage: the plan's short name +// and one window per limit, as a percent used. A window names its span when +// the reply gives one; without times it is just 额度. +export function quotaOf(read) { + const d = read?.body?.data + if (!d || typeof d !== "object") return null + const groups = [...(d.window_limit_section?.window_limit_groups ?? []), ...(d.enterprise_window_limit_section?.window_limit_groups ?? [])] + const windows = [] + for (const g of groups) + for (const w of g?.window_limits ?? []) { + const pct = Number(w?.used_percent) + if (!Number.isFinite(pct)) continue + const span = Number(w.end_time) - Number(w.start_time) + let name = "额度" + if (w.start_time > 0 && span > 0) name = span <= 6 * HOUR ? "5 小时" : span <= 8 * 24 * HOUR ? "每周" : "本月" + const out = { name, used: Math.max(0, Math.min(100, pct)) } + if (w.less_than_one_percent && pct === 0) out.display = "不到 1%" + if (w.end_time > 0) out.resetsAt = Number(w.end_time) + windows.push(out) + } + const exhausted = d.window_limit_section?.usage_exhausted === true || d.enterprise_window_limit_section?.usage_exhausted === true + if (exhausted) for (const w of windows) w.used = 100 + return { plan: String(d.current_subscription?.display?.short_name || d.current_subscription?.display?.product_name || ""), windows } +} + export const usageOf = (raw) => { try { const u = typeof raw === "string" ? JSON.parse(raw) : raw @@ -488,6 +541,19 @@ export class Doubao { return !!this.modelList()[model] } + // quota reads the plan's allowance through the app's page. Only an app + // this plugin has started before is opened for it (its data folder + // exists), so a usage read never launches Doubao for a user who has + // not signed in here. + async quota({ signal } = {}) { + if (!(this.page && !this.page.closed)) { + if (!this.app?.start) throw new DoubaoError("没有找到豆包。", "app_missing") + if (this.app.dataDir && !fs.existsSync(this.app.dataDir)) throw new DoubaoError("还没有登录过豆包工作窗口。", "doubao_signin") + } + const page = await this.connect(signal) + return page.eval(QUOTA) + } + async connect(signal) { if (this.page && !this.page.closed) return this.page const port = await this.app.start({ signal }) diff --git a/packages/doubao-work/index.mjs b/packages/doubao-work/index.mjs index 53749a4..97aa317 100644 --- a/packages/doubao-work/index.mjs +++ b/packages/doubao-work/index.mjs @@ -5,7 +5,7 @@ // request into the input, and reads the reply as Doubao renders it. The // client's tools are asked for as text blocks and given back // as OpenAI tool_calls. See README.md for what that costs. -import { Doubao, DoubaoError, MODELS, choose, usageOf } from "./doubao.mjs" +import { Doubao, DoubaoError, MODELS, choose, quotaOf, usageOf } from "./doubao.mjs" import { completion, sse } from "./openai.mjs" import { flatten } from "./prompt.mjs" @@ -30,6 +30,9 @@ function models(table = MODELS) { reasoning: true, attachment: false, modalities: { input: ["text"], output: ["text"] }, + // the multiple of the plan's allowance a request costs, as the menu + // writes it next to the model (none when it says none) + ...(m.rate > 0 ? { rate: m.rate } : {}), } return out } @@ -70,6 +73,22 @@ export function createPlugin({ doubao = new Doubao(), newId, pick = choose } = { auth: { provider: ID, maxConcurrency: 1, + // the plan's allowance, read through the app's own page + usage: async () => { + const fail = (error) => ({ plan: "", windows: [], error, signIn: "kept" }) + let read + try { + read = await doubao.quota({ signal: AbortSignal.timeout(25000) }) + } catch (e) { + return fail(e?.code === "app_busy" ? BUSY(pick().app.name) : String(e?.message ?? e)) + } + if (read?.error) return fail("读取豆包额度失败:" + read.error) + if (read?.status === 401 || read?.status === 403) return fail("豆包登录已过期,请重新登录豆包工作窗口。") + const u = quotaOf(read) + if (!u) return fail("豆包额度回复里没有额度数据(HTTP " + (read?.status ?? "?") + ")") + if (!u.windows.length) return fail("当前套餐没有额度限制数据") + return u + }, methods: [ { type: "oauth", diff --git a/packages/doubao-work/package.json b/packages/doubao-work/package.json index b0e0428..841ce24 100644 --- a/packages/doubao-work/package.json +++ b/packages/doubao-work/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-doubao-work-auth", - "version": "0.1.8", + "version": "0.1.9", "type": "module", "main": "./opencode.mjs", "files": [