doubao-work 0.1.10: lists 工作任务's real models from brief_list, with 推理强度

XingHeJin on X: 豆包工作 listed only 快速 and 专家, and 测试模型 failed,
while the app offers 自动, 豆包 2.1 Lite/Pro, DeepSeek V4.1 Flash, Kimi
K3.1 Pro (高速), Kimi K3, GLM 5.3 (Flash) and DeepSeek V4 Pro, each with a
推理强度 submenu.

Cause: discover read the model menu of whatever page was open. In 豆包 that
can be the 对话 page, whose menu is 快速/专家; that list was cached, and
pickModel("快速") then failed in the 工作任务 the request opened.

- The list now comes from the request the app's own page makes,
  alice/slot/action_bar_v3/brief_list (coco_deep_thinking, mode_id 3), with
  each model's model_item_key and 推理强度 levels. When it can't be read,
  the menu is read inside a new 工作任务, never the current page's.
- models.json carries a version; a 0.1.9 cache is read again.
- A model is found by id, by Doubao's key or by its name.
- Each model's 推理强度 levels are variants; reasoning_effort (or
  reasoning.effort) picks the nearest level (低 low, 中 medium, 高 high,
  极高 xhigh, 最高 max). With none asked, the model's own default level is
  set, not the one the last request left.
- A Radix menu left open in a background window (its close animation waits
  for a frame that is never drawn) is closed with a pointerdown before
  filling; the message is sent with the send button, Enter only without one.
- A model the list has and the menu doesn't reloads the page once.

Run:
- bun test packages/doubao-work under a temp HOME on mote: 56 pass, 0 fail.
- Broken by hand (cache version check removed, default effort removed, the
  send button skipped): the three tests about them went red, 53 pass 3 fail.
- Full bun test, HOME=$(mktemp -d), on mote at this tree on 14296209:
  8698 pass, 0 fail, 20 skip (606 files).
- Real requests through the plugin against the owner's Doubao account
  (豆包.app on macOS, sandboxed data dir), chat/completion bodies captured:
  deepseek-v4.1-flash xhigh -> person-deepseek-v4-1-flash-261017,
  reasoning_effort 6; glm-5.3 medium -> person-glm-5-3-261111, 5 (高, the
  nearest with a tie going higher); kimi-k3.1-pro-fast low ->
  person-kimi-k3-1-pro-highspeed-261111, 3; auto -> 9. All 200, ~5-7s.
  glm-5.3 with no effort, after a request left 低 -> 高 set, reasoning_effort
  5. provider.models() listed all 10 models with their variants.

