@jixing475/magpie-marvis 0.0.0-stage → 0.3.0

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.
Files changed (79) hide show
  1. package/AGENTS.md +255 -0
  2. package/CHANGELOG.md +726 -0
  3. package/CHECKLIST.md +161 -0
  4. package/CONTRIBUTING.md +83 -0
  5. package/GUIDE.md +275 -0
  6. package/HOOKS.md +1333 -0
  7. package/LICENSE +21 -0
  8. package/MULTI-PROVIDER.md +414 -0
  9. package/NOTICE.md +46 -0
  10. package/OFFICIAL-SOURCES.md +142 -0
  11. package/README-TEMPLATE.md +271 -0
  12. package/README.md +300 -3
  13. package/SCORING.md +151 -0
  14. package/UPDATING.md +660 -0
  15. package/examples/split/README.md +66 -0
  16. package/examples/split/index.mjs +75 -0
  17. package/examples/split/src/hooks/config.mjs +18 -0
  18. package/examples/split/src/hooks/models.mjs +49 -0
  19. package/examples/split/src/hooks/usage.mjs +55 -0
  20. package/extract-contract.py +56 -0
  21. package/index.mjs +48 -0
  22. package/package.json +95 -4
  23. package/panel/first-line.css +112 -0
  24. package/panel/first-line.html +37 -0
  25. package/panel/first-line.js +137 -0
  26. package/registry-entry.json +11 -0
  27. package/scripts/check-magpie-stable.mjs +109 -0
  28. package/scripts/check-maintenance.mjs +146 -0
  29. package/scripts/check.mjs +521 -0
  30. package/scripts/cli.mjs +54 -0
  31. package/scripts/contract-diff.mjs +112 -0
  32. package/scripts/create.mjs +270 -0
  33. package/scripts/npm-name.mjs +19 -0
  34. package/scripts/probe-served-model.mjs +172 -0
  35. package/scripts/probe-vision.mjs +173 -0
  36. package/scripts/publish-npm.mjs +44 -0
  37. package/scripts/release.mjs +442 -0
  38. package/scripts/score.mjs +280 -0
  39. package/src/account-name.mjs +145 -0
  40. package/src/auth.mjs +27 -0
  41. package/src/context.mjs +369 -0
  42. package/src/hooks/config.mjs +236 -0
  43. package/src/hooks/loader.mjs +593 -0
  44. package/src/hooks/methods.mjs +398 -0
  45. package/src/hooks/models.mjs +25 -0
  46. package/src/hooks/refresh.mjs +149 -0
  47. package/src/hooks/usage.mjs +117 -0
  48. package/src/marvis/beacon-mac.mjs +213 -0
  49. package/src/marvis/beacon-shim.mjs +143 -0
  50. package/src/marvis/browser.mjs +598 -0
  51. package/src/marvis/desktop-mac.mjs +232 -0
  52. package/src/marvis/desktop.mjs +273 -0
  53. package/src/marvis/device.mjs +85 -0
  54. package/src/marvis/expiry.mjs +60 -0
  55. package/src/marvis/fingerprint.mjs +168 -0
  56. package/src/marvis/images.mjs +230 -0
  57. package/src/marvis/login.mjs +512 -0
  58. package/src/marvis/profile.mjs +113 -0
  59. package/src/marvis/protocol.mjs +160 -0
  60. package/src/marvis/tool-schema.mjs +97 -0
  61. package/src/quota.mjs +212 -0
  62. package/src/refresh-lock.mjs +115 -0
  63. package/tests/device-registry.test.mjs +48 -0
  64. package/tests/e2e-live.test.mjs +120 -0
  65. package/tests/image-input.test.mjs +314 -0
  66. package/tests/legacy-model-config.test.mjs +349 -0
  67. package/tests/legacy-model-loader.test.mjs +306 -0
  68. package/tests/loader-model-support.test.mjs +823 -0
  69. package/tests/manual-paste-login.test.mjs +228 -0
  70. package/tests/model-alias.test.mjs +59 -0
  71. package/tests/model-catalog-support.test.mjs +241 -0
  72. package/tests/mount.test.mjs +259 -0
  73. package/tests/oauth-exchange.test.mjs +362 -0
  74. package/tests/panel-manifest.test.mjs +73 -0
  75. package/tests/plugin-options.test.mjs +100 -0
  76. package/tests/profile.test.mjs +96 -0
  77. package/tests/refresh-contract.test.mjs +318 -0
  78. package/tests/request-identity.test.mjs +18 -0
  79. package/tests/tool-schema.test.mjs +66 -0
