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/CHANGELOG.md +70 -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 +39 -0
- package/src/identity.mjs +17 -0
- package/src/pure.mjs +350 -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
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
// 豆包网页 Cookie 的本地保管。
|
|
2
|
+
//
|
|
3
|
+
// 为什么不只放在 magpie 的账号 metadata 里:metadata 是整条替换的,
|
|
4
|
+
// 重新登录一次(哪怕选「不绑定额度」)就会把上一次绑好的网页 Cookie 冲掉。
|
|
5
|
+
// 额度凭据和调用凭据是两件事,存在插件自己的文件里更稳:
|
|
6
|
+
// · 登录时写入;
|
|
7
|
+
// · 选「不绑定额度」时不动它,额度继续可用;
|
|
8
|
+
// · 账号 metadata 里有更新的值就优先用 metadata。
|
|
9
|
+
//
|
|
10
|
+
// 文件权限 0600,只放 Cookie 字符串。
|
|
11
|
+
|
|
12
|
+
import fs from "node:fs"
|
|
13
|
+
import os from "node:os"
|
|
14
|
+
import path from "node:path"
|
|
15
|
+
|
|
16
|
+
function configDir() {
|
|
17
|
+
for (const key of ["MAGPIE_CONFIG_DIR", "MAGPIE_HOME", "MAGPIE_CONFIG"]) {
|
|
18
|
+
const value = process.env[key]
|
|
19
|
+
if (value && path.isAbsolute(value)) return value
|
|
20
|
+
}
|
|
21
|
+
return path.join(os.homedir(), ".config", "magpie")
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function cookieFile() {
|
|
25
|
+
return path.join(configDir(), "doubao-cli-webcookie.json")
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export function loadWebCookie() {
|
|
29
|
+
try {
|
|
30
|
+
const raw = fs.readFileSync(cookieFile(), "utf8")
|
|
31
|
+
const data = JSON.parse(raw)
|
|
32
|
+
const cookie = typeof data?.cookie === "string" ? data.cookie.trim() : ""
|
|
33
|
+
return cookie
|
|
34
|
+
} catch {
|
|
35
|
+
return ""
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export function saveWebCookie(cookie) {
|
|
40
|
+
const value = String(cookie || "").trim()
|
|
41
|
+
const file = cookieFile()
|
|
42
|
+
if (!value) return false
|
|
43
|
+
try {
|
|
44
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })
|
|
45
|
+
const temp = `${file}.${process.pid}.tmp`
|
|
46
|
+
fs.writeFileSync(temp, JSON.stringify({ version: 1, cookie: value, savedAt: Date.now() }), { mode: 0o600 })
|
|
47
|
+
fs.renameSync(temp, file)
|
|
48
|
+
try { fs.chmodSync(file, 0o600) } catch {}
|
|
49
|
+
return true
|
|
50
|
+
} catch {
|
|
51
|
+
return false
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function clearWebCookie() {
|
|
56
|
+
try {
|
|
57
|
+
fs.unlinkSync(cookieFile())
|
|
58
|
+
return true
|
|
59
|
+
} catch {
|
|
60
|
+
return false
|
|
61
|
+
}
|
|
62
|
+
}
|
package/src/webquota.mjs
ADDED
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
// 豆包网页会话 → magpie 额度。
|
|
2
|
+
//
|
|
3
|
+
// 这部分和 ACP 调用链是分开的:CLI 的 QR 登录是设备会话,额度接口
|
|
4
|
+
// `/alice/commerce/sale/subscription/quota/summary/` 则需要豆包网页的
|
|
5
|
+
// sessionid Cookie。这里只做额度读取,不发模型请求。
|
|
6
|
+
//
|
|
7
|
+
// 端点与字段来自 magpie-doubao-work-auth 的 lib/session.mjs / lib/quota.mjs
|
|
8
|
+
// (2026-11 实测),原实现使用桌面客户端 Cookie;本插件把同一套请求逻辑
|
|
9
|
+
// 接在用户浏览器登录或粘贴的 Cookie 上。
|
|
10
|
+
|
|
11
|
+
import { normalizeQuota } from "./web-quota-normalize.mjs"
|
|
12
|
+
import { ProviderError, upstreamError } from "./web-errors.mjs"
|
|
13
|
+
|
|
14
|
+
export const BASE = "https://www.doubao.com"
|
|
15
|
+
export const DESKTOP_PARAMS = {
|
|
16
|
+
aid: "497858",
|
|
17
|
+
real_aid: "497858",
|
|
18
|
+
device_platform: "web",
|
|
19
|
+
doubao_device_platform: "web",
|
|
20
|
+
version_code: "20800",
|
|
21
|
+
language: "zh",
|
|
22
|
+
samantha_web: "1",
|
|
23
|
+
"use-olympus-account": "1",
|
|
24
|
+
pkg_type: "release_version",
|
|
25
|
+
web_platform: "browser",
|
|
26
|
+
}
|
|
27
|
+
const UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/147.0.0.0 Safari/537.36"
|
|
28
|
+
export const FALLBACK_BOT = "7338286299411103781"
|
|
29
|
+
|
|
30
|
+
class Jar {
|
|
31
|
+
constructor(cookies = []) { this.cookies = new Map() }
|
|
32
|
+
static from(cookies) {
|
|
33
|
+
const jar = new Jar()
|
|
34
|
+
for (const cookie of cookies) {
|
|
35
|
+
const key = `${cookie.domain}|${cookie.path || "/"}|${cookie.name}`
|
|
36
|
+
jar.cookies.set(key, { ...cookie })
|
|
37
|
+
}
|
|
38
|
+
return jar
|
|
39
|
+
}
|
|
40
|
+
headerFor(url) {
|
|
41
|
+
const host = new URL(url).hostname
|
|
42
|
+
const now = Math.floor(Date.now() / 1000)
|
|
43
|
+
const parts = []
|
|
44
|
+
for (const cookie of this.cookies.values()) {
|
|
45
|
+
const domain = String(cookie.domain || "").replace(/^\./, "")
|
|
46
|
+
if (host !== domain && !host.endsWith(`.${domain}`)) continue
|
|
47
|
+
if (cookie.expires && cookie.expires < now) continue
|
|
48
|
+
parts.push(`${cookie.name}=${cookie.value}`)
|
|
49
|
+
}
|
|
50
|
+
return parts.join("; ")
|
|
51
|
+
}
|
|
52
|
+
absorb(url, setCookies) {
|
|
53
|
+
const host = new URL(url).hostname
|
|
54
|
+
for (const raw of setCookies) {
|
|
55
|
+
const [pair, ...attrs] = String(raw).split(";")
|
|
56
|
+
const index = pair.indexOf("=")
|
|
57
|
+
if (index < 0) continue
|
|
58
|
+
const name = pair.slice(0, index).trim()
|
|
59
|
+
const value = pair.slice(index + 1).trim()
|
|
60
|
+
if (!name) continue
|
|
61
|
+
const cookie = { name, value, domain: host, path: "/", expires: 0, secure: true }
|
|
62
|
+
for (const attr of attrs) {
|
|
63
|
+
const [k, v = ""] = attr.split("=")
|
|
64
|
+
const key = k.trim().toLowerCase()
|
|
65
|
+
if (key === "domain") cookie.domain = v.trim().replace(/^\./, "")
|
|
66
|
+
else if (key === "path") cookie.path = v.trim() || "/"
|
|
67
|
+
else if (key === "max-age") cookie.expires = Math.floor(Date.now() / 1000) + Number(v)
|
|
68
|
+
else if (key === "expires") {
|
|
69
|
+
const t = Date.parse(v)
|
|
70
|
+
if (!Number.isNaN(t)) cookie.expires = Math.floor(t / 1000)
|
|
71
|
+
} else if (key === "secure") cookie.secure = true
|
|
72
|
+
}
|
|
73
|
+
this.cookies.set(`${cookie.domain}|${cookie.path}|${cookie.name}`, cookie)
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** "a=1; b=2" / "Cookie: a=1" → 内部 cookie 数组 */
|
|
79
|
+
export function cookiesFromHeader(text, domain = ".doubao.com") {
|
|
80
|
+
const body = String(text || "").replace(/^\s*cookie\s*:\s*/i, "")
|
|
81
|
+
const out = []
|
|
82
|
+
for (const part of body.split(";")) {
|
|
83
|
+
const index = part.indexOf("=")
|
|
84
|
+
if (index <= 0) continue
|
|
85
|
+
const name = part.slice(0, index).trim()
|
|
86
|
+
const value = part.slice(index + 1).trim()
|
|
87
|
+
if (!name) continue
|
|
88
|
+
out.push({ name, value, domain, path: "/", expires: 0, secure: true })
|
|
89
|
+
}
|
|
90
|
+
return out
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** Playwright/Tabbit 的 Cookie 数组 → Header 字符串 */
|
|
94
|
+
export function cookieHeaderFromCookies(cookies) {
|
|
95
|
+
return (Array.isArray(cookies) ? cookies : [])
|
|
96
|
+
.filter((c) => c && typeof c.name === "string" && typeof c.value === "string")
|
|
97
|
+
.map((c) => `${c.name}=${c.value}`)
|
|
98
|
+
.join("; ")
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function hasLoginCookie(cookies) {
|
|
102
|
+
return (Array.isArray(cookies) ? cookies : []).some((c) =>
|
|
103
|
+
(c?.name === "sessionid" || c?.name === "sessionid_ss" || c?.name === "sessionid_ss") && c?.value)
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export class WebQuotaSession {
|
|
107
|
+
constructor(cookies, { fetcher = fetch } = {}) {
|
|
108
|
+
this.jar = Jar.from(cookies)
|
|
109
|
+
this.fetcher = fetcher
|
|
110
|
+
this.clientInfo = {}
|
|
111
|
+
this.clientVersion = ""
|
|
112
|
+
this.profile = "web"
|
|
113
|
+
this.readyAt = 0
|
|
114
|
+
this.pending = undefined
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
async ready(signal) {
|
|
118
|
+
signal?.throwIfAborted?.()
|
|
119
|
+
if (Date.now() - this.readyAt < 60_000) return
|
|
120
|
+
this.pending ??= this.initialize().finally(() => { this.pending = undefined })
|
|
121
|
+
await this.pending
|
|
122
|
+
signal?.throwIfAborted?.()
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async initialize() {
|
|
126
|
+
const identity = await this.json("/passport/account/info/v2/", undefined, undefined, {
|
|
127
|
+
account_sdk_source: "web",
|
|
128
|
+
sdk_version: "2.2.5",
|
|
129
|
+
})
|
|
130
|
+
const uid = String(identity.user_id_str ?? identity.user_id ?? "")
|
|
131
|
+
if (!uid || uid === "0" || identity.is_visitor_account) {
|
|
132
|
+
throw new ProviderError("豆包网页登录态已失效,请重新绑定网页 Cookie。", 401, "session_expired", { signIn: "expired" })
|
|
133
|
+
}
|
|
134
|
+
const launch = await this.json("/alice/user/launch", {})
|
|
135
|
+
const bot = String(launch.assistant_bot_id ?? "")
|
|
136
|
+
this.bot = /^[1-9]\d*$/.test(bot) ? bot : FALLBACK_BOT
|
|
137
|
+
this.uid = uid
|
|
138
|
+
this.launch = launch
|
|
139
|
+
this.country = launch.country || ""
|
|
140
|
+
this.name = identity.screen_name || identity.name || this.profile
|
|
141
|
+
|
|
142
|
+
const launchWebId = String(launch.config?.web_id ?? launch.web_id ?? "")
|
|
143
|
+
const launchTtwid = String(launch.config?.ttwid ?? launch.ttwid ?? "")
|
|
144
|
+
if (/^[1-9]\d*$/.test(launchWebId)) {
|
|
145
|
+
this.clientInfo.webId = launchWebId
|
|
146
|
+
this.clientInfo.deviceId = launchWebId
|
|
147
|
+
this.clientInfo.teaUuid = launchWebId
|
|
148
|
+
}
|
|
149
|
+
if (launchTtwid) this.clientInfo.ttwid = launchTtwid
|
|
150
|
+
this.readyAt = Date.now()
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
buildUrl(path, params = {}) {
|
|
154
|
+
const url = new URL(path, BASE)
|
|
155
|
+
if (url.origin !== BASE) throw new Error("请求主机不匹配。")
|
|
156
|
+
const client = this.clientInfo
|
|
157
|
+
url.search = new URLSearchParams({
|
|
158
|
+
...DESKTOP_PARAMS,
|
|
159
|
+
...(this.clientVersion ? { pc_version: this.clientVersion, doubao_pc_version: this.clientVersion } : {}),
|
|
160
|
+
...(client ? {
|
|
161
|
+
web_id: client.webId,
|
|
162
|
+
device_id: client.deviceId,
|
|
163
|
+
tea_uuid: client.teaUuid,
|
|
164
|
+
...(client.fingerprint ? { fp: client.fingerprint } : {}),
|
|
165
|
+
...(client.ttwid ? { ttwid: client.ttwid } : {}),
|
|
166
|
+
tz_name: Intl.DateTimeFormat().resolvedOptions().timeZone,
|
|
167
|
+
} : {}),
|
|
168
|
+
...(this.country ? { region: this.country, sys_region: this.country } : {}),
|
|
169
|
+
...params,
|
|
170
|
+
}).toString()
|
|
171
|
+
return url
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
async request(path, body, signal, params = {}, extraHeaders = {}) {
|
|
175
|
+
const url = this.buildUrl(path, params)
|
|
176
|
+
const connectTimeoutMs = 60_000
|
|
177
|
+
const connectAbort = new AbortController()
|
|
178
|
+
const connectTimer = setTimeout(
|
|
179
|
+
() => connectAbort.abort(new Error(`连接豆包超时(${Math.round(connectTimeoutMs / 1000)} 秒没有响应)`)),
|
|
180
|
+
connectTimeoutMs,
|
|
181
|
+
)
|
|
182
|
+
const requestSignal = signal ? AbortSignal.any([signal, connectAbort.signal]) : connectAbort.signal
|
|
183
|
+
let response
|
|
184
|
+
try {
|
|
185
|
+
response = await this.fetcher(url, {
|
|
186
|
+
method: body === undefined ? "GET" : "POST",
|
|
187
|
+
redirect: "error",
|
|
188
|
+
signal: requestSignal,
|
|
189
|
+
headers: Object.assign({
|
|
190
|
+
"Content-Type": "application/json",
|
|
191
|
+
"Agw-Js-Conv": "str",
|
|
192
|
+
Origin: BASE,
|
|
193
|
+
Referer: `${BASE}/`,
|
|
194
|
+
"User-Agent": UA,
|
|
195
|
+
}, extraHeaders, { ["Cookie"]: this.jar.headerFor(url.href) }),
|
|
196
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
197
|
+
})
|
|
198
|
+
} finally {
|
|
199
|
+
clearTimeout(connectTimer)
|
|
200
|
+
}
|
|
201
|
+
const setCookies = response.headers.getSetCookie?.() ?? []
|
|
202
|
+
if (setCookies.length) this.jar.absorb(url.href, setCookies)
|
|
203
|
+
if (!response.ok) {
|
|
204
|
+
const type = response.headers.get("content-type") || ""
|
|
205
|
+
const payload = type.includes("json")
|
|
206
|
+
? await response.json().catch(() => ({}))
|
|
207
|
+
: { message: (await response.text()).slice(0, 300) }
|
|
208
|
+
// 业务错误码可能在 data 里(和 200 时的 json() 一样),先摊平再映射,
|
|
209
|
+
// 否则 401 会被当成普通 upstream_error,账号不会被标成过期
|
|
210
|
+
const flat = payload?.data?.error_code !== undefined
|
|
211
|
+
? { ...payload.data, message: payload.data.message ?? payload.message }
|
|
212
|
+
: payload
|
|
213
|
+
const error = upstreamError(flat, response.status)
|
|
214
|
+
if (!error.signIn && (response.status === 401 || response.status === 403)) {
|
|
215
|
+
error.signIn = "expired"
|
|
216
|
+
}
|
|
217
|
+
throw error
|
|
218
|
+
}
|
|
219
|
+
return response
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
async json(path, body, signal, params, extraHeaders) {
|
|
223
|
+
const response = await this.request(path, body, signal, params, extraHeaders)
|
|
224
|
+
const text = await response.text()
|
|
225
|
+
let result
|
|
226
|
+
try { result = JSON.parse(text) } catch {
|
|
227
|
+
throw new ProviderError(`豆包返回的不是 JSON:${text.slice(0, 200)}`, 502, "invalid_response")
|
|
228
|
+
}
|
|
229
|
+
if ((result.code !== undefined && result.code !== 0) || result.message === "error") {
|
|
230
|
+
const payload = result.data?.error_code !== undefined ? result.data : result
|
|
231
|
+
// 豆包把「会话过期」放在 data.description 里(error_code 13),
|
|
232
|
+
// 用 upstreamError 只会得到"未知错误",这里显式认出来。
|
|
233
|
+
const code = Number(payload?.error_code ?? payload?.error?.code ?? payload?.code)
|
|
234
|
+
const said = String(payload?.description ?? payload?.error?.message ?? payload?.message ?? payload?.msg ?? "")
|
|
235
|
+
if (code === 13 || /会话过期|请重新登录|login invalid|session expired/i.test(said)) {
|
|
236
|
+
throw new ProviderError(`豆包网页登录已失效:${said || "请重新登录"}`, 401, "session_expired", { signIn: "expired" })
|
|
237
|
+
}
|
|
238
|
+
throw upstreamError({ ...payload, message: said || payload?.message })
|
|
239
|
+
}
|
|
240
|
+
if (!result.data) throw new ProviderError("豆包响应缺少 data 字段。", 502, "invalid_response")
|
|
241
|
+
return result.data
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
|
|
246
|
+
|
|
247
|
+
/** 读取套餐额度;返回 magpie 的 auth.usage 结构 */
|
|
248
|
+
export async function readWebQuota(cookieHeaderOrCookies, { signal, fetcher = fetch } = {}) {
|
|
249
|
+
const cookies = Array.isArray(cookieHeaderOrCookies)
|
|
250
|
+
? cookieHeaderOrCookies
|
|
251
|
+
: cookiesFromHeader(cookieHeaderOrCookies)
|
|
252
|
+
if (!hasLoginCookie(cookies) && !cookies.some((c) => c?.name === "sessionid_ss")) {
|
|
253
|
+
return { error: "网页 Cookie 里没有 sessionid,请重新登录豆包网页后复制完整 Cookie。", windows: [] }
|
|
254
|
+
}
|
|
255
|
+
const session = new WebQuotaSession(cookies, { fetcher })
|
|
256
|
+
try {
|
|
257
|
+
await session.ready(signal)
|
|
258
|
+
} catch (error) {
|
|
259
|
+
return { error: String(error?.message || error).slice(0, 300), windows: [], ...(error?.signIn ? { signIn: error.signIn } : {}) }
|
|
260
|
+
}
|
|
261
|
+
const settle = async (path, body) => {
|
|
262
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
263
|
+
if (signal?.aborted) throw new DOMException("cancelled", "AbortError")
|
|
264
|
+
try {
|
|
265
|
+
return await session.json(path, body, signal)
|
|
266
|
+
} catch (error) {
|
|
267
|
+
if (error?.signIn) throw error
|
|
268
|
+
if (attempt === 1) return undefined
|
|
269
|
+
await sleep(400)
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
return undefined
|
|
273
|
+
}
|
|
274
|
+
try {
|
|
275
|
+
const summary = await settle("/alice/commerce/sale/subscription/quota/summary/", { product_line: "membership" })
|
|
276
|
+
if (!summary) return { error: "额度汇总暂时取不到,稍后会自动重试", windows: [] }
|
|
277
|
+
const overview = await settle("/alice/commerce/sale/subscription/overview/", { product_line: "membership" })
|
|
278
|
+
const cards = await settle("/alice/commerce/marketing/card/list/", { status_in: [1, 2, 3, 4], with_limit_status: true })
|
|
279
|
+
return normalizeQuota(overview ?? {}, summary, session.name, undefined, cards)
|
|
280
|
+
} catch (error) {
|
|
281
|
+
if (error?.name === "AbortError") return { error: "额度读取已取消", windows: [] }
|
|
282
|
+
return { error: String(error?.message || error).slice(0, 300), windows: [], ...(error?.signIn ? { signIn: error.signIn } : {}) }
|
|
283
|
+
}
|
|
284
|
+
}
|