@jixing475/magpie-marvis 0.0.0-stage → 0.3.1

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 +751 -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 +312 -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,73 @@
1
+ // tests/panel-manifest.test.mjs —— 首行文本面板的打包面与桥接锁
2
+ //
3
+ // 面板(magpie.panels,slot: provider)的三种失败都是**静默的**:
4
+ // · `file` 不在包的 files 白名单里 → npm 装出来没有这个文件,编辑器里一块空白,没有任何报错;
5
+ // · `slot` 写错 → 永远不出现;
6
+ // · 忘了 `<script src="_magpie/bridge.js">` → 面板读不到 options,一片死白。
7
+ // 契约出处:magpie 源码 docs/subsystems/plugin-runtime.md 的 P5,
8
+ // panels: [{slot, file, title}],slot ∈ {agents, usage, settings, provider},
9
+ // file 必须是插件目录里的 .html;面板通过 bridge 的 magpie.options.get()/.set() 读写本插件选项。
10
+
11
+ import test from "node:test"
12
+ import assert from "node:assert/strict"
13
+ import { readFileSync, existsSync } from "node:fs"
14
+ import { fileURLToPath } from "node:url"
15
+ import { dirname, join } from "node:path"
16
+
17
+ const ROOT = join(dirname(fileURLToPath(import.meta.url)), "..")
18
+ const pkg = JSON.parse(readFileSync(join(ROOT, "package.json"), "utf8"))
19
+ const panels = pkg.magpie?.panels ?? []
20
+ const SLOTS = new Set(["agents", "usage", "settings", "provider"])
21
+
22
+ /** 读面板的 HTML 与它自己的 JS */
23
+ function panelFiles(panel) {
24
+ const html = readFileSync(join(ROOT, panel.file), "utf8")
25
+ const srcs = [...html.matchAll(/<script[^>]+src="([^"]+)"/g)].map((m) => m[1])
26
+ const own = srcs.find((s) => !s.includes("_magpie/"))
27
+ assert.ok(own, `${panel.file} 要有自己的脚本`)
28
+ const js = readFileSync(join(dirname(join(ROOT, panel.file)), own), "utf8")
29
+ return { html, srcs, js }
30
+ }
31
+
32
+ test("magpie.panels 形状合法:slot 在允许集合里、file 存在", () => {
33
+ assert.ok(Array.isArray(panels) && panels.length > 0, "面板清单不能空")
34
+ assert.ok(panels.length <= 8, "magpie 一个插件最多 8 个面板")
35
+ for (const p of panels) {
36
+ assert.ok(SLOTS.has(p.slot), `slot 必须是 ${[...SLOTS].join(" / ")},收到 ${p.slot}`)
37
+ assert.ok(typeof p.title === "string" && p.title.trim(), "要有 title")
38
+ assert.ok(p.file.endsWith(".html"), "file 必须是 .html")
39
+ assert.ok(existsSync(join(ROOT, p.file)), `面板文件不存在:${p.file}`)
40
+ }
41
+ })
42
+
43
+ test("面板要出现在供应商卡片里(slot: provider)", () => {
44
+ assert.ok(panels.some((p) => p.slot === "provider"), "文本框要挂在 provider 编辑器上")
45
+ })
46
+
47
+ test("面板文件必须在 npm 的 files 白名单里(否则用户那边是空白)", () => {
48
+ const files = pkg.files ?? []
49
+ for (const p of panels) {
50
+ const top = p.file.split("/")[0]
51
+ assert.ok(files.includes(top) || files.includes(p.file), `files 里没有 ${top},npm 打包会漏掉面板`)
52
+ }
53
+ })
54
+
55
+ test("走 bridge 读改写:options.get / set 都在,且写回保留别的键", () => {
56
+ for (const panel of panels) {
57
+ const { srcs, js } = panelFiles(panel)
58
+ assert.ok(srcs.some((s) => s.includes("_magpie/bridge.js")), "必须加载 magpie 的 bridge")
59
+ assert.match(js, /magpie\.options\.get\(\)/, "要读当前选项,否则面板打开是空的")
60
+ assert.match(js, /magpie\.options\.set\(/, "要能写选项")
61
+ assert.match(js, /\.\.\.(opts|rest)/, "options.set 是整份替换,写回必须展开读到的整份 opts")
62
+ assert.ok(js.includes("提示词首行替换"), "写回的是 loader 读的那个键「提示词首行替换」(老的 text / firstLine 一并收掉)")
63
+ assert.match(js, /submit/, "写回要挂在「保存」按钮的 submit 上")
64
+ assert.ok(!/addEventListener\("input"/.test(js), "不要边打字边写:options.set 一秒最多一次")
65
+ }
66
+ })
67
+
68
+ test("面板不得自己发网络请求(沙箱里也没有网络)", () => {
69
+ for (const panel of panels) {
70
+ const { js } = panelFiles(panel)
71
+ assert.ok(!/\bfetch\s*\(/.test(js), "面板不该 fetch:越权也没有网络")
72
+ }
73
+ })
@@ -0,0 +1,100 @@
1
+ // tests/plugin-options.test.mjs —— provider 卡片上那些开关的契约锁
2
+ //
3
+ // 机制(magpie 源码 internal/plugin/host.js 的 `optionsOf`,上游 #2038):
4
+ // 插件在 auth 对象上声明 `options: [{key, label, description?, default?, confirm?,
5
+ // labels?, descriptions?, confirms?, filtersModels?}]`,magpie 在**供应商编辑器**里
6
+ // 每条画一行 Off/On,用户点一下立刻保存,插件用 `input.magpie.option(provider, key)` 读。
7
+ //
8
+ // 失败方式是静默的:magpie 对每条做校验,**不合格就整条丢掉**,卡片上什么都不显示、
9
+ // 也没有任何报错。所以这里按它的规则把形状锁住:
10
+ // · key 必须 /^[a-z0-9_-]{1,40}$/,重复的只留第一条
11
+ // · label 必填且 ≤60 字符(trim 后);description ≤300
12
+ // · default 必须是布尔(`o.default === true` 才算开)
13
+ // · 多语言写在 labels / descriptions / confirms 里,label 本身必须留着(老版本只读它)
14
+ // · 最多 16 条
15
+ // · `placement: "top"` → 画在账号下面、路由上面(magpie #5269);不写就排在模型之后
16
+
17
+ import test from "node:test"
18
+ import assert from "node:assert/strict"
19
+
20
+ import { PLUGIN_OPTIONS } from "../src/context.mjs"
21
+ import { authHooks } from "../src/auth.mjs"
22
+
23
+ const OPTION_KEY = /^[a-z0-9_-]{1,40}$/
24
+ const MAX_OPTIONS = 16
25
+
26
+ test("auth.options 里确实带着这两个开关(卡片上才有一行可点)", () => {
27
+ const auth = authHooks({}, {})
28
+ assert.ok(Array.isArray(auth.options), "auth.options 必须是数组,否则 magpie 一个开关都不画")
29
+ const keys = auth.options.map((o) => o.key)
30
+ assert.deepEqual(keys, ["first_line_fallback", "first_line_always"])
31
+ assert.equal(PLUGIN_OPTIONS, auth.options, "同一份声明,别在别处再抄一遍")
32
+ })
33
+
34
+ test("每条开关都符合 magpie 的校验规则(不合格会被静默丢掉)", () => {
35
+ assert.ok(PLUGIN_OPTIONS.length <= MAX_OPTIONS, `最多 ${MAX_OPTIONS} 条`)
36
+ const seen = new Set()
37
+ for (const o of PLUGIN_OPTIONS) {
38
+ assert.match(o.key, OPTION_KEY, `key 不合格会被丢掉:${o.key}`)
39
+ assert.ok(!seen.has(o.key), `key 重复只留第一条:${o.key}`)
40
+ seen.add(o.key)
41
+ assert.equal(typeof o.label, "string")
42
+ assert.ok(o.label.trim().length > 0 && o.label.trim().length <= 60, "label 必填且 ≤60 字符")
43
+ if (o.description !== undefined) {
44
+ assert.ok(o.description.length <= 300, "description ≤300 字符")
45
+ }
46
+ if (o.default !== undefined) {
47
+ assert.equal(typeof o.default, "boolean", "default 必须是布尔,magpie 只认 === true")
48
+ }
49
+ for (const field of ["labels", "descriptions", "confirms"]) {
50
+ if (o[field] === undefined) continue
51
+ assert.ok(o[field] && typeof o[field] === "object" && !Array.isArray(o[field]), `${field} 必须是对象`)
52
+ for (const [lang, words] of Object.entries(o[field])) {
53
+ assert.ok(lang.trim() && lang.length <= 16, `${field} 的语言码不合格:${lang}`)
54
+ assert.ok(typeof words === "string" && words.trim(), `${field}.${lang} 不能是空串(会被丢)`)
55
+ // magpie 的 inLanguages(o.labels, 60):每条译文也按 label 的上限截断,超了整条译文被丢
56
+ if (field === "labels") assert.ok(words.trim().length <= 60, `labels.${lang} 超过 60 字符会被丢`)
57
+ }
58
+ }
59
+ }
60
+ })
61
+
62
+ test("中文用户看得懂:每个开关都有 zh 的 label", () => {
63
+ for (const o of PLUGIN_OPTIONS) {
64
+ assert.ok(o.labels?.zh, `${o.key} 缺 labels.zh`)
65
+ assert.ok(o.labels.zh.trim().length <= 60, `${o.key} 的 labels.zh 超过 60 字符会被丢`)
66
+ }
67
+ })
68
+
69
+ test("一条开关只占一行:不写 description(多一行就会压到「模型」区块上)", () => {
70
+ // magpie 的 .plugin-options 是 flex 的 .stack,但每个选项只预留一行的高度:
71
+ // 有 description 就多画一行,那一行会压在下一个 field(模型列表)上。
72
+ // 插件的渲染改不了,能改的只有「一条只占一行」—— 说明写进 label。
73
+ for (const o of PLUGIN_OPTIONS) {
74
+ assert.equal(o.description, undefined, `${o.key} 写了 description,会多一行压到模型区块上`)
75
+ assert.equal(o.descriptions, undefined, `${o.key} 写了 descriptions,会多一行压到模型区块上`)
76
+ }
77
+ })
78
+
79
+ test("中文 label 要短到能一行放下(汉字宽度约等于两个英文列)", () => {
80
+ // magpie 只按「字符数」校验 label ≤60,中文能过;但一个汉字约两列宽,
81
+ // 40 个汉字 ≈ 80 列,窄一点的窗口就会折行 —— 而选项行只预留一行高度,
82
+ // 折出来的第二行会压在下面「模型」区块上(#59)。这里按显示宽度锁 ≤24 个汉字。
83
+ for (const o of PLUGIN_OPTIONS) {
84
+ const zh = o.labels?.zh ?? ""
85
+ assert.ok(zh.length <= 24, `${o.key} 的 labels.zh 有 ${zh.length} 个字,超过 24 就会在窄窗口折行压到「模型」`)
86
+ }
87
+ })
88
+
89
+ test("两个开关都要置顶(placement: \"top\")—— 排在路由/模型之后等于找不到", () => {
90
+ for (const o of PLUGIN_OPTIONS) {
91
+ assert.equal(o.placement, "top", `${o.key} 缺 placement: "top",会被画在模型之后`)
92
+ }
93
+ })
94
+
95
+ test("默认值就是「被拦才兜底」:fallback 开、always 关", () => {
96
+ const byKey = Object.fromEntries(PLUGIN_OPTIONS.map((o) => [o.key, o]))
97
+ assert.equal(byKey.first_line_fallback.default, true, "默认要能在没配置时救回 403")
98
+ assert.equal(byKey.first_line_always.default, false, "默认不能改写所有请求")
99
+ assert.ok(byKey.first_line_always.confirm, "always 会改掉每个请求,值得一次二次确认")
100
+ })
@@ -0,0 +1,96 @@
1
+ // tests/profile.test.mjs —— 昵称/头像请求的形状锁
2
+ //
3
+ // 实测:GET /marvis_client/marvis_get_user_info → 403;
4
+ // 签名 POST + body {userInfo} → 200 {ret:0, nick_name}。
5
+ // 昵称拿不到必须返回 null,绝不能阻塞登录或编造名字。
6
+
7
+ import test from "node:test"
8
+ import assert from "node:assert/strict"
9
+
10
+ import { fetchUserProfile } from "../src/marvis/profile.mjs"
11
+ import { authOf } from "../src/hooks/methods.mjs"
12
+
13
+ const ACCT = {
14
+ openid: "0123456789abcdef0123456789abcdef",
15
+ accessToken: "mv_test",
16
+ refreshToken: "rt_test",
17
+ guid: "0123456789abcdef0123456789abcdef",
18
+ loginType: "1",
19
+ }
20
+
21
+ function stubFetch(handler) {
22
+ const calls = []
23
+ const real = globalThis.fetch
24
+ globalThis.fetch = async (url, init) => {
25
+ calls.push({ url: String(url), init: init ?? {} })
26
+ return handler(String(url), init ?? {})
27
+ }
28
+ return { calls, restore: () => (globalThis.fetch = real) }
29
+ }
30
+
31
+ test("签名 POST 成功:返回昵称与头像", async () => {
32
+ const s = stubFetch(
33
+ () =>
34
+ new Response(JSON.stringify({ ret: 0, nick_name: "测试昵称", head_img_url: "https://example.test/a.png" }), {
35
+ status: 200,
36
+ headers: { "content-type": "application/json" },
37
+ }),
38
+ )
39
+ try {
40
+ const p = await fetchUserProfile(ACCT)
41
+ assert.deepEqual(p, { nickname: "测试昵称", avatar: "https://example.test/a.png" })
42
+ const { init } = s.calls[0]
43
+ assert.equal(init.method, "POST")
44
+ assert.ok(init.headers["Ual-Access-Businessid"])
45
+ assert.ok(init.headers["Ual-Access-Signature"])
46
+ assert.equal(init.headers["Ual-Access-Access-Token"], undefined, "签名 POST 不能带 token 头")
47
+ const body = JSON.parse(init.body)
48
+ assert.equal(body.userInfo.openId, ACCT.openid)
49
+ assert.equal(body.userInfo.guid, ACCT.guid)
50
+ } finally {
51
+ s.restore()
52
+ }
53
+ })
54
+
55
+ test("ret 非 0 或没有昵称:返回 null,不编造", async () => {
56
+ for (const payload of [{ ret: -107, nick_name: "" }, { ret: 0, nick_name: "" }, { ret: 0 }]) {
57
+ const s = stubFetch(() => new Response(JSON.stringify(payload), { status: 200 }))
58
+ try {
59
+ assert.equal(await fetchUserProfile(ACCT), null)
60
+ } finally {
61
+ s.restore()
62
+ }
63
+ }
64
+ })
65
+
66
+ test("网络错误:返回 null,不抛", async () => {
67
+ const s = stubFetch(() => Promise.reject(new Error("boom")))
68
+ try {
69
+ assert.equal(await fetchUserProfile(ACCT), null)
70
+ } finally {
71
+ s.restore()
72
+ }
73
+ })
74
+
75
+ test("缺 openid / token / guid:直接 null,不发请求", async () => {
76
+ const s = stubFetch(() => new Response("{}"))
77
+ try {
78
+ assert.equal(await fetchUserProfile({}), null)
79
+ assert.equal(s.calls.length, 0)
80
+ } finally {
81
+ s.restore()
82
+ }
83
+ })
84
+
85
+ test("authOf:昵称进 accountId,openid 只进 uid", () => {
86
+ const a = authOf({
87
+ openid: "0123456789abcdef0123456789abcdef",
88
+ accessToken: "mv_test",
89
+ refreshToken: "rt_test",
90
+ guid: "0123456789abcdef0123456789abcdef",
91
+ nickname: "测试昵称",
92
+ loginType: "1",
93
+ })
94
+ assert.equal(a.accountId, "QQ·测试昵称")
95
+ assert.equal(a.uid, "0123456789abcdef0123456789abcdef")
96
+ })
@@ -0,0 +1,318 @@
1
+ // tests/refresh-contract.test.mjs —— 续期契约(2026-11-07 微信被踢事故的回归锁)
2
+ //
3
+ // 事故现场(截图):五个账号里 **两个微信 401「登录态过期」**,三个 QQ 正常。
4
+ // 根因是五件事叠在一起,这个文件把每一件都钉死:
5
+ //
6
+ // ① **签名错**:`auth.refresh` 收的是**账号对象**(`refresh(auth, provider)`),
7
+ // 不是 getter(那是 `loader` / `usage` / `checkin` 的形状)。
8
+ // 写成 `getAuth()` → magpie 报 `getAuth is not a function`,**续期一次都没跑起来过**。
9
+ // ② **端点错**:调的是 `GET /v3/marvis_refresh_token?refresh_token=…`,
10
+ // 恒定回 `-109 RefreshToken missing required param (openid, guid, token)`。
11
+ // 真实续期端点是 `POST /marvis_client_login/marvis_refresh_token`。
12
+ // ③ **-109 被当成登录失效**:参数检查失败 ≠ 会话失效,标 `signIn: "expired"`
13
+ // 会让 magpie 把好账号标成「需要重新登录」。
14
+ // ④ **expires 算错**:`expires_in` 是**相对秒数**(微信 7200 = 2 小时),
15
+ // 旧代码 `> 1e9` 判成「不是绝对时间戳」→ 回退 30 天 → 从不主动续期。
16
+ // ⑤ **refresh_token 空串覆盖**:响应里 `refresh_token: ""`,`??` 不回退,
17
+ // 存成空串后下次 `if (!refreshToken) return {}` 直接短路,永不续期。
18
+ //
19
+ // 全部离线:mock 掉 globalThis.fetch,不联网、不需要凭据。
20
+
21
+ import test from "node:test"
22
+ import assert from "node:assert/strict"
23
+
24
+ import { expiresAtOf, ttlFor, DEFAULT_TTL_MS, WX_TTL_MS } from "../src/marvis/expiry.mjs"
25
+ import { refreshHook } from "../src/hooks/refresh.mjs"
26
+ import { REFRESH_LEAD_MS } from "../src/context.mjs"
27
+
28
+ /** 替换 globalThis.fetch,返回恢复函数 */
29
+ function stubFetch(handler) {
30
+ const original = globalThis.fetch
31
+ globalThis.fetch = handler
32
+ return () => {
33
+ globalThis.fetch = original
34
+ }
35
+ }
36
+
37
+ /** 造一个上游续期响应 */
38
+ function refreshResponse(userInfo) {
39
+ return new Response(JSON.stringify({ code: 0, msg: "RC_SUCCESS", user_info: userInfo }), {
40
+ status: 200,
41
+ headers: { "content-type": "application/json" },
42
+ })
43
+ }
44
+
45
+ /** 造一个账号对象 */
46
+ function account(over = {}) {
47
+ return {
48
+ access: "mv_OLD",
49
+ refresh: "RT_OLD",
50
+ metadata: { openid: "OID", guid: "0".repeat(32), loginType: "2", nickname: "示例昵称" },
51
+ ...over,
52
+ }
53
+ }
54
+
55
+ // ─────────────────────────────────────────────────────────────
56
+ // ④ 有效期归一
57
+ // ─────────────────────────────────────────────────────────────
58
+
59
+ test("expiresAtOf:绝对秒 / 绝对毫秒 / 相对秒 / 兜底 四种形状各走各的分支", () => {
60
+ const now = 1_800_000_000_000
61
+ // 10 位秒 → 乘 1000
62
+ assert.equal(expiresAtOf({ access_token_expire_time: "1796545945" }, { now }), 1_796_545_945_000)
63
+ assert.equal(expiresAtOf({ access_token_expire_time: 1_796_545_945 }, { now }), 1_796_545_945_000)
64
+ // 13 位毫秒 → 原样
65
+ assert.equal(expiresAtOf({ access_token_expire_time: 1_796_545_945_000 }, { now }), 1_796_545_945_000)
66
+ // 相对秒(微信只有 7200)
67
+ assert.equal(expiresAtOf({ expires_in: "7200" }, { now }), now + 7_200_000)
68
+ assert.equal(expiresAtOf({ expires_in: 2591962 }, { now }), now + 2_591_962_000)
69
+ // 都没有 → 兜底
70
+ assert.equal(expiresAtOf({}, { now }), now + DEFAULT_TTL_MS)
71
+ assert.equal(expiresAtOf(undefined, { now }), now + DEFAULT_TTL_MS)
72
+ assert.equal(expiresAtOf({}, { now, fallbackMs: 1234 }), now + 1234)
73
+ // 绝对时间戳优先于 expires_in
74
+ assert.equal(
75
+ expiresAtOf({ access_token_expire_time: 1_796_545_945, expires_in: 7200 }, { now }),
76
+ 1_796_545_945_000,
77
+ )
78
+ })
79
+
80
+ test("ttlFor:微信 2 小时、QQ 30 天 —— 不能共用一个兜底", () => {
81
+ assert.equal(ttlFor("2"), WX_TTL_MS)
82
+ assert.equal(ttlFor("WX"), WX_TTL_MS)
83
+ assert.equal(ttlFor("WXAPP"), WX_TTL_MS)
84
+ assert.equal(ttlFor("1"), DEFAULT_TTL_MS)
85
+ assert.equal(ttlFor("QC"), DEFAULT_TTL_MS)
86
+ assert.equal(ttlFor(undefined), DEFAULT_TTL_MS)
87
+ // 微信 TTL 必须远小于 QQ —— 共用一个就是 360 倍误差
88
+ assert.ok(WX_TTL_MS * 100 < DEFAULT_TTL_MS)
89
+ })
90
+
91
+ test("REFRESH_LEAD_MS 必须小于微信 token 的有效期(否则微信账号从登录那刻起就「永远该刷新」)", () => {
92
+ assert.ok(REFRESH_LEAD_MS > 0)
93
+ assert.ok(REFRESH_LEAD_MS < WX_TTL_MS, `refreshLead=${REFRESH_LEAD_MS} 应小于 ${WX_TTL_MS}`)
94
+ })
95
+
96
+ // ─────────────────────────────────────────────────────────────
97
+ // ① 签名:第一个参数是**账号对象**
98
+ // ─────────────────────────────────────────────────────────────
99
+
100
+ test("refresh:第一个参数按**账号对象**传(不是 getAuth 函数)", async () => {
101
+ let seen = null
102
+ const restore = stubFetch(async () => {
103
+ seen = "called"
104
+ return new Response(JSON.stringify({ code: -107, msg: "x" }), { status: 200 })
105
+ })
106
+ try {
107
+ await assert.rejects(
108
+ () => refreshHook()(account({ refresh: "RT_sig" }), { id: "marvis" }),
109
+ (err) => {
110
+ // 只要没抛 "getAuth is not a function" 就说明签名对了
111
+ assert.ok(!/getAuth is not a function/.test(err.message), err.message)
112
+ assert.match(err.message, /code=-107/)
113
+ return true
114
+ },
115
+ )
116
+ assert.equal(seen, "called")
117
+ } finally {
118
+ restore()
119
+ }
120
+ })
121
+
122
+ test("refresh:也兼容传 getter 的宿主(向后兼容,不能一次写死)", async () => {
123
+ let seen = false
124
+ const restore = stubFetch(async () => {
125
+ seen = true
126
+ return new Response(JSON.stringify({ code: -107, msg: "x" }), { status: 200 })
127
+ })
128
+ try {
129
+ await assert.rejects(
130
+ () => refreshHook()(async () => account({ refresh: "RT_getter" })),
131
+ /code=-107/,
132
+ )
133
+ assert.equal(seen, true)
134
+ } finally {
135
+ restore()
136
+ }
137
+ })
138
+
139
+ // ─────────────────────────────────────────────────────────────
140
+ // ② 端点 + 请求形状
141
+ // ─────────────────────────────────────────────────────────────
142
+
143
+ test("refresh:POST 到 /marvis_client_login/marvis_refresh_token,body 是 userInfo 形状", async () => {
144
+ const calls = []
145
+ const restore = stubFetch(async (url, init) => {
146
+ calls.push({ url: String(url), init })
147
+ // 昵称接口也走 fetch —— 这里让它失败,不影响续期
148
+ if (String(url).includes("marvis_get_user_info")) {
149
+ return new Response(JSON.stringify({ ret: -1 }), { status: 200 })
150
+ }
151
+ return refreshResponse({
152
+ access_token: "mv_NEW",
153
+ refresh_token: "",
154
+ expires_in: "7200",
155
+ login_type: "WX",
156
+ })
157
+ })
158
+
159
+ try {
160
+ const out = await refreshHook()(account())
161
+
162
+ assert.equal(calls.length, 2, "一次续期 + 一次昵称(昵称失败不影响)")
163
+ const [refreshCall] = calls
164
+ assert.match(
165
+ refreshCall.url,
166
+ /^https:\/\/yybadaccess\.3g\.qq\.com\/marvis_client_login\/marvis_refresh_token$/,
167
+ "端点必须是 POST /marvis_client_login/marvis_refresh_token(不是 /v3/marvis_refresh_token)",
168
+ )
169
+ assert.equal(refreshCall.init.method, "POST")
170
+
171
+ const body = JSON.parse(refreshCall.init.body)
172
+ assert.deepEqual(body, {
173
+ userInfo: {
174
+ openId: "OID",
175
+ refreshToken: "RT_OLD",
176
+ accessToken: "mv_OLD",
177
+ // ⚠ 恒为 "Marvis",不是 QC/WX
178
+ loginType: "Marvis",
179
+ },
180
+ })
181
+
182
+ // 签名头必须带(/v3、/marvis_client_login 业务接口都要)
183
+ assert.ok(refreshCall.init.headers["Ual-Access-Signature"])
184
+ assert.ok(refreshCall.init.headers["Ual-Access-Timestamp"])
185
+ assert.ok(refreshCall.init.headers["Ual-Access-Nonce"])
186
+ assert.equal(refreshCall.init.headers["Ual-Access-Openid"], "OID")
187
+ assert.equal(refreshCall.init.headers["Ual-Access-Guid"], "0".repeat(32))
188
+ // ⚠ 模型网关那套 UAL 头**不能**混进来 —— 加了会从 200 变 400
189
+ assert.equal(refreshCall.init.headers["Ual-Access-MarvisExt"], undefined)
190
+
191
+ // ⑤ 空串回退:响应 refresh_token 是 "" 时保留旧的
192
+ assert.equal(out.refresh, "RT_OLD", "空串是「没给新值」,不能覆盖旧 refresh_token")
193
+ assert.equal(out.access, "mv_NEW")
194
+ // ④ expires 按 expires_in=7200 秒算,不是 30 天
195
+ const ttl = out.expires - Date.now()
196
+ assert.ok(ttl > 7_000_000 && ttl < 7_300_000, `expires 应约 2 小时后,实际 ${ttl}ms`)
197
+ // 合并语义:metadata 不能丢
198
+ assert.equal(out.metadata.openid, "OID")
199
+ assert.equal(out.metadata.guid, "0".repeat(32))
200
+ assert.equal(out.metadata.loginType, "2")
201
+ } finally {
202
+ restore()
203
+ }
204
+ })
205
+
206
+ test("refresh:响应给了新 refresh_token 时用新的", async () => {
207
+ const restore = stubFetch(async () => refreshResponse({ access_token: "mv_2", refresh_token: "RT_NEW" }))
208
+ try {
209
+ const out = await refreshHook()(
210
+ account({
211
+ access: "mv_1",
212
+ refresh: "RT_OLD",
213
+ metadata: { openid: "OID2", guid: "1".repeat(32), loginType: "1" },
214
+ }),
215
+ )
216
+ assert.equal(out.refresh, "RT_NEW")
217
+ assert.equal(out.access, "mv_2")
218
+ } finally {
219
+ restore()
220
+ }
221
+ })
222
+
223
+ test("refresh:没有 refresh_token 时直接返回 {}(不凭空造,也不发请求)", async () => {
224
+ let called = false
225
+ const restore = stubFetch(async () => {
226
+ called = true
227
+ return refreshResponse({ access_token: "x" })
228
+ })
229
+ try {
230
+ const out = await refreshHook()(account({ access: "a", refresh: "", metadata: {} }))
231
+ assert.deepEqual(out, {})
232
+ assert.equal(called, false, "没有 refresh_token 就不该发请求")
233
+ } finally {
234
+ restore()
235
+ }
236
+ })
237
+
238
+ // ─────────────────────────────────────────────────────────────
239
+ // ③ 错误分类:只有会话/ token 校验失败才标 signIn=expired
240
+ // ─────────────────────────────────────────────────────────────
241
+
242
+ test("refresh:-107/-101 标 signIn=expired,-109/-7/-5 不标(参数/签名错不是登录失效)", async () => {
243
+ const cases = [
244
+ [-107, true],
245
+ [-101, true],
246
+ [-109, false],
247
+ [-7, false],
248
+ [-5, false],
249
+ ]
250
+ for (const [code, fatal] of cases) {
251
+ const restore = stubFetch(
252
+ async () => new Response(JSON.stringify({ code, msg: `err${code}` }), { status: 200 }),
253
+ )
254
+ try {
255
+ await assert.rejects(
256
+ () =>
257
+ refreshHook()(
258
+ account({
259
+ access: "a",
260
+ refresh: `RT_${code}`,
261
+ metadata: { openid: `OID_${code}`, guid: "2".repeat(32), loginType: "2" },
262
+ }),
263
+ ),
264
+ (err) => {
265
+ assert.equal(
266
+ err.signIn === "expired",
267
+ fatal,
268
+ `code=${code} 的 signIn 应该是 ${fatal ? "expired" : "不设"}`,
269
+ )
270
+ assert.match(err.message, new RegExp(`code=${code}`))
271
+ return true
272
+ },
273
+ )
274
+ } finally {
275
+ restore()
276
+ }
277
+ }
278
+ })
279
+
280
+ test("refresh:非 JSON 响应报清楚,不假装成功", async () => {
281
+ const restore = stubFetch(async () => new Response("<html>502</html>", { status: 502 }))
282
+ try {
283
+ await assert.rejects(
284
+ () =>
285
+ refreshHook()(
286
+ account({
287
+ access: "a",
288
+ refresh: "RT_html",
289
+ metadata: { openid: "OID_html", guid: "3".repeat(32) },
290
+ }),
291
+ ),
292
+ /不是 JSON(502)/,
293
+ )
294
+ } finally {
295
+ restore()
296
+ }
297
+ })
298
+
299
+ test("refresh:网络异常时抛可读错误(不是 undefined is not a function)", async () => {
300
+ const restore = stubFetch(async () => {
301
+ throw new TypeError("fetch failed")
302
+ })
303
+ try {
304
+ await assert.rejects(
305
+ () =>
306
+ refreshHook()(
307
+ account({
308
+ access: "a",
309
+ refresh: "RT_net",
310
+ metadata: { openid: "OID_net", guid: "4".repeat(32) },
311
+ }),
312
+ ),
313
+ /续期请求发不出去/,
314
+ )
315
+ } finally {
316
+ restore()
317
+ }
318
+ })
@@ -0,0 +1,18 @@
1
+ import test from "node:test"
2
+ import assert from "node:assert/strict"
3
+ import { requestIdentity } from "../src/marvis/protocol.mjs"
4
+
5
+ test("requestIdentity 把同一组 id 写进 bus_info", () => {
6
+ const id = requestIdentity(
7
+ { openid: "openid-1", loginType: "2" },
8
+ { model: "main-auto", nonce: "nonce-1", conversationId: "conv_abc", responseId: "resp_def" },
9
+ )
10
+ assert.equal(id.agentTag, "main")
11
+ assert.equal(id.scene, "agent_chat")
12
+ assert.equal(id.loginType, "2")
13
+ assert.match(id.busInfo, /marvisConversationID=conv_abc/)
14
+ assert.match(id.busInfo, /marvisResponseID=resp_def/)
15
+ assert.match(id.busInfo, /model=main-auto/)
16
+ assert.match(id.busInfo, /nonce=nonce-1/)
17
+ assert.match(id.busInfo, /originOpenID=openid-1/)
18
+ })
@@ -0,0 +1,66 @@
1
+ // tests/tool-schema.test.mjs —— Marvis 工具 schema 兼容
2
+ //
3
+ // 实测:DSH 的 bash 工具 parameters 省略了 type:"object",Marvis 直接 400
4
+ // invalid parameter;补上后 57 个工具 + reasoning_effort + 流式全部 200。
5
+
6
+ import test from "node:test"
7
+ import assert from "node:assert/strict"
8
+
9
+ import { withObjectType, normalizeTools } from "../src/marvis/tool-schema.mjs"
10
+
11
+ const BASH = {
12
+ type: "function",
13
+ function: {
14
+ name: "bash",
15
+ description: "run",
16
+ parameters: {
17
+ additionalProperties: false,
18
+ properties: {
19
+ command: { type: "string" },
20
+ description: { type: "string" },
21
+ idle_seconds: { maximum: 900, minimum: 1, type: "integer" },
22
+ },
23
+ required: ["command", "description"],
24
+ },
25
+ },
26
+ }
27
+
28
+ test("缺少 type 的 parameters 补成 object,且不动 additionalProperties", () => {
29
+ const out = withObjectType(BASH.function.parameters)
30
+ assert.equal(out.type, "object")
31
+ assert.equal(out.additionalProperties, false)
32
+ assert.deepEqual(out.required, ["command", "description"])
33
+ assert.equal(out.properties.command.type, "string")
34
+ })
35
+
36
+ test("递归补嵌套 object", () => {
37
+ const schema = {
38
+ properties: {
39
+ opts: { properties: { level: { type: "integer" } } },
40
+ list: { type: "array", items: { properties: { x: { type: "string" } } } },
41
+ },
42
+ }
43
+ const out = withObjectType(schema)
44
+ assert.equal(out.type, "object")
45
+ assert.equal(out.properties.opts.type, "object")
46
+ assert.equal(out.properties.list.items.type, "object")
47
+ })
48
+
49
+ test("已经有 type 时原样返回(同一引用)", () => {
50
+ const schema = { type: "object", properties: { a: { type: "string" } } }
51
+ assert.equal(withObjectType(schema), schema)
52
+ })
53
+
54
+ test("normalizeTools:只改需要改的工具,返回新数组", () => {
55
+ const typed = { type: "function", function: { name: "x", parameters: { type: "object", properties: {} } } }
56
+ const out = normalizeTools([BASH, typed])
57
+ assert.notEqual(out, undefined)
58
+ assert.equal(out[0].function.parameters.type, "object")
59
+ assert.equal(out[1], typed, "已合规的工具保持原对象")
60
+ })
61
+
62
+ test("normalizeTools:全部合规时返回原数组", () => {
63
+ const tools = [{ type: "function", function: { name: "x", parameters: { type: "object", properties: {} } } }]
64
+ assert.equal(normalizeTools(tools), tools)
65
+ assert.equal(normalizeTools(undefined), undefined)
66
+ })