Files
plugins/packages/doubao-work/index.mjs
T
yetone 34f7e7b6cd doubao-work: find 豆包工作 (DoubaoWork.app), not 豆包 (#917)
binary() looked only for /Applications/Doubao.app (豆包,
com.bot.pc.doubao). The reporter has only 豆包工作 at
/Applications/DoubaoWork.app/Contents/MacOS/DoubaoWork
(com.work.pc.doubao), so sign-in always said the app was missing.

choose() now picks { app, binary, dataDir } from both apps, 豆包工作
first, in /Applications and ~/Applications on macOS and under
%LOCALAPPDATA% on Windows. A user already signed in to 豆包 through
the plugin (its profile exists) stays on 豆包 while it is installed, so
the update signs no one out. 豆包工作 keeps its profile, port and model
list in a doubaowork/ subfolder. DOUBAO_WORK_APP still names the binary.
The chat page check (owns, connect) accepts doubaowork://doubaowork-chat/chat
and chrome://doubaowork-chat/chat as well as 豆包's. The busy and
not-installed messages name the chosen app and its download page.

Run (mote, worktree at 6cb5dbe8 + this change; origin/main 1bdc4d4b only
adds an autoclaw change):
- bun test packages/doubao-work: 36 pass, 0 fail.
- bun scripts/check.mjs: exit 0, doubao-work ok.
- Live on this Mac with DoubaoWork 2.36.3 (copied out of the official
  dmg) and a sandbox DOUBAO_WORK_HOME: choose picked 豆包工作, App.start
  launched it, owns accepted it, the page reported
  chrome://doubaowork-chat/chat, input present, signed out; the model
  menu read 自动 / 豆包 2.1 Lite / 豆包 2.1 Pro; the new-task and 云电脑
  steps ran on the real page. A second connect reused the running app.
- 豆包 2.35.8 with a temp profile: same chat page test ids.

Broken by hand (mote): choose searching only 豆包 made "a Mac with only
豆包工作 drives 豆包工作 (#917)" red; the old owns regex made "both apps'
chat pages are the plugin's" red (34 pass, 2 fail). The old code has no
choose/isChat and binary() returns Doubao.app, so the #917 test is red
on it.

Not tried: a signed-in request (no 豆包工作 account here). Windows: the
path %LOCALAPPDATA%\DoubaoWork\Application\app\DoubaoWork.exe comes from
DoubaoWork_installer_2.36.3.exe's config (install_dir_name DoubaoWork,
exe_file_name DoubaoWork.exe) and 豆包's layout; not installed on the
Windows box. Running 豆包工作 and 豆包 side by side.

Reported-by: sinoyster
2026-11-10 12:16:37 +08:00

140 lines
6.6 KiB
JavaScript

// 豆包工作 (Doubao Work) as a model provider. Doubao Work runs its agent
// loop in ByteDance's cloud and has no API, so this plugin uses the app
// the way a person does: it opens 豆包工作 (or 豆包) from a profile of
// its own, starts a new 工作任务 per request on 云电脑, writes the whole
// 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, usageOf } from "./doubao.mjs"
import { completion, sse } from "./openai.mjs"
import { flatten } from "./prompt.mjs"
const ID = "doubao-work"
const BASE = "https://doubao-work.invalid/v1"
const BUSY = (name) => `${name}正在运行。${name}同时只能开一个,插件要用自己的${name}窗口:请先退出${name}(⌘Q)再试。`
const json = (status, message, type) =>
new Response(JSON.stringify({ error: { message, type } }), { status, headers: { "Content-Type": "application/json" } })
// 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(table = MODELS) {
const out = {}
for (const [id, m] of Object.entries(table))
out[id] = {
name: m.name,
limit: { context: 256000, output: 32768 },
tool_call: true,
reasoning: true,
attachment: false,
modalities: { input: ["text"], output: ["text"] },
}
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)
// pick says which app the plugin drives (doubao.mjs choose): its name goes
// in the messages, and no binary at all means Linux.
export function createPlugin({ doubao = new Doubao(), newId, pick = choose } = {}) {
const failed = (e) => {
if (e?.signIn) throw e
if (e?.name === "AbortError" || e?.name === "TimeoutError") throw e
const status = String(e?.code ?? "").startsWith("app_") ? 503 : e?.status ?? 502
return json(status, e?.code === "app_busy" ? BUSY(pick().app.name) : String(e?.message ?? e), e?.code ?? "doubao_error")
}
return {
config: async (cfg) => {
cfg.provider ??= {}
// 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,
maxConcurrency: 1,
methods: [
{
type: "oauth",
label: "在豆包窗口中登录",
authorize: async () => ({
url: "",
method: "auto",
instructions: "将打开一个单独的豆包工作窗口(不影响你平时用的豆包工作或豆包)。请在其中登录,登录后回到这里。",
callback: async () => {
const { app, binary } = pick()
if (!binary) return { type: "failed", error: "豆包工作插件只支持 macOS 和 Windows:豆包工作和豆包都没有 Linux 版。" }
let s
try {
s = await doubao.waitSignedIn()
} catch (e) {
if (e?.code === "app_missing") return { type: "failed", error: `没有找到${app.name},请先安装:${app.download}` }
if (e?.code === "app_busy") return { type: "failed", error: BUSY(app.name) }
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 }
},
}),
},
],
loader: async () => ({
baseURL: BASE,
apiKey: "doubao-desktop",
async fetch(input, init = {}) {
const request = input instanceof Request ? new Request(input, init) : null
const url = new URL(request ? request.url : String(input))
const method = request ? request.method : init.method ?? "GET"
if (url.origin !== new URL(BASE).origin || !url.pathname.endsWith("/chat/completions") || method !== "POST")
return json(404, "豆包工作只提供 chat/completions。", "not_found")
const signal = request ? request.signal : init.signal
let body
try {
body = JSON.parse(request ? await request.text() : typeof init.body === "string" ? init.body : await new Response(init.body).text())
} catch {
return json(400, "请求不是 JSON。", "invalid_request_error")
}
const model = String(body.model ?? "auto").replace(/^doubao-work\//, "")
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)
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 Response.json(completion({ id, model, final, promptTokens: promptTokens(final), newId }))
} catch (e) {
return failed(e)
}
},
}),
},
}
}
export default async function DoubaoWorkProvider() {
return createPlugin()
}
export const _internal = { createPlugin, models, BASE, ID, DoubaoError }