magpie-plugin-doubao-cli-acp 0.0.0-stage → 0.2.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/acp.mjs ADDED
@@ -0,0 +1,558 @@
1
+ // ACP v1 客户端与进程池。
2
+ //
3
+ // 协议形状来自 doubao CLI 2.39.2 的 entry-cli-router/main.js:
4
+ // initialize → { protocolVersion: 1, agentInfo, agentCapabilities }
5
+ // session/new {cwd,mcpServers} → { sessionId, models, configOptions, modes, _meta }
6
+ // session/prompt {sessionId,prompt:[{type:"text",text}]}
7
+ // → 期间通过 session/update 通知流式回包
8
+ // session/set_config_option → 切模型/推理强度
9
+ // session/request_permission → 客户端决定 allow_once / reject_once
10
+ // fs/read_text_file / fs/write_text_file
11
+ //
12
+ // 一个 doubao acp serve 进程可以承载多个 ACP session,所以按插件实例共用
13
+ // 一个进程池:一个 magpie conversation 对应一个 ACP session。
14
+
15
+ import { spawn } from "node:child_process"
16
+ import fsp from "node:fs/promises"
17
+ import path from "node:path"
18
+ import {
19
+ ACP_START_TIMEOUT_MS,
20
+ DEFAULT_IDLE_TIMEOUT_MS,
21
+ DEFAULT_PROMPT_TIMEOUT_MS,
22
+ } from "./constants.mjs"
23
+ import { isPathInside, permissionChoice } from "./pure.mjs"
24
+ import { LoginRequiredError, spawnSpec } from "./cli.mjs"
25
+
26
+ const MAX_LINE = 32 * 1024 * 1024
27
+
28
+ export class AcpError extends Error {
29
+ constructor(message, { code = "acp_error", status = 502, acpError = null } = {}) {
30
+ super(message)
31
+ this.name = "AcpError"
32
+ this.code = code
33
+ this.status = status
34
+ this.acpError = acpError
35
+ }
36
+ }
37
+
38
+ /** 一条 ACP JSON-RPC 连接(一个 doubao acp serve 进程) */
39
+ export class AcpConnection {
40
+ constructor(child, { label = "doubao", onNotification, onRequest, log } = {}) {
41
+ this.child = child
42
+ this.label = label
43
+ this.onNotification = onNotification
44
+ this.onRequest = onRequest
45
+ this.log = log
46
+ this.nextId = 1
47
+ this.pending = new Map()
48
+ this.buffer = ""
49
+ this.closed = false
50
+ this.stderrTail = ""
51
+
52
+ child.stdin?.on?.("error", () => {})
53
+ child.stdout?.setEncoding?.("utf8")
54
+ child.stdout?.on?.("data", (chunk) => this.#onData(chunk))
55
+ child.stderr?.setEncoding?.("utf8")
56
+ child.stderr?.on?.("data", (chunk) => {
57
+ this.stderrTail = (this.stderrTail + String(chunk)).slice(-8_192)
58
+ })
59
+ child.once?.("error", (error) => this.close(new AcpError(`doubao acp 启动失败:${error.message}`, { code: "spawn_failed" })))
60
+ child.once?.("close", (code, signal) => {
61
+ this.close(new AcpError(`doubao acp 退出(${code ?? signal ?? "closed"})${this.stderrTail.trim() ? `:${this.stderrTail.trim().slice(-600)}` : ""}`, { code: "acp_exited" }))
62
+ })
63
+ }
64
+
65
+ request(method, params, { timeoutMs = 0, signal } = {}) {
66
+ if (this.closed) return Promise.reject(new AcpError(`ACP 已关闭,无法请求 ${method}`, { code: "acp_closed" }))
67
+ const id = ++this.nextId
68
+ return new Promise((resolve, reject) => {
69
+ const entry = { resolve, reject, timer: null, signal, onAbort: null }
70
+ if (timeoutMs > 0) {
71
+ entry.timer = setTimeout(() => {
72
+ this.pending.delete(id)
73
+ reject(new AcpError(`doubao ACP ${method} 超时(${Math.round(timeoutMs / 1000)}s)`, { code: "acp_timeout" }))
74
+ }, timeoutMs)
75
+ entry.timer.unref?.()
76
+ }
77
+ if (signal) {
78
+ entry.onAbort = () => {
79
+ this.pending.delete(id)
80
+ if (entry.timer) clearTimeout(entry.timer)
81
+ reject(new AcpError(`doubao ACP ${method} 已取消`, { code: "cancelled", status: 499 }))
82
+ }
83
+ if (signal.aborted) {
84
+ entry.onAbort()
85
+ return
86
+ }
87
+ signal.addEventListener?.("abort", entry.onAbort, { once: true })
88
+ }
89
+ this.pending.set(id, entry)
90
+ try {
91
+ this.#write({ jsonrpc: "2.0", id, method, params })
92
+ } catch (error) {
93
+ this.pending.delete(id)
94
+ if (entry.timer) clearTimeout(entry.timer)
95
+ signal?.removeEventListener?.("abort", entry.onAbort)
96
+ reject(error)
97
+ }
98
+ })
99
+ }
100
+
101
+ notify(method, params) {
102
+ if (this.closed) return
103
+ try {
104
+ this.#write({ jsonrpc: "2.0", method, params })
105
+ } catch {
106
+ // 连接断了就算了,pending 的请求会收到 close
107
+ }
108
+ }
109
+
110
+ close(error) {
111
+ if (this.closed) return
112
+ this.closed = true
113
+ const reason = error || new AcpError("ACP 连接已关闭", { code: "acp_closed" })
114
+ for (const [, entry] of this.pending) {
115
+ if (entry.timer) clearTimeout(entry.timer)
116
+ entry.signal?.removeEventListener?.("abort", entry.onAbort)
117
+ entry.reject(reason)
118
+ }
119
+ this.pending.clear()
120
+ }
121
+
122
+ #write(obj) {
123
+ if (!this.child.stdin) throw new AcpError("ACP 的 stdin 不可写", { code: "acp_closed" })
124
+ this.child.stdin.write(`${JSON.stringify(obj)}\n`)
125
+ }
126
+
127
+ #onData(chunk) {
128
+ this.buffer += String(chunk)
129
+ if (this.buffer.length > MAX_LINE) {
130
+ this.close(new AcpError("ACP 单行消息超过 32 MiB,连接已断开", { code: "acp_oversize" }))
131
+ return
132
+ }
133
+ let nl
134
+ while ((nl = this.buffer.indexOf("\n")) !== -1) {
135
+ const line = this.buffer.slice(0, nl).trim()
136
+ this.buffer = this.buffer.slice(nl + 1)
137
+ if (!line) continue
138
+ let msg
139
+ try {
140
+ msg = JSON.parse(line)
141
+ } catch {
142
+ this.log?.(`ACP 收到无法解析的行:${line.slice(0, 200)}`, "warning")
143
+ continue
144
+ }
145
+ this.#dispatch(msg)
146
+ }
147
+ }
148
+
149
+ #dispatch(msg) {
150
+ if (msg.id !== undefined && msg.id !== null && msg.method === undefined) {
151
+ const entry = this.pending.get(msg.id)
152
+ if (!entry) return
153
+ this.pending.delete(msg.id)
154
+ if (entry.timer) clearTimeout(entry.timer)
155
+ entry.signal?.removeEventListener?.("abort", entry.onAbort)
156
+ if (msg.error) {
157
+ const err = new AcpError(msg.error.message || JSON.stringify(msg.error), {
158
+ code: msg.error.code === -32000 ? "login_required" : "acp_error",
159
+ status: msg.error.code === -32000 ? 401 : 502,
160
+ acpError: msg.error,
161
+ })
162
+ if (err.code === "login_required") {
163
+ entry.reject(new LoginRequiredError(msg.error.message || "doubao CLI 未登录"))
164
+ } else {
165
+ entry.reject(err)
166
+ }
167
+ } else {
168
+ entry.resolve(msg.result)
169
+ }
170
+ return
171
+ }
172
+
173
+ if (msg.id !== undefined && msg.id !== null && typeof msg.method === "string") {
174
+ Promise.resolve()
175
+ .then(() => this.onRequest?.(msg.method, msg.params))
176
+ .then(
177
+ (result) => {
178
+ if (!this.closed) {
179
+ try {
180
+ this.#write({ jsonrpc: "2.0", id: msg.id, result: result ?? {} })
181
+ } catch {}
182
+ }
183
+ },
184
+ (error) => {
185
+ if (!this.closed) {
186
+ try {
187
+ this.#write({
188
+ jsonrpc: "2.0",
189
+ id: msg.id,
190
+ error: { code: error?.code ?? -32603, message: error?.message || String(error) },
191
+ })
192
+ } catch {}
193
+ }
194
+ },
195
+ )
196
+ return
197
+ }
198
+
199
+ if (typeof msg.method === "string") {
200
+ try {
201
+ this.onNotification?.(msg.method, msg.params)
202
+ } catch (error) {
203
+ this.log?.(`ACP 通知处理失败:${error?.message ?? error}`, "warning")
204
+ }
205
+ }
206
+ }
207
+ }
208
+
209
+ let poolSeq = 0
210
+
211
+ /**
212
+ * 一个插件实例的 ACP 进程池。
213
+ *
214
+ * settings:
215
+ * binary findDoubaoBinary() 的结果 {path, kind}
216
+ * model 可选:启动参数 --model
217
+ * effort 可选:启动参数 --effort
218
+ * permissionMode default | auto | plan | bypass_permissions
219
+ * autoApprove none | read | workspace | all
220
+ * allowDelete boolean
221
+ * idleTimeoutMs
222
+ * promptTimeoutMs
223
+ */
224
+ export class DoubaoAcpPool {
225
+ constructor({ binary, settings = {}, log } = {}) {
226
+ this.binary = binary
227
+ this.settings = settings
228
+ this.log = log
229
+ this.proc = null
230
+ this.conn = null
231
+ this.starting = null
232
+ this.sessions = new Map() // key -> { sessionId, cwd, configOptions, busy, lastUsed, queue }
233
+ this.sessionByAcpId = new Map() // acp sessionId -> record
234
+ this.idleTimer = null
235
+ this.seq = ++poolSeq
236
+ }
237
+
238
+ get label() {
239
+ return `doubao-${this.seq}`
240
+ }
241
+
242
+ async ensure() {
243
+ if (this.conn && !this.conn.closed) return this.conn
244
+ if (this.conn?.closed) {
245
+ this.conn = null
246
+ this.proc = null
247
+ this.sessions.clear()
248
+ this.sessionByAcpId.clear()
249
+ }
250
+ if (this.starting) return this.starting
251
+ this.starting = this.#start().finally(() => { this.starting = null })
252
+ return this.starting
253
+ }
254
+
255
+ async #start() {
256
+ // 旧进程的 ACP session 不能带到新连接上
257
+ this.sessions.clear()
258
+ this.sessionByAcpId.clear()
259
+ if (!this.binary?.path) {
260
+ throw new AcpError("没有找到 doubao CLI。先安装 @bytedance/doubao-cli,或在插件选项里设置 binPath。", { code: "cli_not_found", status: 503 })
261
+ }
262
+ const args = ["acp", "serve"]
263
+ if (this.settings.model) args.push("--model", String(this.settings.model))
264
+ if (this.settings.effort) args.push("--effort", String(this.settings.effort))
265
+ if (this.settings.permissionMode) args.push("--permission-mode", String(this.settings.permissionMode))
266
+ const spec = spawnSpec(this.binary, args)
267
+ const child = spawn(spec.file, spec.args, {
268
+ stdio: ["pipe", "pipe", "pipe"],
269
+ env: process.env,
270
+ windowsHide: true,
271
+ ...spec.options,
272
+ })
273
+ const conn = new AcpConnection(child, {
274
+ label: this.label,
275
+ log: this.log,
276
+ onNotification: (method, params) => this.#onNotification(method, params),
277
+ onRequest: (method, params) => this.#onRequest(method, params),
278
+ })
279
+ this.proc = child
280
+ this.conn = conn
281
+
282
+ try {
283
+ const init = await conn.request("initialize", {
284
+ protocolVersion: 1,
285
+ clientCapabilities: {
286
+ fs: { readTextFile: true, writeTextFile: true },
287
+ terminal: false,
288
+ auth: { terminal: false },
289
+ },
290
+ clientInfo: { name: "magpie", version: "0.1.0" },
291
+ }, { timeoutMs: ACP_START_TIMEOUT_MS })
292
+ if (init?.protocolVersion !== 1) {
293
+ throw new AcpError(`doubao ACP 协议版本不匹配:${init?.protocolVersion}`, { code: "acp_version" })
294
+ }
295
+ this.log?.(`doubao ACP 已连接(${init?.agentInfo?.name ?? "doubao"} ${init?.agentInfo?.version ?? ""})`)
296
+ return conn
297
+ } catch (error) {
298
+ conn.close(error)
299
+ try { child.kill("SIGTERM") } catch {}
300
+ this.proc = null
301
+ this.conn = null
302
+ throw error
303
+ }
304
+ }
305
+
306
+ #onNotification(method, params) {
307
+ if (method !== "session/update") return
308
+ const rec = this.sessionByAcpId.get(params?.sessionId)
309
+ if (!rec) return
310
+ rec.lastUsed = Date.now()
311
+ rec.onUpdate?.(params.update, params)
312
+ }
313
+
314
+ async #onRequest(method, params) {
315
+ if (method === "session/request_permission") {
316
+ const rec = this.sessionByAcpId.get(params?.sessionId)
317
+ const cwd = rec?.cwd || ""
318
+ const optionId = permissionChoice(params, {
319
+ cwd,
320
+ autoApprove: this.settings.autoApprove ?? "workspace",
321
+ allowDelete: this.settings.allowDelete === true,
322
+ })
323
+ if (optionId) {
324
+ this.log?.(`ACP 权限放行:${params?.toolCall?.title ?? params?.toolCall?.kind ?? "tool"}`)
325
+ return { outcome: { outcome: "selected", optionId } }
326
+ }
327
+ this.log?.(`ACP 权限拒绝:${params?.toolCall?.title ?? params?.toolCall?.kind ?? "tool"}`, "warning")
328
+ return { outcome: { outcome: "cancelled" } }
329
+ }
330
+
331
+ if (method === "fs/read_text_file") {
332
+ const rec = this.sessionByAcpId.get(params?.sessionId)
333
+ const cwd = rec?.cwd || ""
334
+ const file = path.resolve(String(params?.path || ""))
335
+ if (!cwd || !isPathInside(cwd, file)) throw Object.assign(new Error("路径在会话工作目录之外"), { code: -32602 })
336
+ const stat = await fsp.stat(file)
337
+ if (!stat.isFile()) throw Object.assign(new Error("不是普通文件"), { code: -32602 })
338
+ if (stat.size > 1024 * 1024) throw Object.assign(new Error("文件超过 1 MiB"), { code: -32602 })
339
+ return { content: await fsp.readFile(file, "utf8") }
340
+ }
341
+
342
+ if (method === "fs/write_text_file") {
343
+ const rec = this.sessionByAcpId.get(params?.sessionId)
344
+ const cwd = rec?.cwd || ""
345
+ const file = path.resolve(String(params?.path || ""))
346
+ if (!cwd || !isPathInside(cwd, file)) throw Object.assign(new Error("路径在会话工作目录之外"), { code: -32602 })
347
+ await fsp.mkdir(path.dirname(file), { recursive: true })
348
+ await fsp.writeFile(file, String(params?.content ?? ""), "utf8")
349
+ return {}
350
+ }
351
+
352
+ // terminal/* 没有在 clientCapabilities 里声明;真收到就明确拒绝
353
+ const error = new Error(`未实现的 ACP 客户端方法:${method}`)
354
+ error.code = -32601
355
+ throw error
356
+ }
357
+
358
+ async openSession(key, cwd) {
359
+ const conn = await this.ensure()
360
+ const existing = this.sessions.get(key)
361
+ if (existing && existing.cwd === cwd && !existing.closed) return existing
362
+ if (existing) await this.closeSession(key)
363
+ const result = await conn.request("session/new", { cwd, mcpServers: [] }, {
364
+ timeoutMs: ACP_START_TIMEOUT_MS,
365
+ }).catch(async (error) => {
366
+ // doubao ACP 在登录状态变化后要求重启连接;把旧进程收掉,下一次请求会
367
+ // 用新的登录态重新 initialize。
368
+ if (error?.code === "login_required" || error instanceof LoginRequiredError) {
369
+ await this.dispose().catch(() => {})
370
+ }
371
+ throw error
372
+ })
373
+ if (!result?.sessionId) throw new AcpError("doubao ACP session/new 没有返回 sessionId", { code: "acp_session" })
374
+ const rec = {
375
+ key,
376
+ sessionId: result.sessionId,
377
+ cwd,
378
+ configOptions: Array.isArray(result.configOptions) ? result.configOptions : [],
379
+ models: result.models ?? null,
380
+ busy: false,
381
+ queue: Promise.resolve(),
382
+ lastUsed: Date.now(),
383
+ onUpdate: null,
384
+ closed: false,
385
+ }
386
+ this.sessions.set(key, rec)
387
+ this.sessionByAcpId.set(rec.sessionId, rec)
388
+ this.log?.(`ACP session 已建立:${result.sessionId.slice(0, 8)}…(${cwd})`)
389
+ return rec
390
+ }
391
+
392
+ async closeSession(key) {
393
+ const rec = this.sessions.get(key)
394
+ if (!rec) return
395
+ this.sessions.delete(key)
396
+ this.sessionByAcpId.delete(rec.sessionId)
397
+ rec.closed = true
398
+ if (this.conn && !this.conn.closed) {
399
+ await this.conn.request("session/close", { sessionId: rec.sessionId }, { timeoutMs: 2_000 }).catch(() => {})
400
+ }
401
+ }
402
+
403
+ /** 切模型/推理强度;失败只记日志,不阻断对话 */
404
+ async #configure(rec, model, effort) {
405
+ if (!this.conn || this.conn.closed) return
406
+ const opts = rec.configOptions
407
+ const modelOpt = opts.find((o) => o?.id === "model" || o?.category === "model")
408
+ if (model && model !== "auto" && modelOpt) {
409
+ const values = flattenSelectValues(modelOpt.options)
410
+ if (values.includes(model) && model !== modelOpt.currentValue) {
411
+ try {
412
+ const res = await this.conn.request("session/set_config_option", {
413
+ sessionId: rec.sessionId,
414
+ configId: modelOpt.id,
415
+ value: model,
416
+ }, { timeoutMs: 15_000 })
417
+ if (Array.isArray(res?.configOptions)) rec.configOptions = res.configOptions
418
+ } catch (error) {
419
+ this.log?.(`切换豆包模型失败(${model}):${error?.message ?? error}`, "warning")
420
+ }
421
+ }
422
+ }
423
+ if (effort) {
424
+ const effortOpt = rec.configOptions.find((o) => o?.id === "effort" || o?.category === "thought_level")
425
+ if (effortOpt) {
426
+ const values = flattenSelectValues(effortOpt.options)
427
+ if (values.includes(effort) && effort !== effortOpt.currentValue) {
428
+ try {
429
+ const res = await this.conn.request("session/set_config_option", {
430
+ sessionId: rec.sessionId,
431
+ configId: effortOpt.id,
432
+ value: effort,
433
+ }, { timeoutMs: 15_000 })
434
+ if (Array.isArray(res?.configOptions)) rec.configOptions = res.configOptions
435
+ } catch (error) {
436
+ this.log?.(`切换豆包推理强度失败(${effort}):${error?.message ?? error}`, "warning")
437
+ }
438
+ }
439
+ }
440
+ }
441
+ }
442
+
443
+ /**
444
+ * 在一个 conversation 的 ACP session 里跑一轮 prompt。
445
+ * 同一 session 的请求串行(ACP 的 session 一次只能有一个 turn)。
446
+ */
447
+ async prompt(key, {
448
+ cwd,
449
+ model = "",
450
+ effort = "",
451
+ text,
452
+ signal,
453
+ timeoutMs = this.settings.promptTimeoutMs ?? DEFAULT_PROMPT_TIMEOUT_MS,
454
+ onText,
455
+ onUpdate,
456
+ }) {
457
+ const rec = await this.openSession(key, cwd)
458
+ // 同一会话的请求串行:ACP 的 session 一次只能有一个 turn。第一个请求也
459
+ // 经过同一条链,避免 busy 标志在多个排队请求之间失真。
460
+ const prior = rec.queue || Promise.resolve()
461
+ const task = prior.catch(() => {}).then(() => this.#runPrompt(rec, { text, model, effort, signal, timeoutMs, onText, onUpdate }))
462
+ rec.queue = task
463
+ rec.busy = true
464
+ task.finally(() => {
465
+ if (rec.queue === task) rec.busy = false
466
+ }).catch(() => {})
467
+ return task
468
+ }
469
+
470
+ async #runPrompt(rec, { text, model, effort, signal, timeoutMs, onText, onUpdate }) {
471
+ const conn = await this.ensure()
472
+ rec.lastUsed = Date.now()
473
+ rec.onUpdate = (update) => {
474
+ if (update?.sessionUpdate === "agent_message_chunk" && update.content?.type === "text" && typeof update.content.text === "string") {
475
+ onText?.(update.content.text)
476
+ }
477
+ onUpdate?.(update)
478
+ }
479
+ try {
480
+ await this.#configure(rec, model, effort)
481
+ const result = await conn.request("session/prompt", {
482
+ sessionId: rec.sessionId,
483
+ prompt: [{ type: "text", text }],
484
+ }, { timeoutMs, signal })
485
+ rec.lastUsed = Date.now()
486
+ return result
487
+ } catch (error) {
488
+ if (error instanceof LoginRequiredError) throw error
489
+ if (error?.code === "login_required") throw new LoginRequiredError(error.message)
490
+ if (error?.code === "cancelled" || signal?.aborted) {
491
+ try { conn.notify("session/cancel", { sessionId: rec.sessionId }) } catch {}
492
+ }
493
+ throw error
494
+ } finally {
495
+ rec.onUpdate = null
496
+ this.#armIdle()
497
+ }
498
+ }
499
+
500
+ #armIdle() {
501
+ if (this.idleTimer) clearTimeout(this.idleTimer)
502
+ const ms = this.settings.idleTimeoutMs ?? DEFAULT_IDLE_TIMEOUT_MS
503
+ if (!(ms > 0)) return
504
+ this.idleTimer = setTimeout(() => {
505
+ if ([...this.sessions.values()].some((s) => s.busy)) return this.#armIdle()
506
+ this.dispose().catch(() => {})
507
+ }, ms)
508
+ this.idleTimer.unref?.()
509
+ }
510
+
511
+ async dispose() {
512
+ if (this.idleTimer) {
513
+ clearTimeout(this.idleTimer)
514
+ this.idleTimer = null
515
+ }
516
+ for (const key of [...this.sessions.keys()]) {
517
+ await this.closeSession(key).catch(() => {})
518
+ }
519
+ this.conn?.close()
520
+ if (this.proc && this.proc.exitCode === null && this.proc.signalCode === null) {
521
+ try { this.proc.kill("SIGTERM") } catch {}
522
+ const timer = setTimeout(() => {
523
+ try { this.proc?.kill("SIGKILL") } catch {}
524
+ }, 1_500)
525
+ timer.unref?.()
526
+ }
527
+ this.conn = null
528
+ this.proc = null
529
+ }
530
+ }
531
+
532
+ function flattenSelectValues(options) {
533
+ const out = []
534
+ const walk = (list) => {
535
+ for (const o of Array.isArray(list) ? list : []) {
536
+ if (Array.isArray(o?.options)) walk(o.options)
537
+ else if (typeof o?.value === "string") out.push(o.value)
538
+ }
539
+ }
540
+ walk(options)
541
+ return out
542
+ }
543
+
544
+ /** 进程退出时尽量带走子进程(magpie 自己也会做 host 进程树清理) */
545
+ const livePools = new Set()
546
+ export function registerPool(pool) {
547
+ livePools.add(pool)
548
+ return pool
549
+ }
550
+ export function disposeAllPools() {
551
+ for (const pool of livePools) pool.dispose().catch(() => {})
552
+ livePools.clear()
553
+ }
554
+ process.once?.("exit", () => {
555
+ for (const pool of livePools) {
556
+ try { pool.proc?.kill("SIGKILL") } catch {}
557
+ }
558
+ })