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/pure.mjs ADDED
@@ -0,0 +1,350 @@
1
+ // 纯函数:消息解析、提示词拼装、模型目录、权限判断、SSE 形状。
2
+ //
3
+ // 这里不碰网络、不碰子进程,方便单元测试。
4
+
5
+ import path from "node:path"
6
+ import {
7
+ DEFAULT_CONTEXT_WINDOW,
8
+ DEFAULT_MODEL_ID,
9
+ DEFAULT_OUTPUT_TOKENS,
10
+ NPM,
11
+ PROVIDER,
12
+ } from "./constants.mjs"
13
+
14
+ /** 把任意模型 id 变成 magpie 侧的 slug:保留字母数字和 . _ - : /,其余换成 - */
15
+ export function slugOfModelId(raw) {
16
+ const s = String(raw ?? "").trim()
17
+ if (!s) return ""
18
+ return s
19
+ .replace(/^[a-z0-9_-]+\//i, "") // 去掉 provider 前缀
20
+ .replace(/\[1m\]$/i, "")
21
+ .replace(/\s+/g, "-")
22
+ .replace(/[^A-Za-z0-9._:/+-]/g, "-")
23
+ .replace(/-+/g, "-")
24
+ .replace(/^-|-$/g, "")
25
+ }
26
+
27
+ /** 一个 magpie 模型条目 */
28
+ export function modelEntry(id, name, { contextWindow = DEFAULT_CONTEXT_WINDOW, outputTokens = DEFAULT_OUTPUT_TOKENS, npm = NPM } = {}) {
29
+ return {
30
+ id,
31
+ name: name || id,
32
+ api: { id, url: "doubao-cli://local", npm },
33
+ status: "active",
34
+ cost: { input: 0, output: 0, cache: { read: 0, write: 0 } },
35
+ limit: { context: contextWindow, output: outputTokens },
36
+ // ACP 的 agent 在 CLI 内部执行自己的工具;外层 agent 不需要、也不应该
37
+ // 把 OpenAI tools 再塞进来。所以这里声明 no-tools,避免误路由。
38
+ modalities: { input: ["text"], output: ["text"] },
39
+ capabilities: {
40
+ temperature: false,
41
+ reasoning: false,
42
+ toolcall: false,
43
+ attachment: false,
44
+ input: { text: true, image: false, audio: false, video: false, pdf: false },
45
+ output: { text: true },
46
+ },
47
+ }
48
+ }
49
+
50
+ /** 未登录时的兜底模型表:必须非空 */
51
+ export function staticModels(options = {}) {
52
+ return {
53
+ [DEFAULT_MODEL_ID]: modelEntry(DEFAULT_MODEL_ID, "豆包 CLI(当前账号默认)", options),
54
+ }
55
+ }
56
+
57
+ /**
58
+ * 把 `doubao model list --json` 的输出折成统一目录。
59
+ *
60
+ * 2.39.2 的 JSON 形状(entry-cli-router/main.js):
61
+ * { ok: true, result: { type: "model_list", models: [
62
+ * { id, name, is_default, efforts: ["low", ...], default_effort: "medium" }
63
+ * ] } }
64
+ *
65
+ * 也接受 { models: [...] } / 数组 / 旧版的 { result: { models } }。
66
+ */
67
+ export function parseModelList(payload) {
68
+ let root = payload
69
+ if (typeof root === "string") {
70
+ try {
71
+ root = JSON.parse(root)
72
+ } catch {
73
+ return []
74
+ }
75
+ }
76
+ if (Array.isArray(root)) root = { models: root }
77
+ let models = root?.result?.models ?? root?.models ?? root?.data?.models
78
+ if (!Array.isArray(models)) return []
79
+
80
+ const out = []
81
+ const seen = new Set()
82
+ for (const item of models) {
83
+ if (!item) continue
84
+ const rawId = item.id ?? item.modelId ?? item.value ?? item.model_id
85
+ if (typeof rawId !== "string" || !rawId.trim()) continue
86
+ const id = slugOfModelId(rawId)
87
+ if (!id || seen.has(id)) continue
88
+ seen.add(id)
89
+ const name = String(item.name ?? item.displayName ?? item.display_name ?? id).trim() || id
90
+ out.push({
91
+ id,
92
+ rawId,
93
+ name,
94
+ isDefault: item.is_default === true || item.isDefault === true || item.default === true,
95
+ efforts: Array.isArray(item.efforts)
96
+ ? item.efforts.map((e) => String(e?.level ?? e)).filter(Boolean)
97
+ : Array.isArray(item.effort_levels)
98
+ ? item.effort_levels.map(String)
99
+ : [],
100
+ defaultEffort: String(item.default_effort ?? item.defaultEffort ?? "").trim(),
101
+ })
102
+ }
103
+ return out
104
+ }
105
+
106
+ /** 把模型列表转成 magpie provider.models 需要的对象 */
107
+ export function modelsMap(models, options = {}) {
108
+ const out = {}
109
+ for (const m of models) {
110
+ out[m.id] = modelEntry(m.id, m.name, options)
111
+ }
112
+ if (Object.keys(out).length === 0) return staticModels(options)
113
+ return out
114
+ }
115
+
116
+ /**
117
+ * 解析 `doubao auth status --verify` 的结果。
118
+ * 2.39.2 未登录时 exit=4,stderr 是 `login_required: …`;
119
+ * 已登录时 stdout 是人读文本,账号信息在 account 文件里。
120
+ */
121
+ export function parseAuthStatus({ code = 0, stdout = "", stderr = "" } = {}) {
122
+ const text = `${stdout}\n${stderr}`.trim()
123
+ const lower = text.toLowerCase()
124
+ const notLoggedIn = code !== 0 ||
125
+ /login_required|not logged in|未登录|请运行\s*`?doubao login`?/i.test(text)
126
+ if (notLoggedIn) {
127
+ return { loggedIn: false, raw: text }
128
+ }
129
+ let accountId = ""
130
+ const patterns = [
131
+ /(?:已登录|logged in)\s*[::]?\s*([^\s,,;;]+)/i,
132
+ /(?:account|user|账号|用户)\s*[::]\s*([^\s,,;;]+)/i,
133
+ /(?:email|邮箱)\s*[::]\s*([^\s,,;;]+)/i,
134
+ ]
135
+ for (const re of patterns) {
136
+ const m = text.match(re)
137
+ if (m) {
138
+ accountId = m[1]
139
+ break
140
+ }
141
+ }
142
+ return { loggedIn: true, accountId, raw: text }
143
+ }
144
+
145
+ /** 从 OpenAI content 里取纯文本;图片等非文本部件用占位符表示 */
146
+ export function contentText(content) {
147
+ if (typeof content === "string") return content
148
+ if (!Array.isArray(content)) return ""
149
+ const parts = []
150
+ for (const part of content) {
151
+ if (!part || typeof part !== "object") continue
152
+ if (typeof part.text === "string") {
153
+ parts.push(part.text)
154
+ } else if (typeof part.content === "string") {
155
+ parts.push(part.content)
156
+ } else if (part.type === "image_url" || part.type === "input_image") {
157
+ parts.push("[图片:ACP 插件当前只转发文本,图片未发送]")
158
+ } else if (part.type === "input_file" || part.type === "file") {
159
+ parts.push("[文件:ACP 插件当前只转发文本,附件未发送]")
160
+ }
161
+ }
162
+ return parts.join("\n")
163
+ }
164
+
165
+ /** 把 OpenAI / Responses 形态的消息统一成 [{role, text}] */
166
+ export function normalizeMessages(body) {
167
+ const out = []
168
+ if (Array.isArray(body?.messages)) {
169
+ for (const m of body.messages) {
170
+ if (!m || typeof m !== "object") continue
171
+ const role = String(m.role ?? "").toLowerCase()
172
+ if (!role) continue
173
+ out.push({ role, text: contentText(m.content) })
174
+ }
175
+ return out
176
+ }
177
+ // Responses API: { instructions, input: [...] | "..." }
178
+ if (typeof body?.instructions === "string" && body.instructions.trim()) {
179
+ out.push({ role: "system", text: body.instructions })
180
+ }
181
+ if (typeof body?.input === "string") {
182
+ out.push({ role: "user", text: body.input })
183
+ } else if (Array.isArray(body?.input)) {
184
+ for (const item of body.input) {
185
+ if (!item || typeof item !== "object") continue
186
+ // Responses 的 input item:{role, content:[{type:"input_text",text}]}
187
+ const role = String(item.role ?? "user").toLowerCase()
188
+ out.push({ role, text: contentText(item.content ?? item.text ?? "") })
189
+ }
190
+ }
191
+ return out
192
+ }
193
+
194
+ /** 最后一条 user 消息;没有就返回最后一条有文本的消息 */
195
+ export function lastUserText(messages) {
196
+ for (let i = messages.length - 1; i >= 0; i--) {
197
+ if (messages[i]?.role === "user" && messages[i].text?.trim()) return messages[i].text
198
+ }
199
+ for (let i = messages.length - 1; i >= 0; i--) {
200
+ if (messages[i]?.text?.trim()) return messages[i].text
201
+ }
202
+ return ""
203
+ }
204
+
205
+ const ROLE_LABEL = {
206
+ system: "系统说明",
207
+ developer: "开发者说明",
208
+ user: "用户",
209
+ assistant: "助手",
210
+ tool: "工具结果",
211
+ }
212
+
213
+ function truncate(text, maxChars) {
214
+ const s = String(text ?? "")
215
+ if (!maxChars || s.length <= maxChars) return s
216
+ const head = Math.max(0, maxChars - 200)
217
+ return `${s.slice(0, head)}\n\n[...已截断,共 ${s.length} 字符...]`
218
+ }
219
+
220
+ /**
221
+ * 拼成发给 ACP `session/prompt` 的文本。
222
+ *
223
+ * - fullContext=true:把此前的消息作为「对话背景」带上,最后一条 user 单独作为
224
+ * 当前请求。用于新 ACP session(进程重启、magpie 重启后的第一条)。
225
+ * - fullContext=false:只发最后一条 user(ACP session 自己有上下文)。
226
+ */
227
+ export function buildPrompt(messages, { fullContext = false, maxChars = 240_000 } = {}) {
228
+ const last = lastUserText(messages)
229
+ if (!fullContext) return truncate(last, maxChars)
230
+
231
+ const lastUserIndex = (() => {
232
+ for (let i = messages.length - 1; i >= 0; i--) {
233
+ if (messages[i]?.role === "user" && messages[i].text?.trim()) return i
234
+ }
235
+ return -1
236
+ })()
237
+
238
+ const history = []
239
+ const system = []
240
+ for (let i = 0; i < messages.length; i++) {
241
+ const m = messages[i]
242
+ if (!m?.text?.trim()) continue
243
+ if (i === lastUserIndex) continue
244
+ if (m.role === "system" || m.role === "developer") {
245
+ system.push(m.text.trim())
246
+ } else {
247
+ history.push(`${ROLE_LABEL[m.role] ?? m.role}:\n${m.text.trim()}`)
248
+ }
249
+ }
250
+
251
+ const blocks = []
252
+ if (system.length) {
253
+ blocks.push(`【上层客户端的系统说明(供理解任务背景)】\n${system.join("\n\n")}`)
254
+ }
255
+ if (history.length) {
256
+ blocks.push(`【此前对话】\n${history.join("\n\n")}`)
257
+ }
258
+ blocks.push(`【当前请求】\n${last}`)
259
+ return truncate(blocks.join("\n\n"), maxChars)
260
+ }
261
+
262
+ /** 粗略 token 估算:英文按 4 字符/ token,中文按 1 字符/ token,取保守值 */
263
+ export function estimateTokensFromText(text) {
264
+ const s = String(text ?? "")
265
+ if (!s) return 0
266
+ let ascii = 0
267
+ let nonAscii = 0
268
+ for (const ch of s) {
269
+ if (ch.codePointAt(0) < 128) ascii++
270
+ else nonAscii++
271
+ }
272
+ return Math.ceil(ascii / 4 + nonAscii)
273
+ }
274
+
275
+ /** 估算一个 Chat Completions 请求的 prompt tokens */
276
+ export function estimateInputTokens(body) {
277
+ const messages = normalizeMessages(body)
278
+ const text = messages.map((m) => `${m.role}: ${m.text}`).join("\n")
279
+ return Math.max(1, estimateTokensFromText(text))
280
+ }
281
+
282
+ /** 判断 child 是否在 parent 内部(含相等) */
283
+ export function isPathInside(parent, child) {
284
+ if (!parent || !child) return false
285
+ const rel = path.relative(path.resolve(parent), path.resolve(child))
286
+ return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel))
287
+ }
288
+
289
+ /**
290
+ * ACP `session/request_permission` 的客户端决策。
291
+ *
292
+ * 豆包 CLI 把工具按 kind 分类:read / search / fetch / think / edit / delete /
293
+ * move / execute / other。插件没有 GUI 权限弹窗,所以按下面的策略自动决定:
294
+ *
295
+ * autoApprove = "none" → 只允许纯读取(read/search/fetch/think)
296
+ * autoApprove = "read" → 同上
297
+ * autoApprove = "workspace" → 读取全放;edit/move 仅限 cwd 内;execute 放行;
298
+ * delete 默认拒绝(可开 allowDelete)
299
+ * autoApprove = "all" → 全部 allow_once
300
+ *
301
+ * 返回选中的 optionId,或 null(调用方回 cancelled)。
302
+ */
303
+ export function permissionChoice(params, {
304
+ cwd = "",
305
+ autoApprove = "workspace",
306
+ allowDelete = false,
307
+ } = {}) {
308
+ const tool = params?.toolCall ?? {}
309
+ const kind = String(tool.kind ?? "other").toLowerCase()
310
+ const options = Array.isArray(params?.options) ? params.options : []
311
+ const allow = options.find((o) => o?.kind === "allow_once") ||
312
+ options.find((o) => o?.kind === "allow_same_type") ||
313
+ options.find((o) => o?.kind === "allow_always")
314
+ const reject = options.find((o) => o?.kind === "reject_once") ||
315
+ options.find((o) => o?.kind === "reject_always") ||
316
+ options.find((o) => o?.kind === "reject")
317
+
318
+ const locations = Array.isArray(tool.locations)
319
+ ? tool.locations.map((l) => (typeof l === "string" ? l : l?.path)).filter(Boolean)
320
+ : []
321
+ const inside = locations.length === 0 || locations.every((p) => isPathInside(cwd, p))
322
+
323
+ let ok = false
324
+ if (autoApprove === "all") ok = true
325
+ else if (kind === "read" || kind === "search" || kind === "fetch" || kind === "think") ok = true
326
+ else if (autoApprove === "workspace") {
327
+ if (kind === "edit" || kind === "move" || kind === "overwrite") ok = inside
328
+ else if (kind === "execute") ok = true
329
+ else if (kind === "delete") ok = allowDelete && inside
330
+ else ok = inside
331
+ }
332
+ if (!ok) return reject?.optionId ?? null
333
+ return allow?.optionId ?? null
334
+ }
335
+
336
+ /** 给 SSE 用:JSON 一行 + 两个换行 */
337
+ export function sseData(obj) {
338
+ return `data: ${JSON.stringify(obj)}\n\n`
339
+ }
340
+
341
+ /** 生成一个 Chat Completions chunk */
342
+ export function chatChunk({ id, created, model, delta = {}, finishReason = null }) {
343
+ return {
344
+ id,
345
+ object: "chat.completion.chunk",
346
+ created,
347
+ model,
348
+ choices: [{ index: 0, delta, finish_reason: finishReason }],
349
+ }
350
+ }
@@ -0,0 +1,140 @@
1
+ /**
2
+ * 统一的上游错误。
3
+ *
4
+ * 网关按状态码决定故障切换:401 会把账号标记为需要重新登录,429 会换账号,
5
+ * 403/404 当作「模型被拒」。所以这里必须把豆包的错误码映射准确,
6
+ * 否则一个偶发的限流会把整批账号打成失效。
7
+ */
8
+ export class ProviderError extends Error {
9
+ constructor(message, status = 502, code = 'upstream_error', extra = {}) {
10
+ super(message);
11
+ this.name = 'ProviderError';
12
+ this.status = status;
13
+ this.code = code;
14
+ Object.assign(this, extra);
15
+ }
16
+ }
17
+
18
+ /** 豆包网关错误码 → 我们的状态码 */
19
+ const CODE_MAP = {
20
+ 710012000: [401, 'sign_in_required'], // user invalid
21
+ 710012001: [401, 'sign_in_expired'], // login invalid / 登录已过期
22
+ 710010202: [400, 'invalid_param'], // common invalid param
23
+ 710020202: [400, 'invalid_param'], // 同一类的业务参数拒绝(常见于会话 id 复用)
24
+ 710022004: [403, 'captcha_required'], // 风控验证码
25
+ 710012004: [429, 'rate_limited'],
26
+ // 签到那条路被服务端拒的码。实测拿它试签到一定失败,且失败写入会消耗
27
+ // 当天额度且不可回滚。登记下来是为了报错说得清,不是为了让插件去重试。
28
+ 710010702: [403, 'checkin_rejected'],
29
+ };
30
+
31
+ /**
32
+ * 上游的错误消息对人没什么用(比如风控拦下来也回 "rate limited"),
33
+ * 加上一句能照着做的提示,不然用户只能看到 rate limited 以为是限流。
34
+ */
35
+ const CODE_HINT = {
36
+ captcha_required: '豆包要求人工验证:打开 https://www.doubao.com/chat/ 手动发一句话,过掉验证后再试。',
37
+ invalid_param: '豆包拒绝了请求参数(常见原因是单笔请求过大,插件已自动压缩)。若仍出现,把诊断目录 %LOCALAPPDATA%\\magpie-doubao-work-auth\\diagnostics\\ 下最新的 json 和 magpie 请求记录一起发到插件仓库。',
38
+ rate_limited: '豆包侧限流,稍等一会儿再试。',
39
+ checkin_rejected: '签到只能在豆包电脑版完成,网页接口会被服务端拒绝。插件只显示状态,不代签 —— 代签失败会消耗当天额度且无法回滚。',
40
+ };
41
+
42
+ /**
43
+ * 从上游 payload 里读出 `decision`(JSON 字符串或对象)。
44
+ * 风控拦截时豆包会带这个字段,里面的 `subtype` 说明为什么拦。
45
+ */
46
+ function readDecision(payload) {
47
+ const raw = payload?.extra?.decision ?? payload?.decision;
48
+ if (typeof raw === 'string') {
49
+ try { return JSON.parse(raw); } catch { return undefined; }
50
+ }
51
+ if (raw && typeof raw === 'object') return raw;
52
+ return undefined;
53
+ }
54
+
55
+ /**
56
+ * 这次失败是不是「要人工过验证」的风控拦截。
57
+ *
58
+ * 豆包有两条风控出口,状态码不同但性质一样:
59
+ *
60
+ * 710022004 → 403 一直是按验证码处理的
61
+ * 710012004 → 429 之前当普通限流,结果 magpie 按可重试处理,一开就是 8 连发,
62
+ * 每打一次都把解除时间往后推(Issue #22)
63
+ *
64
+ * 后者 message 也是 "rate limited",光看状态码分不出来,得看 decision:
65
+ * 带了 decision 就是服务端明确要人工处理,不是真限流。
66
+ */
67
+ function isChallenge(code, payload) {
68
+ if (code === 710022004) return true;
69
+ if (code !== 710012004) return false;
70
+ // 710012004 平时就是普通限流,只有带 decision 时才是风控。
71
+ return readDecision(payload) !== undefined;
72
+ }
73
+
74
+ /**
75
+ * 从风控决定里读出具体原因,给一句对症的话。
76
+ *
77
+ * 上游 `710022004` 都带一个 `decision`(JSON 字符串),里面的 `subtype` 说明为什么拦:
78
+ * 有的是要人工过验证码(`semantic_reasoning`),有的是请求本身不可信。
79
+ * 全按「去网页验证」提示会误导人——那种情况在网页上怎么点都没用。
80
+ */
81
+ function challengeHint(payload) {
82
+ const decision = readDecision(payload);
83
+ const subtype = String(decision?.subtype ?? '');
84
+ if (/device|session|fingerprint/i.test(subtype)) {
85
+ return '这次请求缺设备标识,被判定成异常会话。重新登录一次插件(用浏览器登录或粘贴完整 Cookie)通常就好了,去网页点验证没用。';
86
+ }
87
+ if (/rate|frequen|speed/i.test(subtype)) {
88
+ return '请求太密被限流了。停几分钟再用,期间别一直重试——越试恢复越慢。';
89
+ }
90
+ return CODE_HINT.captcha_required;
91
+ }
92
+
93
+ export function upstreamError(payload, fallbackStatus) {
94
+ const code = payload?.error?.code ?? payload?.error_code ?? payload?.code;
95
+ const message = payload?.error?.message ?? payload?.error_msg ?? payload?.message ?? payload?.msg ?? '豆包返回未知错误';
96
+ const [status, ourCode] = CODE_MAP[code] || [fallbackStatus || 502, 'upstream_error'];
97
+
98
+ // 风控拦截可能走 403 也可能走 429,统一当成「要求人工验证」处理:
99
+ // 文案要给对,refused 要带上,冷却也要进——三条都得一致,
100
+ // 否则 429 那条路会退化成「可重试」,越试封得越久(Issue #22)。
101
+ const challenge = isChallenge(code, payload);
102
+ const effectiveCode = challenge ? 'captcha_required' : ourCode;
103
+ const hint = challenge ? challengeHint(payload) : CODE_HINT[ourCode];
104
+ const text = hint ? `${message}(${hint})` : String(message);
105
+ const error = new ProviderError(text.slice(0, 500), status, effectiveCode);
106
+ // 只有登录类错误才让 magpie 标记账号;验证码不标记,避免账号被永久停用
107
+ if (ourCode === 'sign_in_required' || ourCode === 'sign_in_expired') error.signIn = 'expired';
108
+ // 风控不标 refused。这点踩过坑:
109
+ //
110
+ // 最初的想法是「风控了就别重试,越试封得越久」,于是带 X-Magpie-Refused。
111
+ // 但 magpie 看到这个头会**直接放弃整次请求**,连带不再尝试同一供应商的其他账号
112
+ // (fallback.go 的 settle():refused → 停止轮换)。
113
+ // 结果就是有三个账号也只用被风控的那一个,白白挨饿。
114
+ //
115
+ // 正确做法是让它继续换账号:插件这边按账号各自记冷却(session.noteChallenge),
116
+ // 被限的那个账号下一次请求直接在本地返回提示,不打上游;其他账号照常服务。
117
+ return error;
118
+ }
119
+
120
+ export function errorResponse(error) {
121
+ const status = error instanceof ProviderError ? error.status : 502;
122
+ const code = error instanceof ProviderError ? error.code : 'plugin_error';
123
+ const body = {
124
+ error: {
125
+ message: error?.message || '插件内部错误',
126
+ type: code,
127
+ code,
128
+ },
129
+ };
130
+ const headers = { 'Content-Type': 'application/json; charset=utf-8' };
131
+ if (error?.signIn) headers['X-Magpie-Sign-In'] = error.signIn;
132
+ // 风控拦截不是「换个账号就能成」的失败。magpie 的 retryable() 把 401/402/403/404/408/429
133
+ // 和 5xx 都判成可重试,于是同一个请求会连着打好几次,每次都撞在风控上,
134
+ // 反而把解除时间往后推(Issue #22 里就是这样被封了两天)。
135
+ // 带上 X-Magpie-Refused 后,magpie 的 settle() 会把它读成 refusedStatus,跳过重试。
136
+ // 那个判定只看 status >= 400 和这个头,与具体状态码无关——所以风控走 429 时同样有效。
137
+ // HTTP 头只能是 ASCII,中文说明得编码后再放。
138
+ if (error?.refused) headers['X-Magpie-Refused'] = encodeURIComponent(String(error.refused).slice(0, 200));
139
+ return new Response(JSON.stringify(body), { status, headers });
140
+ }
@@ -0,0 +1,160 @@
1
+ /**
2
+ * 额度:把豆包工作的订阅概况翻译成 magpie 的 usage 结构。
3
+ *
4
+ * 这是「积分兑换出来用」的关键一环:magpie 的账号卡片、`magpie quota`
5
+ * 和网关的 /v1/magpie/quotas 都读这个返回值,路由也能据此在账号之间挑选,
6
+ * 所以 amount / limit 必须给真实计数,不能拿百分比糊过去。
7
+ */
8
+ function num(value) {
9
+ if (value === undefined || value === null || value === '') return undefined
10
+ const result = Number(typeof value === 'string' ? value.replaceAll(',', '') : value)
11
+ return Number.isFinite(result) && result >= 0 ? result : undefined
12
+ }
13
+
14
+ function iso(value) {
15
+ const n = num(value)
16
+ if (!n) return undefined
17
+ return new Date(n < 1e12 ? n * 1000 : n).toISOString()
18
+ }
19
+
20
+ const SECTIONS = [
21
+ ['window_limit_section', '订阅额度'],
22
+ ['incentive_quota_section', '活动赠送'],
23
+ ['enterprise_window_limit_section', '企业额度'],
24
+ ]
25
+
26
+ export function normalizeQuota(overview, summary, user, checkin, cards) {
27
+ const sections = SECTIONS.filter(([key]) => (summary?.[key]?.window_limit_groups?.length ?? 0) > 0)
28
+ const subscription = overview?.current_subscription || summary?.current_subscription
29
+ // 30 天赠送订阅:能读到这个标记才说得清「你已经有赠送权益」。
30
+ // 以前完全不读,界面看起来像没订阅。
31
+ const gifted = overview?.is_membership_gift === true || overview?.data?.is_membership_gift === true
32
+
33
+ const windows = []
34
+ // 判断「这个池用光了,但别的池还有余量」时不能只看 usage_exhausted:
35
+ // 实测有的账号活动赠送额度已经 1600/1600(已用 100%),但服务端仍返回
36
+ // usage_exhausted: false。只看这个标志会让 magpie 拿满格的赠送池当总体进度,
37
+ // 界面上显示「几乎用尽」,而订阅额度其实还剩八成 —— issue #20。
38
+ const exhaustedOf = (key) => {
39
+ const section = summary[key]
40
+ if (!section) return false
41
+ if (section.usage_exhausted === true) return true
42
+ // 退一步按窗口实际用量判断:任意一个窗口用满就算这个池尽力了
43
+ for (const group of section.window_limit_groups || []) {
44
+ for (const window of group.window_limits || []) {
45
+ const used = num(window.used_amount)
46
+ const limit = num(window.total_amount)
47
+ if (used !== undefined && limit !== undefined && limit > 0 && used >= limit) return true
48
+ if (num(window.used_percent) === 100) return true
49
+ }
50
+ }
51
+ return false
52
+ }
53
+ for (const [key, label] of sections) {
54
+ const section = summary[key]
55
+ // 另一类额度池还有余量时,这个池耗尽不算账号不可用
56
+ const alternative = sections.some(([other]) => other !== key && !exhaustedOf(other))
57
+ for (const group of section.window_limit_groups) {
58
+ const limits = group.window_limits || []
59
+ for (const [index, window] of limits.entries()) {
60
+ const amount = num(window.used_amount)
61
+ const limit = num(window.total_amount)
62
+ const used = num(window.used_percent)
63
+ const end = iso(window.end_time)
64
+ const fmt = (value) => value.toLocaleString('en-US')
65
+ // 有总量就显示「已用 / 上限」。used_percent 几乎恒存在(赠送套餐恒为 0),
66
+ // 先判它会永远走百分比分支,把 500 的上限藏起来。
67
+ const hasCounts = amount !== undefined && limit !== undefined
68
+ windows.push({
69
+ name: `${group.feature_group_name || label}${limits.length > 1 ? ` · 窗口${window.window_type ?? index + 1}` : ''}`,
70
+ ...(used === undefined ? {} : { used }),
71
+ ...(amount === undefined ? {} : { amount }),
72
+ ...(limit === undefined ? {} : { limit }),
73
+ unit: '积分',
74
+ // 服务端用 less_than_one_percent 表示「不足 1%」,直接采纳而不是自己算
75
+ ...(window.less_than_one_percent === true ? { usedNote: '不足 1%' } : {}),
76
+ display: hasCounts ? `${fmt(amount)} / ${fmt(limit)} 积分` : '服务端未提供计数',
77
+ // 活动赠送额度到期不会补,用 runsOutAt;订阅额度用 resetsAt
78
+ ...(end ? (key === 'incentive_quota_section'
79
+ ? { runsOutAt: end, ...(hasCounts ? { runsOut: Math.max(0, limit - amount) } : {}) }
80
+ : { resetsAt: end }) : {}),
81
+ aside: exhaustedOf(key) && alternative,
82
+ })
83
+ }
84
+ }
85
+ }
86
+
87
+ windows.push(...cardWindows(cards))
88
+
89
+ const unsupported = ['package_entitlement_groups', 'quota_package_entitlement_groups', 'enterprise_package_entitlement_groups']
90
+ .some((key) => (summary?.[key]?.length ?? 0) > 0)
91
+
92
+ return {
93
+ plan: planLabel(subscription, gifted),
94
+ user,
95
+ ...(subscription?.end_time ? { until: iso(subscription.end_time) } : {}),
96
+ windows: [...windows, ...(checkin ? checkinWindow(checkin) ?? [] : [])],
97
+ ...(unsupported ? { error: '账号含额外额度包,其字段尚未验证;这里只显示服务端已识别的窗口。' } : {}),
98
+ }
99
+ }
100
+
101
+ /** 套餐名;赠送订阅加个标记,免得看着像没订阅 */
102
+ function planLabel(subscription, gifted) {
103
+ const base = subscription?.display?.short_name || subscription?.display?.product_name || '豆包工作'
104
+ if (!gifted) return base
105
+ return base.includes('赠送') ? base : `${base}(赠送)`
106
+ }
107
+
108
+ /**
109
+ * 把活动赠送卡做成额度窗口。
110
+ *
111
+ * `/alice/commerce/marketing/card/list/` 里的卡不在 overview 里。免费体验账号
112
+ * 常常只有这里存在额度,不读的话界面显示「暂无额度」,实际是有卡的。
113
+ */
114
+ export function cardWindows(cards) {
115
+ const list = cards?.data?.cards ?? cards?.cards ?? []
116
+ if (!Array.isArray(list) || !list.length) return []
117
+ return list.map((card) => {
118
+ const track = card.track_params || {}
119
+ const remain = num(track.card_balance)
120
+ const validDays = num(track.valid_days)
121
+ const end = card.expire_time ? iso(Date.parse(card.expire_time)) : undefined
122
+ return {
123
+ name: `${card.source_display_text || '活动赠送'} · ${card.card_key || '额度卡'}`,
124
+ ...(remain === undefined ? {} : { amount: remain }),
125
+ unit: '次',
126
+ ...(end ? { runsOutAt: end } : {}),
127
+ ...(validDays === undefined ? {} : { note: `${validDays} 天有效` }),
128
+ display: remain === undefined ? '服务端未提供计数' : `剩 ${remain} 次`,
129
+ ...(card.usable_on_current_device === false ? { aside: true, usedNote: '当前设备不可用' } : {}),
130
+ }
131
+ })
132
+ }
133
+
134
+ /**
135
+ * 把签到状态做成一个额度窗口。
136
+ *
137
+ * 只做展示,不代签:
138
+ * - 已签 → 「今日已签 · 连续 N 天」+ usedNote「已领取」
139
+ * - 未签 → 「今日未签 · 可领 N 额度」+ usedNote「请去豆包电脑版签」
140
+ *
141
+ * 为什么不代签:Web 侧那条路被服务端拒(710010702),而且失败写入会吃掉
142
+ * 当天额度且不可回滚——比签不上更糟。所以宁可让用户多点一下。
143
+ *
144
+ * 状态本身是真查的:读 /alice/ug/campaign/v3/detail/ 里 signin 任务的
145
+ * checked_in_today 与 task_status。查不到就不显示这个窗口,不猜。
146
+ */
147
+ export function checkinWindow(state) {
148
+ if (!state?.found) return undefined
149
+ const note = state.claimed
150
+ ? `今日已签${state.streak ? ` · 连续 ${state.streak} 天` : ''}`
151
+ : `今日未签${state.points ? ` · 可领 ${state.points} 额度` : ''}`
152
+ return [{
153
+ name: `每日签到(${note})`,
154
+ ...(state.streak !== undefined ? { streak: state.streak } : {}),
155
+ ...(state.points !== undefined ? { credit: state.points } : {}),
156
+ usedNote: state.claimed ? '已领取' : '请去豆包电脑版签',
157
+ }]
158
+ }
159
+
160
+ export const _internal = { num, iso }