Not tried: DoubaoWork.app itself (the same page, the 豆包 app was used),
Windows, the reporter's free plan, a Page.reload in real use, and the rates
read from a real menu.
This commit is contained in:
yetone
2026-11-14 01:24:56 +08:00
parent 14296209ea
commit c95e20a352
6 changed files with 1274 additions and 53 deletions
+18 -6
View File
@@ -39,11 +39,23 @@ same, works too:
4. The client's tools are asked for as text, `<tool_call>{"name": …,
"arguments": …}</tool_call>`, and given back as `tool_calls`.
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.
Models: the plugin reads the 工作任务 model list from Doubao itself (the
`brief_list` request the app's own page makes, through the app's page), so
whatever 工作任务 offers is what magpie lists. Before 0.1.10 it read the menu
of whatever page was open, and on 豆包's 对话 page that menu is 快速 and 专家,
which 工作任务 doesn't have. A list cached from that menu is read again. The
name becomes the id: 自动 (`auto`), 豆包 2.1 Lite (`doubao-2.1-lite`), 豆包 2.1
Pro (`doubao-2.1-pro`), DeepSeek V4.1 Flash (`deepseek-v4.1-flash`), GLM 5.3
(`glm-5.3`) and so on. A request may also name a model by Doubao's own key
(`person-deepseek-v4-1-flash-261017`) or by its name (`DeepSeek V4.1 Flash`).
When `brief_list` can't be read, the plugin opens a 工作任务 and reads its
model menu instead.
推理强度: each model's levels are offered as variants, and the client's
`reasoning_effort` (or `reasoning.effort`) picks one: `low` 低, `medium` 中,
`high` 高, `xhigh` 极高, `max` 最高. A level the model lacks goes to the
nearest one it has (a tie goes higher). With no effort asked, the model's own
default level is picked, not the one the last request left the app on.
The list is read when you sign in, and again on a request once the cached list
is more than six hours old, or at once when a request names a model the
@@ -51,7 +63,7 @@ cached list doesn't have (at most once a minute); it is kept in `models.json` un
`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.
fallback for when no list can be read.
A list never read (an account that signed in before the plugin read menus) is
read when magpie lists the models, once a minute at most, and only from an app
the plugin has started before. Rows whose names differ only in Chinese get
+181 -5
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, MENU, READ, STATE, MODELS, idFor, tableFrom, APPS, binary, choose, dataDir, installedAt, hintsWin, hintsMac, owns, isChat, usageOf, QUOTA, quotaOf, rateOf } from "./doubao.mjs"
import { Doubao, NEW_TASK, CLOUD, MENU, LIST, SEND, READ, STATE, MODELS, EFFORT, idFor, tableFrom, listOf, lookup, effortFor, rateIn, 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"
@@ -298,6 +298,7 @@ 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({
v: 2,
at: Date.now(),
models: { auto: MODELS.auto, "glm-5.3": { label: "GLM 5.3", name: "GLM 5.3" } },
}))
@@ -316,6 +317,7 @@ test("models.json is read first, and discover rewrites it", async () => {
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({
v: 2,
at: Date.now(),
models: { auto: MODELS.auto, "glm-5.3": { label: "GLM 5.3", name: "GLM 5.3" } },
}))
@@ -339,13 +341,17 @@ 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 === LIST) return typeof steps.list === "function" ? steps.list() : steps.list ?? { error: "no list step" }
if (expr === QUOTA) return steps.quota ?? { error: "no quota step" }
if (expr === SEND) return steps.send ?? false
if (expr === READ) return reads.length > 1 ? reads.shift() : reads[0]
if (expr.includes("chat_input_action_model")) return steps.model ?? ""
if (expr.includes("推理强度")) return steps.effort ?? ""
if (expr.includes("chat_input_action_model")) return typeof steps.model === "function" ? steps.model(expr) : steps.model ?? ""
if (expr.includes("insertContent")) return 10
throw Error("unexpected eval")
},
async key(k) { keys.push(k) },
async call(method, params) { calls.push(method); return steps.call?.(method, params) ?? {} },
}
}
@@ -608,6 +614,7 @@ test("a model the app added since the last read is found at once, and a made-up
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "doubao-models-"))
// the list was read minutes ago, before Doubao added Kimi
fs.writeFileSync(path.join(dir, "models.json"), JSON.stringify({
v: 2,
at: Date.now(),
models: { auto: MODELS.auto, "doubao-2.1-lite": MODELS["doubao-2.1-lite"] },
}))
@@ -633,7 +640,7 @@ test("a model the app added since the last read is found at once, and a made-up
test("a menu that can't be read leaves the model unknown, not the list emptied (#1048)", 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 } }))
fs.writeFileSync(path.join(dir, "models.json"), JSON.stringify({ v: 2, at: Date.now(), models: { auto: MODELS.auto } }))
const page = fakePage([], { steps: { menu: { error: "no model menu" } } })
const d = new Doubao({ app: { start: async () => 1, dataDir: dir }, openPage: async () => page, poll: 1 })
expect(await d.known("kimi-k3")).toBe(false)
@@ -657,7 +664,7 @@ test("the plugin asks Doubao's menu again for a model its list lacks, and names
expect((await loader.fetch(req({ model: "doubao-work/kimi-k3", messages: [{ role: "user", content: "hi" }] }))).status).toBe(200)
const r = await loader.fetch(req({ model: "gpt-9", messages: [] }))
expect(r.status).toBe(404)
expect((await r.json()).error.message).toBe("没有模型 gpt-9。豆包的模型菜单里有:auto、kimi-k3。")
expect((await r.json()).error.message).toBe("没有模型 gpt-9。豆包工作的模型有:auto、kimi-k3。")
expect(asked).toEqual(["kimi-k3", "gpt-9"])
// a model the list has never asks the menu
expect((await loader.fetch(req({ model: "auto", messages: [{ role: "user", content: "hi" }] }))).status).toBe(200)
@@ -689,7 +696,7 @@ test("a list never read from the menu is read when the plugin lists models, once
test("picking a model from the full list presses that row in the app", async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "doubao-models-"))
fs.writeFileSync(path.join(dir, "models.json"), JSON.stringify({ at: Date.now(), models: tableFrom([{ label: "自动" }, { label: "Kimi K3.1 Pro 高速" }, { label: "DeepSeek V4 Pro" }]) }))
fs.writeFileSync(path.join(dir, "models.json"), JSON.stringify({ v: 2, at: Date.now(), models: tableFrom([{ label: "自动" }, { label: "Kimi K3.1 Pro 高速" }, { label: "DeepSeek V4 Pro" }]) }))
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 })
expect(Object.keys(d.modelList())).toEqual(["auto", "kimi-k3.1-pro-fast", "deepseek-v4-pro"])
@@ -746,3 +753,172 @@ test("a model's multiple is read from its menu row and given as rate", () => {
expect(out["kimi-k3.1-pro"].rate).toBe(2)
expect("rate" in out["deepseek-v4-pro"]).toBe(false)
})
// ---- the model list from brief_list ----
// LIST's reply as the 豆包工作 app's page got it on 2026-11-13 (icons left
// out, as LIST leaves them out)
const BRIEF = JSON.parse(fs.readFileSync(path.join(import.meta.dir, "testdata", "brief-list-2026-11-13.json"), "utf8"))
const WORK = ["自动", "豆包 2.1 Lite", "豆包 2.1 Pro", "DeepSeek V4.1 Flash", "Kimi K3.1 Pro", "Kimi K3.1 Pro 高速", "Kimi K3", "GLM 5.3", "GLM 5.3 Flash", "DeepSeek V4 Pro"]
test("listOf reads 工作任务's models, Doubao's ids and 推理强度 from brief_list", () => {
const rows = listOf(BRIEF)
expect(rows.map((r) => r.label)).toEqual(WORK)
const flash = rows.find((r) => r.label === "DeepSeek V4.1 Flash")
expect(flash).toMatchObject({ key: "person-deepseek-v4-1-flash-261017", efforts: ["低", "中", "高", "极高", "最高"], effort: "高" })
expect(rows.find((r) => r.label === "GLM 5.3").efforts).toEqual(["低", "高", "最高"])
const t = tableFrom(rows)
expect(Object.keys(t)).toEqual(["auto", "doubao-2.1-lite", "doubao-2.1-pro", "deepseek-v4.1-flash", "kimi-k3.1-pro", "kimi-k3.1-pro-fast", "kimi-k3", "glm-5.3", "glm-5.3-flash", "deepseek-v4-pro"])
expect(t.auto).toMatchObject({ label: "自动", key: "9" })
// a request may name a model by the plugin's id, Doubao's own id or its name
expect(lookup(t, "person-deepseek-v4-1-flash-261017").label).toBe("DeepSeek V4.1 Flash")
expect(lookup(t, "Kimi K3.1 Pro 高速").key).toBe("person-kimi-k3-1-pro-highspeed-261111")
expect(lookup(t, "gpt-9")).toBe(null)
// a reply that failed, or has no 工作任务, is no list
expect(listOf({ status: 200, code: 710010702, msg: "系统错误" })).toBe(null)
expect(listOf({ conf: { mode_list: { item_list: [{ mode_id: "1", name: "快速", agent_mode: 0, conversation_mode_list: ["chat"] }] }, model_list: { item_list: [{ name: "快速", model_item_key: "1" }] } } })).toBe(null)
// a 工作任务 that lists only the keys it supports takes them from the shared list
const shared = { conf: { mode_list: { item_list: [{ mode_id: "3", agent_mode: 1, support_models: [{ model_item_key: "b" }] }] }, model_list: { item_list: [{ name: "A", model_item_key: "a" }, { name: "B", model_item_key: "b" }] } } }
expect(listOf(shared).map((r) => r.label)).toEqual(["B"])
})
test("discover takes brief_list's list over the menu, so the 对话 menu's 快速 and 专家 are never the list", async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "doubao-models-"))
// the 豆包 app sitting on a 对话 page: its model menu is 快速 and 专家
const page = fakePage([], { steps: { list: BRIEF, menu: { rows: [{ label: "快速" }, { label: "专家" }] } } })
const d = new Doubao({ app: { start: async () => 1, dataDir: dir }, openPage: async () => page, poll: 1 })
const t = await d.discover()
expect(Object.values(t).map((m) => m.label)).toEqual(WORK)
expect(page.calls.includes(MENU)).toBe(false)
// brief_list failing falls back to the menu of a new work task, not the
// page's current menu
const p2 = fakePage([], { steps: { list: { status: 200, code: 710010702 }, menu: { rows: [{ label: "自动" }, { label: "Kimi K3" }] } } })
const d2 = new Doubao({ app: { start: async () => 1, dataDir: dir }, openPage: async () => p2, poll: 1 })
expect(Object.keys(await d2.discover())).toEqual(["auto", "kimi-k3"])
expect(p2.calls.indexOf(NEW_TASK)).toBeGreaterThan(-1)
expect(p2.calls.indexOf(NEW_TASK)).toBeLessThan(p2.calls.indexOf(MENU))
fs.rmSync(dir, { recursive: true, force: true })
})
test("a models.json 0.1.9 wrote from the 对话 menu (快速, 专家) is read again from brief_list", async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "doubao-models-"))
fs.writeFileSync(path.join(dir, "models.json"), JSON.stringify({ at: Date.now(), models: tableFrom([{ label: "快速" }, { label: "专家" }]) }))
const page = fakePage([], { steps: { list: BRIEF } })
const d = new Doubao({ app: { start: async () => 1, dataDir: dir }, openPage: async () => page, poll: 1 })
const p = I.createPlugin({ doubao: d })
const listed = await p.provider.models({}, {})
expect(Object.values(listed).map((m) => m.name)).toEqual(WORK)
expect(JSON.parse(fs.readFileSync(path.join(dir, "models.json"), "utf8")).v).toBe(2)
fs.rmSync(dir, { recursive: true, force: true })
})
test("effortFor takes the client's reasoning effort to the nearest 推理强度 the model has", () => {
const five = ["低", "中", "高", "极高", "最高"]
expect(effortFor("low", five)).toBe("低")
expect(effortFor("medium", five)).toBe("中")
expect(effortFor("high", five)).toBe("高")
expect(effortFor("xhigh", five)).toBe("极高")
expect(effortFor("max", five)).toBe("最高")
expect(effortFor("minimal", five)).toBe("低")
expect(effortFor("none", five)).toBe("低")
// GLM 5.3 has 低, 高 and 最高: medium and xhigh go one up
expect(effortFor("medium", ["低", "高", "最高"])).toBe("高")
expect(effortFor("xhigh", ["低", "高", "最高"])).toBe("最高")
// nothing asked, an unknown effort or a model without levels keeps Doubao's default
expect(effortFor("", five)).toBe("")
expect(effortFor("turbo", five)).toBe("")
expect(effortFor("high", undefined)).toBe("")
})
test("ask picks the model and the 推理强度 the client asked for", async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "doubao-models-"))
fs.writeFileSync(path.join(dir, "models.json"), JSON.stringify({ v: 2, at: Date.now(), models: tableFrom(listOf(BRIEF)) }))
const ok = { sends: 1, reply: true, text: "ok", reasoning: "", finished: true, reason: "succeed" }
const page = fakePage([ok])
const d = new Doubao({ app: { start: async () => 1, dataDir: dir }, openPage: async () => page, poll: 1 })
await d.ask("x", { model: "person-deepseek-v4-1-flash-261017", effort: "xhigh" })
expect(page.calls).toContain(EFFORT("极高"))
expect(page.calls.some((c) => c.includes('"DeepSeek V4.1 Flash"') && c.includes("chat_input_action_model") && !c.includes("推理强度"))).toBe(true)
// the model before its effort: the effort menu is the picked model's
const i = page.calls.findIndex((c) => c.includes('"DeepSeek V4.1 Flash"'))
expect(i).toBeLessThan(page.calls.indexOf(EFFORT("极高")))
// no effort asked: the model's own default (GLM 5.3's is 高), not the
// level the last request left the app on
const p2 = fakePage([ok])
await new Doubao({ app: { start: async () => 1, dataDir: dir }, openPage: async () => p2, poll: 1 }).ask("x", { model: "glm-5.3" })
expect(p2.calls).toContain(EFFORT("高"))
// a model without levels presses nothing
const p4 = fakePage([ok])
await new Doubao({ app: fakeApp, openPage: async () => p4, poll: 1 }).ask("x", { model: "auto" })
expect(p4.calls.some((c) => c.includes("推理强度"))).toBe(false)
// an effort that can't be set fails the request instead of running another
const p3 = fakePage([ok], { steps: { effort: "no 推理强度 in the model menu" } })
await expect(new Doubao({ app: { start: async () => 1, dataDir: dir }, openPage: async () => p3, poll: 1 }).ask("x", { model: "kimi-k3", effort: "low" })).rejects.toThrow("推理强度")
fs.rmSync(dir, { recursive: true, force: true })
})
test("a model the list has and the app's menu doesn't loads the page again once", async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "doubao-models-"))
fs.writeFileSync(path.join(dir, "models.json"), JSON.stringify({ v: 2, at: Date.now(), models: tableFrom(listOf(BRIEF)) }))
const ok = { sends: 1, reply: true, text: "ok", reasoning: "", finished: true, reason: "succeed" }
let reloaded = false
const steps = {
call: (m) => { if (m === "Page.reload") reloaded = true },
model: () => (reloaded ? "" : "no DeepSeek V4.1 Flash in the model menu"),
}
const page = fakePage([ok], { steps })
const ev = page.eval
page.eval = async (e) => (e === STATE ? { signedIn: true, name: "yetone", input: true, sends: 0 } : ev(e))
const d = new Doubao({ app: { start: async () => 1, dataDir: dir }, openPage: async () => page, poll: 1 })
await d.ask("x", { model: "deepseek-v4.1-flash" })
expect(page.calls.filter((c) => c === "Page.reload").length).toBe(1)
// still missing after the reload: said, and loaded once only
reloaded = false
const p2 = fakePage([ok], { steps: { call: () => {}, model: "no DeepSeek V4.1 Flash in the model menu" } })
const ev2 = p2.eval
p2.eval = async (e) => (e === STATE ? { signedIn: true, name: "yetone", input: true, sends: 0 } : ev2(e))
await expect(new Doubao({ app: { start: async () => 1, dataDir: dir }, openPage: async () => p2, poll: 1 }).ask("x", { model: "deepseek-v4.1-flash" })).rejects.toThrow("no DeepSeek V4.1 Flash in the model menu")
expect(p2.calls.filter((c) => c === "Page.reload").length).toBe(1)
fs.rmSync(dir, { recursive: true, force: true })
})
test("the plugin offers each model's 推理强度 as variants and passes the client's reasoning_effort on", async () => {
const table = tableFrom(listOf(BRIEF))
const asked = []
const p = I.createPlugin({ doubao: { modelList: () => table, ask: async (prompt, o) => { asked.push([o.model, o.effort]); return { text: "ok", reasoning: "" } } }, newId: ids })
const listed = await p.provider.models({}, {})
expect(Object.keys(listed["deepseek-v4.1-flash"].variants)).toEqual(["low", "medium", "high", "xhigh", "max"])
expect(listed["glm-5.3"].variants).toEqual({ low: { reasoningEffort: "low" }, high: { reasoningEffort: "high" }, max: { reasoningEffort: "max" } })
const loader = await p.auth.loader(async () => ({}))
expect((await loader.fetch(req({ model: "doubao-work/deepseek-v4.1-flash", reasoning_effort: "xhigh", messages: [{ role: "user", content: "hi" }] }))).status).toBe(200)
expect((await loader.fetch(req({ model: "person-kimi-k3-261111", messages: [{ role: "user", content: "hi" }] }))).status).toBe(200)
expect(asked).toEqual([["deepseek-v4.1-flash", "xhigh"], ["person-kimi-k3-261111", ""]])
})
test("a model's multiple is read from the menu of the task ask opened, and kept when the menu says none", async () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "doubao-models-"))
const menu = { rows: [{ label: "自动", lines: [] }, { label: "Kimi K3", lines: ["0.65x"] }, { label: "Kimi K3.1 Pro 限时优惠 0.01x", lines: [] }] }
const page = fakePage([], { steps: { list: BRIEF, menu } })
const d = new Doubao({ app: { start: async () => 1, dataDir: dir }, openPage: async () => page, poll: 1 })
const t = await d.discover({ inTask: true })
expect(t["kimi-k3"].rate).toBe(0.65)
expect(t["kimi-k3.1-pro"].rate).toBe(0.01)
// Kimi K3.1 Pro 高速 is not Kimi K3.1 Pro's row
expect(t["kimi-k3.1-pro-fast"].rate).toBeUndefined()
expect(rateIn(menu.rows, "Kimi K3.1 Pro", listOf(BRIEF))).toBe(0.01)
page.calls.length = 0
const again = await new Doubao({ app: { start: async () => 1, dataDir: dir }, openPage: async () => fakePage([], { steps: { list: BRIEF, menu: { rows: [] } } }), poll: 1 }).discover({ inTask: true })
expect(again["kimi-k3"].rate).toBe(0.65)
fs.rmSync(dir, { recursive: true, force: true })
})
test("ask sends with the send button, and with Enter only when there is none", async () => {
const ok = { sends: 1, reply: true, text: "ok", reasoning: "", finished: true, reason: "succeed" }
const page = fakePage([ok], { steps: { send: true } })
await new Doubao({ app: fakeApp, openPage: async () => page, poll: 1 }).ask("x")
expect(page.calls).toContain(SEND)
expect(page.keys).toEqual([])
const p2 = fakePage([ok])
await new Doubao({ app: fakeApp, openPage: async () => p2, poll: 1 }).ask("x")
expect(p2.keys).toEqual(["Enter"])
})
+274 -36
View File
@@ -20,17 +20,48 @@ import { App, Page, sleep } from "./cdp.mjs"
// itself as chrome://doubao(work)-chat/chat from inside.
export const isChat = (url) => /^(doubao|doubaowork|chrome):\/\/(doubao|doubaowork)-chat\/chat/.test(String(url))
// 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.
// The models Doubao offers come from the list its own page asks for
// (brief_list, see LIST and listOf) and change as Doubao adds models. These
// are the ones it listed when the plugin was written; they are only the
// fallback for when nothing could be read. The real list is read by
// 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" },
}
// EFFORTS are the names Doubao gives its 推理强度 levels, lowest first, and
// the OpenAI reasoning_effort each one is offered as.
export const EFFORTS = [
["低", "low"],
["中", "medium"],
["高", "high"],
["极高", "xhigh"],
["最高", "max"],
]
// effortFor turns a client's reasoning_effort into one of a model's
// 推理强度 names: the same level when the model has it, else the nearest,
// the higher one on a tie. none and minimal ask for the lowest. "" when the
// client asked for nothing (or the model has no levels): the model's own
// default stays.
export function effortFor(asked, efforts) {
const list = (efforts ?? []).filter((e) => EFFORTS.some(([n]) => n === e))
const want = String(asked ?? "").trim().toLowerCase()
if (!want || !list.length) return ""
const rank = (name) => EFFORTS.findIndex(([n]) => n === name)
let i = EFFORTS.findIndex(([n, o]) => o === want || n === want)
if (want === "none" || want === "minimal") i = 0
if (i < 0) return ""
let best = list[0]
for (const e of list) {
const d = Math.abs(rank(e) - i), b = Math.abs(rank(best) - i)
if (d < b || (d === b && rank(e) > rank(best))) best = e
}
return best
}
// 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
@@ -68,8 +99,11 @@ export function rateOf(lines) {
return 0
}
// tableFrom builds the model table ({ id: {label, name} }) from the rows
// read off the menu. Nothing read means the fallback stays.
// tableFrom builds the model table from the rows read off Doubao's list
// (listOf) or its menu: { id: {label, name, key?, efforts?, effort?, rate?} }.
// key is Doubao's own id for the model (model_item_key), efforts its
// 推理强度 names and effort the one it picks by default. Nothing read means
// the fallback stays.
export function tableFrom(rows) {
const out = {}
for (const r of rows ?? []) {
@@ -81,14 +115,60 @@ 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 }
if (r.key) out[id].key = String(r.key)
if (Array.isArray(r.efforts) && r.efforts.length) out[id].efforts = r.efforts.map(String)
if (r.effort) out[id].effort = String(r.effort)
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 }
if (out.auto && !out.auto.key) out.auto = { ...MODELS.auto, ...out.auto, label: MODELS.auto.label }
return out
}
// lookup finds a model in the table by the id the plugin gives it, by
// Doubao's own id for it (model_item_key, "person-deepseek-v4-1-flash-261017")
// or by its name as the menu shows it ("DeepSeek V4.1 Flash").
export function lookup(table, model) {
const want = String(model ?? "")
if (table?.[want]) return table[want]
for (const m of Object.values(table ?? {})) if (m?.key === want || m?.label === want) return m
return null
}
// listOf turns LIST's reply into rows for tableFrom: the models of
// 工作任务 (mode 3, the agent mode, the one for "office" conversations),
// in the order Doubao lists them, each with its 推理强度 names. A mode
// without its own list takes the shared list's models it supports. null
// when the reply has no such list.
export function listOf(read) {
const conf = read?.conf
if (!conf || typeof conf !== "object") return null
const modes = conf.mode_list?.item_list ?? []
const mode =
modes.find((m) => String(m?.mode_id) === "3") ??
modes.find((m) => Number(m?.agent_mode) === 1) ??
modes.find((m) => (m?.conversation_mode_list ?? []).includes("office") && String(m?.default_conversation_mode ?? "office") === "office")
let items = mode?.model_list?.item_list
if (!Array.isArray(items) || !items.length) {
const all = conf.model_list?.item_list ?? []
const keys = new Set((mode?.support_models ?? []).map((m) => String(m?.model_item_key)))
// no modes at all: the shared list is the only one; modes without a
// work task (another app's list) give none
items = keys.size ? all.filter((i) => keys.has(String(i?.model_item_key))) : mode || modes.length ? [] : all
}
const rows = []
for (const i of items ?? []) {
const label = String(i?.name ?? "").trim()
if (!label) continue
const opts = i.reasoning_effort_config?.option_list ?? []
const efforts = opts.map((o) => String(o?.name ?? "").trim()).filter(Boolean)
const def = opts.find((o) => o?.level === i.reasoning_effort_config?.default_level)
rows.push({ label, key: String(i.model_item_key ?? ""), efforts, effort: def ? String(def.name).trim() : "", upgrade: !!i.subscribe_config?.need_upgrade })
}
return rows.length ? rows : null
}
// 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")
@@ -268,6 +348,16 @@ const $ = (s, r = document) => r.querySelector(s);
const $$ = (s, r = document) => [...r.querySelectorAll(s)];
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
const press = (el) => { for (const t of ["pointerdown", "mousedown", "pointerup", "mouseup", "click"]) el.dispatchEvent(new MouseEvent(t, { bubbles: true, cancelable: true, view: window })); };
// dismiss closes a menu left open: a pointerdown outside it, as Radix
// takes one. A menu can stay open after its item is pressed (its closing
// animation waits for a frame a window in the background doesn't draw),
// and an open menu keeps the focus, so Enter would not send.
const dismiss = async () => {
if (!$$("[role=menu]").some((m) => $$("[role=menuitem]", m).length)) return;
const at = $(".ProseMirror") || document.body;
for (const t of ["pointerdown", "mousedown", "pointerup", "mouseup"]) at.dispatchEvent(new PointerEvent(t, { bubbles: true, cancelable: true, view: window, pointerType: "mouse" }));
await wait(200);
};
const message = (el) => {
if (!el) return null;
const k = Object.keys(el).find((k) => k.startsWith("__reactFiber"));
@@ -314,22 +404,60 @@ export const CLOUD = js(`
return "the mode stayed " + b.innerText.trim();
`)
// pickModel picks the model whose menu row is label. A row's first line
// is the model's name, maybe followed by a badge ("限时优惠", "0.01x"): a
// row is taken by its exact name first, then by the name and a badge, never
// by a longer name ("Kimi K3.1 Pro" is not "Kimi K3.1 Pro 高速").
export const pickModel = (label) =>
js(`
const label = ${JSON.stringify(label)};
const b = $("[data-testid=chat_input_action_model]");
if (!b) return "no model button";
if (b.innerText.split("\\n")[0].trim() === label) return "";
const esc = () => document.body.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true }));
const first = (e) => e.innerText.split("\\n")[0].trim();
const badge = (t) => t.startsWith(label + " ") && /^(限时|优惠|小额|免费|新|热|推荐|hot|new|beta|[\\d.]+\\s*[x×倍]|[x×]\\s*[\\d.]+)/i.test(t.slice(label.length + 1).trim());
press(b);
let it;
for (let i = 0; i < 20 && !it; i++) { await wait(100); it = $$("[role=menu] [role=menuitem]").find((e) => e.innerText.split("\\n")[0].trim() === label); }
if (!it) { document.body.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); return "no " + label + " in the model menu"; }
if (it.innerText.includes("升级")) { document.body.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); return "upgrade"; }
for (let i = 0; i < 20 && !it; i++) {
await wait(100);
const rows = $$("[role=menu] [role=menuitem]").filter((e) => e.getAttribute("aria-haspopup") !== "menu");
it = rows.find((e) => first(e) === label) || rows.find((e) => badge(first(e)));
}
if (!it) { esc(); return "no " + label + " in the model menu"; }
if (it.innerText.includes("升级")) { esc(); return "upgrade"; }
press(it);
await wait(200);
return "";
`)
// EFFORT sets the 推理强度 of the model picked: the model button shows it
// under the model's name ("自动\n中"); otherwise the model menu's 推理强度
// row opens a submenu (hovered, then ArrowRight, as Radix opens one) and
// the level is pressed there.
export const EFFORT = (name) =>
js(`
const name = ${JSON.stringify(name)};
const b = $("[data-testid=chat_input_action_model]");
if (!b) return "no model button";
const now = () => b.innerText.split("\\n").map((x) => x.trim()).filter(Boolean)[1] || "";
if (now() === name) return "";
const esc = () => { for (let i = 0; i < 2; i++) document.body.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true })); };
press(b);
let row;
for (let i = 0; i < 20 && !row; i++) { await wait(100); row = $$("[role=menu] [role=menuitem]").find((e) => e.getAttribute("aria-haspopup") === "menu" && e.innerText.includes("推理强度")); }
if (!row) { esc(); return "no 推理强度 in the model menu"; }
for (const t of ["pointerenter", "pointermove", "pointerover"]) row.dispatchEvent(new PointerEvent(t, { bubbles: true, pointerType: "mouse" }));
row.dispatchEvent(new KeyboardEvent("keydown", { key: "ArrowRight", bubbles: true }));
let it;
for (let i = 0; i < 20 && !it; i++) { await wait(100); it = $$("[role=menu]").filter((m) => !m.contains(row)).flatMap((m) => $$("[role=menuitem]", m)).find((e) => e.innerText.split("\\n")[0].trim() === name); }
if (!it) { esc(); return "no " + name + " under 推理强度"; }
press(it);
for (let i = 0; i < 10 && now() !== name; i++) await wait(100);
await dismiss();
return now() === name ? "" : "推理强度 stayed " + now();
`)
// 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
@@ -357,6 +485,7 @@ export const MENU = js(`
// Doubao sends newlines (a hard break is dropped).
export const fill = (text) =>
js(`
await dismiss();
const ed = $(".ProseMirror") && $(".ProseMirror").editor;
if (!ed) return -1;
const lines = ${JSON.stringify(String(text).split("\n"))};
@@ -364,6 +493,15 @@ export const fill = (text) =>
return ed.getText({ blockSeparator: "\\n" }).length;
`)
// SEND presses the send button; false when there is none to press.
export const SEND = js(`
await dismiss();
const b = $("[data-testid=chat_input_send_button]");
if (!b || b.disabled || b.getAttribute("aria-disabled") === "true") return false;
b.click();
return true;
`)
export const READ = js(`
const sends = $$("[data-testid=send_message]");
const r = message($$("[data-testid=receive_message]").pop());
@@ -396,6 +534,38 @@ export const QUOTA = js(`
} catch (e) { return { error: String(e && e.message || e) }; }
`)
// BOT_ID is the bot Doubao's page names when it asks for its action bar
// (the app's code has it as a constant); without it brief_list answers
// 710010202.
export const BOT_ID = "7338286299411103781"
// LIST asks Doubao for the action bar its own page builds the model menu
// from (POST /alice/slot/action_bar_v3/brief_list), the way the page does:
// with the page's cookies and the query the page sends (version_code, aid,
// device_id...; the bare path answers 710010702). The query is taken from
// the page's own brief_list call, or from any other /alice/ call it made.
// It returns the deep-thinking entry's menu_conf_v2 with the icons left out.
export const LIST = js(`
const urls = performance.getEntriesByType("resource").map((e) => e.name).filter((u) => u.startsWith("https://www.doubao.com/alice/"));
const own = urls.filter((u) => u.includes("/brief_list?")).pop();
let url = own;
if (!url) {
const any = urls.filter((u) => u.includes("?")).pop();
const q = new URL(any || "https://www.doubao.com/alice/?").searchParams;
q.delete("msToken"); q.delete("a_bogus");
url = "https://www.doubao.com/alice/slot/action_bar_v3/brief_list?" + q;
}
try {
const r = await fetch(url, { method: "POST", credentials: "include", headers: { "content-type": "application/json" }, body: JSON.stringify({ bot_id: ${JSON.stringify(BOT_ID)}, language_code: "zh" }) });
const j = await r.json().catch(() => null);
if (!j || j.code !== 0) return { status: r.status, code: j && j.code, msg: j && j.msg };
const e = ((j.data && j.data.entry_list) || []).find((e) => e.action_bar_key === "coco_deep_thinking");
const v = e && e.active_switch_conf && e.active_switch_conf.menu_conf_v2;
const bare = (x) => JSON.parse(JSON.stringify(x == null ? null : x, (k, val) => (/icon/i.test(k) ? undefined : val)));
return { status: r.status, code: 0, conf: bare(v) };
} 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
@@ -432,6 +602,25 @@ export const usageOf = (raw) => {
}
}
// CACHE is the models.json format: 2 since the list comes from brief_list.
const CACHE = 2
// rateIn finds the multiple the model menu shows for the model named label:
// its row is the one with that name, or that name and a badge ("Kimi K3
// 0.65x") when no other model has the longer name.
export function rateIn(menu, label, rows = []) {
for (const r of menu ?? []) {
const l = String(r?.label ?? "").trim()
if (l === label) return Number(r.rate) || rateOf(r.lines)
}
for (const r of menu ?? []) {
const l = String(r?.label ?? "").trim()
if (l.startsWith(label + " ") && !rows.some((o) => o.label !== label && l.startsWith(o.label) && o.label.length > label.length))
return Number(r.rate) || rateOf([l.slice(label.length), ...(r.lines ?? [])])
}
return 0
}
export class DoubaoError extends Error {
constructor(message, code, extra = {}) {
super(message)
@@ -457,14 +646,16 @@ export class Doubao {
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 is what the plugin offers: the list read last time, or the
// fallback before it has ever been read. It never opens the app — the
// list is read by discover(), on sign-in and on a stale request. A
// models.json older than CACHE is not used: up to 0.1.9 it could hold the
// 对话 menu's 快速 and 专家, so it is read again.
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) {
if (d?.v === CACHE && d?.models && typeof d.at === "number" && Object.keys(d.models).length) {
this.table = d.models
this.tableAt = d.at
return this.table
@@ -487,24 +678,42 @@ export class Doubao {
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.writeFileSync(tmp, JSON.stringify({ v: CACHE, 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 } = {}) {
// discover reads the models Doubao's 工作任务 offers and keeps them. It
// asks Doubao's own list first (LIST), the one the page builds its menu
// from. When that can't be read it reads the model menu of a new work
// task: the page may sit on a 对话 page, whose menu (快速, 专家) is
// another list. Nothing is sent, so no task runs. inTask says the page is
// on a new work task already (ask), so its menu is read too, for the
// multiple each model costs, which only the menu shows.
async discover({ signal, inTask = false } = {}) {
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)
const old = this.modelList()
let rows = null
try { rows = listOf(await page.eval(LIST)) } catch {}
let menu = null
if (!rows || inTask) {
if (!inTask) {
const why = await page.eval(NEW_TASK)
if (why) throw new DoubaoError("豆包读取模型列表失败:" + why, "doubao_ui")
}
const read = await page.eval(MENU)
if (read?.error && !rows) throw new DoubaoError("豆包读取模型列表失败:" + read.error, "doubao_ui")
menu = read?.rows ?? null
}
if (!rows) rows = menu
else if (menu) rows = rows.map((r) => ({ ...r, rate: rateIn(menu, r.label, rows) }))
const table = tableFrom(rows)
// a model whose multiple the menu didn't show this time keeps the one
// it showed before
for (const m of Object.values(table)) {
const was = Object.values(old).find((o) => o?.label === m.label)
if (!(m.rate > 0) && was?.rate > 0) m.rate = was.rate
}
if (read?.error) throw new DoubaoError("豆包读取模型列表失败:" + read.error, "doubao_ui")
const table = tableFrom(read?.rows)
this.#save(table)
return table
}
@@ -532,13 +741,13 @@ export class Doubao {
// The read waits its turn behind a running ask: both press the same
// controls.
async known(model, { signal } = {}) {
if (this.modelList()[model]) return true
if (lookup(this.modelList(), model)) return true
if (!this.app?.start || Date.now() - this.missAt < 60000) return false
this.missAt = Date.now()
const run = this.queue.then(() => this.discover({ signal }))
this.queue = run.catch(() => {})
try { await run } catch { return false }
return !!this.modelList()[model]
return !!lookup(this.modelList(), model)
}
// quota reads the plan's allowance through the app's page. Only an app
@@ -590,7 +799,22 @@ export class Doubao {
return run
}
async #ask(prompt, { model = "auto", signal, onUpdate = () => {} }) {
// reload loads the chat page again: a running app keeps the model menu
// it loaded when it started, and Doubao adds models in between.
async #reload(page, signal) {
await page.call("Page.reload", { ignoreCache: true })
for (const until = Date.now() + 30000; Date.now() < until; ) {
await sleep(500, signal)
let s
try { s = await page.eval(STATE) } catch { continue }
if (s?.input) return
}
throw new DoubaoError("豆包的页面重新加载后没有打开。", "doubao_ui")
}
// effort is the client's reasoning_effort ("low" ... "max"); "" is the
// model's own default.
async #ask(prompt, { model = "auto", effort = "", signal, onUpdate = () => {} }) {
signal?.throwIfAborted()
const page = await this.connect(signal)
const s = await page.eval(STATE)
@@ -601,18 +825,32 @@ export class Doubao {
}
await step(NEW_TASK, "新建任务")
await step(CLOUD, "切换到云电脑")
// 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 {} }
// refresh the list while here when it has not been read for a while
if (this.cacheFile && this.stale()) { try { await this.discover({ signal, inTask: true }) } catch {} }
const table = this.modelList()
const label = (table[model] ?? table.auto ?? MODELS.auto).label
const picked = await page.eval(pickModel(label))
const m = lookup(table, model) ?? table.auto ?? MODELS.auto
const label = m.label
let picked = await page.eval(pickModel(label))
if (/^no .* in the model menu$/.test(picked)) {
// the list has it and the menu doesn't: the menu is the one the page
// loaded with, older than the list. Load the page again, once.
await this.#reload(page, signal)
await step(NEW_TASK, "新建任务")
await step(CLOUD, "切换到云电脑")
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")
// no effort asked: the model's own default, not the level the last
// request left the app on (the app keeps that)
const level = effortFor(effort, m.efforts) || (m.efforts?.includes(m.effort) ? m.effort : "")
if (level) await step(EFFORT(level), "设置推理强度")
const n = await page.eval(fill(prompt))
if (n < 0) throw new DoubaoError("豆包的输入框没有找到。", "doubao_ui")
signal?.throwIfAborted()
await page.key("Enter", { keyCode: 13, text: "\r" })
// the send button, as a person sends; Enter when there is none. Enter
// alone was seen not to send while a menu of the page stayed open.
if (!(await page.eval(SEND))) await page.key("Enter", { keyCode: 13, text: "\r" })
let last = null
let changed = Date.now()
const start = Date.now()
+20 -5
View File
@@ -5,7 +5,7 @@
// request into the input, and reads the reply as Doubao renders it. The
// client's tools are asked for as <tool_call> text blocks and given back
// as OpenAI tool_calls. See README.md for what that costs.
import { Doubao, DoubaoError, MODELS, choose, quotaOf, usageOf } from "./doubao.mjs"
import { Doubao, DoubaoError, EFFORTS, MODELS, choose, lookup, quotaOf, usageOf } from "./doubao.mjs"
import { completion, sse } from "./openai.mjs"
import { flatten } from "./prompt.mjs"
@@ -17,6 +17,17 @@ const BUSY = (name) => `${name}正在运行。${name}同时只能开一个,插
const json = (status, message, type) =>
new Response(JSON.stringify({ error: { message, type } }), { status, headers: { "Content-Type": "application/json" } })
// variantsOf offers a model's 推理强度 levels as reasoning efforts
// (低 low, 中 medium, 高 high, 极高 xhigh, 最高 max).
function variantsOf(m) {
const out = {}
for (const name of m?.efforts ?? []) {
const e = EFFORTS.find(([n]) => n === name)
if (e) out[e[1]] = { reasoningEffort: e[1] }
}
return Object.keys(out).length ? out : null
}
// 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").
@@ -33,6 +44,7 @@ function models(table = MODELS) {
// 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 } : {}),
...(variantsOf(m) ? { variants: variantsOf(m) } : {}),
}
return out
}
@@ -136,15 +148,18 @@ export function createPlugin({ doubao = new Doubao(), newId, pick = choose } = {
return json(400, "请求不是 JSON。", "invalid_request_error")
}
const model = String(body.model ?? "auto").replace(/^doubao-work\//, "")
const known = modelTable(doubao)[model] || (typeof doubao?.known === "function" && (await doubao.known(model, { signal })))
if (!known) return json(404, `没有模型 ${model}。豆包的模型菜单里有:${Object.keys(modelTable(doubao)).join("、")}。`, "model_not_found")
const known = lookup(modelTable(doubao), model) || (typeof doubao?.known === "function" && (await doubao.known(model, { signal })))
if (!known) return json(404, `没有模型 ${model}。豆包工作的模型有:${Object.keys(modelTable(doubao)).join("、")}。`, "model_not_found")
// the client's reasoning effort, as OpenAI's chat completions or
// the Responses API write it
const effort = String(body.reasoning_effort ?? body.reasoning?.effort ?? "")
const prompt = flatten(body)
const id = "chatcmpl-" + Math.random().toString(36).slice(2)
const promptTokens = (r) => usageOf(r?.usage) || Math.ceil(prompt.length / 3)
try {
if (body.stream)
return await sse({ id, model, signal, newId, promptTokens, ask: (onUpdate, sig) => doubao.ask(prompt, { model, signal: sig, onUpdate }) })
const final = await doubao.ask(prompt, { model, signal })
return await sse({ id, model, signal, newId, promptTokens, ask: (onUpdate, sig) => doubao.ask(prompt, { model, effort, signal: sig, onUpdate }) })
const final = await doubao.ask(prompt, { model, effort, signal })
return Response.json(completion({ id, model, final, promptTokens: promptTokens(final), newId }))
} catch (e) {
return failed(e)
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-doubao-work-auth",
"version": "0.1.9",
"version": "0.1.10",
"type": "module",
"main": "./opencode.mjs",
"files": [
+780
View File
@@ -0,0 +1,780 @@
{
"status": 200,
"code": 0,
"conf": {
"default_select_mode_map": {
"creation": {
"mode_id": "3",
"model": {
"item_id": "9",
"model_item_key": "9"
},
"reasoning_effort": 5
},
"office": {
"mode_id": "3",
"model": {
"item_id": "9",
"model_item_key": "9"
},
"reasoning_effort": 5
}
},
"mode_list": {
"expose_config": {
"max_exposed_num": 4,
"text": "更多"
},
"item_list": [
{
"agent_mode": 1,
"conversation_mode_list": [
"office",
"creation"
],
"default_conversation_mode": "office",
"default_model": {
"item_id": "9",
"model_item_key": "9"
},
"mode_id": "3",
"model_list": {
"expose_config": {
"max_exposed_num": 10,
"text": "更多模型"
},
"item_list": [
{
"conversation_mode_list": [
"office",
"creation"
],
"default_mode": "3",
"item_id": 9,
"model_extra_params": {
"total_window_size": "256000"
},
"model_item_key": "9",
"name": "自动",
"reasoning_effort_config": {
"default_level": 5,
"option_list": [
{
"level": 3,
"name": "低"
},
{
"level": 4,
"name": "中"
},
{
"level": 5,
"name": "高"
}
]
},
"show_task_tools": 1
},
{
"conversation_mode_list": [
"office",
"creation"
],
"default_mode": "3",
"item_id": 10001,
"model_extra_params": {
"memory_profile": "256k",
"total_window_size": "256000"
},
"model_item_key": "seed-lite-7b",
"name": "豆包 2.1 Lite",
"reasoning_effort_config": {
"default_level": 5,
"option_list": [
{
"level": 3,
"name": "低"
},
{
"level": 4,
"name": "中"
},
{
"level": 5,
"name": "高"
}
]
},
"show_task_tools": 1
},
{
"conversation_mode_list": [
"office",
"creation"
],
"default_mode": "3",
"item_id": 5,
"model_extra_params": {
"total_window_size": "256000"
},
"model_item_key": "5",
"name": "豆包 2.1 Pro",
"need_login": true,
"reasoning_effort_config": {
"default_level": 5,
"option_list": [
{
"level": 3,
"name": "低"
},
{
"level": 4,
"name": "中"
},
{
"level": 5,
"name": "高"
}
]
},
"show_task_tools": 1,
"subscribe_config": {
"jump_url": "https://www.doubao.com/member/subscription?default_sku_key=doubao_personal_std&enter_method=answer_peak_limit&scene_key=message&trigger_scene=peak_hour_limit",
"need_upgrade": false
}
},
{
"conversation_mode_list": [
"office",
"creation"
],
"default_mode": "3",
"item_id": 10001,
"model_item_key": "person-deepseek-v4-1-flash-261017",
"name": "DeepSeek V4.1 Flash",
"reasoning_effort_config": {
"default_level": 5,
"option_list": [
{
"level": 3,
"name": "低"
},
{
"level": 4,
"name": "中"
},
{
"level": 5,
"name": "高"
},
{
"level": 6,
"name": "极高"
},
{
"level": 7,
"name": "最高"
}
]
},
"show_task_tools": 1
},
{
"conversation_mode_list": [
"office",
"creation"
],
"default_mode": "3",
"item_id": 10001,
"model_item_key": "person-kimi-k3-1-pro-261111",
"name": "Kimi K3.1 Pro",
"reasoning_effort_config": {
"default_level": 5,
"option_list": [
{
"level": 3,
"name": "低"
},
{
"level": 4,
"name": "中"
},
{
"level": 5,
"name": "高"
},
{
"level": 6,
"name": "极高"
},
{
"level": 7,
"name": "最高"
}
]
},
"show_task_tools": 1
},
{
"conversation_mode_list": [
"office",
"creation"
],
"default_mode": "3",
"item_id": 10001,
"model_item_key": "person-kimi-k3-1-pro-highspeed-261111",
"name": "Kimi K3.1 Pro 高速",
"reasoning_effort_config": {
"default_level": 5,
"option_list": [
{
"level": 3,
"name": "低"
},
{
"level": 4,
"name": "中"
},
{
"level": 5,
"name": "高"
},
{
"level": 6,
"name": "极高"
},
{
"level": 7,
"name": "最高"
}
]
},
"show_task_tools": 1
},
{
"conversation_mode_list": [
"office",
"creation"
],
"default_mode": "3",
"item_id": 10001,
"model_item_key": "person-kimi-k3-261111",
"name": "Kimi K3",
"reasoning_effort_config": {
"default_level": 5,
"option_list": [
{
"level": 3,
"name": "低"
},
{
"level": 4,
"name": "中"
},
{
"level": 5,
"name": "高"
},
{
"level": 6,
"name": "极高"
},
{
"level": 7,
"name": "最高"
}
]
},
"show_task_tools": 1
},
{
"conversation_mode_list": [
"office",
"creation"
],
"default_mode": "3",
"item_id": 10001,
"model_item_key": "person-glm-5-3-261111",
"name": "GLM 5.3",
"reasoning_effort_config": {
"default_level": 5,
"option_list": [
{
"level": 3,
"name": "低"
},
{
"level": 5,
"name": "高"
},
{
"level": 7,
"name": "最高"
}
]
},
"show_task_tools": 1
},
{
"conversation_mode_list": [
"office",
"creation"
],
"default_mode": "3",
"item_id": 10001,
"model_item_key": "person-glm-5-3-flash-261111",
"name": "GLM 5.3 Flash",
"reasoning_effort_config": {
"default_level": 5,
"option_list": [
{
"level": 3,
"name": "低"
},
{
"level": 5,
"name": "高"
},
{
"level": 7,
"name": "最高"
}
]
},
"show_task_tools": 1
},
{
"conversation_mode_list": [
"office",
"creation"
],
"default_mode": "3",
"item_id": 10001,
"model_item_key": "person-deepseek-v4-pro-ga-260813",
"name": "DeepSeek V4 Pro",
"reasoning_effort_config": {
"default_level": 5,
"option_list": [
{
"level": 3,
"name": "低"
},
{
"level": 4,
"name": "中"
},
{
"level": 5,
"name": "高"
},
{
"level": 6,
"name": "极高"
},
{
"level": 7,
"name": "最高"
}
]
},
"show_task_tools": 1
}
],
"title": "选择模型"
},
"name": "工作任务",
"need_login": true,
"selected_name": "工作任务",
"show_reasoning_effort": true,
"show_task_tools": 1,
"support_models": [
{
"item_id": "9",
"model_item_key": "9"
},
{
"item_id": "5",
"model_item_key": "5"
},
{
"item_id": "10001",
"model_item_key": "seed-lite-7b"
},
{
"item_id": "10001",
"model_item_key": "person-deepseek-v4-1-flash-261017"
},
{
"item_id": "10001",
"model_item_key": "person-kimi-k3-1-pro-261111"
},
{
"item_id": "10001",
"model_item_key": "person-kimi-k3-1-pro-highspeed-261111"
},
{
"item_id": "10001",
"model_item_key": "person-kimi-k3-261111"
},
{
"item_id": "10001",
"model_item_key": "person-glm-5-3-261111"
},
{
"item_id": "10001",
"model_item_key": "person-glm-5-3-flash-261111"
},
{
"item_id": "10001",
"model_item_key": "person-deepseek-v4-pro-ga-260813"
}
]
}
]
},
"model_list": {
"expose_config": {
"max_exposed_num": 10,
"text": "更多模型"
},
"item_list": [
{
"conversation_mode_list": [
"office",
"creation"
],
"default_mode": "3",
"item_id": 9,
"model_extra_params": {
"total_window_size": "256000"
},
"model_item_key": "9",
"name": "自动",
"reasoning_effort_config": {
"default_level": 5,
"option_list": [
{
"level": 3,
"name": "低"
},
{
"level": 4,
"name": "中"
},
{
"level": 5,
"name": "高"
}
]
},
"show_task_tools": 1
},
{
"conversation_mode_list": [
"office",
"creation"
],
"default_mode": "3",
"item_id": 10001,
"model_extra_params": {
"memory_profile": "256k",
"total_window_size": "256000"
},
"model_item_key": "seed-lite-7b",
"name": "豆包 2.1 Lite",
"reasoning_effort_config": {
"default_level": 5,
"option_list": [
{
"level": 3,
"name": "低"
},
{
"level": 4,
"name": "中"
},
{
"level": 5,
"name": "高"
}
]
},
"show_task_tools": 1
},
{
"conversation_mode_list": [
"office",
"creation"
],
"default_mode": "3",
"item_id": 5,
"model_extra_params": {
"total_window_size": "256000"
},
"model_item_key": "5",
"name": "豆包 2.1 Pro",
"need_login": true,
"reasoning_effort_config": {
"default_level": 5,
"option_list": [
{
"level": 3,
"name": "低"
},
{
"level": 4,
"name": "中"
},
{
"level": 5,
"name": "高"
}
]
},
"show_task_tools": 1,
"subscribe_config": {
"jump_url": "https://www.doubao.com/member/subscription?default_sku_key=doubao_personal_std&enter_method=answer_peak_limit&scene_key=message&trigger_scene=peak_hour_limit",
"need_upgrade": false
}
},
{
"conversation_mode_list": [
"office",
"creation"
],
"default_mode": "3",
"item_id": 10001,
"model_item_key": "person-deepseek-v4-1-flash-261017",
"name": "DeepSeek V4.1 Flash",
"reasoning_effort_config": {
"default_level": 5,
"option_list": [
{
"level": 3,
"name": "低"
},
{
"level": 4,
"name": "中"
},
{
"level": 5,
"name": "高"
},
{
"level": 6,
"name": "极高"
},
{
"level": 7,
"name": "最高"
}
]
},
"show_task_tools": 1
},
{
"conversation_mode_list": [
"office",
"creation"
],
"default_mode": "3",
"item_id": 10001,
"model_item_key": "person-kimi-k3-1-pro-261111",
"name": "Kimi K3.1 Pro",
"reasoning_effort_config": {
"default_level": 5,
"option_list": [
{
"level": 3,
"name": "低"
},
{
"level": 4,
"name": "中"
},
{
"level": 5,
"name": "高"
},
{
"level": 6,
"name": "极高"
},
{
"level": 7,
"name": "最高"
}
]
},
"show_task_tools": 1
},
{
"conversation_mode_list": [
"office",
"creation"
],
"default_mode": "3",
"item_id": 10001,
"model_item_key": "person-kimi-k3-1-pro-highspeed-261111",
"name": "Kimi K3.1 Pro 高速",
"reasoning_effort_config": {
"default_level": 5,
"option_list": [
{
"level": 3,
"name": "低"
},
{
"level": 4,
"name": "中"
},
{
"level": 5,
"name": "高"
},
{
"level": 6,
"name": "极高"
},
{
"level": 7,
"name": "最高"
}
]
},
"show_task_tools": 1
},
{
"conversation_mode_list": [
"office",
"creation"
],
"default_mode": "3",
"item_id": 10001,
"model_item_key": "person-kimi-k3-261111",
"name": "Kimi K3",
"reasoning_effort_config": {
"default_level": 5,
"option_list": [
{
"level": 3,
"name": "低"
},
{
"level": 4,
"name": "中"
},
{
"level": 5,
"name": "高"
},
{
"level": 6,
"name": "极高"
},
{
"level": 7,
"name": "最高"
}
]
},
"show_task_tools": 1
},
{
"conversation_mode_list": [
"office",
"creation"
],
"default_mode": "3",
"item_id": 10001,
"model_item_key": "person-glm-5-3-261111",
"name": "GLM 5.3",
"reasoning_effort_config": {
"default_level": 5,
"option_list": [
{
"level": 3,
"name": "低"
},
{
"level": 5,
"name": "高"
},
{
"level": 7,
"name": "最高"
}
]
},
"show_task_tools": 1
},
{
"conversation_mode_list": [
"office",
"creation"
],
"default_mode": "3",
"item_id": 10001,
"model_item_key": "person-glm-5-3-flash-261111",
"name": "GLM 5.3 Flash",
"reasoning_effort_config": {
"default_level": 5,
"option_list": [
{
"level": 3,
"name": "低"
},
{
"level": 5,
"name": "高"
},
{
"level": 7,
"name": "最高"
}
]
},
"show_task_tools": 1
},
{
"conversation_mode_list": [
"office",
"creation"
],
"default_mode": "3",
"item_id": 10001,
"model_item_key": "person-deepseek-v4-pro-ga-260813",
"name": "DeepSeek V4 Pro",
"reasoning_effort_config": {
"default_level": 5,
"option_list": [
{
"level": 3,
"name": "低"
},
{
"level": 4,
"name": "中"
},
{
"level": 5,
"name": "高"
},
{
"level": 6,
"name": "极高"
},
{
"level": 7,
"name": "最高"
}
]
},
"show_task_tools": 1
}
]
},
"use_mode_model_list": true
}
}