Files
yetone c1ed1b511e doubao-work 0.1.0: 豆包工作 as a provider, by driving the Doubao desktop app
Doubao Work runs its agent loop in ByteDance's cloud and has no API. This
plugin uses the desktop app the way a person does and gives the reply back
as an OpenAI chat completion:

- cdp.mjs (knows nothing about Doubao): starts a Chromium-based app from a
  profile of its own with DevTools on a port it picked and saved, reuses it
  while it runs, never kills anything; Page evaluates and presses keys.
- doubao.mjs: per request a new 工作任务, switched to 云电脑 (Doubao's agent
  never touches this computer), the model picked (Pro needs a paid plan:
  403), the whole request written into tiptap one paragraph a line, Enter,
  and the reply read from the message's content_blocks_v2 (markdown, and
  thinking as reasoning_content) until is_finish. One request at a time.
- prompt.mjs / openai.mjs: system prompt, tools and turns flattened into one
  message; tools asked for as <tool_call>{json}</tool_call> and given back
  as tool_calls; SSE that holds text from the first call (or a tail that
  may start one), and that throws a failure before the reply begins so it
  goes back as an HTTP error.
- Sign-in waits for the account in the separate Doubao window.

Run:
- bun test packages/doubao-work on mote: 24 pass.
- Full suite on mote the way CI runs it (HOME=$(mktemp -d) bun test):
  6936 pass, 20 skip, 0 fail. bun scripts/check.mjs: doubao-work ok.
- Broken by hand: sleep without its aborted check; "an abort between two
  polls stops the ask too" goes red (runs to the 180s idle timeout), green
  with it. Found by the first run: an abort landing between polls was lost.
- Live, the loader against a signed-in Doubao 147 on macOS: auto plain
  answer 200 in 3.9s; doubao-2.1-lite streamed Bash tool call (first byte
  3.6s, total 4.8s); tool result follow-up answered "412 lines"; Pro gave
  403 doubao_upgrade; a 300-word story streamed as 20 content deltas with
  its ```python fence kept; a client abort ended the stream and the next
  request answered 200.

Not tried: through magpie's plugin host and a real agent (Claude Code
sized requests); Windows and Linux (unsupported, sign-in says so). A
stopped request stops being read but Doubao finishes its task (README).
2026-11-09 06:05:35 +08:00

135 lines
5.2 KiB
JavaScript

// What the plugin answers: an OpenAI chat completion, streamed as SSE or
// whole, built from the reads of Doubao's reply.
import { heldFrom, parse } from "./prompt.mjs"
const enc = new TextEncoder()
// Streamer turns successive reads of a growing reply into chunk deltas.
// Text after the first <tool_call> (or a tail that may start one) is held,
// and becomes tool_calls when the reply ends. A read that isn't the last
// one grown (Doubao rewrote what it showed) adds nothing until it is again.
export class Streamer {
constructor() {
this.text = ""
this.shown = 0
this.reasoning = ""
}
update({ text = "", reasoning = "" }) {
const out = {}
if (reasoning.startsWith(this.reasoning) && reasoning.length > this.reasoning.length) {
out.reasoning = reasoning.slice(this.reasoning.length)
this.reasoning = reasoning
}
if (text.startsWith(this.text.slice(0, this.shown))) {
this.text = text
const upto = heldFrom(text)
if (upto > this.shown) {
out.content = text.slice(this.shown, upto)
this.shown = upto
}
}
return out
}
// finish gives what is left of the text and the tool calls. What was
// shown stopped before the first call, so the text with its calls taken
// out still starts with it.
finish(final, newId) {
const p = parse(final?.text ?? this.text, newId)
const shown = this.text.slice(0, this.shown)
let content = p.raw.startsWith(shown) ? p.raw.slice(shown.length) : ""
if (p.calls.length) content = content.replace(/```[a-z]*\s*```/gi, "").trim() ? content.replace(/```[a-z]*\s*```/gi, "").trimEnd() : ""
return { content, calls: p.calls }
}
}
export function usage(promptTokens, text, reasoning = "") {
// Doubao counts the prompt (context_window_usage) but not the reply; the
// reply is estimated at one token for three characters.
const completion = Math.ceil(((text ?? "").length + (reasoning ?? "").length) / 3)
return { prompt_tokens: promptTokens, completion_tokens: completion, total_tokens: promptTokens + completion }
}
const chunk = (id, model, delta, finish = null, extra = {}) =>
enc.encode(
"data: " +
JSON.stringify({ id, object: "chat.completion.chunk", created: Math.floor(Date.now() / 1000), model, choices: [{ index: 0, delta, finish_reason: finish }], ...extra }) +
"\n\n",
)
// sse runs ask(onUpdate, signal) and streams what it reads. It resolves
// once the reply has begun, so a failure before that (not signed in, a
// control not found, the model refused) throws here and goes back as an
// HTTP error, not as a 200 stream.
export async function sse({ id, model, ask, signal, promptTokens = () => 0, newId }) {
const st = new Streamer()
const abort = new AbortController()
const both = signal ? AbortSignal.any([signal, abort.signal]) : abort.signal
const buf = []
let ctl = null
let ended = false
let failure = null
let begun = false
let onFirst
const first = new Promise((r) => (onFirst = r))
const push = (b) => (ctl ? ctl.enqueue(b) : buf.push(b))
const deltas = (d) => {
if (d.reasoning) push(chunk(id, model, { reasoning_content: d.reasoning }))
if (d.content) push(chunk(id, model, { content: d.content }))
}
push(chunk(id, model, { role: "assistant", content: "" }))
;(async () => {
try {
const final = await ask((r) => {
begun = true
onFirst()
deltas(st.update(r))
}, both)
begun = true
deltas(st.update(final))
const { content, calls } = st.finish(final, newId)
if (content) push(chunk(id, model, { content }))
if (calls.length) push(chunk(id, model, { tool_calls: calls.map((x, index) => ({ index, id: x.id, type: "function", function: x.function })) }))
push(chunk(id, model, {}, calls.length ? "tool_calls" : "stop"))
push(chunk(id, model, {}, null, { choices: [], usage: usage(promptTokens(final), final.text, final.reasoning) }))
push(enc.encode("data: [DONE]\n\n"))
} catch (e) {
failure = e
if (begun && !both.aborted) push(enc.encode("data: " + JSON.stringify({ error: { message: String(e?.message ?? e), type: e?.code ?? "doubao_error" } }) + "\n\n"))
} finally {
ended = true
onFirst()
if (ctl) try { ctl.close() } catch {}
}
})()
await first
if (failure && !begun) throw failure
const stream = new ReadableStream({
start(c) {
ctl = c
for (const b of buf.splice(0)) c.enqueue(b)
if (ended) c.close()
},
cancel() {
abort.abort()
},
})
return new Response(stream, { headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache" } })
}
export function completion({ id, model, final, promptTokens, newId }) {
const { text, calls } = parse(final.text ?? "", newId)
const message = { role: "assistant", content: text || (calls.length ? null : "") }
if (final.reasoning) message.reasoning_content = final.reasoning
if (calls.length) message.tool_calls = calls
return {
id,
object: "chat.completion",
created: Math.floor(Date.now() / 1000),
model,
choices: [{ index: 0, message, finish_reason: calls.length ? "tool_calls" : "stop" }],
usage: usage(promptTokens, final.text, final.reasoning),
}
}