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/CHANGELOG.md +77 -0
- package/LICENSE +21 -0
- package/NOTICE.md +19 -0
- package/README.md +304 -2
- package/assets/icon-256.png +0 -0
- package/index.mjs +457 -0
- package/package.json +45 -4
- package/registry-entry.json +11 -0
- package/src/acp.mjs +558 -0
- package/src/browser-login.mjs +431 -0
- package/src/chat.mjs +495 -0
- package/src/cli.mjs +407 -0
- package/src/constants.mjs +46 -0
- package/src/identity.mjs +17 -0
- package/src/pure.mjs +351 -0
- package/src/web-errors.mjs +140 -0
- package/src/web-quota-normalize.mjs +160 -0
- package/src/webcookie.mjs +62 -0
- package/src/webquota.mjs +284 -0
package/index.mjs
ADDED
|
@@ -0,0 +1,457 @@
|
|
|
1
|
+
// 豆包 CLI(ACP)· magpie 供应商插件
|
|
2
|
+
//
|
|
3
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
4
|
+
// 这个插件做什么
|
|
5
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
6
|
+
//
|
|
7
|
+
// 传统「反代 doubao」是抓豆包工作/豆包网页的 HTTP 接口,再翻译成
|
|
8
|
+
// OpenAI Chat Completions。问题是模型本身活在豆包云端,服务端会告诉它
|
|
9
|
+
// “你在 /home/user/Doubao/chats/… 的云端沙箱里”,所以它不会、也不能
|
|
10
|
+
// 操作你本机的项目。
|
|
11
|
+
//
|
|
12
|
+
// 这个插件换了一条路:在本机启动官方 `doubao acp serve`,用 ACP v1
|
|
13
|
+
// (JSON-RPC over stdio)把豆包 CLI 这个完整的本地 agent 接进 magpie。
|
|
14
|
+
// 模型仍然是豆包的模型,但执行工具的是本机 CLI,cwd 就是 magpie 传来的
|
|
15
|
+
// 工作目录,因此读写文件、跑命令都发生在你本机。
|
|
16
|
+
//
|
|
17
|
+
// magpie / Codex / Claude Code
|
|
18
|
+
// │ OpenAI Chat Completions
|
|
19
|
+
// ▼
|
|
20
|
+
// 本插件(Auth + Provider)
|
|
21
|
+
// │ ACP v1 JSON-RPC(stdin/stdout)
|
|
22
|
+
// ▼
|
|
23
|
+
// doubao acp serve ── 豆包模型 + 本地工具(read/edit/exec)
|
|
24
|
+
//
|
|
25
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
26
|
+
// 关键约定
|
|
27
|
+
// ═══════════════════════════════════════════════════════════════════════
|
|
28
|
+
//
|
|
29
|
+
// 1. config.models 必须非空:未登录时也要有 `auto`,否则卡片显示 0 models。
|
|
30
|
+
// 2. authorize() 立刻返回;真正等登录的是 callback(),否则 magpie 会死锁。
|
|
31
|
+
// 3. 入口只导出工厂;helper 全在 src/ 里(`_pure` 是唯一例外)。
|
|
32
|
+
// 4. doubao CLI 的登录态由 CLI 自己维护(`doubao login`),插件只检查状态。
|
|
33
|
+
// 5. 一个插件实例共用一个 `doubao acp serve` 进程;每个 magpie conversation
|
|
34
|
+
// 对应一个 ACP session,session 内有豆包 CLI 自己的上下文。
|
|
35
|
+
|
|
36
|
+
import { pathToFileURL } from "node:url"
|
|
37
|
+
import {
|
|
38
|
+
API_BASE,
|
|
39
|
+
DEFAULT_CONTEXT_WINDOW,
|
|
40
|
+
DEFAULT_IDLE_TIMEOUT_MS,
|
|
41
|
+
DEFAULT_MODEL_ID,
|
|
42
|
+
DEFAULT_OUTPUT_TOKENS,
|
|
43
|
+
DEFAULT_PROMPT_TIMEOUT_MS,
|
|
44
|
+
MODEL_CACHE_TTL_MS,
|
|
45
|
+
NPM,
|
|
46
|
+
NPM_CHAT,
|
|
47
|
+
NPM_RESPONSES,
|
|
48
|
+
PROVIDER,
|
|
49
|
+
PROVIDER_NAME,
|
|
50
|
+
VERSION_CACHE_TTL_MS,
|
|
51
|
+
} from "./src/constants.mjs"
|
|
52
|
+
import { ICON } from "./src/identity.mjs"
|
|
53
|
+
import {
|
|
54
|
+
checkAuth,
|
|
55
|
+
cliVersion,
|
|
56
|
+
findDoubaoBinary,
|
|
57
|
+
installDoubao,
|
|
58
|
+
listModels,
|
|
59
|
+
LoginRequiredError,
|
|
60
|
+
startLogin,
|
|
61
|
+
waitForAuth,
|
|
62
|
+
} from "./src/cli.mjs"
|
|
63
|
+
import { DoubaoAcpPool, registerPool } from "./src/acp.mjs"
|
|
64
|
+
import { createFetch, chatHeaders } from "./src/chat.mjs"
|
|
65
|
+
import { launchLoginBrowser, setBrowserPath, waitForLoginCookies } from "./src/browser-login.mjs"
|
|
66
|
+
import { cookieHeaderFromCookies, readWebQuota } from "./src/webquota.mjs"
|
|
67
|
+
import { loadWebCookie, saveWebCookie } from "./src/webcookie.mjs"
|
|
68
|
+
import { modelsMap, staticModels } from "./src/pure.mjs"
|
|
69
|
+
|
|
70
|
+
const modelCache = new Map() // binary path -> { at, models }
|
|
71
|
+
const versionCache = new Map() // binary path -> { at, version }
|
|
72
|
+
|
|
73
|
+
function positive(value, fallback) {
|
|
74
|
+
const n = Number(value)
|
|
75
|
+
return Number.isFinite(n) && n > 0 ? Math.floor(n) : fallback
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function normalizeSettings(options = {}) {
|
|
79
|
+
const permissionModes = new Set(["default", "auto", "plan", "bypass_permissions"])
|
|
80
|
+
const approveModes = new Set(["none", "read", "workspace", "all"])
|
|
81
|
+
return {
|
|
82
|
+
binPath: typeof options?.binPath === "string" ? options.binPath.trim() : "",
|
|
83
|
+
browserPath: typeof options?.browserPath === "string" ? options.browserPath.trim() : "",
|
|
84
|
+
cwd: typeof options?.cwd === "string" && options.cwd.trim() ? options.cwd.trim() : "",
|
|
85
|
+
permissionMode: permissionModes.has(options?.permissionMode) ? options.permissionMode : "auto",
|
|
86
|
+
autoApprove: approveModes.has(options?.autoApprove) ? options.autoApprove : "workspace",
|
|
87
|
+
allowDelete: options?.allowDelete === true,
|
|
88
|
+
effort: typeof options?.effort === "string" ? options.effort.trim() : "",
|
|
89
|
+
model: typeof options?.model === "string" ? options.model.trim() : "",
|
|
90
|
+
protocol: options?.protocol === "chat" ? "chat" : "responses",
|
|
91
|
+
npm: options?.protocol === "chat" ? NPM_CHAT : NPM_RESPONSES,
|
|
92
|
+
webCookie: typeof options?.webCookie === "string" ? options.webCookie.trim() : "",
|
|
93
|
+
contextWindow: positive(options?.contextWindow, DEFAULT_CONTEXT_WINDOW),
|
|
94
|
+
outputTokens: positive(options?.outputTokens, DEFAULT_OUTPUT_TOKENS),
|
|
95
|
+
idleTimeoutMs: positive(options?.idleTimeoutMs, DEFAULT_IDLE_TIMEOUT_MS),
|
|
96
|
+
promptTimeoutMs: positive(options?.promptTimeoutMs, DEFAULT_PROMPT_TIMEOUT_MS),
|
|
97
|
+
maxPromptChars: positive(options?.maxPromptChars, 240_000),
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function successAccount(status, { webCookie = "" } = {}) {
|
|
102
|
+
return {
|
|
103
|
+
type: "success",
|
|
104
|
+
access: "doubao-cli-local",
|
|
105
|
+
// CLI 自己续登录;这里不造假 refresh token。expires 只用于避免
|
|
106
|
+
// magpie 每次请求都以为账号过期。
|
|
107
|
+
expires: Date.now() + 365 * 24 * 3600_000,
|
|
108
|
+
accountId: status.accountId || status.userId || "豆包 CLI",
|
|
109
|
+
uid: status.userId || "doubao-cli",
|
|
110
|
+
...(webCookie ? { metadata: { webCookie } } : {}),
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function describeLoginError(error, binary) {
|
|
115
|
+
if (!binary) {
|
|
116
|
+
return [
|
|
117
|
+
"没有找到 doubao CLI。",
|
|
118
|
+
"请先安装:npm install -g @bytedance/doubao-cli --allow-scripts=@bytedance/doubao-cli",
|
|
119
|
+
"或在插件选项里设置 binPath 指向 doubao 可执行文件。",
|
|
120
|
+
].join("\n")
|
|
121
|
+
}
|
|
122
|
+
return String(error?.message ?? error)
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export const DoubaoAcpPlugin = async (ctx = {}, options = {}) => {
|
|
126
|
+
const settings = normalizeSettings(options)
|
|
127
|
+
const log = (message, level = "info") => {
|
|
128
|
+
try {
|
|
129
|
+
ctx?.client?.app?.log?.({ service: PROVIDER, level, message })
|
|
130
|
+
} catch {
|
|
131
|
+
// 没有日志通道就算了
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
setBrowserPath(settings.browserPath)
|
|
136
|
+
let binary = findDoubaoBinary({ explicit: settings.binPath })
|
|
137
|
+
const pool = registerPool(new DoubaoAcpPool({ binary, settings, log }))
|
|
138
|
+
|
|
139
|
+
const refreshBinary = () => {
|
|
140
|
+
const found = findDoubaoBinary({ explicit: settings.binPath })
|
|
141
|
+
if (found) binary = found
|
|
142
|
+
return binary
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const cachedModels = async ({ force = false } = {}) => {
|
|
146
|
+
const target = refreshBinary()
|
|
147
|
+
if (!target) throw new LoginRequiredError("没有找到 doubao CLI")
|
|
148
|
+
const hit = modelCache.get(target.path)
|
|
149
|
+
if (!force && hit && Date.now() - hit.at < MODEL_CACHE_TTL_MS) return hit.models
|
|
150
|
+
const models = await listModels(target)
|
|
151
|
+
modelCache.set(target.path, { at: Date.now(), models })
|
|
152
|
+
return models
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const cachedVersion = async () => {
|
|
156
|
+
const target = refreshBinary()
|
|
157
|
+
if (!target) return ""
|
|
158
|
+
const hit = versionCache.get(target.path)
|
|
159
|
+
if (hit && Date.now() - hit.at < VERSION_CACHE_TTL_MS) return hit.version
|
|
160
|
+
const version = await cliVersion(target).catch(() => "")
|
|
161
|
+
versionCache.set(target.path, { at: Date.now(), version })
|
|
162
|
+
return version
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
const afterLogin = async (target) => {
|
|
166
|
+
if (target?.path) modelCache.delete(target.path)
|
|
167
|
+
// 登录/退出后 doubao ACP 要求重启连接;顺手把旧进程收掉
|
|
168
|
+
await pool.dispose().catch(() => {})
|
|
169
|
+
}
|
|
170
|
+
const beginCliLogin = async (target) => {
|
|
171
|
+
const status = await checkAuth(target).catch(() => null)
|
|
172
|
+
if (status?.loggedIn) return { status, login: null }
|
|
173
|
+
const login = await startLogin(target)
|
|
174
|
+
return { status: null, login }
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const qrInstructions = (login) => [
|
|
178
|
+
"已生成豆包 CLI 登录二维码,并尝试用系统默认看图应用打开。",
|
|
179
|
+
"请用豆包 App 扫码并在手机上确认;确认后会自动完成登录,无需输入。",
|
|
180
|
+
`二维码文件:${login.qrPath}`,
|
|
181
|
+
"",
|
|
182
|
+
"如果二维码没有自动打开,手动打开上面的文件即可。",
|
|
183
|
+
].join("\n")
|
|
184
|
+
|
|
185
|
+
// 登录方式只有两个维度,用一个下拉问清额度,而不是摆四个并列按钮:
|
|
186
|
+
// 扫码登录(需要 CLI 二维码) / 用终端已登录的账号
|
|
187
|
+
// 额度:浏览器授权 / 粘贴 Cookie / 不绑
|
|
188
|
+
const QUOTA_PROMPTS = [
|
|
189
|
+
{
|
|
190
|
+
type: "select",
|
|
191
|
+
key: "quota",
|
|
192
|
+
message: "额度怎么绑定?",
|
|
193
|
+
messages: { zh: "额度怎么绑定?", "zh-TW": "額度怎麼綁定?", ja: "使用量の取得方法" },
|
|
194
|
+
options: [
|
|
195
|
+
{
|
|
196
|
+
label: "打开浏览器授权(推荐)",
|
|
197
|
+
value: "browser",
|
|
198
|
+
hint: "调用走 CLI,额度用临时浏览器窗口取,两样一起完成",
|
|
199
|
+
hints: { zh: "调用走 CLI,额度用临时浏览器窗口取,两样一起完成", "zh-TW": "呼叫走 CLI,額度用臨時瀏覽器視窗取,兩樣一起完成" },
|
|
200
|
+
labels: { zh: "打开浏览器授权(推荐)", "zh-TW": "開啟瀏覽器授權(推薦)", ja: "ブラウザで認可(推奨)" },
|
|
201
|
+
},
|
|
202
|
+
{
|
|
203
|
+
label: "粘贴网页 Cookie",
|
|
204
|
+
value: "paste",
|
|
205
|
+
hint: "调用走 CLI,额度用你浏览器里的 sessionid,两样一起完成",
|
|
206
|
+
hints: { zh: "调用走 CLI,额度用你浏览器里的 sessionid,两样一起完成", "zh-TW": "呼叫走 CLI,額度用你瀏覽器裡的 sessionid,兩樣一起完成" },
|
|
207
|
+
labels: { zh: "粘贴网页 Cookie", "zh-TW": "貼上網頁 Cookie", ja: "Cookie を貼り付け" },
|
|
208
|
+
},
|
|
209
|
+
{
|
|
210
|
+
label: "不绑定额度",
|
|
211
|
+
value: "none",
|
|
212
|
+
hint: "只登录调用,额度卡片不显示",
|
|
213
|
+
hints: { zh: "只登录调用,额度卡片不显示", "zh-TW": "只登入呼叫,額度卡片不顯示" },
|
|
214
|
+
labels: { zh: "不绑定额度", "zh-TW": "不綁定額度", ja: "使用量なし" },
|
|
215
|
+
},
|
|
216
|
+
],
|
|
217
|
+
},
|
|
218
|
+
]
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* 一次登录:先确认 CLI 登录,再按选择绑定额度。
|
|
222
|
+
* started.login 存在时是本次新开的扫码流程,结束时必须停掉。
|
|
223
|
+
*/
|
|
224
|
+
const startSignIn = async ({ target, started, inputs, signal }) => {
|
|
225
|
+
const quota = ["browser", "paste", "none"].includes(inputs?.quota) ? inputs.quota : "browser"
|
|
226
|
+
const given = String(inputs?.webCookie || "").trim()
|
|
227
|
+
|
|
228
|
+
// 「粘贴」时不用 prompt 里的第二个输入框(老版本 magpie 不支持 when,
|
|
229
|
+
// 会把它问在所有选项上),改用 code 流程:选完再粘,粘完点继续。
|
|
230
|
+
const needPaste = quota === "paste" && !given
|
|
231
|
+
|
|
232
|
+
let browser = null
|
|
233
|
+
if (quota === "browser") {
|
|
234
|
+
try {
|
|
235
|
+
browser = await launchLoginBrowser()
|
|
236
|
+
} catch (error) {
|
|
237
|
+
started.login?.stop?.()
|
|
238
|
+
return { type: "failed", error: `${String(error?.message || error)}。可以改选「粘贴网页 Cookie」。` }
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
const qrUrl = started.login ? pathToFileURL(started.login.qrPath).href : ""
|
|
243
|
+
const quotaLine = quota === "browser"
|
|
244
|
+
? "已打开豆包登录页:在浏览器里登录后会自动读取额度。"
|
|
245
|
+
: quota === "paste"
|
|
246
|
+
? "下一步粘贴豆包网页 Cookie(sessionid=…)。"
|
|
247
|
+
: "不绑定额度:只完成调用登录。"
|
|
248
|
+
|
|
249
|
+
return {
|
|
250
|
+
url: qrUrl,
|
|
251
|
+
instructions: [
|
|
252
|
+
started.login
|
|
253
|
+
? qrInstructions(started.login)
|
|
254
|
+
: `使用终端里已登录的账号:${started.status?.accountId || started.status?.userId || "当前账号"}`,
|
|
255
|
+
"",
|
|
256
|
+
quotaLine,
|
|
257
|
+
].join("\n"),
|
|
258
|
+
method: needPaste ? "code" : "auto",
|
|
259
|
+
...(needPaste ? { placeholder: "sessionid=…(开发者工具 → Application → Cookies)" } : {}),
|
|
260
|
+
opened: false,
|
|
261
|
+
async callback(code, { signal: cbSignal } = {}) {
|
|
262
|
+
const useSignal = cbSignal || signal
|
|
263
|
+
try {
|
|
264
|
+
let webCookie = ""
|
|
265
|
+
if (quota === "paste") {
|
|
266
|
+
webCookie = given || String(code || "").trim()
|
|
267
|
+
if (!webCookie) return { type: "failed", error: "没有收到网页 Cookie,请重新登录并粘贴 sessionid。" }
|
|
268
|
+
const checked = await readWebQuota(webCookie, { signal: useSignal }).catch((error) => ({ error: String(error?.message || error) }))
|
|
269
|
+
if (checked?.error) return { type: "failed", error: `网页 Cookie 不可用:${checked.error}` }
|
|
270
|
+
saveWebCookie(webCookie)
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
const status = started.status || await waitForAuth(target, { signal: useSignal, timeoutMs: 10 * 60_000 })
|
|
274
|
+
if (!status?.loggedIn) return { type: "failed", error: "CLI 扫码没有完成,请重新发起登录。" }
|
|
275
|
+
|
|
276
|
+
if (quota === "browser") {
|
|
277
|
+
const cookies = await waitForLoginCookies(browser, { signal: useSignal, timeoutMs: 10 * 60_000 })
|
|
278
|
+
if (!cookies?.length) return { type: "failed", error: "网页登录没有完成(没读到 sessionid)。" }
|
|
279
|
+
webCookie = cookieHeaderFromCookies(cookies)
|
|
280
|
+
const checked = await readWebQuota(webCookie, { signal: useSignal }).catch((error) => ({ error: String(error?.message || error) }))
|
|
281
|
+
if (checked?.error) return { type: "failed", error: `额度接口读取失败:${checked.error}` }
|
|
282
|
+
saveWebCookie(webCookie)
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
await afterLogin(target)
|
|
286
|
+
return successAccount(status, { webCookie })
|
|
287
|
+
} finally {
|
|
288
|
+
started.login?.stop?.()
|
|
289
|
+
await browser?.close?.().catch?.(() => {})
|
|
290
|
+
}
|
|
291
|
+
},
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
return {
|
|
296
|
+
// ═══ ① provider 声明 ═════════════════════════════════════════
|
|
297
|
+
config: async (cfg) => {
|
|
298
|
+
cfg.provider ??= {}
|
|
299
|
+
cfg.provider[PROVIDER] ??= {
|
|
300
|
+
name: PROVIDER_NAME,
|
|
301
|
+
npm: settings.npm,
|
|
302
|
+
api: API_BASE,
|
|
303
|
+
models: staticModels({ contextWindow: settings.contextWindow, outputTokens: settings.outputTokens, npm: settings.npm }),
|
|
304
|
+
}
|
|
305
|
+
if (!cfg.provider[PROVIDER].models || Object.keys(cfg.provider[PROVIDER].models).length === 0) {
|
|
306
|
+
cfg.provider[PROVIDER].models = staticModels({
|
|
307
|
+
contextWindow: settings.contextWindow,
|
|
308
|
+
outputTokens: settings.outputTokens,
|
|
309
|
+
npm: settings.npm,
|
|
310
|
+
})
|
|
311
|
+
}
|
|
312
|
+
},
|
|
313
|
+
|
|
314
|
+
auth: {
|
|
315
|
+
provider: PROVIDER,
|
|
316
|
+
icon: ICON,
|
|
317
|
+
maxConcurrency: 2,
|
|
318
|
+
single: true,
|
|
319
|
+
|
|
320
|
+
// magpie 的插件宿主要求:CLI 不存在时可以先安装
|
|
321
|
+
cli: {
|
|
322
|
+
name: "豆包 CLI",
|
|
323
|
+
installed: () => Boolean(findDoubaoBinary({ explicit: settings.binPath })),
|
|
324
|
+
install: async ({ signal } = {}) => {
|
|
325
|
+
await installDoubao({ signal })
|
|
326
|
+
refreshBinary()
|
|
327
|
+
},
|
|
328
|
+
manual: "npm install -g @bytedance/doubao-cli --allow-scripts=@bytedance/doubao-cli",
|
|
329
|
+
},
|
|
330
|
+
|
|
331
|
+
methods: [
|
|
332
|
+
{
|
|
333
|
+
// 两个维度收进一个下拉:登录方式(扫码 / 已登录)+ 额度来源(浏览器 / 粘贴 / 不绑)。
|
|
334
|
+
// 之前四个并列按钮把这两个维度混在一起,选哪个都要先想一遍。
|
|
335
|
+
type: "oauth",
|
|
336
|
+
label: "扫码登录豆包 CLI",
|
|
337
|
+
labels: {
|
|
338
|
+
zh: "扫码登录豆包 CLI",
|
|
339
|
+
"zh-TW": "掃碼登入豆包 CLI",
|
|
340
|
+
ja: "豆包 CLI を QR でログイン",
|
|
341
|
+
},
|
|
342
|
+
prompts: QUOTA_PROMPTS,
|
|
343
|
+
async authorize(inputs, { signal } = {}) {
|
|
344
|
+
const target = refreshBinary()
|
|
345
|
+
if (!target) return { type: "failed", error: describeLoginError(null, null) }
|
|
346
|
+
let started
|
|
347
|
+
try {
|
|
348
|
+
started = await beginCliLogin(target)
|
|
349
|
+
} catch (error) {
|
|
350
|
+
return { type: "failed", error: describeLoginError(error, target) }
|
|
351
|
+
}
|
|
352
|
+
return startSignIn({ target, started, inputs, signal })
|
|
353
|
+
},
|
|
354
|
+
},
|
|
355
|
+
{
|
|
356
|
+
type: "oauth",
|
|
357
|
+
label: "用终端里已登录的账号",
|
|
358
|
+
labels: {
|
|
359
|
+
zh: "用终端里已登录的账号",
|
|
360
|
+
"zh-TW": "用終端機已登入的帳號",
|
|
361
|
+
ja: "ターミナルでログイン済みのアカウント",
|
|
362
|
+
},
|
|
363
|
+
prompts: QUOTA_PROMPTS,
|
|
364
|
+
async authorize(inputs, { signal } = {}) {
|
|
365
|
+
const target = refreshBinary()
|
|
366
|
+
if (!target) return { type: "failed", error: describeLoginError(null, null) }
|
|
367
|
+
const status = await checkAuth(target).catch(() => null)
|
|
368
|
+
if (!status?.loggedIn) {
|
|
369
|
+
return { type: "failed", error: "终端里没有已登录的豆包 CLI。先在终端运行 `doubao login`,或改用「扫码登录豆包 CLI」。" }
|
|
370
|
+
}
|
|
371
|
+
return startSignIn({ target, started: { status, login: null }, inputs, signal })
|
|
372
|
+
},
|
|
373
|
+
},
|
|
374
|
+
],
|
|
375
|
+
|
|
376
|
+
// ═══ ② 请求接管 ═══════════════════════════════════════════
|
|
377
|
+
async loader(getAuth) {
|
|
378
|
+
const auth = await getAuth()
|
|
379
|
+
if (!auth) return {}
|
|
380
|
+
const target = refreshBinary()
|
|
381
|
+
if (!target) {
|
|
382
|
+
throw Object.assign(new Error(describeLoginError(null, null)), { signIn: "expired" })
|
|
383
|
+
}
|
|
384
|
+
// 把最新的 binary 换进 pool(安装后可能从 npm 路径变成 native 路径)
|
|
385
|
+
pool.binary = target
|
|
386
|
+
return {
|
|
387
|
+
baseURL: API_BASE,
|
|
388
|
+
apiKey: "doubao-cli-local",
|
|
389
|
+
headers: {},
|
|
390
|
+
fetch: createFetch({ getAuth, pool, settings, log }),
|
|
391
|
+
}
|
|
392
|
+
},
|
|
393
|
+
|
|
394
|
+
// ═══ ③ 额度 ═══════════════════════════════════════════════
|
|
395
|
+
//
|
|
396
|
+
// 额度走的是豆包网页接口(/alice/commerce/...),需要网页 sessionid
|
|
397
|
+
// Cookie;CLI 的扫码登录是设备会话,两套凭据分开。这里只读网页 Cookie,
|
|
398
|
+
// 不发模型请求。没绑定网页 Cookie 时如实说"读不到",不编百分比。
|
|
399
|
+
async usage(getAuth) {
|
|
400
|
+
const auth = await getAuth()
|
|
401
|
+
if (!auth) return { error: "未登录", windows: [] }
|
|
402
|
+
const cookie = String(auth?.metadata?.webCookie || loadWebCookie() || settings.webCookie || "").trim()
|
|
403
|
+
if (!cookie) {
|
|
404
|
+
return {
|
|
405
|
+
error: "未绑定豆包网页 Cookie。重新登录,额度选「打开浏览器授权」或「粘贴网页 Cookie」。",
|
|
406
|
+
windows: [],
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
try {
|
|
410
|
+
return await readWebQuota(cookie)
|
|
411
|
+
} catch (error) {
|
|
412
|
+
const message = String(error?.message || error)
|
|
413
|
+
if (error?.signIn === "expired" || /401|登录态已失效/.test(message)) {
|
|
414
|
+
return { error: "豆包网页登录已失效,请重新绑定网页 Cookie", windows: [], signIn: "expired" }
|
|
415
|
+
}
|
|
416
|
+
return { error: message.slice(0, 300), windows: [] }
|
|
417
|
+
}
|
|
418
|
+
},
|
|
419
|
+
},
|
|
420
|
+
|
|
421
|
+
// ═══ ③ 每个账号的模型目录 ═══════════════════════════════════
|
|
422
|
+
provider: {
|
|
423
|
+
id: PROVIDER,
|
|
424
|
+
async models(provider, { auth } = {}) {
|
|
425
|
+
const fallback = () => staticModels({ contextWindow: settings.contextWindow, outputTokens: settings.outputTokens, npm: settings.npm })
|
|
426
|
+
if (!auth) return fallback()
|
|
427
|
+
try {
|
|
428
|
+
const models = await cachedModels()
|
|
429
|
+
return modelsMap(models, { contextWindow: settings.contextWindow, outputTokens: settings.outputTokens, npm: settings.npm })
|
|
430
|
+
} catch (error) {
|
|
431
|
+
if (error instanceof LoginRequiredError || error?.code === "login_required") {
|
|
432
|
+
return fallback()
|
|
433
|
+
}
|
|
434
|
+
log(`读取豆包模型列表失败:${error?.message ?? error}`, "warning")
|
|
435
|
+
return fallback()
|
|
436
|
+
}
|
|
437
|
+
},
|
|
438
|
+
},
|
|
439
|
+
|
|
440
|
+
// ═══ ④ 每请求加会话头 ═══════════════════════════════════════
|
|
441
|
+
"chat.headers": async (input, output) => {
|
|
442
|
+
if ((input?.model?.providerID ?? input?.provider?.info?.id) !== PROVIDER) return
|
|
443
|
+
chatHeaders(input, output)
|
|
444
|
+
},
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
// 供测试引用(入口不能导出 helper 函数,否则会被当插件工厂调用)
|
|
449
|
+
export const _pure = {
|
|
450
|
+
PROVIDER,
|
|
451
|
+
NPM,
|
|
452
|
+
PROVIDER_NAME,
|
|
453
|
+
DEFAULT_MODEL_ID,
|
|
454
|
+
staticModels,
|
|
455
|
+
modelsMap,
|
|
456
|
+
normalizeSettings,
|
|
457
|
+
}
|