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

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/chat.mjs ADDED
@@ -0,0 +1,495 @@
1
+ // 把 OpenAI Responses / Chat Completions 请求翻译成一次 doubao ACP prompt,
2
+ // 并把 `session/update` 的文本增量翻译回对应协议的 SSE。
3
+ //
4
+ // 这不是逐 token 的模型反代:豆包 CLI 是一个完整的 agent,它会用自己的
5
+ // 工具在 cwd 里读文件、跑命令。插件只负责:
6
+ // 用户消息 → session/prompt → agent_message_chunk → SSE
7
+ //
8
+ // 因此外层 agent 看到的是「一个会自己动手的模型」:模型返回纯文本,但文件
9
+ // 操作已经在豆包 CLI 那边完成。
10
+
11
+ import crypto from "node:crypto"
12
+ import fs from "node:fs"
13
+ import os from "node:os"
14
+ import path from "node:path"
15
+ import {
16
+ DEFAULT_MODEL_ID,
17
+ } from "./constants.mjs"
18
+ import {
19
+ buildPrompt,
20
+ chatChunk,
21
+ estimateInputTokens,
22
+ estimateTokensFromText,
23
+ lastUserText,
24
+ normalizeMessages,
25
+ sseData,
26
+ } from "./pure.mjs"
27
+ import { LoginRequiredError } from "./cli.mjs"
28
+
29
+ const MAX_BODY = 8 * 1024 * 1024
30
+
31
+ function jsonError(status, message, code = "upstream_error", headers = {}) {
32
+ return new Response(JSON.stringify({ error: { message, type: "upstream_error", code, status } }), {
33
+ status,
34
+ headers: { "content-type": "application/json", ...headers },
35
+ })
36
+ }
37
+
38
+ function decodeWorkDir(headers) {
39
+ const raw = headers.get("x-magpie-work-dir") || ""
40
+ if (!raw) return ""
41
+ try {
42
+ return decodeURIComponent(raw)
43
+ } catch {
44
+ return raw
45
+ }
46
+ }
47
+
48
+ function conversationKey(headers, body, cwd) {
49
+ const direct = headers.get("x-doubao-conversation") ||
50
+ headers.get("x-magpie-conversation") ||
51
+ headers.get("x-magpie-session") ||
52
+ ""
53
+ if (direct) return direct.slice(0, 200)
54
+ const messages = normalizeMessages(body)
55
+ const seed = `${cwd}\n${body?.model ?? ""}\n${lastUserText(messages)}\n${messages.length}`
56
+ return `anon-${crypto.createHash("sha256").update(seed).digest("hex").slice(0, 16)}`
57
+ }
58
+
59
+ function chooseCwd(requested, fallback) {
60
+ for (const candidate of [requested, fallback]) {
61
+ if (!candidate || typeof candidate !== "string") continue
62
+ try {
63
+ const st = fs.statSync(candidate)
64
+ if (st.isDirectory()) return candidate
65
+ } catch {
66
+ // 下一个
67
+ }
68
+ }
69
+ return os.homedir()
70
+ }
71
+
72
+ /**
73
+ * @param {object} deps
74
+ * @param {() => Promise<object|undefined>} deps.getAuth
75
+ * @param {import("./acp.mjs").DoubaoAcpPool} deps.pool
76
+ * @param {object} deps.settings
77
+ * @param {(msg:string, level?:string)=>void} deps.log
78
+ */
79
+ export function createFetch({ getAuth, pool, settings = {}, log } = {}) {
80
+ return async function doubaoFetch(input, init = {}) {
81
+ const url = typeof input === "string"
82
+ ? input
83
+ : input instanceof URL
84
+ ? input.href
85
+ : input?.url || ""
86
+ const method = String(init.method || input?.method || "POST").toUpperCase()
87
+
88
+ if (method !== "POST") {
89
+ return jsonError(405, "只支持 POST /responses 或 /chat/completions", "method_not_allowed")
90
+ }
91
+ const isResponses = /\/responses(?:$|[/?#])/i.test(url)
92
+ if (!isResponses && !/\/chat\/completions(?:$|[/?#])/i.test(url)) {
93
+ return jsonError(404, `不支持的端点:${url}`, "not_found")
94
+ }
95
+
96
+ const auth = await getAuth()
97
+ if (!auth) {
98
+ return jsonError(401, "豆包 CLI 未登录:请先在终端运行 `doubao login`", "sign_in_required", {
99
+ "x-magpie-sign-in": "expired",
100
+ })
101
+ }
102
+
103
+ let raw = ""
104
+ try {
105
+ if (typeof init.body === "string") raw = init.body
106
+ else if (init.body != null) raw = new TextDecoder().decode(init.body)
107
+ else if (typeof input?.text === "function") raw = await input.text()
108
+ } catch (error) {
109
+ return jsonError(400, `读取请求体失败:${error.message}`, "invalid_request")
110
+ }
111
+ if (Buffer.byteLength(raw, "utf8") > MAX_BODY) {
112
+ return jsonError(413, "请求体超过 8 MiB", "request_too_large")
113
+ }
114
+ let body
115
+ try {
116
+ body = JSON.parse(raw)
117
+ } catch {
118
+ return jsonError(400, "请求体不是合法 JSON", "invalid_request")
119
+ }
120
+
121
+ const headers = new Headers(init.headers || input?.headers || {})
122
+ const messages = normalizeMessages(body)
123
+ if (!messages.length) return jsonError(400, "messages 为空", "invalid_request")
124
+
125
+ const cwd = chooseCwd(decodeWorkDir(headers), settings.cwd)
126
+ const conversation = conversationKey(headers, body, cwd)
127
+ const model = String(body.model ?? "").replace(/^.*\//, "") || DEFAULT_MODEL_ID
128
+ const effort = String(body.reasoning_effort ?? body.reasoning?.effort ?? settings.effort ?? "").trim()
129
+
130
+ // 第一次见这个 conversation(或工作目录变了、session 要重建)时带上完整
131
+ // 上下文;之后的轮次 ACP session 自己有记忆。
132
+ const existing = pool.sessions.get(conversation)
133
+ const fullContext = !existing || existing.cwd !== cwd || existing.closed || pool.conn?.closed === true
134
+ const prompt = buildPrompt(messages, {
135
+ fullContext,
136
+ maxChars: settings.maxPromptChars ?? 240_000,
137
+ })
138
+ if (!prompt.trim()) return jsonError(400, "最后一条用户消息为空", "invalid_request")
139
+
140
+ const id = `chatcmpl-${crypto.randomUUID().replace(/-/g, "").slice(0, 24)}`
141
+ const created = Math.floor(Date.now() / 1000)
142
+ const requestedModel = String(body.model ?? model)
143
+ const stream = body.stream === true
144
+ const promptTokens = estimateInputTokens(body)
145
+
146
+ if (isResponses) {
147
+ return handleResponses({
148
+ body, messages, prompt, cwd, conversation, model, requestedModel: String(body.model ?? model),
149
+ effort, stream, promptTokens, init, input, settings, pool, log,
150
+ })
151
+ }
152
+
153
+ if (!stream) {
154
+ try {
155
+ let text = ""
156
+ const result = await pool.prompt(conversation, {
157
+ cwd,
158
+ model,
159
+ effort,
160
+ text: prompt,
161
+ signal: init.signal || input?.signal,
162
+ onText: (chunk) => { text += chunk },
163
+ })
164
+ return Response.json({
165
+ id,
166
+ object: "chat.completion",
167
+ created,
168
+ model: requestedModel,
169
+ choices: [{
170
+ index: 0,
171
+ message: { role: "assistant", content: text },
172
+ finish_reason: result?.stopReason === "max_tokens" ? "length" : "stop",
173
+ }],
174
+ usage: {
175
+ prompt_tokens: promptTokens,
176
+ completion_tokens: estimateTokensFromText(text),
177
+ total_tokens: promptTokens + estimateTokensFromText(text),
178
+ },
179
+ })
180
+ } catch (error) {
181
+ return errorResponse(error)
182
+ }
183
+ }
184
+
185
+ const encoder = new TextEncoder()
186
+ const abort = new AbortController()
187
+ const signal = init.signal ? AbortSignal.any([init.signal, abort.signal]) : abort.signal
188
+
189
+ const responseStream = new ReadableStream({
190
+ start(controller) {
191
+ let closed = false
192
+ const emit = (obj) => {
193
+ if (closed) return
194
+ try { controller.enqueue(encoder.encode(sseData(obj))) } catch { closed = true }
195
+ }
196
+ const finish = () => {
197
+ if (closed) return
198
+ try { controller.enqueue(encoder.encode("data: [DONE]\n\n")) } catch {}
199
+ closed = true
200
+ try { controller.close() } catch {}
201
+ }
202
+ const fail = (error) => {
203
+ if (closed) return
204
+ const payload = errorPayload(error)
205
+ emit({ error: payload })
206
+ finish()
207
+ }
208
+ const ping = setInterval(() => {
209
+ if (closed) return
210
+ try { controller.enqueue(encoder.encode(": keepalive\n\n")) } catch {}
211
+ }, 5_000)
212
+ ping.unref?.()
213
+
214
+ emit(chatChunk({ id, created, model: requestedModel, delta: { role: "assistant", content: "" } }))
215
+
216
+ pool.prompt(conversation, {
217
+ cwd,
218
+ model,
219
+ effort,
220
+ text: prompt,
221
+ signal,
222
+ onText: (chunk) => {
223
+ emit(chatChunk({ id, created, model: requestedModel, delta: { content: chunk } }))
224
+ },
225
+ }).then((result) => {
226
+ const finishReason = result?.stopReason === "max_tokens" ? "length"
227
+ : result?.stopReason === "cancelled" ? "stop"
228
+ : "stop"
229
+ emit(chatChunk({
230
+ id,
231
+ created,
232
+ model: requestedModel,
233
+ delta: {},
234
+ finishReason,
235
+ }))
236
+ finish()
237
+ }).catch(fail).finally(() => clearInterval(ping))
238
+
239
+ // 客户端断开:取消 ACP turn
240
+ signal.addEventListener?.("abort", () => {
241
+ try { abort.abort() } catch {}
242
+ clearInterval(ping)
243
+ if (!closed) {
244
+ closed = true
245
+ try { controller.close() } catch {}
246
+ }
247
+ }, { once: true })
248
+ },
249
+ cancel() {
250
+ abort.abort()
251
+ },
252
+ })
253
+
254
+ return new Response(responseStream, {
255
+ status: 200,
256
+ headers: {
257
+ "content-type": "text/event-stream; charset=utf-8",
258
+ "cache-control": "no-cache",
259
+ connection: "keep-alive",
260
+ },
261
+ })
262
+ }
263
+ }
264
+
265
+
266
+ // ---- Responses API ---------------------------------------------------------
267
+
268
+ function responseUsage(promptTokens, text) {
269
+ const output = estimateTokensFromText(text)
270
+ return {
271
+ input_tokens: promptTokens,
272
+ input_tokens_details: { cached_tokens: 0 },
273
+ output_tokens: output,
274
+ output_tokens_details: { reasoning_tokens: 0 },
275
+ total_tokens: promptTokens + output,
276
+ }
277
+ }
278
+
279
+ function responseObject({ id, created, model, status, text, promptTokens, messageId }) {
280
+ const output = status === "completed"
281
+ ? [{
282
+ id: messageId || `msg_${id.slice(-24)}`,
283
+ type: "message",
284
+ status: "completed",
285
+ role: "assistant",
286
+ content: [{ type: "output_text", text, annotations: [] }],
287
+ }]
288
+ : []
289
+ return {
290
+ id,
291
+ object: "response",
292
+ created_at: created,
293
+ status,
294
+ model,
295
+ output,
296
+ error: null,
297
+ incomplete_details: null,
298
+ parallel_tool_calls: false,
299
+ tool_choice: "auto",
300
+ tools: [],
301
+ usage: status === "completed" ? responseUsage(promptTokens, text) : null,
302
+ }
303
+ }
304
+
305
+ function responsesEvent(type, payload) {
306
+ return `event: ${type}\ndata: ${JSON.stringify(payload)}\n\n`
307
+ }
308
+
309
+ async function handleResponses({
310
+ body, prompt, cwd, conversation, model, requestedModel, effort, stream, promptTokens, init, input, pool,
311
+ }) {
312
+ const id = `resp_${crypto.randomUUID().replace(/-/g, "").slice(0, 24)}`
313
+ const created = Math.floor(Date.now() / 1000)
314
+ const messageId = `msg_${crypto.randomUUID().replace(/-/g, "").slice(0, 24)}`
315
+
316
+ if (!stream) {
317
+ try {
318
+ let text = ""
319
+ const result = await pool.prompt(conversation, {
320
+ cwd,
321
+ model,
322
+ effort,
323
+ text: prompt,
324
+ signal: init.signal || input?.signal,
325
+ onText: (chunk) => { text += chunk },
326
+ })
327
+ return Response.json(responseObject({
328
+ id, created, model: requestedModel,
329
+ status: "completed",
330
+ text,
331
+ promptTokens,
332
+ }))
333
+ } catch (error) {
334
+ return errorResponse(error)
335
+ }
336
+ }
337
+
338
+ const encoder = new TextEncoder()
339
+ const abort = new AbortController()
340
+ const signal = init.signal ? AbortSignal.any([init.signal, abort.signal]) : abort.signal
341
+ const streamResponse = new ReadableStream({
342
+ start(controller) {
343
+ let closed = false
344
+ let text = ""
345
+ const emit = (type, payload) => {
346
+ if (closed) return
347
+ try { controller.enqueue(encoder.encode(responsesEvent(type, payload))) } catch { closed = true }
348
+ }
349
+ const finish = () => {
350
+ if (closed) return
351
+ closed = true
352
+ try { controller.close() } catch {}
353
+ }
354
+ const fail = (error) => {
355
+ if (closed) return
356
+ const payload = errorPayload(error)
357
+ emit("response.failed", {
358
+ type: "response.failed",
359
+ response: {
360
+ id,
361
+ object: "response",
362
+ created_at: created,
363
+ status: "failed",
364
+ model: requestedModel,
365
+ output: [],
366
+ error: { code: payload.code, message: payload.message },
367
+ usage: null,
368
+ },
369
+ })
370
+ finish()
371
+ }
372
+ const ping = setInterval(() => {
373
+ if (closed) return
374
+ try { controller.enqueue(encoder.encode(": keepalive\n\n")) } catch {}
375
+ }, 5_000)
376
+ ping.unref?.()
377
+
378
+ const inProgress = responseObject({ id, created, model: requestedModel, status: "in_progress", text: "", promptTokens })
379
+ emit("response.created", { type: "response.created", response: inProgress })
380
+ emit("response.in_progress", { type: "response.in_progress", response: inProgress })
381
+ emit("response.output_item.added", {
382
+ type: "response.output_item.added",
383
+ output_index: 0,
384
+ item: { id: messageId, type: "message", status: "in_progress", role: "assistant", content: [] },
385
+ })
386
+ emit("response.content_part.added", {
387
+ type: "response.content_part.added",
388
+ item_id: messageId,
389
+ output_index: 0,
390
+ content_index: 0,
391
+ part: { type: "output_text", text: "", annotations: [] },
392
+ })
393
+
394
+ pool.prompt(conversation, {
395
+ cwd,
396
+ model,
397
+ effort,
398
+ text: prompt,
399
+ signal,
400
+ onText: (chunk) => {
401
+ if (!chunk) return
402
+ text += chunk
403
+ emit("response.output_text.delta", {
404
+ type: "response.output_text.delta",
405
+ item_id: messageId,
406
+ output_index: 0,
407
+ content_index: 0,
408
+ delta: chunk,
409
+ logprobs: [],
410
+ })
411
+ },
412
+ }).then(() => {
413
+ emit("response.output_text.done", {
414
+ type: "response.output_text.done",
415
+ item_id: messageId,
416
+ output_index: 0,
417
+ content_index: 0,
418
+ text,
419
+ logprobs: [],
420
+ })
421
+ emit("response.content_part.done", {
422
+ type: "response.content_part.done",
423
+ item_id: messageId,
424
+ output_index: 0,
425
+ content_index: 0,
426
+ part: { type: "output_text", text, annotations: [] },
427
+ })
428
+ emit("response.output_item.done", {
429
+ type: "response.output_item.done",
430
+ output_index: 0,
431
+ item: {
432
+ id: messageId,
433
+ type: "message",
434
+ status: "completed",
435
+ role: "assistant",
436
+ content: [{ type: "output_text", text, annotations: [] }],
437
+ },
438
+ })
439
+ emit("response.completed", {
440
+ type: "response.completed",
441
+ response: responseObject({ id, created, model: requestedModel, status: "completed", text, promptTokens, messageId }),
442
+ })
443
+ finish()
444
+ }).catch(fail).finally(() => clearInterval(ping))
445
+
446
+ signal.addEventListener?.("abort", () => {
447
+ try { abort.abort() } catch {}
448
+ clearInterval(ping)
449
+ if (!closed) {
450
+ closed = true
451
+ try { controller.close() } catch {}
452
+ }
453
+ }, { once: true })
454
+ },
455
+ cancel() {
456
+ abort.abort()
457
+ },
458
+ })
459
+
460
+ return new Response(streamResponse, {
461
+ status: 200,
462
+ headers: {
463
+ "content-type": "text/event-stream; charset=utf-8",
464
+ "cache-control": "no-cache",
465
+ connection: "keep-alive",
466
+ },
467
+ })
468
+ }
469
+
470
+ function errorPayload(error) {
471
+ if (error instanceof LoginRequiredError || error?.code === "login_required") {
472
+ return { message: error.message || "豆包 CLI 未登录", type: "upstream_error", code: "sign_in_required" }
473
+ }
474
+ return {
475
+ message: error?.message || String(error),
476
+ type: "upstream_error",
477
+ code: error?.code || "upstream_error",
478
+ }
479
+ }
480
+
481
+ function errorResponse(error) {
482
+ const payload = errorPayload(error)
483
+ const status = error instanceof LoginRequiredError || error?.code === "login_required" ? 401 : (error?.status || 502)
484
+ return jsonError(status, payload.message, payload.code, status === 401 ? { "x-magpie-sign-in": "expired" } : {})
485
+ }
486
+
487
+ /** 给 count_tokens 端点用 */
488
+ export function countTokensResponse(body) {
489
+ return Response.json({ input_tokens: estimateInputTokens(body) })
490
+ }
491
+
492
+ /** chat.headers hook:把 magpie 的 session id 变成 ACP 会话键 */
493
+ export function chatHeaders(input, output) {
494
+ if (input?.sessionID) output.headers["x-doubao-conversation"] = String(input.sessionID).slice(0, 200)
495
+ }