doubao-work 0.1.4: read the model list from Doubao's own menu (#916)

Reads Doubao Work's model list from the app's own model menu, keeps it in
models.json, and offers those models (0.1.4).

Reviewed at 43b3d5d (the author's 50c1448 plus a maintainer fix: the
config hook now keeps a model the user declared themselves, as every
other package does).

Run on mote: bun test packages/doubao-work 34 pass; bun scripts/check.mjs
doubao-work ok. Broken by hand: model lookup back on the built-in table
fails 2 tests; the old merge order fails the user-settings assertion.
Not tried: a real Doubao app (the author ran it on macOS, 8 models).
This commit is contained in:
zt8989
2026-11-10 10:31:28 +08:00
committed by GitHub
parent 042e8517b4
commit e9c7de3708
5 changed files with 240 additions and 11 deletions
+12 -2
View File
@@ -19,8 +19,18 @@ an OpenAI chat completion:
4. The client's tools are asked for as text, `<tool_call>{"name": …,
"arguments": …}</tool_call>`, and given back as `tool_calls`.
Models: 自动 (`auto`), 豆包 2.1 Lite (`doubao-2.1-lite`) and 豆包 2.1 Pro
(`doubao-2.1-pro`, needs a paid Doubao plan).
Models: the plugin reads Doubao's own model menu, so whatever the app offers
is what magpie lists. The menu row text becomes the id: 自动 (`auto`), 豆包 2.1
Lite (`doubao-2.1-lite`), 豆包 2.1 Pro (`doubao-2.1-pro`, needs a paid Doubao
plan), DeepSeek V4.1 Flash (`deepseek-v4.1-flash`), GLM 5.3 (`glm-5.3`) and so
on. Rows that open a submenu (推理强度) are not models and are skipped.
The list is read when you sign in, and again on a request once the cached list
is more than six hours old; it is kept in `models.json` under
`DOUBAO_WORK_HOME` (`~/Library/Application Support/magpie-doubao-work` on
macOS, `%LOCALAPPDATA%\magpie-doubao-work` on Windows) and read before
anything else. The three models the plugin was written with stay as the
fallback for when the menu cannot be read.
## What it costs
+71 -1
View File
@@ -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, READ, STATE, binary, dataDir, owns, usageOf } from "./doubao.mjs"
import { Doubao, NEW_TASK, CLOUD, MENU, READ, STATE, MODELS, idFor, tableFrom, binary, dataDir, owns, usageOf } from "./doubao.mjs"
import { Streamer, sse, completion } from "./openai.mjs"
import { flatten, parse, heldFrom } from "./prompt.mjs"
import { _internal as I } from "./index.mjs"
@@ -183,6 +183,58 @@ test("owns knows Doubao's chat page", () => {
expect(owns([{ url: "chrome://newtab" }, { url: "https://doubao-chat/chat" }])).toBe(false)
})
// ---- models ----
test("idFor names a model from what its menu row says", () => {
expect(idFor("自动")).toBe("auto")
expect(idFor("豆包 2.1 Lite")).toBe("doubao-2.1-lite")
expect(idFor("豆包 2.2 Turbo")).toBe("doubao-2.2-turbo")
expect(idFor("DeepSeek V4.1 Flash")).toBe("deepseek-v4.1-flash")
expect(idFor("Kimi K3.1 Pro")).toBe("kimi-k3.1-pro")
expect(idFor("GLM 5.3")).toBe("glm-5.3")
expect(idFor("星火 4.0")).toBe("model-4.0")
expect(idFor("")).toBe("auto")
expect(idFor("纯中文模型").startsWith("model-")).toBe(true)
})
test("tableFrom keeps every model row, and falls back when nothing was read", () => {
const t = tableFrom([{ label: "自动" }, { label: "GLM 5.3" }, { label: "GLM 5.3" }, { label: "" }])
expect(Object.keys(t)).toEqual(["auto", "glm-5.3"])
expect(Object.keys(tableFrom([])).sort()).toEqual(Object.keys(MODELS).sort())
})
test("models.json is read first, and discover rewrites it", async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "doubao-models-"))
const file = path.join(dir, "models.json")
fs.writeFileSync(file, JSON.stringify({
at: Date.now(),
models: { auto: MODELS.auto, "glm-5.3": { label: "GLM 5.3", name: "GLM 5.3" } },
}))
const page = fakePage([], { steps: { menu: { rows: [{ label: "自动" }, { label: "DeepSeek V4.1 Flash" }] } } })
const d = new Doubao({ app: { start: async () => 1, dataDir: dir }, openPage: async () => page, poll: 1 })
// the file wins over the built-in list, without opening the app
expect(Object.keys(d.modelList())).toEqual(["auto", "glm-5.3"])
const table = await d.discover()
expect(Object.keys(table)).toEqual(["auto", "deepseek-v4.1-flash"])
expect(Object.keys(JSON.parse(fs.readFileSync(file, "utf8")).models)).toEqual(["auto", "deepseek-v4.1-flash"])
// and the rewritten file is what the next start reads
expect(Object.keys(new Doubao({ app: { start: async () => 1, dataDir: dir } }).modelList())).toEqual(["auto", "deepseek-v4.1-flash"])
fs.rmSync(dir, { recursive: true, force: true })
})
test("ask picks a model that only the menu knows about", async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "doubao-models-"))
fs.writeFileSync(path.join(dir, "models.json"), JSON.stringify({
at: Date.now(),
models: { auto: MODELS.auto, "glm-5.3": { label: "GLM 5.3", name: "GLM 5.3" } },
}))
const page = fakePage([{ sends: 1, reply: true, text: "ok", reasoning: "", finished: true, reason: "succeed" }])
const d = new Doubao({ app: { start: async () => 1, dataDir: dir }, openPage: async () => page, poll: 1 })
await d.ask("x", { model: "glm-5.3" })
expect(page.calls.some((c) => c.includes('"GLM 5.3"'))).toBe(true)
fs.rmSync(dir, { recursive: true, force: true })
})
function fakePage(reads, { signedIn = true, steps = {} } = {}) {
const calls = []
const keys = []
@@ -195,6 +247,7 @@ function fakePage(reads, { signedIn = true, steps = {} } = {}) {
if (expr === STATE) return { signedIn, name: "yetone", sends: 0 }
if (expr === NEW_TASK) return steps.newTask ?? ""
if (expr === CLOUD) return steps.cloud ?? ""
if (expr === MENU) return steps.menu ?? { rows: [] }
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
@@ -397,6 +450,23 @@ test("the plugin serves chat completions through Doubao, whole and streamed", as
expect((await loader.fetch(new Request("https://elsewhere.example/v1/chat/completions", { method: "POST", body: "{}" }))).status).toBe(404)
})
test("the plugin lists the models models.json has, not only the built-in ones", async () => {
const table = { auto: MODELS.auto, "glm-5.3": { label: "GLM 5.3", name: "GLM 5.3" } }
const p = I.createPlugin({ doubao: { modelList: () => table, ask: async () => ({ text: "ok", reasoning: "" }) } })
const cfg = {}
await p.config(cfg)
expect(Object.keys(cfg.provider["doubao-work"].models)).toEqual(["auto", "glm-5.3"])
// a model the user declared keeps their settings
const own = { provider: { "doubao-work": { models: { "glm-5.3": { name: "mine", limit: { context: 1000, output: 10 } } } } } }
await p.config(own)
expect(own.provider["doubao-work"].models["glm-5.3"].name).toBe("mine")
expect(own.provider["doubao-work"].models.auto.name).toBe("自动")
expect(Object.keys(await p.provider.models({}, {}))).toEqual(["auto", "glm-5.3"])
const loader = await p.auth.loader(async () => ({}))
expect((await loader.fetch(req({ model: "glm-5.3", messages: [{ role: "user", content: "hi" }] }))).status).toBe(200)
expect((await loader.fetch(req({ model: "gpt-9", messages: [] }))).status).toBe(404)
})
test("the plugin passes a sign-out on for re-sign-in and other failures as HTTP errors", async () => {
const fail = (e) => I.createPlugin({ doubao: { ask: async () => { throw e } } })
const out = await fail(Object.assign(Error("signed out"), { signIn: "expired" })).auth.loader(async () => ({}))
+131 -3
View File
@@ -7,17 +7,63 @@
// (the page's text loses code fences), a text block under a thinking block
// is the reasoning, ext.is_finish says it is done, and
// ext.context_window_usage counts the prompt's tokens.
import fs from "node:fs"
import os from "node:os"
import path from "node:path"
import { App, Page, sleep } from "./cdp.mjs"
export const CHAT = "doubao-chat/chat"
// Doubao has no API to ask which models it offers: the app's own model menu
// is the list, and it changes as Doubao adds models. These are the ones the
// menu showed when the plugin was written; they are only the fallback for
// when the menu cannot be read. The real list is read from the menu (see
// Doubao#discover) and kept in models.json under DOUBAO_WORK_HOME.
export const MODELS = {
auto: { label: "自动", name: "自动" },
"doubao-2.1-lite": { label: "豆包 2.1 Lite", name: "豆包 2.1 Lite" },
"doubao-2.1-pro": { label: "豆包 2.1 Pro", name: "豆包 2.1 Pro" },
}
// idFor turns the first line of a menu row into the model id a client
// writes as doubao-work/<id>: "DeepSeek V4.1 Flash" -> "deepseek-v4.1-flash",
// "豆包 2.1 Lite" -> "doubao-2.1-lite", "自动" -> "auto". A label with no
// Latin letters or digits gets a stable hash instead.
export function idFor(label) {
const text = String(label ?? "").trim()
if (!text || text === "自动") return "auto"
let id = text
.replace(/豆包/g, "doubao ")
.toLowerCase()
.replace(/[^a-z0-9.]+/g, "-")
.replace(/-{2,}/g, "-")
.replace(/^-+|-+$/g, "")
if (!id) {
let h = 0
for (const ch of text) h = (h * 31 + ch.codePointAt(0)) >>> 0
id = "model-" + h.toString(36)
} else if (!/^[a-z]/.test(id)) {
id = "model-" + id
}
return id
}
// 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) {
const out = {}
for (const r of rows ?? []) {
const label = String(r?.label ?? "").trim()
if (!label) continue
const id = idFor(label)
if (out[id]) continue
out[id] = { label, name: label }
}
if (!Object.keys(out).length) return { ...MODELS }
if (out.auto) out.auto = { ...MODELS.auto }
return out
}
// localAppData is %LOCALAPPDATA%, where Doubao's Windows installer puts
// the app for the user who installs it.
const localAppData = (home) => process.env.LOCALAPPDATA || path.win32.join(home, "AppData", "Local")
@@ -111,6 +157,29 @@ export const pickModel = (label) =>
return "";
`)
// MENU reads the model list off the app's own menu: press the model button,
// wait for the menu that has rows, and take the first line of each row.
// Rows that open a submenu ("推理强度", a "more models" entry) are not
// models and are left out. The menu is closed again with Escape.
export const MENU = js(`
const b = $("[data-testid=chat_input_action_model]");
if (!b) return { error: "no model button" };
press(b);
let menu;
for (let i = 0; i < 30 && !menu; i++) {
await wait(100);
menu = $$("[role=menu]").find((m) => $$("[role=menuitem]", m).length);
}
if (!menu) return { error: "no model menu" };
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("升级") }))
.filter((r) => r.label);
document.body.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
return { rows };
`)
// fill puts the prompt in the editor, one paragraph a line: that is how
// Doubao sends newlines (a hard break is dropped).
export const fill = (text) =>
@@ -161,13 +230,68 @@ export class DoubaoError extends Error {
// Doubao drives the app. One request runs at a time: there is one window.
export class Doubao {
constructor({ app, openPage = Page.open, poll = 150, idle = 180000, total = 900000 } = {}) {
constructor({ app, openPage = Page.open, poll = 150, idle = 180000, total = 900000, fresh = 6 * 60 * 60 * 1000 } = {}) {
this.app = app ?? new App({ binary: binary(), dataDir: dataDir(), owns })
Object.assign(this, { openPage, poll, idle, total })
Object.assign(this, { openPage, poll, idle, total, fresh })
this.cacheFile = this.app?.dataDir ? path.join(this.app.dataDir, "models.json") : ""
this.table = null
this.tableAt = 0
this.page = null
this.queue = Promise.resolve()
}
// modelList is what the plugin offers: the menu read last time, or the
// fallback before the menu has ever been read. It never opens the app —
// the menu is read by discover(), on sign-in and on a stale request.
modelList() {
if (this.table) return this.table
try {
const d = JSON.parse(fs.readFileSync(this.cacheFile, "utf8"))
if (d?.models && typeof d.at === "number" && Object.keys(d.models).length) {
this.table = d.models
this.tableAt = d.at
return this.table
}
} catch {}
this.table = { ...MODELS }
this.tableAt = 0
return this.table
}
stale() {
this.modelList()
return !this.tableAt || Date.now() - this.tableAt > this.fresh
}
#save(table) {
this.table = table
this.tableAt = Date.now()
if (!this.cacheFile) return
try {
fs.mkdirSync(path.dirname(this.cacheFile), { recursive: true })
const tmp = this.cacheFile + ".tmp"
fs.writeFileSync(tmp, JSON.stringify({ at: this.tableAt, models: table }, null, 1))
fs.renameSync(tmp, this.cacheFile)
} catch {}
}
// discover reads Doubao's model menu and keeps the result. It opens a
// new task first when the current page has no model button (the app can
// sit on 技能 or another page); nothing is sent, so no task runs.
async discover({ signal } = {}) {
const page = await this.connect(signal)
let read = await page.eval(MENU)
if (read?.error === "no model button") {
const why = await page.eval(NEW_TASK)
if (why) throw new DoubaoError("豆包读取模型列表失败:" + why, "doubao_ui")
read = await page.eval(MENU)
}
if (read?.error) throw new DoubaoError("豆包读取模型列表失败:" + read.error, "doubao_ui")
const table = tableFrom(read?.rows)
this.#save(table)
return table
}
async connect(signal) {
if (this.page && !this.page.closed) return this.page
const port = await this.app.start({ signal })
@@ -215,7 +339,11 @@ export class Doubao {
}
await step(NEW_TASK, "新建任务")
await step(CLOUD, "切换到云电脑")
const label = (MODELS[model] ?? MODELS.auto).label
// the menu is open anyway to pick a model: refresh the list while here
// when it has not been read for a while
if (this.cacheFile && this.stale()) { try { await this.discover({ signal }) } catch {} }
const table = this.modelList()
const label = (table[model] ?? table.auto ?? MODELS.auto).label
const picked = await page.eval(pickModel(label))
if (picked === "upgrade") throw new DoubaoError(`${label} 需要升级豆包会员。`, "doubao_upgrade", { status: 403 })
if (picked) throw new DoubaoError(`豆包选择模型失败:${picked}`, "doubao_ui")
+25 -4
View File
@@ -20,9 +20,9 @@ const json = (status, message, type) =>
// models are named as Doubao's menu names them: magpie adds the
// provider's name. Each says it takes text only, or magpie would ask
// models.dev about another vendor's model of the same id ("auto").
function models() {
function models(table = MODELS) {
const out = {}
for (const [id, m] of Object.entries(MODELS))
for (const [id, m] of Object.entries(table))
out[id] = {
name: m.name,
limit: { context: 256000, output: 32768 },
@@ -34,6 +34,10 @@ function models() {
return out
}
// modelTable is the list the plugin offers: Doubao's menu as discover read
// it (never opening the app here), or the built-in fallback.
const modelTable = (doubao) => (typeof doubao?.modelList === "function" ? doubao.modelList() : MODELS)
export function createPlugin({ doubao = new Doubao(), newId, appBinary = binary } = {}) {
const failed = (e) => {
if (e?.signIn) throw e
@@ -44,7 +48,19 @@ export function createPlugin({ doubao = new Doubao(), newId, appBinary = binary
return {
config: async (cfg) => {
cfg.provider ??= {}
cfg.provider[ID] ??= { name: "豆包工作", npm: "@ai-sdk/openai-compatible", api: BASE, models: models() }
// the list comes from Doubao's menu, so it is merged in on every load
// instead of being frozen in the declaration; a model the user
// declared themselves keeps their settings
cfg.provider[ID] ??= { name: "豆包工作", npm: "@ai-sdk/openai-compatible", api: BASE }
cfg.provider[ID].models = { ...models(modelTable(doubao)), ...(cfg.provider[ID].models ?? {}) }
},
// each account is offered the models its own menu shows (the cache
// discover() writes; no app is opened from here)
provider: {
id: ID,
async models() {
return models(modelTable(doubao))
},
},
auth: {
provider: ID,
@@ -68,6 +84,11 @@ export function createPlugin({ doubao = new Doubao(), newId, appBinary = binary
return { type: "failed", error: "打开豆包失败:" + String(e?.message ?? e) }
}
if (!s) return { type: "failed", error: "五分钟内没有在豆包窗口里登录,请再试一次。" }
// read the model menu now that the window is open and signed
// in, so the models it shows are listed at once
if (typeof doubao.discover === "function") {
try { await doubao.discover({ signal: AbortSignal.timeout(20000) }) } catch {}
}
return { type: "success", access: "doubao-desktop", refresh: "", expires: 0, accountId: "豆包工作 · " + s.name, name: s.name }
},
}),
@@ -90,7 +111,7 @@ export function createPlugin({ doubao = new Doubao(), newId, appBinary = binary
return json(400, "请求不是 JSON。", "invalid_request_error")
}
const model = String(body.model ?? "auto").replace(/^doubao-work\//, "")
if (!MODELS[model]) return json(404, `没有模型 ${model}。`, "model_not_found")
if (!modelTable(doubao)[model]) return json(404, `没有模型 ${model}。`, "model_not_found")
const prompt = flatten(body)
const id = "chatcmpl-" + Math.random().toString(36).slice(2)
const promptTokens = (r) => usageOf(r?.usage) || Math.ceil(prompt.length / 3)
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-doubao-work-auth",
"version": "0.1.3",
"version": "0.1.4",
"type": "module",
"main": "./opencode.mjs",
"files": [