@@ -0,0 +1,160 @@
1
+ // Marvis 上游协议 —— 请求头与签名
2
+ //
3
+ // 两个上游,两套鉴权,**不能混**:
4
+ // /v1/chat/completions 模型网关 → 只要 Ual-Access-Openid/Access-Token/Login-Type/Guid
5
+ // + Ual-Access-MarvisExt(uskey 指纹)。**不要**签名。
6
+ // /v3/* 业务接口 → 要 md5(query + timestamp + accessKey + nonce) 签名。
7
+ //
8
+ // 把签名头加到模型网关上是**错**的:会从 403 风控变成 401 登录态过期(实测)。
9
+ //
10
+ // ⚠ 模型网关的 UA 必须是 `AsyncOpenAI/Python 2.32.0`(Marvis agent 自己的)。
11
+ // 换成浏览器 UA 或 magpie 自己的 UA 都会被风控拦(4100404)。
12
+
13
+ import { createHash, randomUUID } from "node:crypto"
14
+ import { ACCESS_KEY, BUSINESS_ID, CLIENT, BROWSER_UA, BASE } from "../context.mjs"
15
+ import { uskeyOf, qimei36 } from "./fingerprint.mjs"
16
+
17
+ function hex32() {
18
+ return randomUUID().replace(/-/g, "")
19
+ }
20
+
21
+ /**
22
+ * 本次请求的 Marvis 上下文。uskey 的 bus_info 和 Marvis-* 头必须用同一份 id。
23
+ *
24
+ * @param {{ openid?: string, loginType?: string }} acct
25
+ * @param {{ scene?: string, agentTag?: string, model?: string, conversationId?: string, responseId?: string, nonce?: string }} [opts]
26
+ */
27
+ export function requestIdentity(acct, opts = {}) {
28
+ const agentTag = opts.agentTag || "main"
29
+ const scene = opts.scene || "agent_chat"
30
+ const model = opts.model || "main-auto"
31
+ const conversationId = opts.conversationId || `conv_${hex32()}`
32
+ const responseId = opts.responseId || `resp_${hex32()}`
33
+ const nonce = opts.nonce || randomUUID()
34
+ const loginType = String(opts.loginType || acct?.loginType || "1")
35
+ const busInfo = [
36
+ `marvisAgentTag=${agentTag}`,
37
+ `marvisConversationID=${conversationId}`,
38
+ `marvisResponseID=${responseId}`,
39
+ `marvisScene=${scene}`,
40
+ `model=${model}`,
41
+ `nonce=${nonce}`,
42
+ `originOpenID=${acct?.openid ?? ""}`,
43
+ ].join("&")
44
+ return { agentTag, scene, model, conversationId, responseId, nonce, loginType, busInfo }
45
+ }
46
+
47
+ /**
48
+ * 模型网关要求的 `Ual-Access-MarvisExt`。uskey 按 bus_info 现签。
49
+ *
50
+ * @param {{ guid?: string, openid?: string, clientVersion?: string, loginType?: string }} acct
51
+ * @param {{ busInfo: string, nonce: string, loginType?: string }} identity
52
+ * @returns {Promise<string>}
53
+ */
54
+ export async function marvisExt(acct, identity) {
55
+ const uskey = await uskeyOf(acct, identity)
56
+ const qimei = qimei36()
57
+ // 设备形态跟随真实系统:在 Mac 上用 Windows 的身份反而更容易被关联判定
58
+ const onMac = process.platform === "darwin"
59
+ return JSON.stringify({
60
+ ...(qimei ? { qimei36: qimei } : {}),
61
+ osVersion:
62
+ process.env.MARVIS_OS_VERSION ||
63
+ (onMac ? "Mac OS X 15.5" : "Windows-10-10.0.26100"),
64
+ guid: acct.guid ?? "",
65
+ uskey,
66
+ nonce: identity.nonce,
67
+ reqScene: 1,
68
+ taskType: "user",
69
+ clientVersion: acct.clientVersion || process.env.MARVIS_CLIENT_VERSION || "1.60.3400.795",
70
+ clientPlatform: process.env.MARVIS_CLIENT_PLATFORM || (onMac ? "Mac" : "Windows"),
71
+ clientPlatformVersion: process.env.MARVIS_CLIENT_PLATFORM_VERSION || "1.60.3400.35",
72
+ isIoa: false,
73
+ })
74
+ }
75
+
76
+ /**
77
+ * 模型网关的完整请求头。
78
+ *
79
+ * @param {{ openid: string, accessToken: string, guid: string, loginType?: string }} acct
80
+ * @param {{ scene?: string, agentTag?: string, model?: string, conversationId?: string, responseId?: string }} [opts]
81
+ * @returns {Promise<Record<string, string>>}
82
+ */
83
+ export async function llmHeaders(acct, opts = {}) {
84
+ const identity = requestIdentity(acct, opts)
85
+ const ext = await marvisExt(acct, identity)
86
+ return {
87
+ Accept: "application/json",
88
+ "Content-Type": "application/json",
89
+ "User-Agent": CLIENT,
90
+ "X-Stainless-Lang": "python",
91
+ "X-Stainless-Package-Version": "2.32.0",
92
+ "X-Stainless-OS": "Windows",
93
+ "X-Stainless-Arch": "other:amd64",
94
+ "X-Stainless-Runtime": "CPython",
95
+ "X-Stainless-Runtime-Version": "3.11.9",
96
+ "X-Stainless-Async": "async:asyncio",
97
+ "X-Stainless-Raw-Response": "true",
98
+ "X-Stainless-Read-Timeout": "600.0",
99
+ "X-Stainless-Retry-Count": "0",
100
+ Authorization: "Bearer placeholder",
101
+ "Ual-Access-Openid": acct.openid,
102
+ "Ual-Access-Access-Token": acct.accessToken,
103
+ "Ual-Access-Login-Type": identity.loginType,
104
+ "Ual-Access-Guid": acct.guid ?? "",
105
+ "Ual-Access-Requestid": identity.responseId,
106
+ "Marvis-AgentTag": identity.agentTag,
107
+ "Marvis-Conversation-ID": identity.conversationId,
108
+ "Marvis-Response-ID": identity.responseId,
109
+ "Marvis-Scene": identity.scene,
110
+ "Marvis-Model-Level": "1",
111
+ "Marvis-Protocol-Version": "1000",
112
+ "X-Device-GUID": acct.guid ?? "",
113
+ "Ual-Access-MarvisExt": ext,
114
+ }
115
+ }
116
+
117
+ /**
118
+ * `/v3/*` 业务接口的签名。
119
+ *
120
+ * 逆向自 Marvis 主进程:`md5(query + timestamp + accessKey + nonce)`,
121
+ * accessKey 硬编码在渲染层(`fpzkeTlcGLVP37qiOWd29MyaOqaJYxMi`)。
122
+ * 实测重放真实请求返回 200。
123
+ *
124
+ * @param {string} query 签名原文 —— GET 是查询串(不含 `?`),POST 是 JSON body
125
+ * @param {string} timestamp 毫秒时间戳
126
+ * @param {string} nonce 4 位随机数
127
+ * @returns {string} 32 位小写 hex
128
+ */
129
+ export function ualSignature(query, timestamp, nonce) {
130
+ return createHash("md5").update(query + timestamp + ACCESS_KEY + nonce).digest("hex")
131
+ }
132
+
133
+ /**
134
+ * `/v3/*` 业务接口的完整请求头。
135
+ *
136
+ * @param {{ openid: string, accessToken: string, guid: string, loginType?: string }} acct
137
+ * @param {{ query: string, method?: string }} opts
138
+ * @returns {Record<string, string>}
139
+ */
140
+ export function businessHeaders(acct, { query, method = "GET" }) {
141
+ const timestamp = String(Date.now())
142
+ const nonce = String(1000 + Math.floor(Math.random() * 9000))
143
+ return {
144
+ Accept: "*/*",
145
+ "Content-Type": "application/json; charset=utf-8",
146
+ "User-Agent": BROWSER_UA,
147
+ "Ual-Access-Businessid": BUSINESS_ID,
148
+ "Ual-Access-Timestamp": timestamp,
149
+ "Ual-Access-Nonce": nonce,
150
+ "Ual-Access-Signature": ualSignature(query, timestamp, nonce),
151
+ "Ual-Access-Guid": acct.guid ?? "",
152
+ "Ual-Access-Access-Token": acct.accessToken,
153
+ "Ual-Access-Login-Type": acct.loginType ?? "1",
154
+ "Ual-Access-Openid": acct.openid,
155
+ ...(method === "POST" ? {} : {}),
156
+ }
157
+ }
158
+
159
+ /** 模型网关地址 */
160
+ export const CHAT_URL = `${BASE}/v1/chat/completions`
@@ -0,0 +1,97 @@
1
+ // tool schema 兼容 —— Marvis 的严格校验
2
+ //
3
+ // 实测(DSH 真实请求,57 个工具):只要有一个 `function.parameters` 缺少顶层
4
+ // `type: "object"`,`/v1/chat/completions` 就返回
5
+ // `{"code":3000101,"msg":"invalid parameter"}`
6
+ // 而 OpenAI 兼容端通常容忍省略 type。补上 type 后,`additionalProperties:false`、
7
+ // 57 个工具、reasoning_effort、流式全部通过(实测 200)。
8
+ //
9
+ // 只补缺失的 `type`,不动 `properties` / `required` / `additionalProperties`。
10
+
11
+ /**
12
+ * 递归补齐对象 schema 的 `type: "object"`。
13
+ *
14
+ * @param {any} schema
15
+ * @returns {any} 原对象(没有改动时)或新对象
16
+ */
17
+ export function withObjectType(schema) {
18
+ if (!schema || typeof schema !== "object") return schema
19
+ if (Array.isArray(schema)) {
20
+ let changed = false
21
+ const out = schema.map((x) => {
22
+ const y = withObjectType(x)
23
+ if (y !== x) changed = true
24
+ return y
25
+ })
26
+ return changed ? out : schema
27
+ }
28
+
29
+ let changed = false
30
+ /** @type {Record<string, any>} */
31
+ const out = { ...schema }
32
+ if (out.properties && typeof out.properties === "object" && !out.type) {
33
+ out.type = "object"
34
+ changed = true
35
+ }
36
+
37
+ for (const key of ["properties", "patternProperties"]) {
38
+ const map = out[key]
39
+ if (!map || typeof map !== "object" || Array.isArray(map)) continue
40
+ /** @type {Record<string, any>} */
41
+ const next = {}
42
+ let mapChanged = false
43
+ for (const [name, child] of Object.entries(map)) {
44
+ const y = withObjectType(child)
45
+ next[name] = y
46
+ if (y !== child) mapChanged = true
47
+ }
48
+ if (mapChanged) {
49
+ out[key] = next
50
+ changed = true
51
+ }
52
+ }
53
+
54
+ for (const key of ["items", "additionalProperties", "not", "if", "then", "else"]) {
55
+ if (out[key] && typeof out[key] === "object") {
56
+ const y = withObjectType(out[key])
57
+ if (y !== out[key]) {
58
+ out[key] = y
59
+ changed = true
60
+ }
61
+ }
62
+ }
63
+
64
+ for (const key of ["anyOf", "oneOf", "allOf", "prefixItems"]) {
65
+ if (Array.isArray(out[key])) {
66
+ const y = withObjectType(out[key])
67
+ if (y !== out[key]) {
68
+ out[key] = y
69
+ changed = true
70
+ }
71
+ }
72
+ }
73
+
74
+ return changed ? out : schema
75
+ }
76
+
77
+ /**
78
+ * 补齐 tools 数组里每个 function.parameters 的 type。
79
+ * 没有改动时返回原数组,方便调用方判断要不要重写 body。
80
+ *
81
+ * @param {any} tools
82
+ * @returns {any}
83
+ */
84
+ export function normalizeTools(tools) {
85
+ if (!Array.isArray(tools)) return tools
86
+ let changed = false
87
+ const out = tools.map((tool) => {
88
+ if (!tool || typeof tool !== "object") return tool
89
+ const fn = tool.function
90
+ if (!fn || typeof fn !== "object" || !fn.parameters) return tool
91
+ const params = withObjectType(fn.parameters)
92
+ if (params === fn.parameters) return tool
93
+ changed = true
94
+ return { ...tool, function: { ...fn, parameters: params } }
95
+ })
96
+ return changed ? out : tools
97
+ }
package/src/quota.mjs ADDED
@@ -0,0 +1,212 @@
1
+ // 额度窗口的构造器 —— 把「写错不报错,但 GUI 和路由会坏」的那些坑变成运行时错误。
2
+ //
3
+ // 为什么需要它:`usage` 钩子返回的窗口是 magpie 画额度条 **和** 智能路由排序的输入。
4
+ // 写错字段不会让插件崩,只会让用户看到「剩余额度未知」、让这个号在路由里被当成不存在 ——
5
+ // 而插件作者从日志里什么都看不到。
6
+ //
7
+ // ⚠ 机制已于 2026-10-29 按上游结论更正(issue #468,magpie v0.1.1934):
8
+ // · **判断一个窗口有没有「占比」只看 `used`**,与 `aside` 无关。没有 `used` 的窗口是
9
+ // text-only:卡片只显示 `display`,**路由不计入**(`allowanceOf` 跳过 ⇒ `routedAllowance`
10
+ // 不 ok ⇒ 该号在路由里等于不存在)。
11
+ // · magpie **≥ 0.1.1934**(commit 1390aa458)起,有 `amount` + `limit` 但没有 `used` 的窗口
12
+ // 会用 `amount / limit` 推算占比;更旧的版本会把它当 text-only 丢掉。
13
+ // · `aside: true` 的意思是「用光也不停账号」,**路由从不读 aside 窗口**,它只上卡片。
14
+ //
15
+ // 所以这个构造器的规则是:**`amount` + `limit` 必须同时有 `used`**(没给就自动算),
16
+ // 这样跨 magpie 版本行为一致,也不依赖 `aside`。要 text-only 的窗口必须**显式**写
17
+ // `textOnly: true`,不能靠「忘了写 used」蒙混过去。
18
+ //
19
+ // 用法:
20
+ // import { usageWindow, usage } from "./quota.mjs"
21
+ // return usage({
22
+ // plan: "Pro",
23
+ // windows: [
24
+ // usageWindow({ name: "5 hours", used: 37, resetsAt: u.resets_at, span: 18000 }),
25
+ // usageWindow({ name: "积分", amount: 370, limit: 1000, unit: "积分" }), // used 自动 = 37
26
+ // usageWindow({ name: "积分", balance: 6291, unit: "积分" }),
27
+ // usageWindow({ name: "赠送", used: 0, aside: true, display: "5,500" }), // 只上卡片
28
+ // usageWindow({ name: "用量", textOnly: true, display: "1,234 剩余(上限未知)" }),
29
+ // ],
30
+ // })
31
+
32
+ /** 写法错误(不是上游失败)。调用方应当**重新抛出**,而不是吞成 usage.error ——
33
+ * 因为那是编码错误,静默掉就又会变成「GUI 坏了但日志里什么都没有」。 */
34
+ export class QuotaShapeError extends Error {
35
+ constructor(message) {
36
+ super(message)
37
+ this.name = "QuotaShapeError"
38
+ }
39
+ }
40
+
41
+ const TIME_KEYS = ["resetsAt", "runsOutAt", "until"]
42
+
43
+ /** 把厂商给的时间(ISO / 秒 / 毫秒时间戳 / Date)统一成 ISO 字符串。解析不了就抛。 */
44
+ export function toIso(value, field = "time") {
45
+ if (value == null) return undefined
46
+ if (value instanceof Date) {
47
+ if (Number.isNaN(value.getTime())) throw new QuotaShapeError(`${field}: 无效的 Date`)
48
+ return value.toISOString()
49
+ }
50
+ if (typeof value === "number") {
51
+ // 厂商常给秒级时间戳:10 位按秒、13 位按毫秒
52
+ const ms = value < 1e12 ? value * 1000 : value
53
+ const d = new Date(ms)
54
+ if (Number.isNaN(d.getTime())) throw new QuotaShapeError(`${field}: ${value} 不是有效时间戳`)
55
+ return d.toISOString()
56
+ }
57
+ const s = String(value).trim()
58
+ // 先原样试(ISO),再试「2026-10-28 23:59:59」这种厂商原样格式
59
+ const direct = Date.parse(s)
60
+ if (!Number.isNaN(direct)) return new Date(direct).toISOString()
61
+ const m = s.match(/^(\d{4})[-/](\d{2})[-/](\d{2})[ T](\d{2}):(\d{2})(?::(\d{2}))?/)
62
+ if (m) {
63
+ const d = new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]), Number(m[4]), Number(m[5]), Number(m[6] ?? 0))
64
+ if (!Number.isNaN(d.getTime())) return d.toISOString()
65
+ }
66
+ throw new QuotaShapeError(
67
+ `${field}: 无法解析 "${s}"。magpie 只认 ISO / 时间戳 —— ` +
68
+ `塞厂商原样格式会让整条窗口被丢掉(AGENTS 坑 22)`,
69
+ )
70
+ }
71
+
72
+ /**
73
+ * 构造一个额度窗口,并在构造时把「静默失败」的写法拦下来。
74
+ * 返回的对象可以直接放进 `usage().windows`。
75
+ *
76
+ * 四种形态,选一种:
77
+ * ① 占比型 `used`(0-100,可 >100)
78
+ * ② 数量型 `amount` + `limit`(`used` 没给就按 amount/limit 算)
79
+ * ③ 钱包型 `balance` + `unit`(只给余额,不给 used/limit)
80
+ * ④ 文本型 `textOnly: true` + `display`(明确「我不知道占比」,路由不计这个窗口)
81
+ */
82
+ export function usageWindow(w = {}) {
83
+ const out = {}
84
+ for (const [k, v] of Object.entries(w)) if (v !== undefined && k !== "textOnly") out[k] = v
85
+
86
+ for (const k of TIME_KEYS) if (out[k] !== undefined) out[k] = toIso(out[k], k)
87
+
88
+ const isWallet = out.balance !== undefined
89
+ const isTextOnly = w.textOnly === true
90
+ const hasShare = out.used !== undefined
91
+
92
+ if (out.name === undefined || String(out.name).trim() === "") {
93
+ throw new QuotaShapeError("窗口必须有 name —— 它显示在进度条上方")
94
+ }
95
+ const who = `窗口 "${out.name}"`
96
+
97
+ // ── ④ 文本型:必须显式声明,且必须有 display ────────────────────────
98
+ if (isTextOnly) {
99
+ if (hasShare || isWallet || out.amount !== undefined || out.limit !== undefined) {
100
+ throw new QuotaShapeError(
101
+ `${who}: textOnly: true 不能再给 used / balance / amount / limit —— ` +
102
+ `text-only 的意思是「这个窗口没有占比」,混着写会让读者分不清你到底是知道还是不知道`,
103
+ )
104
+ }
105
+ if (out.display === undefined || String(out.display).trim() === "") {
106
+ throw new QuotaShapeError(
107
+ `${who}: textOnly 窗口必须有 display —— 没有占比又没有文字,卡片上就只剩一个空标签`,
108
+ )
109
+ }
110
+ // 官方 #468 结论:没有 used 的窗口路由不计入。这不是错,但调用方要知道。
111
+ return out
112
+ }
113
+
114
+ // ── aside 窗口:路由从不读它,只上卡片(官方 #468 结论)──────────────
115
+ // 但给 amount/limit 会算出「假占比」:分母就是余额本身,永远显示剩余 100%。
116
+ if (out.aside === true && (out.amount !== undefined || out.limit !== undefined)) {
117
+ throw new QuotaShapeError(
118
+ `${who}: aside: true 的窗口不要给 amount/limit —— ` +
119
+ `aside 表示「用光也不停账号」,本来就没有上限;拿余额当分母算出来永远是「剩余 100%」` +
120
+ `(看着漂亮、含义是错的)。只想展示文字就只给 display;真要占比就别标 aside`,
121
+ )
122
+ }
123
+
124
+ // ── ③ 钱包型:只有余额,没有上限 ────────────────────────────────────
125
+ if (isWallet) {
126
+ if (!Number.isFinite(Number(out.balance))) {
127
+ throw new QuotaShapeError(`${who}: balance 必须是有限数字,收到 ${out.balance}`)
128
+ }
129
+ out.balance = Number(out.balance)
130
+ if (hasShare) {
131
+ throw new QuotaShapeError(`${who}: 钱包型(有 balance)不要再给 used —— magpie 会把它当占比读`)
132
+ }
133
+ if (out.amount !== undefined || out.limit !== undefined) {
134
+ throw new QuotaShapeError(`${who}: 钱包型不要再给 amount/limit —— 余额就是「剩多少」,没有上限可算占比`)
135
+ }
136
+ return finish(out)
137
+ }
138
+
139
+ // ── ② 数量型:amount + limit 成对,used 缺了就自动算 ────────────────
140
+ const hasAmount = out.amount !== undefined || out.limit !== undefined
141
+ if (hasAmount) {
142
+ if (out.amount === undefined || out.limit === undefined) {
143
+ throw new QuotaShapeError(
144
+ `${who}: amount 与 limit 必须成对(收到 amount=${out.amount}, limit=${out.limit})—— ` +
145
+ `只给一个的话 magpie 算不出占比`,
146
+ )
147
+ }
148
+ const amount = Number(out.amount)
149
+ const limit = Number(out.limit)
150
+ if (!Number.isFinite(amount) || !Number.isFinite(limit) || limit <= 0) {
151
+ throw new QuotaShapeError(`${who}: amount/limit 必须是有限数字且 limit > 0(收到 amount=${amount}, limit=${limit})`)
152
+ }
153
+ out.amount = amount
154
+ out.limit = limit
155
+ if (!hasShare) {
156
+ // 上游 #468 结论:≥0.1.1934 会用 amount/limit 推算;更旧的版本会当成 text-only 丢掉。
157
+ // 自己算出来,跨版本一致。
158
+ out.used = Math.round((amount / limit) * 10000) / 100
159
+ }
160
+ }
161
+
162
+ // ── ① 占比型(或数量型补完之后):used 必须落在有限数字上 ──────────
163
+ if (!Number.isFinite(Number(out.used))) {
164
+ throw new QuotaShapeError(
165
+ `${who}: used 必填(收到 ${out.used})。` +
166
+ `没有 used 的窗口是 text-only,**magpie 的路由不会计入它** —— ` +
167
+ `要表达「只有文字、没有占比」请显式写 textOnly: true;要占比就填 0-100 的有限数字`,
168
+ )
169
+ }
170
+ out.used = Number(out.used)
171
+
172
+ return finish(out)
173
+ }
174
+
175
+ function finish(out) {
176
+ if (out.span !== undefined) {
177
+ if (!Number.isInteger(Number(out.span)) || Number(out.span) <= 0) {
178
+ throw new QuotaShapeError(`窗口 "${out.name}": span 是窗口长度(秒),必须是正整数,收到 ${out.span}`)
179
+ }
180
+ out.span = Number(out.span)
181
+ }
182
+ return out
183
+ }
184
+
185
+ /** 构造整个 usage 返回值。窗口逐个过一遍 usageWindow。 */
186
+ export function usage(u = {}) {
187
+ const out = { ...u }
188
+ if (u.windows !== undefined) {
189
+ if (!Array.isArray(u.windows)) throw new QuotaShapeError("usage.windows 必须是数组")
190
+ out.windows = u.windows.map((w) => usageWindow(w))
191
+
192
+ // 官方 #468 结论:路由跳过 aside 窗口和没有 used 的窗口。一条都不剩 ⇒ 这个号在路由里
193
+ // 等于不存在(路由页「剩余额度未知」,且永远排在已知账号之后)。
194
+ // 例外:钱包型窗口(只有 balance)没有 used,但宿主会按余额读它 —— 它是可路由的。
195
+ // 判据与 Magicrew 实际写法(src/hooks/usage.mjs:53-59)一致,否则只有钱包窗口的账号会被误杀。
196
+ const routable = out.windows.filter(
197
+ (w) => w.aside !== true && (w.used !== undefined || w.balance !== undefined),
198
+ )
199
+ if (out.windows.length > 0 && routable.length === 0) {
200
+ throw new QuotaShapeError(
201
+ "所有窗口都不参与路由(全是 aside: true 或 textOnly)—— " +
202
+ "这个账号会在路由页显示「剩余额度未知」,而且一律排在已知账号之后。" +
203
+ "至少留一条带 used 的窗口(哪怕百分比没有信息量),否则智能路由里就没有这个号",
204
+ )
205
+ }
206
+ }
207
+ for (const k of TIME_KEYS) if (out[k] !== undefined) out[k] = toIso(out[k], k)
208
+ if (out.error !== undefined && typeof out.error !== "string") {
209
+ throw new QuotaShapeError("usage.error 必须是字符串(显示在额度窗口的位置)")
210
+ }
211
+ return out
212
+ }
@@ -0,0 +1,115 @@
1
+ // src/refresh-lock.mjs —— 一次性 refresh_token 的并发闸
2
+ //
3
+ // 为什么必须有它:refresh_token **一次性**的厂商,同账号并发刷新两次时,
4
+ // 第二次会拿着已经被轮换掉的旧 token 去换 —— 结果不是「慢一点」,而是
5
+ // 「登录莫名失效」。宿主自己的 `auth.refresh` 与请求链路可能同时触发刷新,
6
+ // 所以插件侧必须把同一次刷新合并成一次。
7
+ //
8
+ // 模式来源(都是 MIT):
9
+ // · magpie-officeace/src/login.mjs:292-310 —— `refreshOnce`,键 = refreshToken
10
+ // · magpie-magicrew-auth/src/key-store.mjs:171-188 —— `renewOnce`,键 = siteId + account
11
+ // · @magpie-community/opencode-raccoon-auth/index.mjs:228-286 —— renewing + renewed 双 Map,结果回放 60 秒
12
+ //
13
+ // 本模块只保留协议原语:存储、厂商刷新函数、账号解析都由调用方注入。
14
+
15
+ const DEFAULT_REPLAY_MS = 60_000
16
+
17
+ /**
18
+ * 建一个按 key 合并并发的刷新闸。
19
+ *
20
+ * @param {{replayMs?: number}} [options]
21
+ * replayMs:成功结果在内存里保留多久(毫秒)。0 表示不回放。
22
+ * @returns {{
23
+ * run(key: string, fn: () => unknown | Promise<unknown>): Promise<unknown>,
24
+ * clear(key: string): void,
25
+ * readonly size: number,
26
+ * readonly pending: number,
27
+ * }}
28
+ */
29
+ export function createRefreshLock({ replayMs = DEFAULT_REPLAY_MS } = {}) {
30
+ if (typeof replayMs !== "number" || !Number.isFinite(replayMs) || replayMs < 0) {
31
+ throw new TypeError(`createRefreshLock: replayMs 必须是非负有限数字,收到 ${replayMs}`)
32
+ }
33
+
34
+ /** @type {Map<string, Promise<unknown>>} */
35
+ const inflight = new Map()
36
+ /** @type {Map<string, { value: unknown, expiresAt: number }>} */
37
+ const replay = new Map()
38
+
39
+ function assertKey(key) {
40
+ if (typeof key !== "string" || key.trim() === "") {
41
+ throw new TypeError(
42
+ "refresh lock 的 key 必须是非空字符串 —— 键必须来自凭据身份(如 refresh_token),不能用 provider id," +
43
+ "否则同渠道的多个账号会共享同一次刷新结果",
44
+ )
45
+ }
46
+ }
47
+
48
+ /** 清掉所有已过期的回放项。每次 run 前调用一次,避免账号多时 Map 无界增长。 */
49
+ function sweep() {
50
+ const at = Date.now()
51
+ let removed = 0
52
+ for (const [key, entry] of replay) {
53
+ if (entry.expiresAt <= at) {
54
+ replay.delete(key)
55
+ removed += 1
56
+ }
57
+ }
58
+ return removed
59
+ }
60
+
61
+ return {
62
+ run(key, fn) {
63
+ assertKey(key)
64
+ if (typeof fn !== "function") throw new TypeError("refresh lock 的 fn 必须是函数")
65
+
66
+ sweep() // 顺手清理过期项,避免 replay Map 只增不减
67
+
68
+ // ① 成功结果短回放:宿主 auth.refresh 与请求链路各花一次旧 token 的常见场景
69
+ const cached = replay.get(key)
70
+ if (cached) {
71
+ if (cached.expiresAt > Date.now()) return Promise.resolve(cached.value)
72
+ replay.delete(key)
73
+ }
74
+
75
+ // ② 同一 key 的 in-flight 合并:所有等待者拿到同一个 promise(同一个错误对象)
76
+ const pending = inflight.get(key)
77
+ if (pending) return pending
78
+
79
+ let task = Promise.resolve()
80
+ .then(fn)
81
+ .then((value) => {
82
+ replay.set(key, { value, expiresAt: Date.now() + replayMs })
83
+ return value
84
+ })
85
+ // 失败不缓存:finally 只清理 in-flight,下一次调用会重新执行
86
+ task = task.finally(() => {
87
+ if (inflight.get(key) === task) inflight.delete(key)
88
+ })
89
+ inflight.set(key, task)
90
+ return task
91
+ },
92
+
93
+ /**
94
+ * 只清成功回放,不动 in-flight:那次刷新还在花同一个 refresh_token,
95
+ * 清掉 in-flight 会让新调用再发一次,正是本模块要防的事。
96
+ */
97
+ clear(key) {
98
+ assertKey(key)
99
+ replay.delete(key)
100
+ },
101
+
102
+ /** 显式清理过期回放项,返回清理条数(诊断用) */
103
+ sweep,
104
+
105
+ /** 回放缓存条数(测试与诊断用) */
106
+ get size() {
107
+ return replay.size
108
+ },
109
+
110
+ /** 正在执行的刷新次数(测试与诊断用) */
111
+ get pending() {
112
+ return inflight.size
113
+ },
114
+ }
115
+ }
@@ -0,0 +1,48 @@
1
+ // tests/device-registry.test.mjs —— 每账号虚拟设备 guid 的形状锁
2
+ //
3
+ // token 与 guid 绑定:换掉 guid 会掉登录态。
4
+ // 所以「多账号并行」= 每个账号登录时生成独立 guid,并且不能在并发登录间串号。
5
+
6
+ import test from "node:test"
7
+ import assert from "node:assert/strict"
8
+
9
+ import { createDeviceRegistry, newDeviceGuid, stateOfUrl } from "../src/marvis/device.mjs"
10
+
11
+ test("newDeviceGuid 是 32 位小写 hex,且每次不同", () => {
12
+ const a = newDeviceGuid()
13
+ const b = newDeviceGuid()
14
+ assert.match(a, /^[0-9a-f]{32}$/)
15
+ assert.match(b, /^[0-9a-f]{32}$/)
16
+ assert.notEqual(a, b)
17
+ })
18
+
19
+ test("registry:state 一次性取出,take 后不再返回", () => {
20
+ const r = createDeviceRegistry()
21
+ r.remember("s1", "g1")
22
+ assert.equal(r.take("s1"), "g1")
23
+ assert.equal(r.take("s1"), "", "同一个 state 不能被取两次")
24
+ })
25
+
26
+ test("registry:并发两个 state 互不覆盖", () => {
27
+ const r = createDeviceRegistry()
28
+ r.remember("s1", "g1")
29
+ r.remember("s2", "g2")
30
+ assert.equal(r.size, 2)
31
+ assert.equal(r.take("s2"), "g2")
32
+ assert.equal(r.take("s1"), "g1")
33
+ })
34
+
35
+ test("registry:超过 TTL 的条目会被清掉", () => {
36
+ let now = 1000
37
+ const r = createDeviceRegistry({ ttlMs: 100, now: () => now })
38
+ r.remember("s1", "g1")
39
+ now = 1101
40
+ assert.equal(r.take("s1"), "")
41
+ assert.equal(r.size, 0)
42
+ })
43
+
44
+ test("stateOfUrl:能取 state,坏 URL 返回空串", () => {
45
+ assert.equal(stateOfUrl("https://x/cb?code=1&state=31.117"), "31.117")
46
+ assert.equal(stateOfUrl("https://x/cb?code=1"), "")
47
+ assert.equal(stateOfUrl("not a url"), "")
48
+ })