From c1ed1b511ec30f5f3387192508e1d793d70ebe28 Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 9 Nov 2026 06:05:35 +0800 Subject: [PATCH] =?UTF-8?q?doubao-work=200.1.0:=20=E8=B1=86=E5=8C=85?= =?UTF-8?q?=E5=B7=A5=E4=BD=9C=20as=20a=20provider,=20by=20driving=20the=20?= =?UTF-8?q?Doubao=20desktop=20app?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 {json} 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). --- README.md | 1 + packages/doubao-work/README.md | 53 ++ packages/doubao-work/cdp.mjs | 178 +++++++ packages/doubao-work/doubao-work.test.mjs | 354 +++++++++++++ packages/doubao-work/doubao.mjs | 244 +++++++++ packages/doubao-work/index.mjs | 102 ++++ packages/doubao-work/openai.mjs | 134 +++++ packages/doubao-work/opencode.mjs | 5 + packages/doubao-work/opencode2.mjs | 596 ++++++++++++++++++++++ packages/doubao-work/package.json | 30 ++ packages/doubao-work/prompt.mjs | 142 ++++++ registry.json | 1 + 12 files changed, 1840 insertions(+) create mode 100644 packages/doubao-work/README.md create mode 100644 packages/doubao-work/cdp.mjs create mode 100644 packages/doubao-work/doubao-work.test.mjs create mode 100644 packages/doubao-work/doubao.mjs create mode 100644 packages/doubao-work/index.mjs create mode 100644 packages/doubao-work/openai.mjs create mode 100644 packages/doubao-work/opencode.mjs create mode 100644 packages/doubao-work/opencode2.mjs create mode 100644 packages/doubao-work/package.json create mode 100644 packages/doubao-work/prompt.mjs diff --git a/README.md b/README.md index 733b30a..1b6fc54 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ subscription and makes its requests. The packages work in OpenCode and in | [grok](packages/grok) | Grok (SuperGrok / X Premium+), through the Grok Build CLI's sign-in | `grok` | | [inkstone](packages/inkstone) | (Unofficial) 书生·端砚 Token Plan: browser sign-in gives the ink-credit balance, the 5-hour and 7-day windows and the credit packs, and creates an `ink-*` API key to serve the plan's models for chat | `intern-inkstone` | | [joycode](packages/joycode) | JoyCode IDE credits with JD account browser sign-in, live models and credit multipliers (unofficial) | `joycode` | +| [doubao-work](packages/doubao-work) | Doubao Work (豆包工作), whose agent runs in the cloud with no API, through the Doubao desktop app driven the way a person uses it (macOS) | `doubao-work` | | [kimi-work](packages/kimi-work) | Ordinary Kimi desktop Work subscription, through the desktop app's local sign-in; separate from Kimi Code | `kimi-work` | | [kiro](packages/kiro) | Kiro (Free, Pro, Pro+, Power), with Kiro's sign-in, kiro-cli's or the IDE's, or an API key | `kiro` | | [loomy](packages/loomy) | iFlytek's Loomy (loomyad.xunfei.cn), with SMS sign-in | `loomy` | diff --git a/packages/doubao-work/README.md b/packages/doubao-work/README.md new file mode 100644 index 0000000..acb0785 --- /dev/null +++ b/packages/doubao-work/README.md @@ -0,0 +1,53 @@ +# 豆包工作 (Doubao Work) + +Doubao Work runs its agent loop in ByteDance's cloud and has no API, so +there is no request to make on its behalf. This plugin uses the Doubao +desktop app the way a person does instead, and gives what it reads back as +an OpenAI chat completion: + +1. It starts Doubao from a profile of its own (`~/Library/Application + Support/magpie-doubao-work/profile`), with Chrome DevTools on a local + port. Your everyday Doubao is not touched; you sign in once in this + second window. +2. Each request opens a new 工作任务, switches it from 本地电脑 to 云电脑 + (so Doubao's agent never reads or runs anything on your computer), picks + the model, and writes the whole request (system prompt, tools, every + turn) into the input as one message. +3. It reads the reply from the message Doubao renders, as it streams: the + raw markdown, and the thinking as `reasoning_content`. +4. The client's tools are asked for as text, `{"name": …, + "arguments": …}`, 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). + +## What it costs + +- **Unofficial.** It uses Doubao the way its own window does, but ByteDance + may not like it. Use an account you can afford to lose. +- **One request at a time.** There is one window. +- **Every request is a new task** in your Doubao history. +- **A request the client stops** stops being read, but Doubao finishes + its task in the cloud anyway. +- **Slower** than an API: a task takes a few seconds to open, and the reply + is read about seven times a second. +- **Text only.** Images and files in a request are left out. +- **Usage** is Doubao's own prompt count; the reply's tokens are estimated. +- **The DevTools port** is on 127.0.0.1 only, but any program on this + computer can drive the signed-in Doubao window through it while it runs. +- macOS only for now. + +## Settings + +- `DOUBAO_WORK_APP`: the Doubao binary, if it is not at + `/Applications/Doubao.app/Contents/MacOS/Doubao`. +- `DOUBAO_WORK_HOME`: where the profile and port live. + +## Adding another cloud agent + +`cdp.mjs` knows nothing about Doubao: it starts a Chromium-based desktop app +from its own profile and drives one page. `doubao.mjs` is everything that is +Doubao's: which buttons to press and where the reply is. `prompt.mjs` and +`openai.mjs` turn a chat request into one message and the reply back into a +completion. Another app built on Chromium or Electron needs only its own +`doubao.mjs`. diff --git a/packages/doubao-work/cdp.mjs b/packages/doubao-work/cdp.mjs new file mode 100644 index 0000000..a26a134 --- /dev/null +++ b/packages/doubao-work/cdp.mjs @@ -0,0 +1,178 @@ +// A small Chrome DevTools Protocol driver for desktop apps built on +// Chromium. It knows nothing about any one app: an adapter (doubao.mjs) +// says which binary to start, which page to drive and what to do there. +// +// The app runs from a profile of its own (a user-data-dir under the +// plugin's folder), so it never touches the user's everyday copy of the +// app, and Chromium allows remote debugging only for such a profile. The +// debugging port is one this driver picked and saved beside the profile, +// so a later request finds the same running app instead of starting +// another. +import { spawn as nodeSpawn } from "node:child_process" +import fs from "node:fs" +import net from "node:net" +import path from "node:path" + +// sleep waits ms, or rejects at once when signal is (or becomes) aborted. +const sleep = (ms, signal) => + new Promise((resolve, reject) => { + if (signal?.aborted) return reject(signal.reason ?? Error("aborted")) + const stop = () => { clearTimeout(t); reject(signal.reason ?? Error("aborted")) } + const t = setTimeout(() => { signal?.removeEventListener("abort", stop); resolve() }, ms) + signal?.addEventListener("abort", stop, { once: true }) + }) + +// freePort asks the system for a port no one holds, then lets it go. The +// app is started on it a moment later. +export function freePort() { + return new Promise((resolve, reject) => { + const s = net.createServer() + s.unref() + s.on("error", reject) + s.listen(0, "127.0.0.1", () => { const { port } = s.address(); s.close(() => resolve(port)) }) + }) +} + +async function getJSON(url, ms = 1500, fetchImpl = fetch) { + const r = await fetchImpl(url, { signal: AbortSignal.timeout(ms) }) + if (!r.ok) throw Error(`${url}: HTTP ${r.status}`) + return r.json() +} + +// targets lists the pages of the app on port, or null when nothing (or +// something that isn't a DevTools endpoint) answers there. +export async function targets(port, fetchImpl = fetch) { + try { + const list = await getJSON(`http://127.0.0.1:${port}/json/list`, 1500, fetchImpl) + return Array.isArray(list) ? list : null + } catch { + return null + } +} + +// App starts and finds one Chromium-based desktop app run from its own +// profile. +// binary the executable +// dataDir the plugin's folder for this app: profile/ and port live here +// owns (targets) => true when the pages on a port are this app's, +// so a port another program took since is never driven +// args more command-line switches +export class App { + constructor({ binary, dataDir, owns, args = [], spawn = nodeSpawn, fetchImpl = fetch }) { + Object.assign(this, { binary, dataDir, owns, args, spawn, fetchImpl }) + this.profile = path.join(dataDir, "profile") + this.portFile = path.join(dataDir, "port") + } + + savedPort() { + try { + const n = Number(fs.readFileSync(this.portFile, "utf8").trim()) + return Number.isInteger(n) && n > 0 && n < 65536 ? n : 0 + } catch { + return 0 + } + } + + // running gives the port of this app when it is up, else 0. + async running() { + const port = this.savedPort() + if (!port) return 0 + const list = await targets(port, this.fetchImpl) + return list && this.owns(list) ? port : 0 + } + + // start runs the app when it isn't running yet and waits until its pages + // answer. It never stops or kills anything: a port someone else holds is + // left to them and the app is started on another. + async start({ timeout = 45000, signal } = {}) { + const up = await this.running() + if (up) return up + if (!fs.existsSync(this.binary)) throw Object.assign(Error(`${this.binary} is not installed`), { code: "app_missing" }) + fs.mkdirSync(this.profile, { recursive: true }) + const port = await freePort() + fs.writeFileSync(this.portFile, String(port)) + const child = this.spawn(this.binary, [`--remote-debugging-port=${port}`, `--user-data-dir=${this.profile}`, ...this.args], { + detached: true, + stdio: "ignore", + }) + child.unref?.() + const until = Date.now() + timeout + while (Date.now() < until) { + await sleep(400, signal) + const list = await targets(port, this.fetchImpl) + if (list && this.owns(list)) return port + } + throw Object.assign(Error(`${path.basename(this.binary)} did not open its debugging port in ${Math.round(timeout / 1000)}s`), { code: "app_start_timeout" }) + } +} + +// Page is one CDP session on a page target. +export class Page { + static async open(port, pick, { fetchImpl = fetch, WebSocketImpl = globalThis.WebSocket } = {}) { + const list = (await targets(port, fetchImpl)) ?? [] + const t = list.find((x) => x.type === "page" && pick(x)) + if (!t?.webSocketDebuggerUrl) return null + const page = new Page(t, WebSocketImpl) + await page.ready + return page + } + + constructor(target, WebSocketImpl) { + this.target = target + this.id = 0 + this.pending = new Map() + this.closed = false + this.ws = new WebSocketImpl(target.webSocketDebuggerUrl) + this.ready = new Promise((resolve, reject) => { + this.ws.onopen = () => resolve() + this.ws.onerror = (e) => reject(Error("DevTools connection failed: " + (e?.message ?? "error"))) + }) + this.ws.onmessage = (m) => { + let d + try { d = JSON.parse(typeof m.data === "string" ? m.data : String(m.data)) } catch { return } + const p = this.pending.get(d.id) + if (!p) return + this.pending.delete(d.id) + if (d.error) p.reject(Error(`${p.method}: ${d.error.message}`)) + else p.resolve(d.result) + } + this.ws.onclose = () => { + this.closed = true + for (const p of this.pending.values()) p.reject(Error("DevTools connection closed")) + this.pending.clear() + } + } + + call(method, params = {}) { + if (this.closed) return Promise.reject(Error("DevTools connection closed")) + return new Promise((resolve, reject) => { + const id = ++this.id + this.pending.set(id, { resolve, reject, method }) + this.ws.send(JSON.stringify({ id, method, params })) + }) + } + + // eval runs an expression in the page and gives back its value (awaited + // when it is a promise). A page-side exception becomes an Error here. + async eval(expression) { + const r = await this.call("Runtime.evaluate", { expression, returnByValue: true, awaitPromise: true }) + if (r?.exceptionDetails) { + const d = r.exceptionDetails + throw Error("page: " + (d.exception?.description ?? d.text ?? "exception").split("\n")[0]) + } + return r?.result?.value + } + + // key presses one key the way a user's keyboard does. + async key(key, { code = key, keyCode = 0, text, modifiers = 0 } = {}) { + await this.call("Input.dispatchKeyEvent", { type: "keyDown", key, code, windowsVirtualKeyCode: keyCode, text, modifiers }) + await this.call("Input.dispatchKeyEvent", { type: "keyUp", key, code, windowsVirtualKeyCode: keyCode, modifiers }) + } + + close() { + this.closed = true + try { this.ws.close() } catch {} + } +} + +export { sleep } diff --git a/packages/doubao-work/doubao-work.test.mjs b/packages/doubao-work/doubao-work.test.mjs new file mode 100644 index 0000000..4f0b617 --- /dev/null +++ b/packages/doubao-work/doubao-work.test.mjs @@ -0,0 +1,354 @@ +import { test, expect } from "bun:test" +import fs from "node:fs" +import os from "node:os" +import path from "node:path" +import { App, Page } from "./cdp.mjs" +import { Doubao, NEW_TASK, CLOUD, READ, STATE, 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" + +let n = 0 +const ids = () => "call_" + ++n + +// ---- prompt ---- + +test("flatten writes system, tools and every turn, calls and results by name", () => { + const p = flatten({ + messages: [ + { role: "system", content: "Be brief." }, + { role: "user", content: [{ type: "text", text: "How long is main.go?" }, { type: "image_url", image_url: { url: "data:," } }] }, + { role: "assistant", content: null, tool_calls: [{ id: "c1", type: "function", function: { name: "Bash", arguments: '{"command":"wc -l main.go"}' } }] }, + { role: "tool", tool_call_id: "c1", content: "412 main.go" }, + ], + tools: [{ type: "function", function: { name: "Bash", description: "Run a command", parameters: { type: "object", properties: { command: { type: "string" } } } } }], + }) + expect(p).toContain("Be brief.") + expect(p).toContain("## Bash\nRun a command") + expect(p).toContain('{"name":"Bash","arguments":{"command":"wc -l main.go"}}') + expect(p).toContain("[tool result of Bash]\n412 main.go") + expect(p).toContain("[image omitted") + expect(p.indexOf("[user]")).toBeLessThan(p.indexOf("[assistant]")) +}) + +test("tool_choice none leaves the tools out; a named one is required", () => { + const tools = [{ type: "function", function: { name: "Read", parameters: {} } }] + const msgs = [{ role: "user", content: "hi" }] + expect(flatten({ messages: msgs, tools, tool_choice: "none" })).not.toContain("") + expect(flatten({ messages: msgs, tools, tool_choice: { type: "function", function: { name: "Read" } } })).toContain("You must call the tool Read now.") + expect(flatten({ messages: msgs })).not.toContain("# Tools") +}) + +test("parse reads calls, keeps a block it can't read as text, and reads an unclosed last call", () => { + const r = parse('Looking.\n{"name":"Read","arguments":{"path":"a"}}\n```json\n{"name":"Bash","parameters":{"command":"ls"}}\n```', ids) + expect(r.calls.map((c) => [c.function.name, JSON.parse(c.function.arguments)])).toEqual([["Read", { path: "a" }], ["Bash", { command: "ls" }]]) + expect(r.text).toBe("Looking.") + expect(parse("not json", ids)).toMatchObject({ calls: [], text: "not json" }) + expect(parse('{"name":"Read","arguments":{"path":"b"}}', ids).calls[0].function.arguments).toBe('{"path":"b"}') + expect(parse("plain answer", ids)).toMatchObject({ calls: [], text: "plain answer" }) +}) + +test("heldFrom holds a tail that could start a call", () => { + expect(heldFrom("abc")).toBe(3) + expect(heldFrom("abc {")).toBe(4) + expect(heldFrom("a < b")).toBe(5) +}) + +// ---- openai ---- + +test("Streamer shows text up to a call and gives calls at the end", () => { + const s = new Streamer() + expect(s.update({ text: "Let me ", reasoning: "think" })).toEqual({ reasoning: "think", content: "Let me " }) + expect(s.update({ text: "Let me look.{"name":"Read","arguments":{}}' })).toEqual({}) + const f = s.finish({ text: 'Let me look.{"name":"Read","arguments":{}}\n' }, ids) + expect(f.content).toBe("") + expect(f.calls[0].function.name).toBe("Read") +}) + +test("Streamer: a '<' that isn't a call is shown at the end", () => { + const s = new Streamer() + expect(s.update({ text: "1 <" })).toEqual({ content: "1 " }) + expect(s.finish({ text: "1 <" }, ids)).toEqual({ content: "<", calls: [] }) +}) + +const events = async (res) => + (await res.text()) + .split("\n\n") + .filter(Boolean) + .map((l) => l.replace(/^data: /, "")) + .map((l) => (l === "[DONE]" ? l : JSON.parse(l))) + +test("sse streams reasoning, content, tool_calls, finish and usage", async () => { + const res = await sse({ + id: "x", + model: "auto", + newId: ids, + promptTokens: () => 100, + ask: async (on) => { + on({ text: "", reasoning: "hmm" }) + on({ text: "Reading.", reasoning: "hmm" }) + return { text: 'Reading.{"name":"Read","arguments":{"path":"x"}}', reasoning: "hmm" } + }, + }) + expect(res.headers.get("content-type")).toBe("text/event-stream") + const ev = await events(res) + const deltas = ev.filter((e) => e !== "[DONE]" && e.choices?.length).map((e) => e.choices[0]) + expect(deltas.map((d) => d.delta.reasoning_content).filter(Boolean).join("")).toBe("hmm") + expect(deltas.map((d) => d.delta.content).filter(Boolean).join("")).toBe("Reading.") + expect(deltas.find((d) => d.delta.tool_calls).delta.tool_calls[0]).toMatchObject({ index: 0, type: "function", function: { name: "Read", arguments: '{"path":"x"}' } }) + expect(deltas.at(-1).finish_reason).toBe("tool_calls") + expect(ev.find((e) => e.usage).usage.prompt_tokens).toBe(100) + expect(ev.at(-1)).toBe("[DONE]") +}) + +test("sse throws a failure that comes before the reply, and streams one after it", async () => { + const boom = Object.assign(Error("not signed in"), { code: "doubao_signed_out" }) + await expect(sse({ id: "x", model: "auto", ask: async () => { throw boom } })).rejects.toBe(boom) + const res = await sse({ id: "x", model: "auto", ask: async (on) => { on({ text: "par" }); throw Error("cut off") } }) + const ev = await events(res) + expect(ev.at(-1).error.message).toBe("cut off") +}) + +test("sse cancel aborts the ask", async () => { + let seen + const res = await sse({ + id: "x", + model: "auto", + ask: (on, signal) => + new Promise((_, reject) => { + seen = signal + on({ text: "a" }) + signal.addEventListener("abort", () => reject(signal.reason)) + }), + }) + await res.body.cancel() + expect(seen.aborted).toBe(true) +}) + +test("completion gives a whole message", () => { + const c = completion({ id: "x", model: "auto", final: { text: '{"name":"Read","arguments":{"path":"y"}}', reasoning: "r" }, promptTokens: 5, newId: ids }) + expect(c.choices[0]).toMatchObject({ finish_reason: "tool_calls", message: { content: null, reasoning_content: "r" } }) + expect(c.usage.prompt_tokens).toBe(5) +}) + +// ---- doubao adapter ---- + +test("usageOf adds Doubao's prompt counts", () => { + expect(usageOf('{"system_prompt":6423,"messages":111175,"skills":0,"tools":0,"total_window_size":256000}')).toBe(117598) + expect(usageOf("")).toBe(0) + expect(usageOf("nope")).toBe(0) +}) + +test("owns knows Doubao's chat page", () => { + expect(owns([{ url: "doubao://doubao-chat/chat" }])).toBe(true) + expect(owns([{ url: "chrome://newtab" }, { url: "https://doubao-chat/chat" }])).toBe(false) +}) + +function fakePage(reads, { signedIn = true, steps = {} } = {}) { + const calls = [] + const keys = [] + return { + calls, + keys, + closed: false, + async eval(expr) { + calls.push(expr) + if (expr === STATE) return { signedIn, name: "yetone", sends: 0 } + if (expr === NEW_TASK) return steps.newTask ?? "" + if (expr === CLOUD) return steps.cloud ?? "" + 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 + throw Error("unexpected eval") + }, + async key(k) { keys.push(k) }, + } +} + +const fakeApp = { start: async () => 1 } + +test("ask opens a task on 云电脑, sends, and follows the reply to its end", async () => { + const page = fakePage([ + { sends: 0, reply: false }, + { sends: 1, reply: false }, + { sends: 1, reply: true, text: "Hel", reasoning: "", finished: false }, + { sends: 1, reply: true, text: "Hello", reasoning: "", finished: true, status: "Success", reason: "succeed:completion", usage: '{"messages":12}' }, + ]) + const d = new Doubao({ app: fakeApp, openPage: async () => page, poll: 1 }) + const seen = [] + const r = await d.ask("hi\nthere", { model: "doubao-2.1-lite", onUpdate: (x) => seen.push(x.text) }) + expect(r.text).toBe("Hello") + expect(seen).toEqual(["Hel", "Hello"]) + expect(page.keys).toEqual(["Enter"]) + const order = page.calls.map((c) => (c === STATE ? "state" : c === NEW_TASK ? "new" : c === CLOUD ? "cloud" : c.includes("豆包 2.1 Lite") ? "model" : c.includes("insertContent") ? "fill" : "read")) + expect(order.slice(0, 5)).toEqual(["state", "new", "cloud", "model", "fill"]) + expect(page.calls.find((c) => c.includes("insertContent"))).toContain('["hi","there"]') +}) + +test("ask refuses when Doubao is signed out, and a paid model with 403", async () => { + const out = new Doubao({ app: fakeApp, openPage: async () => fakePage([], { signedIn: false }), poll: 1 }) + await expect(out.ask("x")).rejects.toMatchObject({ signIn: "expired", code: "doubao_signed_out" }) + const pro = new Doubao({ app: fakeApp, openPage: async () => fakePage([], { steps: { model: "upgrade" } }), poll: 1 }) + await expect(pro.ask("x", { model: "doubao-2.1-pro" })).rejects.toMatchObject({ status: 403, code: "doubao_upgrade" }) + const stuck = new Doubao({ app: fakeApp, openPage: async () => fakePage([], { steps: { cloud: "no 云电脑 in the mode menu" } }), poll: 1 }) + await expect(stuck.ask("x")).rejects.toMatchObject({ code: "doubao_ui" }) +}) + +test("ask fails a reply that ended empty, and one that stopped growing", async () => { + const empty = new Doubao({ app: fakeApp, openPage: async () => fakePage([{ sends: 1, reply: true, text: "", reasoning: "", finished: true, status: "Failed", reason: "fail:risk" }]), poll: 1 }) + await expect(empty.ask("x")).rejects.toMatchObject({ code: "doubao_failed", status: 502 }) + const idle = new Doubao({ app: fakeApp, openPage: async () => fakePage([{ sends: 1, reply: true, text: "a", reasoning: "", finished: false }]), poll: 1, idle: 20 }) + await expect(idle.ask("x")).rejects.toMatchObject({ code: "doubao_timeout" }) +}) + +test("requests run one at a time", async () => { + let open = 0 + let most = 0 + const page = fakePage([{ sends: 1, reply: true, text: "ok", reasoning: "", finished: true, reason: "succeed" }]) + const ev = page.eval.bind(page) + page.eval = async (e) => { + if (e === NEW_TASK) { open++; most = Math.max(most, open) } + if (e === READ) { await new Promise((r) => setTimeout(r, 5)); open-- } + return ev(e) + } + const d = new Doubao({ app: fakeApp, openPage: async () => page, poll: 1 }) + await Promise.all([d.ask("a"), d.ask("b"), d.ask("c")]) + expect(most).toBe(1) +}) + +test("an aborted ask stops", async () => { + const d = new Doubao({ app: fakeApp, openPage: async () => fakePage([{ sends: 1, reply: true, text: "a", reasoning: "", finished: false }]), poll: 5 }) + const ac = new AbortController() + const p = d.ask("x", { signal: ac.signal }) + setTimeout(() => ac.abort(), 20) + await expect(p).rejects.toBeDefined() +}) + +// ---- cdp ---- + +test("App reuses its own running app and never drives a port someone else took", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "dw-")) + try { + fs.writeFileSync(path.join(dir, "port"), "4567") + const spawned = [] + const mk = (pages) => + new App({ + binary: "/bin/sh", + dataDir: dir, + owns, + spawn: (...a) => { spawned.push(a); return { unref() {} } }, + fetchImpl: async (url) => Response.json(String(url).includes(":4567/") ? pages : [{ type: "page", url: "doubao://doubao-chat/chat" }]), + }) + expect(await mk([{ type: "page", url: "doubao://doubao-chat/chat" }]).start()).toBe(4567) + expect(spawned.length).toBe(0) + const port = await mk([{ type: "page", url: "https://example.com" }]).start({ timeout: 2000 }) + expect(port).not.toBe(4567) + expect(spawned[0][1]).toEqual([`--remote-debugging-port=${port}`, `--user-data-dir=${path.join(dir, "profile")}`]) + expect(fs.readFileSync(path.join(dir, "port"), "utf8")).toBe(String(port)) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } +}) + +test("App says when the app is not installed", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "dw-")) + try { + const app = new App({ binary: path.join(dir, "nope"), dataDir: dir, owns, fetchImpl: async () => { throw Error("refused") } }) + await expect(app.start()).rejects.toMatchObject({ code: "app_missing" }) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } +}) + +class FakeWS { + constructor(url) { + this.url = url + this.sent = [] + queueMicrotask(() => this.onopen?.()) + } + send(s) { + const m = JSON.parse(s) + this.sent.push(m) + queueMicrotask(() => { + if (m.params?.expression === "throw") this.onmessage({ data: JSON.stringify({ id: m.id, result: { exceptionDetails: { exception: { description: "Error: boom\n at x" } } } }) }) + else this.onmessage({ data: JSON.stringify({ id: m.id, result: { result: { value: m.params?.expression === "1+1" ? 2 : null } } }) }) + }) + } + close() { this.onclose?.() } +} + +test("Page evaluates, turns page exceptions into errors, and fails calls once closed", async () => { + const page = await Page.open(1, (t) => t.url.includes("chat"), { + fetchImpl: async () => Response.json([{ type: "page", url: "doubao://doubao-chat/chat", webSocketDebuggerUrl: "ws://x" }]), + WebSocketImpl: FakeWS, + }) + expect(await page.eval("1+1")).toBe(2) + await expect(page.eval("throw")).rejects.toThrow("page: Error: boom") + await page.key("Enter", { keyCode: 13, text: "\r" }) + expect(page.ws.sent.filter((m) => m.method === "Input.dispatchKeyEvent").map((m) => m.params.type)).toEqual(["keyDown", "keyUp"]) + page.ws.close() + await expect(page.eval("1+1")).rejects.toThrow("closed") +}) + +// ---- plugin ---- + +const req = (body) => new Request(I.BASE + "/chat/completions", { method: "POST", body: JSON.stringify(body), headers: { "Content-Type": "application/json" } }) + +test("the plugin serves chat completions through Doubao, whole and streamed", async () => { + const asked = [] + const doubao = { + ask: async (prompt, { model, onUpdate }) => { + asked.push({ prompt, model }) + onUpdate?.({ text: "Hi", reasoning: "" }) + return { text: "Hi there", reasoning: "", usage: '{"messages":42}' } + }, + } + const p = I.createPlugin({ doubao, newId: ids }) + const cfg = {} + await p.config(cfg) + expect(Object.keys(cfg.provider["doubao-work"].models)).toEqual(["auto", "doubao-2.1-lite", "doubao-2.1-pro"]) + const loader = await p.auth.loader(async () => ({})) + const whole = await (await loader.fetch(req({ model: "doubao-2.1-lite", messages: [{ role: "user", content: "hello" }] }))).json() + expect(whole.choices[0].message.content).toBe("Hi there") + expect(whole.usage.prompt_tokens).toBe(42) + expect(asked[0].model).toBe("doubao-2.1-lite") + expect(asked[0].prompt).toContain("[user]\nhello") + const streamed = await events(await loader.fetch(req({ model: "auto", stream: true, messages: [{ role: "user", content: "hello" }] }))) + expect(streamed.filter((e) => e.choices?.[0]?.delta?.content).map((e) => e.choices[0].delta.content).join("")).toBe("Hi there") + expect((await loader.fetch(req({ model: "gpt-9", messages: [] }))).status).toBe(404) + expect((await loader.fetch(new Request("https://elsewhere.example/v1/chat/completions", { method: "POST", body: "{}" }))).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 () => ({})) + await expect(out.fetch(req({ model: "auto", messages: [] }))).rejects.toMatchObject({ signIn: "expired" }) + const missing = await fail(Object.assign(Error("not installed"), { code: "app_missing" })).auth.loader(async () => ({})) + expect((await missing.fetch(req({ model: "auto", stream: true, messages: [] }))).status).toBe(503) + const paid = await fail(Object.assign(Error("upgrade"), { code: "doubao_upgrade", status: 403 })).auth.loader(async () => ({})) + const r = await paid.fetch(req({ model: "auto", messages: [] })) + expect(r.status).toBe(403) + expect((await r.json()).error.type).toBe("doubao_upgrade") +}) + +test("sign-in waits for the Doubao window's account", async () => { + const ok = I.createPlugin({ doubao: { waitSignedIn: async () => ({ signedIn: true, name: "yetone" }) } }) + const r = await (await ok.auth.methods[0].authorize()).callback() + expect(r).toMatchObject({ type: "success", accountId: "豆包工作 · yetone" }) + const late = I.createPlugin({ doubao: { waitSignedIn: async () => null } }) + expect(await (await late.auth.methods[0].authorize()).callback()).toMatchObject({ type: "failed" }) +}) + +test("an abort between two polls stops the ask too", async () => { + const ac = new AbortController() + const page = fakePage([{ sends: 1, reply: true, text: "a", reasoning: "", finished: false }]) + const ev = page.eval.bind(page) + page.eval = async (e) => { + if (e === READ) ac.abort() + return ev(e) + } + const d = new Doubao({ app: fakeApp, openPage: async () => page, poll: 1 }) + await expect(d.ask("x", { signal: ac.signal })).rejects.toBeDefined() +}) diff --git a/packages/doubao-work/doubao.mjs b/packages/doubao-work/doubao.mjs new file mode 100644 index 0000000..4b9252a --- /dev/null +++ b/packages/doubao-work/doubao.mjs @@ -0,0 +1,244 @@ +// The Doubao adapter: what the generic driver (cdp.mjs) does in Doubao's +// desktop app (com.bot.pc.doubao, a Chromium fork) to run one request as +// one new 工作任务 and read its reply. +// +// The reply is read from the React props of the reply's node, the message +// object Doubao itself renders from: its text blocks are the raw markdown +// (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 os from "node:os" +import path from "node:path" +import { App, Page, sleep } from "./cdp.mjs" + +export const CHAT = "doubao-chat/chat" +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" }, +} + +export function binary(platform = process.platform) { + if (process.env.DOUBAO_WORK_APP) return process.env.DOUBAO_WORK_APP + if (platform === "darwin") return "/Applications/Doubao.app/Contents/MacOS/Doubao" + return "" +} + +export function dataDir(platform = process.platform, home = os.homedir()) { + if (process.env.DOUBAO_WORK_HOME) return process.env.DOUBAO_WORK_HOME + if (platform === "darwin") return path.join(home, "Library", "Application Support", "magpie-doubao-work") + return path.join(process.env.XDG_DATA_HOME || path.join(home, ".local", "share"), "magpie-doubao-work") +} + +export const owns = (list) => list.some((t) => String(t.url).includes(CHAT) && /^(doubao|chrome):/.test(String(t.url))) + +// Page-side helpers, run through Runtime.evaluate. They read the page and +// press its controls the way a pointer does (Radix menus open on +// pointerdown, not on click()). +const LIB = String.raw` +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 })); }; +const message = (el) => { + if (!el) return null; + const k = Object.keys(el).find((k) => k.startsWith("__reactFiber")); + let f = k && el[k]; + for (let d = 0; f && d < 40; d++, f = f.return) { const m = f.memoizedProps && f.memoizedProps.message; if (m && m.message_id !== undefined && m.content_blocks_v2) return m; } + return null; +}; +` + +const js = (body) => `(async () => { ${LIB}\n${body} })()` + +export const STATE = js(` + const sb = $("[data-testid=sidebar_bottom]"); + const login = sb ? $$("button, [role=button]", sb).some((b) => b.innerText.trim() === "登录") : false; + const out = location.href.includes("from_logout"); + return { url: location.href, signedIn: !!sb && !login && !out, name: sb ? sb.innerText.split("\\n")[0].trim() : "", + input: !!($(".ProseMirror") && $(".ProseMirror").editor), sends: $$("[data-testid=send_message]").length }; +`) + +export const NEW_TASK = js(` + const b = $("[data-testid=create_office_task_button] [role=button]") || $("[data-testid=create_office_task_button]"); + if (!b) return "no new-task button"; + b.click(); + for (let i = 0; i < 50; i++) { + await wait(100); + if (!$$("[data-testid=send_message]").length && $(".ProseMirror") && $(".ProseMirror").editor && /\\/chat\\/?$/.test(location.pathname + "")) return ""; + if (!$$("[data-testid=send_message]").length && $(".ProseMirror") && $(".ProseMirror").editor && !/\\/chat\\/\\d/.test(location.href)) return ""; + } + return "the new task did not open"; +`) + +// Work tasks start on 本地电脑, which lets Doubao's agent read and run +// things on this computer. A request is the client's, so it goes on 云电脑. +export const CLOUD = js(` + const b = $("[data-testid=chat_input_action_mode]"); + if (!b) return "no mode button"; + if (b.innerText.trim() === "云电脑") return ""; + press(b); + let it; + for (let i = 0; i < 20 && !it; i++) { await wait(100); it = $$("[role=menuitem]").find((e) => e.innerText.includes("云电脑")); } + if (!it) return "no 云电脑 in the mode menu"; + press(it); + for (let i = 0; i < 20; i++) { await wait(100); if (b.isConnected && b.innerText.trim() === "云电脑") return ""; } + return "the mode stayed " + b.innerText.trim(); +`) + +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 ""; + 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"; } + press(it); + await wait(200); + return ""; +`) + +// 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) => + js(` + const ed = $(".ProseMirror") && $(".ProseMirror").editor; + if (!ed) return -1; + const lines = ${JSON.stringify(String(text).split("\n"))}; + ed.chain().clearContent(true).insertContent(lines.map((l) => ({ type: "paragraph", content: l ? [{ type: "text", text: l }] : [] }))).focus("end").run(); + return ed.getText({ blockSeparator: "\\n" }).length; +`) + +export const READ = js(` + const sends = $$("[data-testid=send_message]"); + const r = message($$("[data-testid=receive_message]").pop()); + if (!r) return { sends: sends.length, reply: false }; + const blocks = r.content_blocks_v2 || []; + const thinking = new Set(blocks.filter((b) => b.block_type === 10040).map((b) => b.block_id)); + let text = "", reasoning = ""; + for (const b of blocks) { + const t = b.content && b.content.text_block; + if (b.block_type !== 10000 || !t || typeof t.text !== "string") continue; + if (b.parent_id && thinking.has(b.parent_id)) reasoning += t.text; + else text += t.text; + } + const ext = r.ext || {}; + return { sends: sends.length, reply: true, id: String(r.message_id || r.unique_id || ""), text, reasoning, + finished: ext.is_finish === "1" || !!(r.final_status && r.final_status.session), + status: (r.final_status && r.final_status.session) || "", reason: ext.finish_reason_chat || "", + usage: ext.context_window_usage || "", error: r.error_details ? JSON.stringify(r.error_details) : "" }; +`) + +export const usageOf = (raw) => { + try { + const u = typeof raw === "string" ? JSON.parse(raw) : raw + const n = ["system_prompt", "messages", "skills", "tools"].reduce((s, k) => s + (Number(u?.[k]) || 0), 0) + return n > 0 ? n : 0 + } catch { + return 0 + } +} + +export class DoubaoError extends Error { + constructor(message, code, extra = {}) { + super(message) + Object.assign(this, { code }, extra) + } +} + +// 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 } = {}) { + this.app = app ?? new App({ binary: binary(), dataDir: dataDir(), owns }) + Object.assign(this, { openPage, poll, idle, total }) + this.page = null + this.queue = Promise.resolve() + } + + async connect(signal) { + if (this.page && !this.page.closed) return this.page + const port = await this.app.start({ signal }) + this.page = await this.openPage(port, (t) => String(t.url).includes(CHAT)) + if (!this.page) throw new DoubaoError("豆包的对话窗口没有打开。请在豆包里打开一个对话窗口后再试。", "doubao_no_window") + return this.page + } + + async state(signal) { + const page = await this.connect(signal) + return page.eval(STATE) + } + + // waitSignedIn opens the app and waits until the user has signed in to + // it, for a first sign-in. + async waitSignedIn({ timeout = 300000, signal } = {}) { + const until = Date.now() + timeout + for (;;) { + let s + try { s = await this.state(signal) } catch (e) { if (e?.code === "app_missing") throw e; s = null } + if (s?.signedIn && s.name) return s + if (Date.now() > until) return null + await sleep(1500, signal) + } + } + + // ask runs one prompt in a new task. onUpdate gets each new read of the + // reply ({text, reasoning}); it returns the finished read. + ask(prompt, opts = {}) { + const run = this.queue.then(() => this.#ask(prompt, opts)) + this.queue = run.catch(() => {}) + return run + } + + async #ask(prompt, { model = "auto", signal, onUpdate = () => {} }) { + signal?.throwIfAborted() + const page = await this.connect(signal) + const s = await page.eval(STATE) + if (!s.signedIn) throw new DoubaoError("豆包没有登录。请在 magpie 里重新登录豆包工作。", "doubao_signed_out", { signIn: "expired" }) + const step = async (expr, what) => { + const why = await page.eval(expr) + if (why) throw new DoubaoError(`豆包${what}失败:${why}`, "doubao_ui") + } + await step(NEW_TASK, "新建任务") + await step(CLOUD, "切换到云电脑") + const label = (MODELS[model] ?? 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") + 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" }) + let last = null + let changed = Date.now() + const start = Date.now() + for (let sent = false; ; ) { + await sleep(this.poll, signal) + const r = await page.eval(READ) + if (!sent) { + if (r.sends > 0) sent = true + else if (Date.now() - start > 15000) throw new DoubaoError("豆包没有发出这条消息。", "doubao_ui") + else continue + } + if (!r.reply) { + if (Date.now() - start > 120000) throw new DoubaoError("豆包两分钟没有回复。", "doubao_timeout", { status: 504 }) + continue + } + if (!last || r.text !== last.text || r.reasoning !== last.reasoning) { + changed = Date.now() + onUpdate(r) + } + last = r + if (r.finished) { + if (!r.text && !r.reasoning && (r.error || !/^succeed/i.test(r.reason || "succeed"))) + throw new DoubaoError(`豆包没有回复(${r.status || r.reason || r.error || "unknown"})`, "doubao_failed", { status: 502 }) + return r + } + if (Date.now() - changed > this.idle) throw new DoubaoError("豆包的回复停了三分钟。", "doubao_timeout", { status: 504 }) + if (Date.now() - start > this.total) throw new DoubaoError("豆包的回复超过了 15 分钟。", "doubao_timeout", { status: 504 }) + } + } +} diff --git a/packages/doubao-work/index.mjs b/packages/doubao-work/index.mjs new file mode 100644 index 0000000..bcbb087 --- /dev/null +++ b/packages/doubao-work/index.mjs @@ -0,0 +1,102 @@ +// 豆包工作 (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 Doubao's desktop app 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 text blocks and given back +// as OpenAI tool_calls. See README.md for what that costs. +import { Doubao, DoubaoError, MODELS, binary, 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 json = (status, message, type) => + new Response(JSON.stringify({ error: { message, type } }), { status, headers: { "Content-Type": "application/json" } }) + +function models() { + const out = {} + for (const [id, m] of Object.entries(MODELS)) + out[id] = { name: m.name, limit: { context: 256000, output: 32768 }, tool_call: true, reasoning: true, attachment: false } + return out +} + +export function createPlugin({ doubao = new Doubao(), newId } = {}) { + const failed = (e) => { + if (e?.signIn) throw e + if (e?.name === "AbortError" || e?.name === "TimeoutError") throw e + const status = e?.code === "app_missing" || e?.code === "app_start_timeout" ? 503 : e?.status ?? 502 + return json(status, String(e?.message ?? e), e?.code ?? "doubao_error") + } + return { + config: async (cfg) => { + cfg.provider ??= {} + cfg.provider[ID] ??= { name: "豆包工作", npm: "@ai-sdk/openai-compatible", api: BASE, models: models() } + }, + auth: { + provider: ID, + maxConcurrency: 1, + methods: [ + { + type: "oauth", + label: "在豆包窗口中登录", + authorize: async () => ({ + url: "", + method: "auto", + instructions: "将打开一个单独的豆包窗口(不影响你平时用的豆包)。请在其中登录,登录后回到这里。", + callback: async () => { + if (!binary()) return { type: "failed", error: "豆包工作插件目前只支持 macOS 上的豆包桌面版。" } + let s + try { + s = await doubao.waitSignedIn() + } catch (e) { + if (e?.code === "app_missing") return { type: "failed", error: "没有找到豆包桌面版,请先安装:https://www.doubao.com/download/desktop" } + return { type: "failed", error: "打开豆包失败:" + String(e?.message ?? e) } + } + if (!s) return { type: "failed", error: "五分钟内没有在豆包窗口里登录,请再试一次。" } + 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 (!MODELS[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 } diff --git a/packages/doubao-work/openai.mjs b/packages/doubao-work/openai.mjs new file mode 100644 index 0000000..b0cc2c7 --- /dev/null +++ b/packages/doubao-work/openai.mjs @@ -0,0 +1,134 @@ +// 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 (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), + } +} diff --git a/packages/doubao-work/opencode.mjs b/packages/doubao-work/opencode.mjs new file mode 100644 index 0000000..b2fe57b --- /dev/null +++ b/packages/doubao-work/opencode.mjs @@ -0,0 +1,5 @@ +// The package's OpenCode 1.x plugins, as OpenCode 1.x and magpie's host +// load them: its plugin functions and nothing else (1.x refuses a +// package whose exports include anything but plugins). OpenCode 2.x +// loads opencode2.mjs, which runs these. +export { default } from "./index.mjs" diff --git a/packages/doubao-work/opencode2.mjs b/packages/doubao-work/opencode2.mjs new file mode 100644 index 0000000..364ea8a --- /dev/null +++ b/packages/doubao-work/opencode2.mjs @@ -0,0 +1,596 @@ +// The OpenCode 2.x face of a package whose plugins are written for +// OpenCode 1.x (and magpie's plugin host). +// +// OpenCode 2.x loads a package's `exports["."]` and wants its default to be +// {id, setup(ctx)}; it has no fallback for a 1.x plugin's named functions +// (plugins#657). This file is that default. It runs each 1.x plugin the +// package's opencode.mjs exports and hands 2.x what the plugin's hooks say: +// +// auth.methods → the integration's sign-in methods +// config() → the provider, its package, base URL and models +// provider.models → the signed-in account's own model list +// auth.loader → each request's base URL, key, headers and fetch +// +// What 2.x has no place for is left out: chat.headers and chat.params +// (2.x's sdk hook doesn't carry the session), magpie's usage and checkin, +// tools and events. +// +// scripts/opencode2.mjs is the one copy that is edited. Every package that +// has it carries the same bytes as packages//opencode2.mjs, and +// scripts/check.mjs fails when a copy differs. + +import { readFileSync } from "node:fs" +import * as v1 from "./opencode.mjs" + +const pkg = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8")) + +// The key the SDK is made with: the account's own goes on each request in +// its place (see wrapFetch), so a key read when the SDK was made can't go +// out after the account changed. +const PLACEHOLDER = "opencode2-v1-key" + +// The SDK package a 1.x npm name runs as on 2.x. A version keeps 2.x from +// swapping @ai-sdk/* for its native providers, which never call the sdk +// hook below; openai-compatible's is the one 2.x ships, the others are AI +// SDK v6's dist-tag, the line 2.x's bridge runs. +export function packageOf(npm) { + const name = npm || "@ai-sdk/openai-compatible" + if (name === "@ai-sdk/openai-compatible") return "aisdk:@ai-sdk/openai-compatible@2.0.41" + if (/^@ai-sdk\/[^/@]+$/.test(name)) return `aisdk:${name}@ai-v6` + return `aisdk:${name}` +} + +// The plugins a 1.x module exports, as magpie's host and OpenCode 1.x read +// them: a default {server} is the one plugin, else every function export +// and every {server} object. +export function pluginsOf(mod) { + const d = mod?.default + if (d && typeof d === "object" && ("server" in d || "id" in d || "tui" in d)) + return typeof d.server === "function" ? [d.server] : [] + const out = [] + for (const value of Object.values(mod ?? {})) { + const fn = typeof value === "function" ? value : value && typeof value === "object" && typeof value.server === "function" ? value.server : null + if (fn && !out.includes(fn)) out.push(fn) + } + return out +} + +const int = (n, fallback = 0) => { + const v = Math.trunc(Number(n)) + return Number.isFinite(v) && v >= 0 ? v : fallback +} +const money = (n) => (Number.isFinite(Number(n)) && Number(n) >= 0 ? Number(n) : 0) +const record = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : {}) +const json = (v) => { + try { + return JSON.parse(JSON.stringify(v ?? null)) + } catch { + return null + } +} +const strings = (v) => Object.fromEntries(Object.entries(record(v)).filter(([, s]) => typeof s === "string")) +const nonEmpty = (o) => (Object.keys(o).length ? o : undefined) + +// connKey names a connection the way 2.x does. +const connKey = (c) => (!c ? "" : c.type === "credential" ? `credential:${c.id}` : `env:${c.name}`) + +// ---- sign-in ------------------------------------------------------------ + +// fields is a 1.x method's prompts as a 2.x form. +export function fieldsOf(prompts) { + const out = [] + for (const p of prompts ?? []) { + if (!p?.key) continue + const f = { key: String(p.key), type: "string", title: String(p.message ?? p.key) } + if (p.placeholder) f.placeholder = String(p.placeholder) + if (p.type === "select" && Array.isArray(p.options)) + f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) + // a prompt shown only when another answer says so can't be required, and + // neither can one whose own validate() accepts an empty answer (the + // browser sign-in's optional API key) + if (!p.condition && p.required !== false) f.required = true + out.push(f) + } + return out.length ? out : undefined +} + +// v1Saved is what a 1.x sign-in's success is saved as, the way 1.x writes +// auth.json: the result without its type and provider. +function v1Saved(r) { + const { type: _t, provider: _p, ...rest } = r + if ("key" in r) return { type: "api", ...rest } + return { type: "oauth", ...rest } +} + +// credentialOf is a 1.x sign-in's success as a 2.x credential: OAuth for +// both kinds, the 1.x auth kept whole in its metadata. No refresh is +// registered, so 2.x hands the credential over as it is and the plugin's +// own loader renews it, as it does on 1.x. +export function credentialOf(methodID, r) { + if (!r || r.type !== "success") throw new Error(r?.error || r?.message || "the sign-in failed") + const saved = json(v1Saved(r)) + if (saved.type === "api") + return { type: "oauth", methodID, access: String(saved.key ?? ""), refresh: "", expires: 0, metadata: { v1: saved } } + return { + type: "oauth", + methodID, + access: String(saved.access ?? ""), + refresh: String(saved.refresh ?? ""), + expires: int(saved.expires), + metadata: { v1: saved }, + } +} + +// authOfValue is the 1.x auth a 2.x credential stands for. +export function authOfValue(value) { + if (!value) return null + if (value.type === "oauth") { + const v1 = record(value.metadata).v1 + if (v1 && typeof v1 === "object") return v1 + return { type: "oauth", access: value.access, refresh: value.refresh, expires: value.expires } + } + if (value.type === "key") { + const meta = value.metadata && Object.keys(value.metadata).length ? { metadata: value.metadata } : {} + return { type: "api", key: value.key, ...meta } + } + return null +} + +const fingerprint = (a) => JSON.stringify([a?.type, a?.access ?? a?.key ?? "", a?.refresh ?? ""]) + +// ---- models ------------------------------------------------------------- + +const MODALITIES = ["text", "audio", "image", "video", "pdf"] + +// internalOf is a config model as 1.x hands it to provider.models: what +// fromModelsDevModel makes of it, with the config's own variants. +export function internalOf(providerID, conf, key, m) { + const mods = record(m.modalities) + const has = (list, k) => Array.isArray(list) && list.includes(k) + const cost = record(m.cost) + return { + ...m, + id: key, + providerID, + name: m.name ?? key, + api: { id: m.id ?? key, url: m.provider?.api ?? conf.api ?? conf.options?.baseURL ?? "", npm: m.provider?.npm ?? conf.npm ?? "@ai-sdk/openai-compatible" }, + status: m.status ?? "active", + headers: m.headers ?? {}, + options: m.options ?? {}, + cost: { input: money(cost.input), output: money(cost.output), cache: { read: money(cost.cache_read), write: money(cost.cache_write) } }, + limit: { context: int(m.limit?.context), input: m.limit?.input, output: int(m.limit?.output) }, + capabilities: { + temperature: m.temperature ?? false, + reasoning: m.reasoning ?? false, + attachment: m.attachment ?? false, + toolcall: m.tool_call ?? true, + input: Object.fromEntries(MODALITIES.map((k) => [k, mods.input ? has(mods.input, k) : k === "text"])), + output: Object.fromEntries(MODALITIES.map((k) => [k, mods.output ? has(mods.output, k) : k === "text"])), + interleaved: m.interleaved ?? false, + }, + release_date: m.release_date ?? "", + variants: record(m.variants), + } +} + +// modelOf is a 1.x model, in config or internal form, as a 2.x Model.Info. +export function modelOf(providerID, provider, key, m) { + const caps = record(m.capabilities) + const listFrom = (obj, list) => { + if (obj && typeof obj === "object") return MODALITIES.filter((k) => obj[k]) + if (Array.isArray(list)) return list.map(String) + return ["text"] + } + const input = listFrom(caps.input, m.modalities?.input) + const output = listFrom(caps.output, m.modalities?.output) + const c = record(m.cost) + const cache = record(c.cache) + const npm = m.api?.npm ?? m.provider?.npm + const url = m.api?.url ?? m.provider?.api + const settings = { ...record(json(m.options)) } + if (url && url !== provider.baseURL) settings.baseURL = url + const variants = Object.entries(record(m.variants)) + .filter(([, v]) => !record(v).disabled) + .map(([id, v]) => { + const { disabled: _d, ...rest } = record(json(v)) + return nonEmpty(rest) ? { id, settings: rest } : { id } + }) + const status = ["alpha", "beta", "deprecated", "active"].includes(m.status) ? m.status : "active" + const out = { + id: key, + modelID: String(m.api?.id ?? m.id ?? key), + providerID, + name: String(m.name ?? key), + capabilities: { + tools: caps.toolcall ?? m.tool_call ?? true, + input: input.length ? input : ["text"], + output: output.length ? output : ["text"], + ...(typeof (caps.temperature ?? m.temperature) === "boolean" ? { temperature: caps.temperature ?? m.temperature } : {}), + }, + variants, + time: { released: Date.parse(m.release_date ?? "") || 0 }, + cost: [{ input: money(c.input), output: money(c.output), cache: { read: money(cache.read ?? c.cache_read), write: money(cache.write ?? c.cache_write) } }], + status, + enabled: true, + limit: { context: int(m.limit?.context, 128000) || 128000, output: int(m.limit?.output, 8192) || 8192 }, + } + if (m.limit?.input) out.limit.input = int(m.limit.input) + if (npm && npm !== provider.npm) out.package = packageOf(npm) + if (nonEmpty(settings)) out.settings = settings + const headers = strings(m.headers) + if (nonEmpty(headers)) out.headers = headers + return out +} + +// ---- requests ----------------------------------------------------------- + +const urlOf = (input) => (typeof input === "string" ? input : input instanceof URL ? input.href : input?.url ?? String(input)) + +// wrapFetch sends a request the SDK made from the provider's settings the +// way 1.x would have sent it with the loader's options: the loader's base +// URL in place of the configured one, the account's key in place of the +// placeholder, the loader's headers added, through the loader's fetch. +export function wrapFetch(next, base, options) { + return async (input, init = {}) => { + const o = await options() + let url = urlOf(input) + const from = String(base ?? "").replace(/\/+$/, "") + const to = o.baseURL ? String(o.baseURL).replace(/\/+$/, "") : "" + if (from && to && from !== to && url.startsWith(from)) url = to + url.slice(from.length) + const req = input instanceof Request ? input : null + const headers = new Headers(init.headers ?? req?.headers ?? undefined) + for (const [k, v] of [...headers.entries()]) { + if (!v.includes(PLACEHOLDER)) continue + if (o.key) headers.set(k, v.replaceAll(PLACEHOLDER, o.key)) + else headers.delete(k) + } + for (const [k, v] of Object.entries(strings(o.headers))) headers.set(k, v) + const send = typeof o.fetch === "function" ? o.fetch : next ?? fetch + if (req && init.body === undefined) { + const body = req.method === "GET" || req.method === "HEAD" ? undefined : await req.text() + return send(url, { method: req.method, headers, body, signal: init.signal ?? req.signal }) + } + return send(url, { ...init, headers }) + } +} + +// ---- one plugin --------------------------------------------------------- + +async function setupPlugin(ctx, fn, live) { + const directory = ctx?.location?.directory ?? process.cwd() + // the active account each provider was last read for, and the renewed + // auth a plugin saved for it (2.x has no way for a plugin to write a + // credential back, so it is kept in the plugin's storage, under the + // credential it renews and the token it was renewed from) + const current = new Map() + const saved = new Map() + const signingIn = new Map() + const storeKey = (id, key) => `v1auth/${id}/${key}` + + const client = { + auth: { + async set(arg) { + const id = arg?.path?.id + const body = json(arg?.body) + const cur = id && current.get(id) + // a sign-in's own saves belong to the credential it is about to + // make, not the one that was active when it started + if (!cur || !body || signingIn.get(id) > 0) return { data: true } + const entry = { fp: cur.fp, auth: body } + saved.set(storeKey(id, cur.key), entry) + await Promise.resolve() + .then(() => ctx.storage?.set?.(storeKey(id, cur.key), entry)) + .catch(() => {}) + return { data: true } + }, + async get() { + return { data: undefined } + }, + }, + app: { log: async () => ({ data: true }) }, + } + + const hooks = (await fn({ client, directory, worktree: directory, project: {}, serverUrl: undefined, $: undefined }, {})) ?? {} + const cfg = { provider: {} } + try { + await hooks.config?.(cfg) + } catch {} + const auth = hooks.auth + const authID = auth?.provider ? String(auth.provider) : undefined + const providers = record(cfg.provider) + + // getAuth reads the active account: the credential 2.x holds, or what the + // plugin last saved renewing it. + const getAuth = async (id) => { + const connection = await ctx.integration.connection.active(id).catch(() => undefined) + if (!connection) { + current.delete(id) + return undefined + } + const value = await ctx.integration.connection.resolve(connection).catch(() => undefined) + const base = authOfValue(value) + if (!base) { + current.delete(id) + return undefined + } + const key = connKey(connection) + const fp = fingerprint(base) + // ours: a credential one of this plugin's own sign-ins made + const ours = value?.type === "oauth" && !!record(value.metadata).v1 + current.set(id, { key, fp, ours }) + const sk = storeKey(id, key) + let entry = saved.get(sk) + if (!entry) { + entry = await Promise.resolve() + .then(() => ctx.storage?.get?.(sk)) + .catch(() => undefined) + if (entry) saved.set(sk, entry) + } + return entry && entry.fp === fp && entry.auth ? entry.auth : base + } + + // the sign-in methods + if (authID && Array.isArray(auth.methods) && auth.methods.length) { + const label = (c) => { + const a = authOfValue(c) + const name = a?.name ?? a?.email ?? a?.metadata?.name ?? a?.metadata?.email ?? a?.account + return typeof name === "string" && name ? name : undefined + } + const begin = () => signingIn.set(authID, (signingIn.get(authID) ?? 0) + 1) + const end = () => signingIn.set(authID, Math.max(0, (signingIn.get(authID) ?? 1) - 1)) + const title = record(providers[authID]).name + // 2.x runs a transform again on every reload, from nothing + await ctx.integration.transform((editor) => { + let keyed = false + // the integration 2.x makes for an id it doesn't know is named by the + // id; the provider's own name reads better in the sign-in list + if (typeof title === "string" && title) + try { + editor.update?.(authID, (i) => { + if (i && (!i.name || i.name === authID)) i.name = title + }) + } catch {} + auth.methods.forEach((m, i) => { + if (!m) return + const methodID = `v1-${i}` + const form = fieldsOf(m.prompts) + if (m.type === "api" && typeof m.authorize !== "function") { + if (keyed) return + keyed = true + editor.method.update({ integrationID: authID, method: { type: "key", label: String(m.label ?? "API key"), ...(form ? { form } : {}) } }) + return + } + if (typeof m.authorize !== "function") return + editor.method.update({ + integrationID: authID, + method: { id: methodID, type: "oauth", label: String(m.label ?? authID), ...(form ? { form } : {}) }, + async authorize(answer) { + begin() + let ended = false + const done = () => { + if (!ended) end() + ended = true + } + try { + const inputs = Object.fromEntries(Object.entries(record(answer)).map(([k, v]) => [k, String(v)])) + const r = await m.authorize(inputs) + if (m.type === "api") { + done() + return { url: "", instructions: "", mode: "auto", callback: Promise.resolve().then(() => credentialOf(methodID, r)) } + } + if (r?.method === "code") + return { + url: String(r.url ?? ""), + instructions: String(r.instructions ?? ""), + mode: "code", + callback: async (code) => { + try { + return credentialOf(methodID, await r.callback(code)) + } finally { + done() + } + }, + } + const callback = Promise.resolve() + .then(() => r.callback()) + .then((res) => credentialOf(methodID, res)) + .finally(done) + callback.catch(() => {}) + return { url: String(r?.url ?? ""), instructions: String(r?.instructions ?? ""), mode: "auto", callback } + } catch (e) { + done() + throw e + } + }, + label, + }) + }) + }) + } + + // the loader's options for the account signed in now, read again when + // the account changes + let loaded = null + const loaderOptions = async (id) => { + if (id !== authID || typeof auth?.loader !== "function") { + const a = authID === id ? await getAuth(id) : undefined + return { key: a?.type === "api" ? a.key : undefined } + } + const a = await getAuth(id) + if (!a) return {} + const fp = current.get(id)?.key + "\0" + fingerprint(a) + if (loaded?.fp !== fp) { + const p = Promise.resolve() + .then(() => auth.loader(() => getAuth(id), providerOf(id))) + .then((o) => record(o)) + loaded = { fp, p } + p.catch(() => { + if (loaded?.fp === fp) loaded = null + }) + } + const o = await loaded.p + const key = typeof o.apiKey === "string" && o.apiKey ? o.apiKey : a.type === "api" ? a.key : undefined + return { baseURL: o.baseURL, key, headers: o.headers, fetch: o.fetch } + } + + // the providers, with the list the account's own read last gave each + const source = new Map() + // providerOf is a provider as 1.x hands it to provider.models and + // auth.loader + const providerOf = (id) => { + const conf = record(providers[id]) + const models = Object.fromEntries(Object.entries(record(conf.models)).map(([k, m]) => [k, internalOf(id, conf, k, record(m))])) + return { id, name: conf.name ?? id, source: "config", env: [], options: record(conf.options), models } + } + const listed = new Set() + for (const [id, conf0] of Object.entries(providers)) { + const conf = record(conf0) + // a provider entry that only names the sign-in (no package, no models) + // is not a provider of models + if (!conf.npm && !Object.keys(record(conf.models)).length) continue + const options = record(conf.options) + const { apiKey: _k, baseURL: _b, fetch: _f, headers: optHeaders, ...rest } = options + // with no base URL the config leaves it to the loader: a name that + // can't resolve stands in for it, and each request swaps in the + // loader's (wrapFetch) + const baseURL = options.baseURL ?? conf.api ?? `https://${id.replace(/[^a-z0-9-]/gi, "-")}.opencode2-v1.invalid` + const npm = conf.npm ?? "@ai-sdk/openai-compatible" + const info = { + id, + ...(id === authID ? { integrationID: id } : {}), + name: String(conf.name ?? id), + activation: "auto", + package: packageOf(npm), + settings: { ...record(json(rest)), ...(baseURL ? { baseURL: String(baseURL) } : {}) }, + } + const headers = { ...strings(conf.headers), ...strings(optHeaders) } + if (nonEmpty(headers)) info.headers = headers + const prov = { baseURL, npm } + const fromConfig = () => + Object.entries(record(conf.models)).map(([key, m]) => modelOf(id, prov, key, internalOf(id, conf, key, record(m)))) + listed.add(id) + await ctx.provider.transform((editor) => { + const s = source.get(id) + editor.add({ info, models: s?.models ?? fromConfig(), sourceConnection: s?.connection }) + }) + source.set(id, { conf, prov, models: null, connection: undefined }) + } + + // each request: the placeholder key, and the fetch that swaps in the + // account's. A provider the package doesn't list (one 2.x has built in + // that the plugin only signs in to) is left to 2.x unless the plugin's + // loader serves it and one of the plugin's own sign-ins is active. + const own = authID && !listed.has(authID) && typeof auth?.loader === "function" ? [authID] : [] + for (const id of new Set([...listed, ...own])) { + const base = source.get(id)?.prov.baseURL + await ctx.aisdk.hook( + "sdk", + async (evt) => { + const opts = evt.options + if (!opts || opts.__opencode2) return + if (!listed.has(id)) { + await getAuth(id) + if (!current.get(id)?.ours) return + } + opts.__opencode2 = true + opts.apiKey = PLACEHOLDER + opts.fetch = wrapFetch(opts.fetch, opts.baseURL ?? base, () => loaderOptions(id)) + }, + { providerID: id }, + ) + } + + // refresh reads the account's own list after a sign-in or a switch + const listID = hooks.provider?.id ? String(hooks.provider.id) : undefined + let refreshing = null + let again = false + // the account the list was last read for: a credential.updated that + // leaves it as it was reads nothing again + let readFor = null + const stateOf = async () => { + const c = await ctx.integration.connection.active(authID).catch(() => undefined) + const a = c ? await getAuth(authID) : undefined + return connKey(c) + "\0" + (a ? fingerprint(a) : "") + } + const refresh = () => { + if (refreshing) { + again = true + return refreshing + } + refreshing = (async () => { + try { + if (!authID || !source.has(authID)) return + const s = source.get(authID) + const connection = await ctx.integration.connection.active(authID).catch(() => undefined) + const a = connection ? await getAuth(authID) : undefined + readFor = connKey(connection) + "\0" + (a ? fingerprint(a) : "") + if (!a || listID !== authID || typeof hooks.provider?.models !== "function") { + if (s.connection || s.models) { + s.connection = undefined + s.models = null + await ctx.provider.reload() + } + return + } + const provider = providerOf(authID) + let got + try { + got = await hooks.provider.models(provider, { auth: a }) + } catch { + got = null + } + if (connKey(await ctx.integration.connection.active(authID).catch(() => undefined)) !== connKey(connection)) { + again = true + return + } + s.connection = connection + s.models = got && typeof got === "object" ? Object.entries(got).map(([k, m]) => modelOf(authID, s.prov, k, record(m))) : null + await ctx.provider.reload() + await ctx.model?.reload?.() + } finally { + refreshing = null + if (again && live.on) { + again = false + void refresh() + } + } + })() + return refreshing + } + + if (authID && ctx.event?.subscribe) + void (async () => { + try { + // a switch names the integration; an update (a sign-in, a removal) + // names nothing, so it reads again only when this account changed + const types = ["credential.switched", "credential.updated"] + for await (const event of ctx.event.subscribe({ types })) { + if (!live.on) return + if (event?.type === "credential.switched" && event?.data?.integrationID === authID) { + loaded = null + await refresh() + } else if (event?.type === "credential.updated" && (await stateOf()) !== readFor) { + await refresh() + } + } + } catch {} + })() + void refresh() +} + +export async function setup(ctx, mod = v1) { + const live = { on: true } + for (const fn of pluginsOf(mod)) { + try { + await setupPlugin(ctx, fn, live) + } catch (e) { + // one plugin failing to start leaves the package's others working + console.error(`${pkg.name}: ${e?.message ?? e}`) + } + } + return () => { + live.on = false + } +} + +export default { id: pkg.name, setup: (ctx) => setup(ctx) } diff --git a/packages/doubao-work/package.json b/packages/doubao-work/package.json new file mode 100644 index 0000000..2c20caf --- /dev/null +++ b/packages/doubao-work/package.json @@ -0,0 +1,30 @@ +{ + "name": "@magpie-community/opencode-doubao-work-auth", + "version": "0.1.0", + "type": "module", + "main": "./opencode.mjs", + "files": [ + "index.mjs", + "cdp.mjs", + "doubao.mjs", + "openai.mjs", + "prompt.mjs", + "opencode.mjs", + "opencode2.mjs", + "README.md" + ], + "description": "Doubao Work (豆包工作) as a model provider, by driving the Doubao desktop app the way a person does", + "magpie": { + "maxConcurrency": 1 + }, + "repository": { + "type": "git", + "url": "git+https://github.com/magpie-community/plugins.git", + "directory": "packages/doubao-work" + }, + "keywords": ["magpie", "magpie-plugin", "doubao", "doubao-work"], + "license": "MIT", + "exports": { + ".": "./opencode2.mjs" + } +} diff --git a/packages/doubao-work/prompt.mjs b/packages/doubao-work/prompt.mjs new file mode 100644 index 0000000..8a4a08f --- /dev/null +++ b/packages/doubao-work/prompt.mjs @@ -0,0 +1,142 @@ +// 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: {json} +// blocks, which are read back into OpenAI tool_calls. + +const OPEN = "" +const CLOSE = "" + +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": "", "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 , 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 } +} diff --git a/registry.json b/registry.json index f7f61fb..e12f89f 100644 --- a/registry.json +++ b/registry.json @@ -25,6 +25,7 @@ "summary": { "en": "GitHub Copilot on GitHub.com or GitHub Enterprise, with premium request or credit usage, remaining allowance and quota reset dates.", "zh": "GitHub Copilot:支持 GitHub.com 与 GitHub Enterprise,显示高级请求或积分用量、剩余额度和重置时间。" } }, { "package": "@magpie-community/opencode-joycode-auth", "name": "JoyCode", "providers": ["joycode"], "community": true, "summary": { "en": "Unofficial JoyCode provider: JD account browser sign-in, live models and credit multipliers, plan credits and streaming tool calls.", "zh": "非官方 JoyCode 插件:京东账号浏览器登录,动态模型与积分倍率、套餐额度及流式工具调用。" } }, + {"package": "@magpie-community/opencode-doubao-work-auth", "name": "豆包工作", "icon": "doubao-color", "providers": ["doubao-work"], "community": true, "summary": {"en": "Doubao Work, which runs its agent in the cloud and has no API, used through the Doubao desktop app the way a person does: one new task per request, the client's tools asked for as text. macOS; unofficial.", "zh": "豆包工作的智能体跑在云端、没有 API,本插件像人一样操作豆包桌面版来用它:每个请求开一个新任务,客户端的工具以文本方式调用。仅 macOS;非官方。"}}, {"package": "@magpie-community/opencode-kimi-work-auth", "name": "Kimi Work", "icon": "kimi", "providers": ["kimi-work"], "community": true, "summary": {"en": "Kimi desktop Work subscription through its local sign-in, with live Work models and shared membership usage. Separate from Kimi Code.", "zh": "使用本机普通 Kimi 桌面版的 Work 登录,自动读取 Work 模型和会员共享用量;独立于 Kimi Code。"}}, { "package": "@magpie-community/opencode-zen-free-auth", "name": "OpenCode Zen Free", "icon": "opencode", "providers": ["opencode-zen-free"], "community": true, "summary": { "en": "OpenCode Zen's free models with the public credential, automatic discovery and native streaming protocols.", "zh": "使用 public 凭证接入 OpenCode Zen 免费模型,自动发现模型并支持原生流式协议。" } },