Files
plugins/packages/doubao-work/prompt.mjs
T
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

143 lines
6.5 KiB
JavaScript

// A cloud agent is not a model: it takes one message and runs its own
// loop. To serve a client's chat request through it, the whole request
// (system prompt, tools, every turn) is written into one message, and the
// client's tools are asked for as text: <tool_call>{json}</tool_call>
// blocks, which are read back into OpenAI tool_calls.
const OPEN = "<tool_call>"
const CLOSE = "</tool_call>"
function partText(content) {
if (content == null) return ""
if (typeof content === "string") return content
if (!Array.isArray(content)) return typeof content === "object" ? JSON.stringify(content) : String(content)
return content
.map((p) => {
if (typeof p === "string") return p
if (p?.type === "text" || p?.type === "input_text") return p.text ?? ""
if (p?.type === "image_url" || p?.type === "input_image" || p?.type === "image") return "[image omitted: only text reaches this model]"
if (p?.type === "file" || p?.type === "input_file") return "[file omitted: only text reaches this model]"
return p?.text ?? ""
})
.join("")
}
function toolLine(t) {
const f = t?.function ?? t
if (!f?.name) return null
const desc = String(f.description ?? "").trim()
const params = f.parameters ? JSON.stringify(f.parameters) : "{}"
return `## ${f.name}\n${desc ? desc + "\n" : ""}Arguments (JSON Schema): ${params}`
}
function callText(c) {
const f = c?.function ?? c
let args = f?.arguments ?? {}
if (typeof args === "string") {
try { args = JSON.parse(args || "{}") } catch {}
}
return OPEN + JSON.stringify({ name: f?.name, arguments: args }) + CLOSE
}
// choice reads tool_choice into what the prompt asks of the model.
function choice(body, names) {
const c = body.tool_choice
if (c === "none") return { off: true }
if (c === "required") return { must: true }
const name = c?.function?.name ?? c?.name
if (name && names.includes(name)) return { must: true, only: name }
return {}
}
// flatten writes an OpenAI chat request as one message for the agent.
export function flatten(body) {
const messages = Array.isArray(body?.messages) ? body.messages : []
const tools = (Array.isArray(body?.tools) ? body.tools : []).map((t) => ({ line: toolLine(t), name: (t?.function ?? t)?.name })).filter((t) => t.line)
const ch = choice(body ?? {}, tools.map((t) => t.name))
const useTools = tools.length > 0 && !ch.off
const out = []
out.push("You are the language model behind a client application. You cannot run anything yourself and must not use your own tools, web search, files or computer: you only write text.")
if (useTools) {
out.push(
`When an action is needed, reply with one or more blocks of exactly\n${OPEN}{"name": "<tool>", "arguments": {...}}${CLOSE}\nand nothing after them. The caller runs them and sends you the results in the next message. When no action is needed, answer in plain text with no ${OPEN} block.`,
)
if (ch.only) out.push(`You must call the tool ${ch.only} now.`)
else if (ch.must) out.push("You must call at least one tool now.")
}
const system = messages.filter((m) => m?.role === "system" || m?.role === "developer").map((m) => partText(m.content).trim()).filter(Boolean)
if (system.length) out.push("# Instructions from the client\n\n" + system.join("\n\n"))
if (useTools) out.push("# Tools\n\n" + tools.map((t) => t.line).join("\n\n"))
if (body?.response_format?.type === "json_object" || body?.response_format?.type === "json_schema") {
const schema = body.response_format.json_schema?.schema
out.push("Answer with one JSON value and nothing else." + (schema ? " It must match this JSON Schema: " + JSON.stringify(schema) : ""))
}
const names = new Map()
const turns = []
for (const m of messages) {
if (!m || m.role === "system" || m.role === "developer") continue
if (m.role === "user") turns.push("[user]\n" + partText(m.content))
else if (m.role === "assistant") {
const parts = []
const text = partText(m.content)
if (text.trim()) parts.push(text)
for (const c of m.tool_calls ?? []) {
names.set(c.id, c.function?.name)
parts.push(callText(c))
}
if (parts.length) turns.push("[assistant]\n" + parts.join("\n"))
} else if (m.role === "tool" || m.role === "function") {
const n = m.name ?? names.get(m.tool_call_id)
turns.push(`[tool result${n ? " of " + n : ""}]\n` + partText(m.content))
}
}
out.push("# Conversation so far\n\n" + turns.join("\n\n"))
out.push("Write the next [assistant] turn now, without the [assistant] label.")
return out.join("\n\n")
}
// heldFrom is where text stops being safe to show while it streams: the
// first <tool_call>, or a tail that could be the start of one.
export function heldFrom(text) {
const at = text.indexOf(OPEN)
if (at >= 0) return at
for (let n = Math.min(OPEN.length - 1, text.length); n > 0; n--) if (OPEN.startsWith(text.slice(-n))) return text.length - n
return text.length
}
function parseCall(raw) {
let s = raw.trim().replace(/^```(?:json)?\s*/i, "").replace(/\s*```$/, "").trim()
let v
try { v = JSON.parse(s) } catch { return null }
if (Array.isArray(v)) v = v[0]
const name = v?.name ?? v?.function?.name ?? v?.tool
if (typeof name !== "string" || !name) return null
let args = v.arguments ?? v.parameters ?? v.input ?? v.args ?? v.function?.arguments ?? {}
if (typeof args === "string") {
try { args = JSON.parse(args) } catch {}
}
return { name, arguments: typeof args === "string" ? args : JSON.stringify(args ?? {}) }
}
// parse splits a finished reply into its text and tool calls. A block that
// isn't a call it can read stays in the text, so nothing the model wrote is
// lost. An unclosed last block is read to the end.
export function parse(text, newId = () => "call_" + Math.random().toString(36).slice(2, 14)) {
const calls = []
let rest = ""
let i = 0
while (i < text.length) {
const at = text.indexOf(OPEN, i)
if (at < 0) { rest += text.slice(i); break }
rest += text.slice(i, at)
const end = text.indexOf(CLOSE, at + OPEN.length)
const raw = text.slice(at + OPEN.length, end < 0 ? text.length : end)
const call = parseCall(raw)
if (call) calls.push({ id: newId(), type: "function", function: call })
else rest += text.slice(at, end < 0 ? text.length : end + CLOSE.length)
i = end < 0 ? text.length : end + CLOSE.length
}
// fences left empty around a call (```xml … ```) are not text
const cleaned = calls.length ? rest.replace(/```[a-z]*\s*```/gi, "") : rest
return { text: calls.length ? cleaned.trim() : rest, calls, raw: rest }
}