magpie-plugin-loomy-auth 0.1.18 → 0.1.21

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 CHANGED
@@ -1,818 +1,818 @@
1
- // Loomy · 纯函数层(不碰网络、不碰文件,由 index.mjs 经 `_internal` 交给测试)
2
- //
3
- // ⚠ magpie 的宿主会把入口模块的**每一个函数导出**都当插件工厂调用
4
- // (`internal/plugin/host.js` 的 `servers()`)。所以 helper 一律待在这个
5
- // `_pure` 数据对象里,index.mjs 只导出「一个工厂 + `_internal`」。
6
- //
7
- // ════════════════════════════════════════════════════════════════════
8
- // 三条实测结论,本文件的设计全由此而来(测于 2026-10-26)
9
- // ════════════════════════════════════════════════════════════════════
10
- //
11
- // ① `dailyQuota` **不在任何只读端点上**。
12
- // 实测 `/api/v1/points/records`、`/api/v1/points/balance`、`/api/v2/points/records`
13
- // 都只回 `balance` / `dailyBalance` / `availableBalance`;
14
- // 只有 `POST /api/v1/points/first-login`(写端点,幂等)带
15
- // `dailyQuota` / `dailyConsumed` / `dailyCycleDate`。
16
- // ⇒ 上限只能「签到/登录时拿到并记进凭据」,**不许硬编码 5000**(活动会变)。
17
- //
18
- // ② 但**今日消耗可以从流水读出来**(降级路径)。
19
- // V1 `/api/v1/points/records` 每条 debit 带 `consumeSource`(`daily`/`permanent`)
20
- // 与 `dailyCycleDate`,于是
21
- // quota ≈ dailyBalance + Σ(本业务日 consumeSource=daily 的扣分)
22
- // 两号实测:181\*\*\*\*0632(0/0)→ quota=5000、used=100%;
23
- // 189\*\*\*\*8051 → quota=5000、used=3.96%。
24
- //
25
- // ③ 永久池**不该参与路由**。它无周期、无上限,所以 `aside: true` 且
26
- // **不给 `amount`/`limit`** —— 给了,magpie 就把它当一条真额度算占比,
27
- // 而「永久池总量 = 剩余」这种假总量正是市场现有插件的缺陷来源。
28
- //
29
- // ════════════════════════════════════════════════════════════════════
30
- // magpie 如何用这些窗口(从二进制里取证的原文,决定本文件所有取舍)
31
- // ════════════════════════════════════════════════════════════════════
32
- //
33
- // const group = (w) => w.used >= 98 ? "spent" : w.used >= 90 ? "low" : "fine"
34
- // quotaFill(w){ const used = Math.round(to100(w.used)); return quotaLeft ? 100-used : used }
35
- // quotaCount(w){ if (!(w.limit > 0)) return w.display || ""; … }
36
- // const counted = q.windows.filter((w) => !w.unlimited); // 卡片主环
37
- // … else if (w.aside) s = t("{api} only after the others") // aside 排后面
38
- // smart 路由:spent 的账号 "answers only when nothing else can" // 排最后
39
- // usage 归一:used: Math.max(0, num(w?.used)) // 缺省即 0
40
- //
41
- // ⇒ **一个空号若不画任何参与路由的窗口,就会以 used:0 的姿态排在前面。**
42
- // 这正是市场插件把蹬空的号顶到路由队首、白撞几百次的根因。
43
-
44
- import { BEIJING_UTC_OFFSET_MS, PROVIDER } from "./constants.mjs"
45
-
46
- /** 邀请双方各得的积分(客户端常量 `nb = 5e3`)。 */
47
- const INVITE_REWARD_POINTS = 5000
48
-
49
- export const _pure = {
50
- windowsOf,
51
- balanceLine,
52
-
53
- beijingCycleDate,
54
- beijingResetAt,
55
- quotaCoversCycle,
56
- parseCycle,
57
-
58
- dailyConsumedByCycle,
59
- mergeQuotaReadings,
60
-
61
- credentialOf,
62
- maskPhone,
63
- normalizePhone,
64
- normalizeCode,
65
-
66
- splitRateSuffix,
67
- isFreeModel,
68
- parseModels,
69
- modelShape,
70
-
71
- prefersTagFormat,
72
- rewriteImagesToTags,
73
-
74
- buildEscapedPath,
75
- signedHeaders,
76
-
77
- businessCode,
78
- upstreamMessage,
79
- isAuthErrorCode,
80
- ensureSuccess,
81
- looksLikeInsufficientPoints,
82
- checkinOutcome,
83
-
84
- onboardingPoints,
85
- onboardingTitles,
86
- normalizeTasks,
87
- earnedPoints,
88
- pendingTasks,
89
- onboardingWindow,
90
-
91
- normalizeInviteCode,
92
- pickInviteCode,
93
- INVITE_REWARD_POINTS,
94
- }
95
-
96
- const round = (n) => Math.round(n * 100) / 100
97
-
98
- /** 任意值读成有限数;非法回 fallback(**不编造 0** 的场景都显式传 undefined)。 */
99
- function num(value, fallback) {
100
- const n = typeof value === "string" && value.trim() !== "" ? Number(value.trim()) : Number(value)
101
- return Number.isFinite(n) ? n : fallback
102
- }
103
-
104
- // ════════════════════════════════════════════════════════════════════
105
- // ① 额度窗口 —— 本插件的核心
106
- // ════════════════════════════════════════════════════════════════════
107
-
108
- /**
109
- * @param pools 只读端点的余额读数 `{permanent, daily, total}`
110
- * @param quota `{value?, consumed?, cycleDate?, known:boolean, source}`
111
- * @param now epoch 毫秒
112
- *
113
- * 判据表(四条语义各有单测锁死):
114
- *
115
- * | 情形 | 今日池 | 永久池 |
116
- * |---|---|---|
117
- * | 知道上限、有/无消耗 | `used = 100*consumed/quota`,带 amount/limit/resetsAt | `aside`,只 display |
118
- * | 上限未知但可从流水推 | 用推导值,正常占比 | 同上 |
119
- * | 上限未知也推不出 | `aside` + `used:0`,**绝不谎报成满额或假占比** | 同上 |
120
- * | **两池皆 0(号被蹬空)** | 合成一条 `used:100` 的**参与路由**窗口 | 不画(本来就没) |
121
- */
122
- function windowsOf(pools, quota, now) {
123
- const permanent = Math.max(0, num(pools?.permanent, 0))
124
- const daily = Math.max(0, num(pools?.daily, 0))
125
- const total = num(pools?.total, permanent + daily)
126
- const windows = []
127
-
128
- // —— 蹬空的号:必须画一条参与路由的满额窗口,让它沉底 ——
129
- if (total <= 0) {
130
- windows.push({
131
- name: "今日积分",
132
- used: 100,
133
- display: "积分已耗尽",
134
- unit: "积分",
135
- ...(quota?.cycleDate ? { resetsAt: beijingResetAt(quota.cycleDate, now) } : {}),
136
- })
137
- return windows
138
- }
139
-
140
- const ceiling = num(quota?.value, undefined)
141
- if (quota?.known && ceiling !== undefined && ceiling > 0) {
142
- const consumed = num(quota?.consumed, undefined) ?? Math.max(0, ceiling - daily)
143
- const used = round(Math.max(0, Math.min(100, (100 * Math.max(0, consumed)) / ceiling)))
144
- windows.push({
145
- name: "今日积分",
146
- used,
147
- display: `${daily} / ${ceiling} 积分`,
148
- amount: Math.max(0, ceiling - daily),
149
- limit: ceiling,
150
- unit: "积分",
151
- resetsAt: beijingResetAt(quota.cycleDate, now),
152
- })
153
- } else {
154
- // 上限拿不到:说还剩多少,但**不声称占比**(画成 aside 即不参与路由打分)。
155
- windows.push({
156
- name: "今日积分",
157
- used: 0,
158
- aside: true,
159
- display: `${daily} 积分剩余(今日上限未知)`,
160
- unit: "积分",
161
- ...(quota?.cycleDate ? { resetsAt: beijingResetAt(quota.cycleDate, now) } : {}),
162
- })
163
- }
164
-
165
- if (permanent > 0) {
166
- windows.push({
167
- name: "永久积分",
168
- used: 0,
169
- aside: true,
170
- display: `${permanent} 积分`,
171
- unit: "积分",
172
- })
173
- }
174
-
175
- return windows
176
- }
177
-
178
- /** 卡片顶部的总余额行(厂商自己的数,不做二次加工)。 */
179
- function balanceLine(total) {
180
- const n = num(total, 0)
181
- return `${Math.max(0, Math.round(n))} 积分`
182
- }
183
-
184
- // ════════════════════════════════════════════════════════════════════
185
- // ② 业务日(东八区)
186
- // ════════════════════════════════════════════════════════════════════
187
-
188
- /** epoch 毫秒 → 东八区业务日 `YYYY-MM-DD`。 */
189
- function beijingCycleDate(now) {
190
- return new Date(now + BEIJING_UTC_OFFSET_MS).toISOString().slice(0, 10)
191
- }
192
-
193
- /** `YYYY-MM-DD` → 该日 00:00(东八区)的 epoch 毫秒;解析失败回 undefined。 */
194
- function parseCycle(cycleDate) {
195
- const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(cycleDate ?? "").trim())
196
- if (!m) return undefined
197
- return Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3])) - BEIJING_UTC_OFFSET_MS
198
- }
199
-
200
- /**
201
- * 该业务日的重置时刻 = 次一北京日的 **00:05**(ISO 字符串)。
202
- *
203
- * 留 5 分钟:踩北京 0 点的那次请求不该记到厂商已经关闭的那一天上。
204
- * `cycleDate` 解析不出来时,退到「now 所在北京日的次日 00:05」。
205
- * 若算出来已经过去(缓存里的旧日期),再推一天,**不返回过去的时间**
206
- * —— magpie 拿 resetsAt 算倒计时,给旧值会显示成「已重置」。
207
- */
208
- function beijingResetAt(cycleDate, now) {
209
- const parsed = parseCycle(cycleDate)
210
- const day = parsed !== undefined ? parsed : beijingMidnightOf(now)
211
- let reset = day + 86_400_000 + 5 * 60_000
212
- while (reset <= now) reset += 86_400_000
213
- return new Date(reset).toISOString()
214
- }
215
-
216
- function beijingMidnightOf(now) {
217
- const d = new Date(now + BEIJING_UTC_OFFSET_MS)
218
- return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()) - BEIJING_UTC_OFFSET_MS
219
- }
220
-
221
- /**
222
- * 这条 quota 是否还描述**当前**这个北京日。
223
- *
224
- * ⚠ 旧上限不能跨日沿用:上限是厂商的(活动会调),而它是**昨天**签到时
225
- * 拿到的。沿用昨天的数会让今日占比算错,所以日期已过就当作没有,
226
- * 等今天的签到 —— 宁可降级成「上限未知」,也不要谎报一个错占比。
227
- * ⚠ 完全没有日期时**保守保留**:`dailyCycleDate` 是厂商字段,可能不下发,
228
- * 而「永远等不到上限」比「偶尔沿用一次」更接近缺陷。
229
- */
230
- function quotaCoversCycle(cycleDate, now) {
231
- const parsed = parseCycle(cycleDate)
232
- if (parsed === undefined) return true
233
- return parsed + 86_400_000 + 5 * 60_000 > now + 60_000
234
- }
235
-
236
- // ════════════════════════════════════════════════════════════════════
237
- // ③ 流水推导 + 读数合并
238
- // ════════════════════════════════════════════════════════════════════
239
-
240
- /** 本业务日从 daily 池扣掉的总分(V1 records 才有这两个维度)。 */
241
- function dailyConsumedByCycle(list, cycleDate) {
242
- let sum = 0
243
- for (const row of Array.isArray(list) ? list : []) {
244
- if (row?.direction !== "debit") continue
245
- if (row?.consumeSource !== "daily") continue
246
- const rowCycle = typeof row?.dailyCycleDate === "string" ? row.dailyCycleDate.trim() : ""
247
- if (cycleDate !== undefined && rowCycle !== "" && rowCycle !== cycleDate) continue
248
- const n = num(row?.pointsActual, 0)
249
- if (n > 0) sum += n
250
- }
251
- return sum
252
- }
253
-
254
- /**
255
- * 把三个上限来源合成一条 quota。优先序:
256
- * 签到实测(凭据里记的)> 流水推导 > 未知
257
- *
258
- * 每条都过 `quotaCoversCycle`:跨日的旧值一律作废。
259
- */
260
- function mergeQuotaReadings(remembered, derived, now) {
261
- const remValue = num(remembered?.value, undefined)
262
- if (
263
- remValue !== undefined &&
264
- remValue > 0 &&
265
- quotaCoversCycle(remembered?.cycleDate, now)
266
- ) {
267
- return {
268
- value: remValue,
269
- cycleDate: remembered?.cycleDate ?? undefined,
270
- consumed: num(derived?.consumed, undefined),
271
- known: true,
272
- source: "checkin",
273
- }
274
- }
275
-
276
- const derValue = num(derived?.value, undefined)
277
- if (derValue !== undefined && derValue > 0) {
278
- return {
279
- value: derValue,
280
- cycleDate: derived?.cycleDate ?? undefined,
281
- consumed: num(derived?.consumed, 0),
282
- known: true,
283
- source: "derived",
284
- }
285
- }
286
-
287
- return { value: undefined, cycleDate: undefined, consumed: undefined, known: false, source: "unknown" }
288
- }
289
-
290
- // ════════════════════════════════════════════════════════════════════
291
- // ④ 凭据形状
292
- // ════════════════════════════════════════════════════════════════════
293
-
294
- /**
295
- * magpie 交来的 auth 有四种形态,全部要认(sucooer 只认第一种,
296
- * 于是收到 provider 映射就返回 null → 卡片永远「未登录」):
297
- *
298
- * A `{type:"oauth", access, refresh, expires, accountId, uid, phone, dailyQuota…}`
299
- * B `{type:"oauth", access}`
300
- * C provider 映射 `{"loomy":{…}, "loomy#xxxx":{…}}`
301
- * D 裸 session 字符串
302
- */
303
- function credentialOf(auth) {
304
- if (typeof auth === "string") {
305
- const session = auth.trim()
306
- return session ? { session, accountId: "", uid: "", phone: "" } : null
307
- }
308
- if (!auth || typeof auth !== "object") return null
309
-
310
- if (typeof auth.access === "string" && auth.access.trim()) return fromRecord(auth)
311
-
312
- const candidates = [auth[PROVIDER], ...Object.values(auth)].filter(
313
- (v) => v && typeof v === "object" && typeof v.access === "string" && v.access.trim(),
314
- )
315
- return candidates.length ? fromRecord(candidates[0]) : null
316
- }
317
-
318
- function fromRecord(rec) {
319
- return {
320
- session: String(rec.access).trim(),
321
- accountId: typeof rec.accountId === "string" ? rec.accountId : "",
322
- uid: typeof rec.uid === "string" ? rec.uid : "",
323
- phone: typeof rec.phone === "string" ? rec.phone : "",
324
- dailyQuota: num(rec.dailyQuota, undefined),
325
- dailyCycleDate: typeof rec.dailyCycleDate === "string" && rec.dailyCycleDate.trim()
326
- ? rec.dailyCycleDate.trim()
327
- : undefined,
328
- expires: num(rec.expires, undefined),
329
- }
330
- }
331
-
332
- function maskPhone(phone) {
333
- const chars = [...String(phone ?? "")]
334
- if (chars.length < 7) return String(phone ?? "")
335
- return `${chars.slice(0, 3).join("")}****${chars.slice(-4).join("")}`
336
- }
337
-
338
- function normalizePhone(raw) {
339
- const trimmed = String(raw ?? "").replace(/[\s-]/g, "").replace(/^\+86/, "")
340
- const digits = /^86\d{11}$/.test(trimmed) ? trimmed.slice(2) : trimmed
341
- if (!/^1[3-9]\d{9}$/.test(digits)) throw Object.assign(new Error("请填写 11 位中国大陆手机号"), { status: 400 })
342
- return digits
343
- }
344
-
345
- function normalizeCode(raw) {
346
- const trimmed = String(raw ?? "").trim()
347
- if (!/^\d{6}$/.test(trimmed)) throw Object.assign(new Error("请填写 6 位数字验证码"), { status: 400 })
348
- return trimmed
349
- }
350
-
351
- // ════════════════════════════════════════════════════════════════════
352
- // ⑤ 模型目录
353
- // ════════════════════════════════════════════════════════════════════
354
-
355
- /** 从展示名尾部拆 `(x3.0)` / `(x0.8)` 形态的积分倍率,其余标签原样保留。 */
356
- function splitRateSuffix(name) {
357
- const trimmed = String(name ?? "").trimEnd()
358
- const half = trimmed.endsWith(")")
359
- const full = trimmed.endsWith(")")
360
- if (!half && !full) return [trimmed, undefined]
361
- const open = trimmed.lastIndexOf(half ? "(" : "(")
362
- if (open < 0) return [trimmed, undefined]
363
- const inner = trimmed.slice(open + 1, trimmed.length - 1).trim()
364
- const digits = /^[xX]([\d.]+)$/.exec(inner)?.[1]
365
- if (!digits || !/\d/.test(digits)) return [trimmed, undefined]
366
- const body = trimmed.slice(0, open).trimEnd()
367
- return [body || trimmed, `x${digits}`]
368
- }
369
-
370
- /**
371
- * 这个模型**不花账号的积分**吗?—— magpie 的 `free` 字段。
372
- *
373
- * 为什么需要它:magpie 有 `"free"` 这个路由模式(界面叫 *Free first*),
374
- * 契约原文是「模型供应商不消耗本订阅的额度或积分」。命中它的模型会被
375
- * **优先派发**,所以标错等于把本该免费的请求算进收费档。
376
- *
377
- * ⚠ 判据**不能**只看 `rate === 0`:
378
- * - 本机实测 `plugin-providers.json` 里 `rate === 0` 的条目 51 条,
379
- * 其中 `free: true` 只有 13 条 —— 其余是「套餐内不按次计费」,
380
- * 例如 qoder 的 `ultimate` / `dfmodel`,它们仍消耗套餐额度,不是免费。
381
- * - Loomy 的 `auto`(自动·均衡)也没有倍率文本,但它会落到别的模型上
382
- * 去花积分,同样不是免费。
383
- *
384
- * Loomy 的判据只有两条,且都来自上游自己的文字:
385
- * 1. 展示名里明确写了「免费」(如 `Spark-X2.6 正式版(限时免费)(x0.0)`)
386
- * 2. 倍率文本是 `x0.0`(成本 0 倍,即不扣分)
387
- * 两者都是上游写在 `name` 里的声明,不是我们从别处推的。
388
- */
389
- function isFreeModel(displayName, rate) {
390
- const name = String(displayName ?? "")
391
- if (/免费/.test(name)) return true
392
- return typeof rate === "string" && /^x0(\.0+)?$/i.test(rate.trim())
393
- }
394
-
395
- /**
396
- * 解析 `GET /api/v1/models`(实测 13 条 chat 模型)。
397
- *
398
- * ⚠ 只保留 `type === "chat"`:上游还下发 image 型条目,列出来就是
399
- * 让用户选中一个必然失败的「模型」。
400
- */
401
- function parseModels(payload) {
402
- const rows = Array.isArray(payload?.data) ? payload.data : Array.isArray(payload) ? payload : []
403
- const out = []
404
- for (const row of rows) {
405
- const id = typeof row?.id === "string" ? row.id.trim() : ""
406
- if (!id) continue
407
- if (typeof row?.type === "string" && row.type !== "chat") continue
408
-
409
- const caps = row?.capabilities && typeof row.capabilities === "object" ? row.capabilities : undefined
410
- const [name, rate] = splitRateSuffix(typeof row?.name === "string" && row.name.trim() ? row.name : id)
411
- const efforts = Array.isArray(row?.reasoning_efforts)
412
- ? row.reasoning_efforts.filter((e) => typeof e === "string" && e.trim() !== "")
413
- : []
414
-
415
- out.push({
416
- id,
417
- name: name || id,
418
- context: positive(row?.context_length) ?? positive(row?.context_window) ?? positive(row?.max_input_tokens),
419
- output: positive(row?.max_output_tokens) ?? positive(row?.max_completion_tokens),
420
- reasoning: caps?.reasoning === true || efforts.length > 0,
421
- toolCall: caps?.function_calling !== false,
422
- images: caps?.vision === true || hasModality(caps?.input_modalities, "image"),
423
- video: hasModality(caps?.input_modalities, "video"),
424
- efforts,
425
- defaultEffort:
426
- typeof row?.default_reasoning_effort === "string" ? row.default_reasoning_effort : undefined,
427
- rate,
428
- free: isFreeModel(row?.name, rate),
429
- })
430
- }
431
- return out
432
- }
433
-
434
- function hasModality(list, want) {
435
- return Array.isArray(list) && list.some((v) => typeof v === "string" && v.toLowerCase() === want)
436
- }
437
-
438
- function positive(v) {
439
- const n = Number(v)
440
- return Number.isFinite(n) && n > 0 ? n : undefined
441
- }
442
-
443
- /**
444
- * 上游模型 → magpie 的模型条目。
445
- *
446
- * ⚠ `limit.context` 会被 magpie 转给 agent,决定它何时压缩对话;更要紧的是
447
- * **路由组按组内最大值算窗口** —— 填小会把整组拉低(本工作区踩过:
448
- * 插件声明 131072 而卡片填 1M,同一个模型两条路径报两个值)。
449
- * Loomy 的 chat 模型上游实测就是 1,048,576,**原样上报,不二次收缩**。
450
- */
451
- function modelShape(m, base = {}) {
452
- const efforts = m.efforts ?? []
453
- const shape = {
454
- ...base,
455
- id: m.id,
456
- name: m.name || m.id,
457
- api: { id: m.id, url: base?.api?.url, npm: base?.api?.npm },
458
- status: "active",
459
- limit: {
460
- context: m.context ?? base?.limit?.context ?? 0,
461
- output: m.output ?? base?.limit?.output ?? 0,
462
- },
463
- capabilities: {
464
- temperature: true,
465
- reasoning: !!m.reasoning,
466
- attachment: !!m.images,
467
- toolcall: m.toolCall !== false,
468
- input: { text: true, image: !!m.images, audio: false, video: !!m.video, pdf: false },
469
- output: { text: true, image: false, audio: false, video: false, pdf: false },
470
- interleaved: false,
471
- },
472
- variants: m.reasoning
473
- ? Object.fromEntries((efforts.length ? efforts : ["low", "medium", "high"]).map((e) => [e, {}]))
474
- : {},
475
- }
476
- if (m.rate) shape.rate = m.rate
477
- // ⚠ free 只由模型自己的声明决定(见 isFreeModel 的判据),
478
- // **不要**在这里按「有没有 rate」反推 —— 那样 `x0.0` 会被误判成收费。
479
- shape.free = m.free === true
480
- return shape
481
- }
482
-
483
- // ════════════════════════════════════════════════════════════════════
484
- // ⑥ 图片格式适配
485
- // ════════════════════════════════════════════════════════════════════
486
-
487
- /**
488
- * deepseek 系模型只认 `<image_base64>` 标记;喂标准 `image_url` data URI
489
- * 会被上游当成截断的 base64 文本读(agent2api loomy/images.rs 的实测结论)。
490
- * 宁可不转,不能转错 —— 非 deepseek 一律不动。
491
- */
492
- function prefersTagFormat(modelId) {
493
- return String(modelId ?? "").toLowerCase().includes("deepseek")
494
- }
495
-
496
- function tagOfBlock(block) {
497
- if (!block || block.type !== "image_url") return null
498
- const url = block?.image_url?.url
499
- if (typeof url !== "string" || !url.startsWith("data:")) return null
500
- const comma = url.indexOf(",")
501
- if (comma < 0) return null
502
- return `<image_base64>${url.slice(comma + 1)}</image_base64>`
503
- }
504
-
505
- /** 把 image 块并入相邻 text 块(上游实测认可的形态)。 */
506
- function rewriteImagesToTags(body) {
507
- const messages = Array.isArray(body?.messages) ? body.messages : null
508
- if (!messages) return body
509
- const convertible = messages.some(
510
- (msg) => Array.isArray(msg?.content) && msg.content.some((b) => tagOfBlock(b) !== null),
511
- )
512
- if (!convertible) return body
513
-
514
- const next = JSON.parse(JSON.stringify(body))
515
- for (const message of next.messages) {
516
- if (!Array.isArray(message?.content)) continue
517
- const content = message.content
518
- for (let index = content.length - 1; index >= 0; index--) {
519
- const tag = tagOfBlock(content[index])
520
- if (tag === null) continue
521
- content.splice(index, 1)
522
- const previous = index > 0 ? content[index - 1] : null
523
- if (previous?.type === "text" && typeof previous.text === "string") {
524
- previous.text += `\n${tag}`
525
- } else if (content[index]?.type === "text" && typeof content[index].text === "string") {
526
- content[index].text = `${tag}\n${content[index].text}`
527
- } else {
528
- content.splice(index, 0, { type: "text", text: tag })
529
- }
530
- }
531
- }
532
- return next
533
- }
534
-
535
- // ════════════════════════════════════════════════════════════════════
536
- // ⑦ 账号接口签名(HMAC-SHA1,复刻客户端 generateSignature)
537
- // ════════════════════════════════════════════════════════════════════
538
-
539
- /** 路径分段转义。当前账号接口只含字母与 `/`,仍实现完整规则以免将来静默出错。 */
540
- function buildEscapedPath(p) {
541
- let clean = String(p ?? "")
542
- if (!clean.startsWith("/")) clean = `/${clean}`
543
- if (clean.length > 1 && clean.endsWith("/")) clean = clean.slice(0, -1)
544
- return clean
545
- .split("/")
546
- .map((segment) => {
547
- let out = ""
548
- for (const byte of new TextEncoder().encode(segment)) {
549
- const ch = String.fromCharCode(byte)
550
- out += /[A-Za-z0-9\-_.~]/.test(ch) ? ch : `%${byte.toString(16).toUpperCase().padStart(2, "0")}`
551
- }
552
- return out
553
- })
554
- .join("/")
555
- }
556
-
557
- /**
558
- * 待签串 9 段 `\n` 连接:
559
- * METHOD\n ESCAPED_PATH\n ""(query)\n CONTENT_MD5\n content-type\n
560
- * DATE(UTC)\n NONCE\n ""(signed headers)\n ""(canonicalized headers)
561
- *
562
- * 加密原语由调用方注入(`crypto.mjs`),这样本文件保持纯函数、可离线测。
563
- */
564
- function signedHeaders(method, path, bodyString, secrets) {
565
- const md5 = bodyString ? secrets.md5Base64(bodyString) : ""
566
- const date = secrets.utcnow()
567
- const nonce = secrets.uuid()
568
- const stringToSign = [
569
- String(method).toUpperCase(),
570
- buildEscapedPath(path),
571
- "",
572
- md5,
573
- "application/json",
574
- date,
575
- nonce,
576
- "",
577
- "",
578
- ].join("\n")
579
- const signature = secrets.hmacSha1Base64(secrets.accessKeySecret, stringToSign)
580
- const headers = {
581
- Authorization: `account ${secrets.accessKeyId}:${signature}`,
582
- Date: date,
583
- Nonce: nonce,
584
- }
585
- if (md5) headers["Content-MD5"] = md5
586
- return headers
587
- }
588
-
589
- // ════════════════════════════════════════════════════════════════════
590
- // ⑧ 信封、错误归类、签到 outcome
591
- // ════════════════════════════════════════════════════════════════════
592
-
593
- function businessCode(payload) {
594
- return typeof payload?.code === "string" ? payload.code.trim() : ""
595
- }
596
-
597
- function upstreamMessage(payload) {
598
- const text = payload?.desc ?? payload?.message ?? payload?.msg
599
- return typeof text === "string" ? text.trim() : ""
600
- }
601
-
602
- function isAuthErrorCode(code) {
603
- return ["020002", "100002"].includes(code)
604
- }
605
-
606
- /** 业务码非 000000 时抛;登录态失效归 401 并带 `signIn:"expired"`(magpie 据此标记账号)。 */
607
- function ensureSuccess(payload, what) {
608
- const code = businessCode(payload)
609
- if (code === "000000") return
610
- const message = upstreamMessage(payload)
611
- const detail = message ? `${what}:${message}` : `${what}失败(上游 code=${code || "无"})`
612
- if (isAuthErrorCode(code)) throw Object.assign(new Error(detail), { signIn: "expired", status: 401 })
613
- throw Object.assign(new Error(detail), { status: 502 })
614
- }
615
-
616
- /**
617
- * 「积分余额不足」判据 —— 必须**窄**。
618
- *
619
- * 上游是 HTTP 400 + 中文文案,不是结构化额度错误;泛词(quota/balance/不足)
620
- * 会误伤模型正文里恰好讨论「余额」的内容。
621
- */
622
- function looksLikeInsufficientPoints(text) {
623
- const t = String(text ?? "")
624
- return /积分余额不足|积分不足|余额不足,请获取积分|请获取积分后再试/.test(t)
625
- }
626
-
627
- /**
628
- * 把签到结果映射成 magpie 的 outcome。
629
- *
630
- * ⚠⚠ 这是市场插件正在犯的那个错:契约的合法值只有
631
- * `claimed / done / ineligible / inactive / captcha / failed`
632
- * (`magpie-plugin-contract-full.txt` 的 `checkinOutcomes`)。
633
- * sucooer 成功时返回 `{outcome:"success"}` —— 不在表里,
634
- * magpie 一律归为 `failed` 但**保留 message**,于是用户看到
635
- * 「签到失败 · 每日赠送积分已刷新」这种自相矛盾的行。
636
- *
637
- * 幂等判据是响应体的 `alreadyProcessed`(重复调用同样回 HTTP 200),
638
- * 所以「今天已领」必须是 `done` 而不是 `claimed` —— 后者会让用户
639
- * 以为每天都真的加了额度。
640
- */
641
- function checkinOutcome(raw) {
642
- if (raw?.ok === false) {
643
- return { outcome: "failed", message: raw.message || "每日额度刷新失败" }
644
- }
645
- if (raw?.alreadyProcessed === true) {
646
- const quota = num(raw?.dailyQuota, undefined)
647
- const balance = num(raw?.dailyBalance, undefined)
648
- return {
649
- outcome: "done",
650
- message: quota === undefined
651
- ? "今日额度已刷新"
652
- : `今日额度已刷新(${balance ?? 0}/${quota} 积分)`,
653
- }
654
- }
655
- // 首次处理:本次新发放的额度 = quota - consumed(两个都缺时不编造)
656
- const quota = num(raw?.dailyQuota, undefined)
657
- const consumed = num(raw?.dailyConsumed, undefined)
658
- const balance = num(raw?.dailyBalance, undefined)
659
- const credit =
660
- quota !== undefined && consumed !== undefined
661
- ? Math.max(0, quota - consumed)
662
- : (balance ?? quota ?? 0)
663
- return {
664
- outcome: "claimed",
665
- credit,
666
- message: `每日赠送额度已刷新(+${credit} 积分)`,
667
- }
668
- }
669
-
670
- // ════════════════════════════════════════════════════════════════════
671
- // ⑨ 新手任务(onboarding)—— 一次性可领的 1 万分
672
- // ════════════════════════════════════════════════════════════════════
673
- //
674
- // Loomy 把「新手任务」的奖励做成一笔**可主动领取**的积分,总计 10,000 分:
675
- //
676
- // | key | 任务 | 分值 |
677
- // |---|---|---|
678
- // | first_message | 发送你的第一条消息 | 500 |
679
- // | pick_skill | 试试选择一个技能 | 1000 |
680
- // | generate_ppt | 生成第一份 PPT | 1500 |
681
- // | set_schedule | 设置定时任务 | 1000 |
682
- // | install_skill | 在技能广场安装一个技能 | 1500 |
683
- // | configure_remote | 配置远程控制 | 1000 |
684
- // | create_soul | 创建你的第一个搭子 | 1500 |
685
- // | share_soul | 把搭子分享给朋友 | 2000 |
686
- //
687
- // 端点:`GET /api/v1/onboarding/tasks`(只读)与
688
- // `POST /api/v1/onboarding/tasks/complete {key}`(幂等写)。
689
- // 实测(2026-10-26):两个账号都能读,`first_message` 已完成的那个账号
690
- // 流水里确实有「新手任务-发送第一条消息 +500」的 credit 记录 —— 说明
691
- // 领取是真到账的,不是展示用的假数字。
692
- //
693
- // ⚠ 这笔钱**不参与每日池**,也不该拿它去算占比(它是一次性的,
694
- // 领完就没了)。所以只作为 `aside` 窗口展示「还能领多少」,不驱动路由。
695
-
696
- /** 任务 key → 分值。**上游可能调**,所以按「未知 key 忽略」处理,不硬断言总数。 */
697
- function onboardingPoints() {
698
- return {
699
- first_message: 500,
700
- pick_skill: 1000,
701
- generate_ppt: 1500,
702
- set_schedule: 1000,
703
- install_skill: 1500,
704
- configure_remote: 1000,
705
- create_soul: 1500,
706
- share_soul: 2000,
707
- }
708
- }
709
-
710
- function onboardingTitles() {
711
- return {
712
- first_message: "发送第一条消息",
713
- pick_skill: "选择一个技能",
714
- generate_ppt: "生成第一份 PPT",
715
- set_schedule: "设置定时任务",
716
- install_skill: "安装一个技能",
717
- configure_remote: "配置远程控制",
718
- create_soul: "创建第一个搭子",
719
- share_soul: "分享搭子给朋友",
720
- }
721
- }
722
-
723
- /** 把上游 `tasks` 归一成只有已知 key 的布尔表(未知 key 丢掉,缺的补 false)。 */
724
- function normalizeTasks(raw) {
725
- const src = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {}
726
- const out = {}
727
- for (const key of Object.keys(onboardingPoints())) out[key] = src[key] === true
728
- return out
729
- }
730
-
731
- /** 已领取的分值合计。 */
732
- function earnedPoints(tasks) {
733
- const points = onboardingPoints()
734
- let sum = 0
735
- for (const [key, value] of Object.entries(points)) if (tasks?.[key] === true) sum += value
736
- return sum
737
- }
738
-
739
- /**
740
- * 未领取的任务,按分值从高到低(先领大的)。
741
- *
742
- * ⚠ 只列**未完成**的:已完成的再 POST 是幂等的,但没必要发请求。
743
- * ⚠ 不要在 usage 的热路径上调这个 —— 它是另一个端点,而 usage 会频繁刷新。
744
- * 只在 checkin(每天一次)和显式领取时读。
745
- */
746
- function pendingTasks(tasks) {
747
- const points = onboardingPoints()
748
- const titles = onboardingTitles()
749
- return Object.entries(points)
750
- .filter(([key]) => tasks?.[key] !== true)
751
- .map(([key, value]) => ({ key, points: value, title: titles[key] }))
752
- .sort((a, b) => b.points - a.points)
753
- }
754
-
755
- /**
756
- * 新手任务作为一个 `aside` 窗口:只说「还能领多少」,不参与路由。
757
- *
758
- * 为什么不参与路由:这笔额度是一次性的,领完即止;把它算进占比会让
759
- * 一个「任务没做完」的账号看起来还有大量额度,从而被优先派活。
760
- */
761
- function onboardingWindow(tasks, total) {
762
- const points = onboardingPoints()
763
- const earned = earnedPoints(tasks)
764
- const cap = Number.isFinite(total) && total > 0 ? total : Object.values(points).reduce((a, b) => a + b, 0)
765
- const left = Math.max(0, cap - earned)
766
- if (left <= 0) return null
767
- const pending = pendingTasks(tasks).length
768
- return {
769
- name: "新手任务",
770
- used: 0,
771
- aside: true,
772
- display: `可领 ${left} 积分(${pending} 项待完成)`,
773
- unit: "积分",
774
- }
775
- }
776
-
777
- // ════════════════════════════════════════════════════════════════════
778
- // ⑩ 邀请码
779
- // ════════════════════════════════════════════════════════════════════
780
- //
781
- // 客户端文案原文(asar 里 `gde()`,常量 `nb = 5e3`):
782
- // 「分享有礼 — 邀请好友双方各获取 5000 积分」
783
- // ⚠ 是 **5000**。别和新手任务里 `share_soul` 的 2000 搞混 —— 那是两笔不同的奖励。
784
- //
785
- // 每个账号**只能兑换一次**(客户端文案:「您可以使用邀请码兑换一次积分」),
786
- // 所以「新账号登录时捎上老账号的邀请码」这件事,天然只在首次有意义。
787
-
788
- /** 邀请码的形态校验:上游实测是 6 位大写字母数字(`E4DPT6` / `FDW3CU`)。 */
789
- function normalizeInviteCode(raw) {
790
- const code = String(raw ?? "").trim().toUpperCase()
791
- if (!code) return ""
792
- if (!/^[A-Z0-9]{4,16}$/.test(code)) return ""
793
- return code
794
- }
795
-
796
- /** 双方各得的积分(客户端常量 `nb = 5e3`)。 */
797
- /**
798
- * 从已有账号的邀请码里挑一个给新账号用。
799
- *
800
- * 规则:
801
- * - 只用 `status === "active"` 且**还有余量**(`usedCount < maxUses`)的码
802
- * - `maxUses <= 0` 视为不限(上游没给上限)
803
- * - 优先**用得最少**的(把额度摊开,而不是把一个码用满)
804
- * - 排除新账号自己的码(不能自己邀请自己)
805
- */
806
- function pickInviteCode(candidates, selfCode) {
807
- const usable = (Array.isArray(candidates) ? candidates : []).filter(
808
- (x) =>
809
- x &&
810
- typeof x.code === "string" &&
811
- x.code &&
812
- x.code !== selfCode &&
813
- (x.status === "" || x.status === "active") &&
814
- (x.maxUses <= 0 || x.usedCount < x.maxUses),
815
- )
816
- if (!usable.length) return undefined
817
- return usable.sort((a, b) => a.usedCount - b.usedCount || a.code.localeCompare(b.code))[0]
818
- }
1
+ // Loomy · 纯函数层(不碰网络、不碰文件,由 index.mjs 经 `_internal` 交给测试)
2
+ //
3
+ // ⚠ magpie 的宿主会把入口模块的**每一个函数导出**都当插件工厂调用
4
+ // (`internal/plugin/host.js` 的 `servers()`)。所以 helper 一律待在这个
5
+ // `_pure` 数据对象里,index.mjs 只导出「一个工厂 + `_internal`」。
6
+ //
7
+ // ════════════════════════════════════════════════════════════════════
8
+ // 三条实测结论,本文件的设计全由此而来(测于 2026-10-26)
9
+ // ════════════════════════════════════════════════════════════════════
10
+ //
11
+ // ① `dailyQuota` **不在任何只读端点上**。
12
+ // 实测 `/api/v1/points/records`、`/api/v1/points/balance`、`/api/v2/points/records`
13
+ // 都只回 `balance` / `dailyBalance` / `availableBalance`;
14
+ // 只有 `POST /api/v1/points/first-login`(写端点,幂等)带
15
+ // `dailyQuota` / `dailyConsumed` / `dailyCycleDate`。
16
+ // ⇒ 上限只能「签到/登录时拿到并记进凭据」,**不许硬编码 5000**(活动会变)。
17
+ //
18
+ // ② 但**今日消耗可以从流水读出来**(降级路径)。
19
+ // V1 `/api/v1/points/records` 每条 debit 带 `consumeSource`(`daily`/`permanent`)
20
+ // 与 `dailyCycleDate`,于是
21
+ // quota ≈ dailyBalance + Σ(本业务日 consumeSource=daily 的扣分)
22
+ // 两号实测:181\*\*\*\*0632(0/0)→ quota=5000、used=100%;
23
+ // 189\*\*\*\*8051 → quota=5000、used=3.96%。
24
+ //
25
+ // ③ 永久池**不该参与路由**。它无周期、无上限,所以 `aside: true` 且
26
+ // **不给 `amount`/`limit`** —— 给了,magpie 就把它当一条真额度算占比,
27
+ // 而「永久池总量 = 剩余」这种假总量正是市场现有插件的缺陷来源。
28
+ //
29
+ // ════════════════════════════════════════════════════════════════════
30
+ // magpie 如何用这些窗口(从二进制里取证的原文,决定本文件所有取舍)
31
+ // ════════════════════════════════════════════════════════════════════
32
+ //
33
+ // const group = (w) => w.used >= 98 ? "spent" : w.used >= 90 ? "low" : "fine"
34
+ // quotaFill(w){ const used = Math.round(to100(w.used)); return quotaLeft ? 100-used : used }
35
+ // quotaCount(w){ if (!(w.limit > 0)) return w.display || ""; … }
36
+ // const counted = q.windows.filter((w) => !w.unlimited); // 卡片主环
37
+ // … else if (w.aside) s = t("{api} only after the others") // aside 排后面
38
+ // smart 路由:spent 的账号 "answers only when nothing else can" // 排最后
39
+ // usage 归一:used: Math.max(0, num(w?.used)) // 缺省即 0
40
+ //
41
+ // ⇒ **一个空号若不画任何参与路由的窗口,就会以 used:0 的姿态排在前面。**
42
+ // 这正是市场插件把蹬空的号顶到路由队首、白撞几百次的根因。
43
+
44
+ import { BEIJING_UTC_OFFSET_MS, PROVIDER } from "./constants.mjs"
45
+
46
+ /** 邀请双方各得的积分(客户端常量 `nb = 5e3`)。 */
47
+ const INVITE_REWARD_POINTS = 5000
48
+
49
+ export const _pure = {
50
+ windowsOf,
51
+ balanceLine,
52
+
53
+ beijingCycleDate,
54
+ beijingResetAt,
55
+ quotaCoversCycle,
56
+ parseCycle,
57
+
58
+ dailyConsumedByCycle,
59
+ mergeQuotaReadings,
60
+
61
+ credentialOf,
62
+ maskPhone,
63
+ normalizePhone,
64
+ normalizeCode,
65
+
66
+ splitRateSuffix,
67
+ isFreeModel,
68
+ parseModels,
69
+ modelShape,
70
+
71
+ prefersTagFormat,
72
+ rewriteImagesToTags,
73
+
74
+ buildEscapedPath,
75
+ signedHeaders,
76
+
77
+ businessCode,
78
+ upstreamMessage,
79
+ isAuthErrorCode,
80
+ ensureSuccess,
81
+ looksLikeInsufficientPoints,
82
+ checkinOutcome,
83
+
84
+ onboardingPoints,
85
+ onboardingTitles,
86
+ normalizeTasks,
87
+ earnedPoints,
88
+ pendingTasks,
89
+ onboardingWindow,
90
+
91
+ normalizeInviteCode,
92
+ pickInviteCode,
93
+ INVITE_REWARD_POINTS,
94
+ }
95
+
96
+ const round = (n) => Math.round(n * 100) / 100
97
+
98
+ /** 任意值读成有限数;非法回 fallback(**不编造 0** 的场景都显式传 undefined)。 */
99
+ function num(value, fallback) {
100
+ const n = typeof value === "string" && value.trim() !== "" ? Number(value.trim()) : Number(value)
101
+ return Number.isFinite(n) ? n : fallback
102
+ }
103
+
104
+ // ════════════════════════════════════════════════════════════════════
105
+ // ① 额度窗口 —— 本插件的核心
106
+ // ════════════════════════════════════════════════════════════════════
107
+
108
+ /**
109
+ * @param pools 只读端点的余额读数 `{permanent, daily, total}`
110
+ * @param quota `{value?, consumed?, cycleDate?, known:boolean, source}`
111
+ * @param now epoch 毫秒
112
+ *
113
+ * 判据表(四条语义各有单测锁死):
114
+ *
115
+ * | 情形 | 今日池 | 永久池 |
116
+ * |---|---|---|
117
+ * | 知道上限、有/无消耗 | `used = 100*consumed/quota`,带 amount/limit/resetsAt | `aside`,只 display |
118
+ * | 上限未知但可从流水推 | 用推导值,正常占比 | 同上 |
119
+ * | 上限未知也推不出 | `aside` + `used:0`,**绝不谎报成满额或假占比** | 同上 |
120
+ * | **两池皆 0(号被蹬空)** | 合成一条 `used:100` 的**参与路由**窗口 | 不画(本来就没) |
121
+ */
122
+ function windowsOf(pools, quota, now) {
123
+ const permanent = Math.max(0, num(pools?.permanent, 0))
124
+ const daily = Math.max(0, num(pools?.daily, 0))
125
+ const total = num(pools?.total, permanent + daily)
126
+ const windows = []
127
+
128
+ // —— 蹬空的号:必须画一条参与路由的满额窗口,让它沉底 ——
129
+ if (total <= 0) {
130
+ windows.push({
131
+ name: "今日积分",
132
+ used: 100,
133
+ display: "积分已耗尽",
134
+ unit: "积分",
135
+ ...(quota?.cycleDate ? { resetsAt: beijingResetAt(quota.cycleDate, now) } : {}),
136
+ })
137
+ return windows
138
+ }
139
+
140
+ const ceiling = num(quota?.value, undefined)
141
+ if (quota?.known && ceiling !== undefined && ceiling > 0) {
142
+ const consumed = num(quota?.consumed, undefined) ?? Math.max(0, ceiling - daily)
143
+ const used = round(Math.max(0, Math.min(100, (100 * Math.max(0, consumed)) / ceiling)))
144
+ windows.push({
145
+ name: "今日积分",
146
+ used,
147
+ display: `${daily} / ${ceiling} 积分`,
148
+ amount: Math.max(0, ceiling - daily),
149
+ limit: ceiling,
150
+ unit: "积分",
151
+ resetsAt: beijingResetAt(quota.cycleDate, now),
152
+ })
153
+ } else {
154
+ // 上限拿不到:说还剩多少,但**不声称占比**(画成 aside 即不参与路由打分)。
155
+ windows.push({
156
+ name: "今日积分",
157
+ used: 0,
158
+ aside: true,
159
+ display: `${daily} 积分剩余(今日上限未知)`,
160
+ unit: "积分",
161
+ ...(quota?.cycleDate ? { resetsAt: beijingResetAt(quota.cycleDate, now) } : {}),
162
+ })
163
+ }
164
+
165
+ if (permanent > 0) {
166
+ windows.push({
167
+ name: "永久积分",
168
+ used: 0,
169
+ aside: true,
170
+ display: `${permanent} 积分`,
171
+ unit: "积分",
172
+ })
173
+ }
174
+
175
+ return windows
176
+ }
177
+
178
+ /** 卡片顶部的总余额行(厂商自己的数,不做二次加工)。 */
179
+ function balanceLine(total) {
180
+ const n = num(total, 0)
181
+ return `${Math.max(0, Math.round(n))} 积分`
182
+ }
183
+
184
+ // ════════════════════════════════════════════════════════════════════
185
+ // ② 业务日(东八区)
186
+ // ════════════════════════════════════════════════════════════════════
187
+
188
+ /** epoch 毫秒 → 东八区业务日 `YYYY-MM-DD`。 */
189
+ function beijingCycleDate(now) {
190
+ return new Date(now + BEIJING_UTC_OFFSET_MS).toISOString().slice(0, 10)
191
+ }
192
+
193
+ /** `YYYY-MM-DD` → 该日 00:00(东八区)的 epoch 毫秒;解析失败回 undefined。 */
194
+ function parseCycle(cycleDate) {
195
+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(cycleDate ?? "").trim())
196
+ if (!m) return undefined
197
+ return Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3])) - BEIJING_UTC_OFFSET_MS
198
+ }
199
+
200
+ /**
201
+ * 该业务日的重置时刻 = 次一北京日的 **00:05**(ISO 字符串)。
202
+ *
203
+ * 留 5 分钟:踩北京 0 点的那次请求不该记到厂商已经关闭的那一天上。
204
+ * `cycleDate` 解析不出来时,退到「now 所在北京日的次日 00:05」。
205
+ * 若算出来已经过去(缓存里的旧日期),再推一天,**不返回过去的时间**
206
+ * —— magpie 拿 resetsAt 算倒计时,给旧值会显示成「已重置」。
207
+ */
208
+ function beijingResetAt(cycleDate, now) {
209
+ const parsed = parseCycle(cycleDate)
210
+ const day = parsed !== undefined ? parsed : beijingMidnightOf(now)
211
+ let reset = day + 86_400_000 + 5 * 60_000
212
+ while (reset <= now) reset += 86_400_000
213
+ return new Date(reset).toISOString()
214
+ }
215
+
216
+ function beijingMidnightOf(now) {
217
+ const d = new Date(now + BEIJING_UTC_OFFSET_MS)
218
+ return Date.UTC(d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate()) - BEIJING_UTC_OFFSET_MS
219
+ }
220
+
221
+ /**
222
+ * 这条 quota 是否还描述**当前**这个北京日。
223
+ *
224
+ * ⚠ 旧上限不能跨日沿用:上限是厂商的(活动会调),而它是**昨天**签到时
225
+ * 拿到的。沿用昨天的数会让今日占比算错,所以日期已过就当作没有,
226
+ * 等今天的签到 —— 宁可降级成「上限未知」,也不要谎报一个错占比。
227
+ * ⚠ 完全没有日期时**保守保留**:`dailyCycleDate` 是厂商字段,可能不下发,
228
+ * 而「永远等不到上限」比「偶尔沿用一次」更接近缺陷。
229
+ */
230
+ function quotaCoversCycle(cycleDate, now) {
231
+ const parsed = parseCycle(cycleDate)
232
+ if (parsed === undefined) return true
233
+ return parsed + 86_400_000 + 5 * 60_000 > now + 60_000
234
+ }
235
+
236
+ // ════════════════════════════════════════════════════════════════════
237
+ // ③ 流水推导 + 读数合并
238
+ // ════════════════════════════════════════════════════════════════════
239
+
240
+ /** 本业务日从 daily 池扣掉的总分(V1 records 才有这两个维度)。 */
241
+ function dailyConsumedByCycle(list, cycleDate) {
242
+ let sum = 0
243
+ for (const row of Array.isArray(list) ? list : []) {
244
+ if (row?.direction !== "debit") continue
245
+ if (row?.consumeSource !== "daily") continue
246
+ const rowCycle = typeof row?.dailyCycleDate === "string" ? row.dailyCycleDate.trim() : ""
247
+ if (cycleDate !== undefined && rowCycle !== "" && rowCycle !== cycleDate) continue
248
+ const n = num(row?.pointsActual, 0)
249
+ if (n > 0) sum += n
250
+ }
251
+ return sum
252
+ }
253
+
254
+ /**
255
+ * 把三个上限来源合成一条 quota。优先序:
256
+ * 签到实测(凭据里记的)> 流水推导 > 未知
257
+ *
258
+ * 每条都过 `quotaCoversCycle`:跨日的旧值一律作废。
259
+ */
260
+ function mergeQuotaReadings(remembered, derived, now) {
261
+ const remValue = num(remembered?.value, undefined)
262
+ if (
263
+ remValue !== undefined &&
264
+ remValue > 0 &&
265
+ quotaCoversCycle(remembered?.cycleDate, now)
266
+ ) {
267
+ return {
268
+ value: remValue,
269
+ cycleDate: remembered?.cycleDate ?? undefined,
270
+ consumed: num(derived?.consumed, undefined),
271
+ known: true,
272
+ source: "checkin",
273
+ }
274
+ }
275
+
276
+ const derValue = num(derived?.value, undefined)
277
+ if (derValue !== undefined && derValue > 0) {
278
+ return {
279
+ value: derValue,
280
+ cycleDate: derived?.cycleDate ?? undefined,
281
+ consumed: num(derived?.consumed, 0),
282
+ known: true,
283
+ source: "derived",
284
+ }
285
+ }
286
+
287
+ return { value: undefined, cycleDate: undefined, consumed: undefined, known: false, source: "unknown" }
288
+ }
289
+
290
+ // ════════════════════════════════════════════════════════════════════
291
+ // ④ 凭据形状
292
+ // ════════════════════════════════════════════════════════════════════
293
+
294
+ /**
295
+ * magpie 交来的 auth 有四种形态,全部要认(sucooer 只认第一种,
296
+ * 于是收到 provider 映射就返回 null → 卡片永远「未登录」):
297
+ *
298
+ * A `{type:"oauth", access, refresh, expires, accountId, uid, phone, dailyQuota…}`
299
+ * B `{type:"oauth", access}`
300
+ * C provider 映射 `{"loomy":{…}, "loomy#xxxx":{…}}`
301
+ * D 裸 session 字符串
302
+ */
303
+ function credentialOf(auth) {
304
+ if (typeof auth === "string") {
305
+ const session = auth.trim()
306
+ return session ? { session, accountId: "", uid: "", phone: "" } : null
307
+ }
308
+ if (!auth || typeof auth !== "object") return null
309
+
310
+ if (typeof auth.access === "string" && auth.access.trim()) return fromRecord(auth)
311
+
312
+ const candidates = [auth[PROVIDER], ...Object.values(auth)].filter(
313
+ (v) => v && typeof v === "object" && typeof v.access === "string" && v.access.trim(),
314
+ )
315
+ return candidates.length ? fromRecord(candidates[0]) : null
316
+ }
317
+
318
+ function fromRecord(rec) {
319
+ return {
320
+ session: String(rec.access).trim(),
321
+ accountId: typeof rec.accountId === "string" ? rec.accountId : "",
322
+ uid: typeof rec.uid === "string" ? rec.uid : "",
323
+ phone: typeof rec.phone === "string" ? rec.phone : "",
324
+ dailyQuota: num(rec.dailyQuota, undefined),
325
+ dailyCycleDate: typeof rec.dailyCycleDate === "string" && rec.dailyCycleDate.trim()
326
+ ? rec.dailyCycleDate.trim()
327
+ : undefined,
328
+ expires: num(rec.expires, undefined),
329
+ }
330
+ }
331
+
332
+ function maskPhone(phone) {
333
+ const chars = [...String(phone ?? "")]
334
+ if (chars.length < 7) return String(phone ?? "")
335
+ return `${chars.slice(0, 3).join("")}****${chars.slice(-4).join("")}`
336
+ }
337
+
338
+ function normalizePhone(raw) {
339
+ const trimmed = String(raw ?? "").replace(/[\s-]/g, "").replace(/^\+86/, "")
340
+ const digits = /^86\d{11}$/.test(trimmed) ? trimmed.slice(2) : trimmed
341
+ if (!/^1[3-9]\d{9}$/.test(digits)) throw Object.assign(new Error("请填写 11 位中国大陆手机号"), { status: 400 })
342
+ return digits
343
+ }
344
+
345
+ function normalizeCode(raw) {
346
+ const trimmed = String(raw ?? "").trim()
347
+ if (!/^\d{6}$/.test(trimmed)) throw Object.assign(new Error("请填写 6 位数字验证码"), { status: 400 })
348
+ return trimmed
349
+ }
350
+
351
+ // ════════════════════════════════════════════════════════════════════
352
+ // ⑤ 模型目录
353
+ // ════════════════════════════════════════════════════════════════════
354
+
355
+ /** 从展示名尾部拆 `(x3.0)` / `(x0.8)` 形态的积分倍率,其余标签原样保留。 */
356
+ function splitRateSuffix(name) {
357
+ const trimmed = String(name ?? "").trimEnd()
358
+ const half = trimmed.endsWith(")")
359
+ const full = trimmed.endsWith(")")
360
+ if (!half && !full) return [trimmed, undefined]
361
+ const open = trimmed.lastIndexOf(half ? "(" : "(")
362
+ if (open < 0) return [trimmed, undefined]
363
+ const inner = trimmed.slice(open + 1, trimmed.length - 1).trim()
364
+ const digits = /^[xX]([\d.]+)$/.exec(inner)?.[1]
365
+ if (!digits || !/\d/.test(digits)) return [trimmed, undefined]
366
+ const body = trimmed.slice(0, open).trimEnd()
367
+ return [body || trimmed, `x${digits}`]
368
+ }
369
+
370
+ /**
371
+ * 这个模型**不花账号的积分**吗?—— magpie 的 `free` 字段。
372
+ *
373
+ * 为什么需要它:magpie 有 `"free"` 这个路由模式(界面叫 *Free first*),
374
+ * 契约原文是「模型供应商不消耗本订阅的额度或积分」。命中它的模型会被
375
+ * **优先派发**,所以标错等于把本该免费的请求算进收费档。
376
+ *
377
+ * ⚠ 判据**不能**只看 `rate === 0`:
378
+ * - 本机实测 `plugin-providers.json` 里 `rate === 0` 的条目 51 条,
379
+ * 其中 `free: true` 只有 13 条 —— 其余是「套餐内不按次计费」,
380
+ * 例如 qoder 的 `ultimate` / `dfmodel`,它们仍消耗套餐额度,不是免费。
381
+ * - Loomy 的 `auto`(自动·均衡)也没有倍率文本,但它会落到别的模型上
382
+ * 去花积分,同样不是免费。
383
+ *
384
+ * Loomy 的判据只有两条,且都来自上游自己的文字:
385
+ * 1. 展示名里明确写了「免费」(如 `Spark-X2.6 正式版(限时免费)(x0.0)`)
386
+ * 2. 倍率文本是 `x0.0`(成本 0 倍,即不扣分)
387
+ * 两者都是上游写在 `name` 里的声明,不是我们从别处推的。
388
+ */
389
+ function isFreeModel(displayName, rate) {
390
+ const name = String(displayName ?? "")
391
+ if (/免费/.test(name)) return true
392
+ return typeof rate === "string" && /^x0(\.0+)?$/i.test(rate.trim())
393
+ }
394
+
395
+ /**
396
+ * 解析 `GET /api/v1/models`(实测 13 条 chat 模型)。
397
+ *
398
+ * ⚠ 只保留 `type === "chat"`:上游还下发 image 型条目,列出来就是
399
+ * 让用户选中一个必然失败的「模型」。
400
+ */
401
+ function parseModels(payload) {
402
+ const rows = Array.isArray(payload?.data) ? payload.data : Array.isArray(payload) ? payload : []
403
+ const out = []
404
+ for (const row of rows) {
405
+ const id = typeof row?.id === "string" ? row.id.trim() : ""
406
+ if (!id) continue
407
+ if (typeof row?.type === "string" && row.type !== "chat") continue
408
+
409
+ const caps = row?.capabilities && typeof row.capabilities === "object" ? row.capabilities : undefined
410
+ const [name, rate] = splitRateSuffix(typeof row?.name === "string" && row.name.trim() ? row.name : id)
411
+ const efforts = Array.isArray(row?.reasoning_efforts)
412
+ ? row.reasoning_efforts.filter((e) => typeof e === "string" && e.trim() !== "")
413
+ : []
414
+
415
+ out.push({
416
+ id,
417
+ name: name || id,
418
+ context: positive(row?.context_length) ?? positive(row?.context_window) ?? positive(row?.max_input_tokens),
419
+ output: positive(row?.max_output_tokens) ?? positive(row?.max_completion_tokens),
420
+ reasoning: caps?.reasoning === true || efforts.length > 0,
421
+ toolCall: caps?.function_calling !== false,
422
+ images: caps?.vision === true || hasModality(caps?.input_modalities, "image"),
423
+ video: hasModality(caps?.input_modalities, "video"),
424
+ efforts,
425
+ defaultEffort:
426
+ typeof row?.default_reasoning_effort === "string" ? row.default_reasoning_effort : undefined,
427
+ rate,
428
+ free: isFreeModel(row?.name, rate),
429
+ })
430
+ }
431
+ return out
432
+ }
433
+
434
+ function hasModality(list, want) {
435
+ return Array.isArray(list) && list.some((v) => typeof v === "string" && v.toLowerCase() === want)
436
+ }
437
+
438
+ function positive(v) {
439
+ const n = Number(v)
440
+ return Number.isFinite(n) && n > 0 ? n : undefined
441
+ }
442
+
443
+ /**
444
+ * 上游模型 → magpie 的模型条目。
445
+ *
446
+ * ⚠ `limit.context` 会被 magpie 转给 agent,决定它何时压缩对话;更要紧的是
447
+ * **路由组按组内最大值算窗口** —— 填小会把整组拉低(本工作区踩过:
448
+ * 插件声明 131072 而卡片填 1M,同一个模型两条路径报两个值)。
449
+ * Loomy 的 chat 模型上游实测就是 1,048,576,**原样上报,不二次收缩**。
450
+ */
451
+ function modelShape(m, base = {}) {
452
+ const efforts = m.efforts ?? []
453
+ const shape = {
454
+ ...base,
455
+ id: m.id,
456
+ name: m.name || m.id,
457
+ api: { id: m.id, url: base?.api?.url, npm: base?.api?.npm },
458
+ status: "active",
459
+ limit: {
460
+ context: m.context ?? base?.limit?.context ?? 0,
461
+ output: m.output ?? base?.limit?.output ?? 0,
462
+ },
463
+ capabilities: {
464
+ temperature: true,
465
+ reasoning: !!m.reasoning,
466
+ attachment: !!m.images,
467
+ toolcall: m.toolCall !== false,
468
+ input: { text: true, image: !!m.images, audio: false, video: !!m.video, pdf: false },
469
+ output: { text: true, image: false, audio: false, video: false, pdf: false },
470
+ interleaved: false,
471
+ },
472
+ variants: m.reasoning
473
+ ? Object.fromEntries((efforts.length ? efforts : ["low", "medium", "high"]).map((e) => [e, {}]))
474
+ : {},
475
+ }
476
+ if (m.rate) shape.rate = m.rate
477
+ // ⚠ free 只由模型自己的声明决定(见 isFreeModel 的判据),
478
+ // **不要**在这里按「有没有 rate」反推 —— 那样 `x0.0` 会被误判成收费。
479
+ shape.free = m.free === true
480
+ return shape
481
+ }
482
+
483
+ // ════════════════════════════════════════════════════════════════════
484
+ // ⑥ 图片格式适配
485
+ // ════════════════════════════════════════════════════════════════════
486
+
487
+ /**
488
+ * deepseek 系模型只认 `<image_base64>` 标记;喂标准 `image_url` data URI
489
+ * 会被上游当成截断的 base64 文本读(agent2api loomy/images.rs 的实测结论)。
490
+ * 宁可不转,不能转错 —— 非 deepseek 一律不动。
491
+ */
492
+ function prefersTagFormat(modelId) {
493
+ return String(modelId ?? "").toLowerCase().includes("deepseek")
494
+ }
495
+
496
+ function tagOfBlock(block) {
497
+ if (!block || block.type !== "image_url") return null
498
+ const url = block?.image_url?.url
499
+ if (typeof url !== "string" || !url.startsWith("data:")) return null
500
+ const comma = url.indexOf(",")
501
+ if (comma < 0) return null
502
+ return `<image_base64>${url.slice(comma + 1)}</image_base64>`
503
+ }
504
+
505
+ /** 把 image 块并入相邻 text 块(上游实测认可的形态)。 */
506
+ function rewriteImagesToTags(body) {
507
+ const messages = Array.isArray(body?.messages) ? body.messages : null
508
+ if (!messages) return body
509
+ const convertible = messages.some(
510
+ (msg) => Array.isArray(msg?.content) && msg.content.some((b) => tagOfBlock(b) !== null),
511
+ )
512
+ if (!convertible) return body
513
+
514
+ const next = JSON.parse(JSON.stringify(body))
515
+ for (const message of next.messages) {
516
+ if (!Array.isArray(message?.content)) continue
517
+ const content = message.content
518
+ for (let index = content.length - 1; index >= 0; index--) {
519
+ const tag = tagOfBlock(content[index])
520
+ if (tag === null) continue
521
+ content.splice(index, 1)
522
+ const previous = index > 0 ? content[index - 1] : null
523
+ if (previous?.type === "text" && typeof previous.text === "string") {
524
+ previous.text += `\n${tag}`
525
+ } else if (content[index]?.type === "text" && typeof content[index].text === "string") {
526
+ content[index].text = `${tag}\n${content[index].text}`
527
+ } else {
528
+ content.splice(index, 0, { type: "text", text: tag })
529
+ }
530
+ }
531
+ }
532
+ return next
533
+ }
534
+
535
+ // ════════════════════════════════════════════════════════════════════
536
+ // ⑦ 账号接口签名(HMAC-SHA1,复刻客户端 generateSignature)
537
+ // ════════════════════════════════════════════════════════════════════
538
+
539
+ /** 路径分段转义。当前账号接口只含字母与 `/`,仍实现完整规则以免将来静默出错。 */
540
+ function buildEscapedPath(p) {
541
+ let clean = String(p ?? "")
542
+ if (!clean.startsWith("/")) clean = `/${clean}`
543
+ if (clean.length > 1 && clean.endsWith("/")) clean = clean.slice(0, -1)
544
+ return clean
545
+ .split("/")
546
+ .map((segment) => {
547
+ let out = ""
548
+ for (const byte of new TextEncoder().encode(segment)) {
549
+ const ch = String.fromCharCode(byte)
550
+ out += /[A-Za-z0-9\-_.~]/.test(ch) ? ch : `%${byte.toString(16).toUpperCase().padStart(2, "0")}`
551
+ }
552
+ return out
553
+ })
554
+ .join("/")
555
+ }
556
+
557
+ /**
558
+ * 待签串 9 段 `\n` 连接:
559
+ * METHOD\n ESCAPED_PATH\n ""(query)\n CONTENT_MD5\n content-type\n
560
+ * DATE(UTC)\n NONCE\n ""(signed headers)\n ""(canonicalized headers)
561
+ *
562
+ * 加密原语由调用方注入(`crypto.mjs`),这样本文件保持纯函数、可离线测。
563
+ */
564
+ function signedHeaders(method, path, bodyString, secrets) {
565
+ const md5 = bodyString ? secrets.md5Base64(bodyString) : ""
566
+ const date = secrets.utcnow()
567
+ const nonce = secrets.uuid()
568
+ const stringToSign = [
569
+ String(method).toUpperCase(),
570
+ buildEscapedPath(path),
571
+ "",
572
+ md5,
573
+ "application/json",
574
+ date,
575
+ nonce,
576
+ "",
577
+ "",
578
+ ].join("\n")
579
+ const signature = secrets.hmacSha1Base64(secrets.accessKeySecret, stringToSign)
580
+ const headers = {
581
+ Authorization: `account ${secrets.accessKeyId}:${signature}`,
582
+ Date: date,
583
+ Nonce: nonce,
584
+ }
585
+ if (md5) headers["Content-MD5"] = md5
586
+ return headers
587
+ }
588
+
589
+ // ════════════════════════════════════════════════════════════════════
590
+ // ⑧ 信封、错误归类、签到 outcome
591
+ // ════════════════════════════════════════════════════════════════════
592
+
593
+ function businessCode(payload) {
594
+ return typeof payload?.code === "string" ? payload.code.trim() : ""
595
+ }
596
+
597
+ function upstreamMessage(payload) {
598
+ const text = payload?.desc ?? payload?.message ?? payload?.msg
599
+ return typeof text === "string" ? text.trim() : ""
600
+ }
601
+
602
+ function isAuthErrorCode(code) {
603
+ return ["020002", "100002"].includes(code)
604
+ }
605
+
606
+ /** 业务码非 000000 时抛;登录态失效归 401 并带 `signIn:"expired"`(magpie 据此标记账号)。 */
607
+ function ensureSuccess(payload, what) {
608
+ const code = businessCode(payload)
609
+ if (code === "000000") return
610
+ const message = upstreamMessage(payload)
611
+ const detail = message ? `${what}:${message}` : `${what}失败(上游 code=${code || "无"})`
612
+ if (isAuthErrorCode(code)) throw Object.assign(new Error(detail), { signIn: "expired", status: 401 })
613
+ throw Object.assign(new Error(detail), { status: 502 })
614
+ }
615
+
616
+ /**
617
+ * 「积分余额不足」判据 —— 必须**窄**。
618
+ *
619
+ * 上游是 HTTP 400 + 中文文案,不是结构化额度错误;泛词(quota/balance/不足)
620
+ * 会误伤模型正文里恰好讨论「余额」的内容。
621
+ */
622
+ function looksLikeInsufficientPoints(text) {
623
+ const t = String(text ?? "")
624
+ return /积分余额不足|积分不足|余额不足,请获取积分|请获取积分后再试/.test(t)
625
+ }
626
+
627
+ /**
628
+ * 把签到结果映射成 magpie 的 outcome。
629
+ *
630
+ * ⚠⚠ 这是市场插件正在犯的那个错:契约的合法值只有
631
+ * `claimed / done / ineligible / inactive / captcha / failed`
632
+ * (`magpie-plugin-contract-full.txt` 的 `checkinOutcomes`)。
633
+ * sucooer 成功时返回 `{outcome:"success"}` —— 不在表里,
634
+ * magpie 一律归为 `failed` 但**保留 message**,于是用户看到
635
+ * 「签到失败 · 每日赠送积分已刷新」这种自相矛盾的行。
636
+ *
637
+ * 幂等判据是响应体的 `alreadyProcessed`(重复调用同样回 HTTP 200),
638
+ * 所以「今天已领」必须是 `done` 而不是 `claimed` —— 后者会让用户
639
+ * 以为每天都真的加了额度。
640
+ */
641
+ function checkinOutcome(raw) {
642
+ if (raw?.ok === false) {
643
+ return { outcome: "failed", message: raw.message || "每日额度刷新失败" }
644
+ }
645
+ if (raw?.alreadyProcessed === true) {
646
+ const quota = num(raw?.dailyQuota, undefined)
647
+ const balance = num(raw?.dailyBalance, undefined)
648
+ return {
649
+ outcome: "done",
650
+ message: quota === undefined
651
+ ? "今日额度已刷新"
652
+ : `今日额度已刷新(${balance ?? 0}/${quota} 积分)`,
653
+ }
654
+ }
655
+ // 首次处理:本次新发放的额度 = quota - consumed(两个都缺时不编造)
656
+ const quota = num(raw?.dailyQuota, undefined)
657
+ const consumed = num(raw?.dailyConsumed, undefined)
658
+ const balance = num(raw?.dailyBalance, undefined)
659
+ const credit =
660
+ quota !== undefined && consumed !== undefined
661
+ ? Math.max(0, quota - consumed)
662
+ : (balance ?? quota ?? 0)
663
+ return {
664
+ outcome: "claimed",
665
+ credit,
666
+ message: `每日赠送额度已刷新(+${credit} 积分)`,
667
+ }
668
+ }
669
+
670
+ // ════════════════════════════════════════════════════════════════════
671
+ // ⑨ 新手任务(onboarding)—— 一次性可领的 1 万分
672
+ // ════════════════════════════════════════════════════════════════════
673
+ //
674
+ // Loomy 把「新手任务」的奖励做成一笔**可主动领取**的积分,总计 10,000 分:
675
+ //
676
+ // | key | 任务 | 分值 |
677
+ // |---|---|---|
678
+ // | first_message | 发送你的第一条消息 | 500 |
679
+ // | pick_skill | 试试选择一个技能 | 1000 |
680
+ // | generate_ppt | 生成第一份 PPT | 1500 |
681
+ // | set_schedule | 设置定时任务 | 1000 |
682
+ // | install_skill | 在技能广场安装一个技能 | 1500 |
683
+ // | configure_remote | 配置远程控制 | 1000 |
684
+ // | create_soul | 创建你的第一个搭子 | 1500 |
685
+ // | share_soul | 把搭子分享给朋友 | 2000 |
686
+ //
687
+ // 端点:`GET /api/v1/onboarding/tasks`(只读)与
688
+ // `POST /api/v1/onboarding/tasks/complete {key}`(幂等写)。
689
+ // 实测(2026-10-26):两个账号都能读,`first_message` 已完成的那个账号
690
+ // 流水里确实有「新手任务-发送第一条消息 +500」的 credit 记录 —— 说明
691
+ // 领取是真到账的,不是展示用的假数字。
692
+ //
693
+ // ⚠ 这笔钱**不参与每日池**,也不该拿它去算占比(它是一次性的,
694
+ // 领完就没了)。所以只作为 `aside` 窗口展示「还能领多少」,不驱动路由。
695
+
696
+ /** 任务 key → 分值。**上游可能调**,所以按「未知 key 忽略」处理,不硬断言总数。 */
697
+ function onboardingPoints() {
698
+ return {
699
+ first_message: 500,
700
+ pick_skill: 1000,
701
+ generate_ppt: 1500,
702
+ set_schedule: 1000,
703
+ install_skill: 1500,
704
+ configure_remote: 1000,
705
+ create_soul: 1500,
706
+ share_soul: 2000,
707
+ }
708
+ }
709
+
710
+ function onboardingTitles() {
711
+ return {
712
+ first_message: "发送第一条消息",
713
+ pick_skill: "选择一个技能",
714
+ generate_ppt: "生成第一份 PPT",
715
+ set_schedule: "设置定时任务",
716
+ install_skill: "安装一个技能",
717
+ configure_remote: "配置远程控制",
718
+ create_soul: "创建第一个搭子",
719
+ share_soul: "分享搭子给朋友",
720
+ }
721
+ }
722
+
723
+ /** 把上游 `tasks` 归一成只有已知 key 的布尔表(未知 key 丢掉,缺的补 false)。 */
724
+ function normalizeTasks(raw) {
725
+ const src = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {}
726
+ const out = {}
727
+ for (const key of Object.keys(onboardingPoints())) out[key] = src[key] === true
728
+ return out
729
+ }
730
+
731
+ /** 已领取的分值合计。 */
732
+ function earnedPoints(tasks) {
733
+ const points = onboardingPoints()
734
+ let sum = 0
735
+ for (const [key, value] of Object.entries(points)) if (tasks?.[key] === true) sum += value
736
+ return sum
737
+ }
738
+
739
+ /**
740
+ * 未领取的任务,按分值从高到低(先领大的)。
741
+ *
742
+ * ⚠ 只列**未完成**的:已完成的再 POST 是幂等的,但没必要发请求。
743
+ * ⚠ 不要在 usage 的热路径上调这个 —— 它是另一个端点,而 usage 会频繁刷新。
744
+ * 只在 checkin(每天一次)和显式领取时读。
745
+ */
746
+ function pendingTasks(tasks) {
747
+ const points = onboardingPoints()
748
+ const titles = onboardingTitles()
749
+ return Object.entries(points)
750
+ .filter(([key]) => tasks?.[key] !== true)
751
+ .map(([key, value]) => ({ key, points: value, title: titles[key] }))
752
+ .sort((a, b) => b.points - a.points)
753
+ }
754
+
755
+ /**
756
+ * 新手任务作为一个 `aside` 窗口:只说「还能领多少」,不参与路由。
757
+ *
758
+ * 为什么不参与路由:这笔额度是一次性的,领完即止;把它算进占比会让
759
+ * 一个「任务没做完」的账号看起来还有大量额度,从而被优先派活。
760
+ */
761
+ function onboardingWindow(tasks, total) {
762
+ const points = onboardingPoints()
763
+ const earned = earnedPoints(tasks)
764
+ const cap = Number.isFinite(total) && total > 0 ? total : Object.values(points).reduce((a, b) => a + b, 0)
765
+ const left = Math.max(0, cap - earned)
766
+ if (left <= 0) return null
767
+ const pending = pendingTasks(tasks).length
768
+ return {
769
+ name: "新手任务",
770
+ used: 0,
771
+ aside: true,
772
+ display: `可领 ${left} 积分(${pending} 项待完成)`,
773
+ unit: "积分",
774
+ }
775
+ }
776
+
777
+ // ════════════════════════════════════════════════════════════════════
778
+ // ⑩ 邀请码
779
+ // ════════════════════════════════════════════════════════════════════
780
+ //
781
+ // 客户端文案原文(asar 里 `gde()`,常量 `nb = 5e3`):
782
+ // 「分享有礼 — 邀请好友双方各获取 5000 积分」
783
+ // ⚠ 是 **5000**。别和新手任务里 `share_soul` 的 2000 搞混 —— 那是两笔不同的奖励。
784
+ //
785
+ // 每个账号**只能兑换一次**(客户端文案:「您可以使用邀请码兑换一次积分」),
786
+ // 所以「新账号登录时捎上老账号的邀请码」这件事,天然只在首次有意义。
787
+
788
+ /** 邀请码的形态校验:上游实测是 6 位大写字母数字(`E4DPT6` / `FDW3CU`)。 */
789
+ function normalizeInviteCode(raw) {
790
+ const code = String(raw ?? "").trim().toUpperCase()
791
+ if (!code) return ""
792
+ if (!/^[A-Z0-9]{4,16}$/.test(code)) return ""
793
+ return code
794
+ }
795
+
796
+ /** 双方各得的积分(客户端常量 `nb = 5e3`)。 */
797
+ /**
798
+ * 从已有账号的邀请码里挑一个给新账号用。
799
+ *
800
+ * 规则:
801
+ * - 只用 `status === "active"` 且**还有余量**(`usedCount < maxUses`)的码
802
+ * - `maxUses <= 0` 视为不限(上游没给上限)
803
+ * - 优先**用得最少**的(把额度摊开,而不是把一个码用满)
804
+ * - 排除新账号自己的码(不能自己邀请自己)
805
+ */
806
+ function pickInviteCode(candidates, selfCode) {
807
+ const usable = (Array.isArray(candidates) ? candidates : []).filter(
808
+ (x) =>
809
+ x &&
810
+ typeof x.code === "string" &&
811
+ x.code &&
812
+ x.code !== selfCode &&
813
+ (x.status === "" || x.status === "active") &&
814
+ (x.maxUses <= 0 || x.usedCount < x.maxUses),
815
+ )
816
+ if (!usable.length) return undefined
817
+ return usable.sort((a, b) => a.usedCount - b.usedCount || a.code.localeCompare(b.code))[0]
818
+ }