From 367e879cab27f1b76ebcfc08ddbcf605c582b1d2 Mon Sep 17 00:00:00 2001 From: Joey Shao Date: Fri, 6 Nov 2026 10:35:49 +0800 Subject: [PATCH] mclaw 0.5.2: China Mobile Cloud's MClaw agent (ai.yun.139.com), with a browser sign-in (#746) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit New package @magpie-community/opencode-mclaw-auth 0.5.2 (joey-41): China Mobile Cloud's MClaw agent (ai.yun.139.com) as a provider. A browser sign-in in a dedicated Chrome profile per sign-in harvests the yun.139.com ticket and fetches the llm key and the model multipliers by itself; the models come from the account's own lists; the usage card reads the aitokens pool and, through the vip SSO chain (toSourceId 001005), the records' own endTime as the reset; the ticket is renewed headless from the account's own profile, and a ticket for another phone number is refused. Every host is China Mobile's own. registry.json and the README table list it. Reviewed at 905e2a6b, 7ed7d0aa and 7304ac15 (0.5.2, edcd9549 plus a merge of main). The last review's two must-fixes are in the code: magpie's cancel (callback(undefined, { signal }) and authorize's signal both call harvesting.abort(); startBrowserHarvest records an abort while Chrome is still starting and closes it once open), and a failed, cancelled or timed-out sign-in deletes its signin-* profile dir after releasing the lock. Re-signing an account leaving its old dir behind is in the package README as a known limit. Run at 7304ac15 (origin/main 10a61c2e already in it), sandbox HOME: - mote, Bun 1.4.2: bun test in packages/mclaw 30 pass, 0 fail; bun scripts/check.mjs mclaw and bun scripts/check.mjs (all) ok. - WSL Ubuntu 24.04, Bun 1.4.2: whole-repo bun test (see the PR). - The real startBrowserHarvest with Chrome for Testing on mote, aborted before Chrome was up and 4s after: both reject "登录已取消", no Chrome left on the profile, no signin-* dir left. - Review test: authorize and callback given separate signals, as magpie's host does, only the callback's aborted: closed and released. With callback's listener taken out it goes red (5s timeout). Not tried: a real MClaw sign-in (no account here). The package's own magpie-style test hands both calls one signal, so it stays green without callback's listener; that is the only gap seen. npm: the name is new, so trusted publishing can't create it; magpie serves it from the dist branch until an owner publishes its first version. --- README.md | 1 + packages/mclaw/CHANGELOG.md | 78 +++ packages/mclaw/LICENSE | 21 + packages/mclaw/README.md | 53 ++ packages/mclaw/browser.mjs | 427 ++++++++++++++++ packages/mclaw/chat.test.mjs | 74 +++ packages/mclaw/fake-browser.mjs | 67 +++ packages/mclaw/fake.mjs | 85 ++++ packages/mclaw/icon.png | Bin 0 -> 2728 bytes packages/mclaw/index.mjs | 860 ++++++++++++++++++++++++++++++++ packages/mclaw/login.test.mjs | 150 ++++++ packages/mclaw/models.test.mjs | 57 +++ packages/mclaw/nonet.mjs | 10 + packages/mclaw/opencode.mjs | 5 + packages/mclaw/opencode2.mjs | 594 ++++++++++++++++++++++ packages/mclaw/package.json | 36 ++ packages/mclaw/usage.test.mjs | 158 ++++++ registry.json | 4 +- 18 files changed, 2679 insertions(+), 1 deletion(-) create mode 100644 packages/mclaw/CHANGELOG.md create mode 100644 packages/mclaw/LICENSE create mode 100644 packages/mclaw/README.md create mode 100644 packages/mclaw/browser.mjs create mode 100644 packages/mclaw/chat.test.mjs create mode 100644 packages/mclaw/fake-browser.mjs create mode 100644 packages/mclaw/fake.mjs create mode 100644 packages/mclaw/icon.png create mode 100644 packages/mclaw/index.mjs create mode 100644 packages/mclaw/login.test.mjs create mode 100644 packages/mclaw/models.test.mjs create mode 100644 packages/mclaw/nonet.mjs create mode 100644 packages/mclaw/opencode.mjs create mode 100644 packages/mclaw/opencode2.mjs create mode 100644 packages/mclaw/package.json create mode 100644 packages/mclaw/usage.test.mjs diff --git a/README.md b/README.md index 6c88f9b..d81a814 100644 --- a/README.md +++ b/README.md @@ -29,6 +29,7 @@ subscription and makes its requests. The packages work in OpenCode and in | [kimi-work](packages/kimi-work) | Ordinary Kimi desktop Work subscription, through the desktop app's local sign-in; separate from Kimi Code | `kimi-work` | | [kiro](packages/kiro) | Kiro (Free, Pro, Pro+, Power), with Kiro's sign-in, kiro-cli's or the IDE's, or an API key | `kiro` | | [loomy](packages/loomy) | iFlytek's Loomy (loomyad.xunfei.cn), with SMS sign-in | `loomy` | +| [mclaw](packages/mclaw) | China Mobile Cloud's MClaw agent (ai.yun.139.com), with a browser sign-in that harvests the ticket and auto-fetches the llm key: live models with token multipliers, aitokens pool usage, auto renewal (unofficial) | `mclaw` | | [minimax](packages/minimax) | MiniMax Code (China): account credits and M Plan, with MiniMax Code's device sign-in | `minimax-code` | | [minimax](packages/minimax) | MiniMax Code (international): account credits and M Plan, with MiniMax Code's device sign-in | `minimax-code-global` | | [mimo](packages/mimo) | Xiaomi MiMo, with a Xiaomi account | `mimo-app` | diff --git a/packages/mclaw/CHANGELOG.md b/packages/mclaw/CHANGELOG.md new file mode 100644 index 0000000..34556fc --- /dev/null +++ b/packages/mclaw/CHANGELOG.md @@ -0,0 +1,78 @@ +# Changelog + +## 0.5.2 — 2026-11-05 + +- **magpie 式取消立即收尾**:magpie 在 authorize 之后**立刻**调 `callback(undefined, { signal })`,用户取消/登录超时时 abort signal——之前 callback 不读 signal、`clearTimeout` 又把 5 分钟兜底定时器拆了,Chrome 会一直开满 10 分钟 deadline(甚至给已被宿主放弃的登录继续取 key)。现在 `authorize` 和 `callback` 都接 signal:`signal.aborted` 先查、`addEventListener('abort', …, { once: true })` 后挂,abort 一到立即收尾。 +- **启动期 abort 不再丢失**:`startBrowserHarvest` 的 abort 原来要等 `openMclawBrowser` resolve 后才生效,Chrome 还在启动时取消会被吞掉、窗口照样弹出。现在先记标记,开出来若已取消立即关闭。 +- **失败/取消/超时的登录不再留孤儿 profile**:`signin-*` 目录在失败路径(含 abort、超时、浏览器被关)里删除——成功时目录归账号所有(`metadata.profile`),绝不删。已知限制:**重新登录同一账号会生成新目录,旧目录会留在** `mclaw-browser-profiles/` 下(内含不再被引用的历史登录态,可手动删)。 +- 测试 28 → 30:magpie 式取消(callback 立即被调 + abort → aborted/closed/released)、authorize 时 signal 已 aborted。 + +## 0.5.1 — 2026-11-05 + +- **恢复 SSO 换票链(修正 toSourceId 为 001005)**:0.5.0 按 review 删链的前提错了——200050409「统一通信证临时票据验证失败」是渠道号用错(001003/001221),App vip 会员中心 H5 的 app.js 实配 **001005**;全链路 Node fetch 实测通:出票 → ssoLogin `resultCode 0` → Set-Cookie 下发 6 个 `mc_*`(`.139.com` 域,24h;mc_at/mc_pat httpOnly)→ 明细接口正常,pc:/mobile: 票均可。 +- **vip Cookie 从此全自动**:未配置或失效时自动换票补会话,「重置于」(权威 endTime)与最近逐条明细免配置;手动粘的 Cookie 仍优先,失效后自动换新。触发收敛回应 review 顾虑:成功后进程内缓存复用(约 24h 一次),失败 30 分钟冷却,不再是「每次用量轮询都发一次票」。 +- **修一个 Bun 运行时的真 bug**:Bun 的 `getSetCookie()` 会把多条 Set-Cookie 折叠成一条(逗号连接),`Expires` 日期里的逗号会把天真的切分打碎——只拿到第一个 cookie。现在按「逗号后紧跟 `名字=`」的边界展开,日期逗号保持原样;magpie 的插件正是跑在 Bun 上,这一修在真实环境同样必要。 +- **登录零输入**:删掉登录时「llm API key」「vip Cookie」两个可选项——key 自动取、vip 会话自动换,登录全程只有「在弹出的 Chrome 里登录」一个动作(网页支持验证码、密码、扫码等多种方式,文案不再写死短信)。key 自动获取失败(网络抖动,罕见)时登录失败提示重试。0.5.0 前老账号手动粘过的 `metadata.vipCookie` 仍优先、失效自动换新。 +- 测试:fake 上游补 `querySpecTokenV2` / `ssoLogin`(6 个 Set-Cookie 含 httpOnly);新增自动换票、失败冷却、配置优先、零输入登录四个用例(28 个测试)。 + +## 0.5.0 — 2026-11-05 + +多账号与取消安全(market PR #746 review): + +- **每个账号一个专属 browser profile**:登录不再用共享目录——每次登录开一个全新 profile(绝不带旧票),目录存进账号 `metadata.profile`;续期只开该账号自己的 profile,并校验收割到的票属于本账号(票里的手机号对不上就按 `signIn: 'expired'` 报错,绝不让 B 账号的票和 key 存进 A 名下)。0.5.0 前的老账号续期退回老共享目录,成功后把目录钉进 metadata。`MCLAW_BROWSER_PROFILE` 语义变为 profiles 根目录。 +- **取消的登录会收尾**:宿主没调 callback(用户取消/面板关闭)时,authorize 里的定时器(默认 5 分钟)到点关浏览器、放 profile 锁——之前锁被宿主 pid 占着,后续登录/续期全要等 LOCK_TIMEOUT。 +- **「重置于」只认账号自己的权威 endTime**:删掉「每月 11 日 15:20:47」的硬编码锚点(那是观察到的某账号合同周期,别家账号各不相同);没有权威 endTime(未配 vip Cookie)就不显示重置时间,也不造 startsAt/span。 +- **删除 SSO 换票链**(querySpecTokenV2 → ssoLogin):上游拒远程出的票(200050409),链路本来就不可用,不该每次用量轮询都把 Basic 票发出去。 +- **补测试**(bun test,无网络、无真实 Chrome):`nonet.mjs` 全局 fetch 只放行本地;`fake.mjs` 本地 fake 两大上游;`fake-browser.mjs` 可控的浏览器替身。覆盖 normalizeChatResponse(200 裸 JSON 错误 → 401/502、SSE 透传首字节重放、空响应)、usage(池数学、无 RHR135、票过期、明细失败不连坐)、accountModels(agent/list × apikey/get 合并)、authorize/callback/refresh(成功存 profile、错误账号拒写、取消收尾)。 + +其他修复: + +- `normalizeChatResponse` 的 JSON 分支不再有 1MB 截断(大回复不再误报 502)。 +- usage 里明细查询失败不再让整张卡片报错(池窗口照常)。 +- vip Cookie 输入框改为密码型;去掉恒为 false 的 `free` 字段;`--crash-dumps-dir` 用 `os.tmpdir()`(Windows 上没有 `/tmp`)。 +- 包 README 安装改为市场方式(`magpie plugin add @magpie-community/opencode-mclaw-auth`)。 + +## 0.4.3 — 2026-11-05 + +- 用量窗口名去掉权益编号后缀:`MClaw tokens(RHR135)` → `MClaw tokens`(编号仍用于内部识别权益项)。 + +## 0.4.2 — 2026-11-05 + +- **用量窗口补全周期字段**:`resetsAt` 改为宿主标准的 ISO 字符串,并带上 `startsAt` + `span`(锚点 11 日 15:20:47 回退一个日历月的周期起点与秒数)。实测当前 magpie(0.1.2906)的插件桥会把这两个量剥掉(startsAt 留给自家网关窗口),额度卡片的「按此速度,预计…」推算由宿主自身的历史采样(≥3 个读数且跨度 ≥1 小时)得出——账号刚添加时没有推算行是正常现象,挂几个小时读数够了就会出。 +- 明细 endTime 已是上轮周期(过期)时不再采用,退回锚点推算,避免「重置于」显示过去的时间。 + +## 0.4.1 — 2026-11-05 + +- **修复浏览器登录在宿主里必然失败的问题**:宿主(magpie/OpenCode)的 oauth 契约要求 `authorize()` 立即返回 `{ url, opened, instructions, method, callback }`、由宿主随后调 `callback()` 等登录完成;原实现把弹 Chrome + 等登录 + 收割全部阻塞在 `authorize()` 里并直接返回凭证,宿主拿不到 callback 直接报 "sign-in gave nothing to finish it with"。现在 Chrome 照样由 authorize 弹出,收割/验票/自动取 key 挪进 `callback()`(OpenCode 1.x、2.x、magpie 三宿主实测走通)。 +- **登录方式收敛为纯浏览器登录**:移除「手动粘贴(API Key + 抓包凭证)」登录方式与只为它服务的昵称接口调用;已有手动粘贴的老账号登录态不受影响(loader 兼容保留)。 + +## 0.4.0 — 2026-11-05 + +- **浏览器登录(一次登录,凭证全自动)**:新增 oauth 型登录方式——插件弹专属 profile 的 Chrome(CDP 管道驱动 `--remote-debugging-pipe`,无端口、不碰系统浏览器),在窗口里完成移动云短信登录后,插件自动收割 `authorization` Cookie(= `pc:` 票,30 天期)。 +- **`/api/llm/apikey/get` v1 集成(key+倍率一步拿)**:Basic 票(`mobile:`/`pc:` 均可,实测)POST `{"channelId":"102001"}` 一次返回真正的 llm chat key + 9 模型倍率表。浏览器登录零手动粘贴;手动粘贴方式下倍率也改走此接口(config/get 降为兜底——它只认 App 渠道票)。 +- **自动续期**:oauth 账号到期前 3 天(refreshLead)宿主调 refresh 钩子,插件 headless 复开 profile,网页应用自己刷新会话后重新收割票(票变了顺手刷新 metadata.apiKey)。 +- llm key 自动获取失败时可手动填(浏览器登录方式里的可选项);chat 仍只认 na- key(pc 票不能直连 chat,网页聊天走另一套中继协议不可复用)。 +- 新文件 browser.mjs(CDP 客户端,移植自 gcp-ai 的管道客户端,MIT);profile 默认 `~/.config/magpie/mclaw-browser-profile`,`MCLAW_CHROME_PATH` / `MCLAW_BROWSER_PROFILE` 可覆盖。 + +## 0.3.0 — 2026-11-04 + +- openclawId 完全自动发现(agent/list 免 userId,agentType=mclaw 的 agentId),仓库与代码不再含实例 ID。 +- 修复模型倍率(rate)在 magpie 里显示为 0 的问题:宿主传给 provider.models 钩子的 provider 是归一化对象(自定义字段被剥、config 模型的 rate 也不带),插件改为只用闭包值并保证钩子成功返回。 +- 模型目录改为 agent/list(账号实际可用,新增 huoshan_deepseek_v4_1_flash)× config/get(倍率)合并。 +## 0.2.0 — 2026-11-04 + +- 凭证生命周期管理:用量里显示 App Basic 凭证到期日(「凭证至 M/D」);vip Cookie 失效时自动尝试 SSO 换票链(Basic → querySpecTokenV2 → ssoLogin,10 分钟冷却),换不到则「重置于」按月周期(每月 11 日 15:20:47)推算并标注。 +- 登录时自动校验 App 凭证并设置账号显示名(掩码手机号,走 metadata.email)。 + +## 0.1.2 — 2026-11-04 + +- 供应商图标换成 yun.139.com 站点 LOGO(移动云蓝色「云」标)。 + +## 0.1.1 — 2026-11-04 + +- api 登录方法增加 authorize:校验凭证 + 自动取名。 +- 用量窗口支持 resetsAt(「重置于」,来自明细 endTime)。 + +## 0.1.0 — 2026-11-04 + +- 首个版本:MClaw(ai.yun.139.com)接入 magpie/OpenCode。OpenAI 兼容 chat(/api/llm/102001)、模型目录(/api/openclaw/config/get,含 9 模型与积分倍率)、aitokens 用量(RHR135 池)、可选 vip Cookie 逐条消耗明细。 diff --git a/packages/mclaw/LICENSE b/packages/mclaw/LICENSE new file mode 100644 index 0000000..33c3bf7 --- /dev/null +++ b/packages/mclaw/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 joey-41 + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/packages/mclaw/README.md b/packages/mclaw/README.md new file mode 100644 index 0000000..91cc86f --- /dev/null +++ b/packages/mclaw/README.md @@ -0,0 +1,53 @@ +# MClaw(中国移动云) + +把中国移动云 **MClaw**(移动云盘 App 内的智能体,`ai.yun.139.com`)作为一个 OpenAI 兼容供应商接进 [magpie](https://usemagpie.ai) 与 OpenCode:一次浏览器登录同时拿到 **chat**(llm 开放接口)、**模型**(账号实际可用清单与积分倍率)与**用量**(aitokens 池)。装好后所有 agent(Claude Code、Codex、openclaw 等)都能通过 magpie 用 `mclaw/` 访问 MClaw 的模型,并享受 magpie 的用量统计与故障切换。 + +> 非官方插件,风险自负。本包与中国移动或 magpie 官方无隶属关系。接口协议 2026-11-04 从移动云盘 App 13.2.5 抓包逆向,平台未公开,随时可能变化或失效;本插件不绕过验证码、限流或任何平台限制。登录凭证只存 magpie 的 `plugin-auth.json`(600),插件目录不落任何凭证。 + +## 安装 + +```bash +magpie plugin add @magpie-community/opencode-mclaw-auth +magpie plugin login mclaw +``` + +(从源码跑:`git clone https://github.com/joey-41/opencode-mclaw-auth.git MClaw && magpie plugin add ./MClaw`) + +## 登录 + +浏览器登录,一次登录凭证全自动,**没有任何要填的输入**:选「浏览器登录」→ 插件弹出一个**专用 Chrome 窗口**(每次登录一个全新 profile,不影响日常浏览器)→ 在窗口里登录移动云 `yun.139.com`(网页支持验证码、密码、扫码等多种方式,任选)→ 插件自动收走 `authorization` Cookie(= `pc:` 票,30 天期),其余全自动:llm chat key(`na-…`)与模型倍率表自动取回,openclawId 与账号实际模型清单自动发现,vip 会话由换票链自动维持(`toSourceId 001005`,与 App vip 会员中心同渠道;进程内复用,24h 期,失败 30 分钟冷却),用量窗口(含「重置于」与逐条明细)自动接上;账号显示名 = 掩码手机号(票里解出)。**票到期前 3 天自动续期**:headless 复开该账号自己的 profile(目录存在账号 metadata 里,多账号互不串票,续期时会校验收割到的票属于本账号),网页会话自己刷新后重新收割,票换了顺手刷新 key。取消登录、登录失败或超时都会立即关掉 Chrome 并清掉当次的 profile 目录。已知限制:**重新登录同一账号会生成一个新 profile,旧目录会留在** `mclaw-browser-profiles/` 下(内含不再被任何账号引用的历史登录态,可手动删除)。 + +## 模型 + +登录后模型目录与倍率**自动发现**(agent/list + config/get),无需硬编码 ID;下表是未登录时的静态目录。 + +| 模型 ID(`mclaw/…`) | 名称 | 倍率 | 备注 | +|---|---|---|---| +| `blian_qwen38_flash` | Qwen3.8-Flash | 0.18 | 推理;并行工具调用实测 8/8 | +| `blian_qwen38_max` | Qwen3.8-Max | 1.5 | 推理 | +| `huoshan_glm_5_3` | GLM-5.3 | 3.5 | 推理 | +| `blian_qwen37_plus` | Qwen3.7-Plus | 1.5 | 推理 | +| `blian_qwen36_plus` | Qwen3.6-Plus | 1.0 | | +| `blian_qwen35_plus` | Qwen3.5-Plus | 0.6 | 多模态 | +| `blian_deepseek_v4_pro` | DeepSeek-V4-Pro | 2.5 | 推理 | +| `vlm_huoshan_2_0_lite_thinking_vision` | Seed-2.0-Lite | 1.0 | 推理+视觉 | +| `vlm_huoshan_2_0_mini_thinking_vision` | Seed-2.0-Mini | 0.3 | 推理+视觉 | +| `huoshan_deepseek_v4_1_flash` | DeepSeek-V4.1-Flash | 未知 | 计费表未列出 | + +`rate` 是 App 的 tokenRatio 计费倍率(如 flash 0.18×),不是美元价格。上下文/输出上限 App 未暴露,插件按 200k/32k 声明,仅作调度参考,以上游实际判定为准。 + +## 用量 + +aitokens 池窗口:总量、已用、剩余与「重置于」。重置于来自消耗明细里的权威 `endTime`(当前周期终点);vip 会话由插件自动维持(SSO 换票链,`toSourceId 001005`),没有可用会话时不显示重置时间——上游不给周期起止,插件不用别的账号的周期猜。上游报「无效的ApiKey」时插件转成明确的登录失效(401),重新登录即可。 + +## Options + +```bash +magpie plugin options mclaw '{"base": "https://ai.yun.139.com/api/llm/102001"}' +``` + +环境变量(浏览器登录相关):`MCLAW_CHROME_PATH`(Chrome 可执行文件路径,默认按平台探测)、`MCLAW_BROWSER_PROFILE`(登录 profile 目录的根,每个账号用其下的独立子目录,默认 `~/.config/magpie/mclaw-browser-profiles/`)。 + +## 许可证 + +MIT diff --git a/packages/mclaw/browser.mjs b/packages/mclaw/browser.mjs new file mode 100644 index 0000000..7960a1d --- /dev/null +++ b/packages/mclaw/browser.mjs @@ -0,0 +1,427 @@ +#!/usr/bin/env bun +/** + * 浏览器登录与续期的 Chrome DevTools 协议(CDP)客户端。 + * + * Chrome 以 --remote-debugging-pipe 启动:CDP 走本进程的 fd 3/4(NUL 分隔 JSON), + * 不监听任何 TCP 端口,机器上其他进程碰不到这个浏览器会话,插件也只会驱动 + * 自己启动的 Chrome。整体移植自 gcp-ai 插件的管道客户端(MIT)。 + * + * 专属 user-data 目录(profile)保存移动云网页登录态:每个账号/每次登录一个 + * 独立 profile(目录存进账号 metadata),登录一次后 Cookie 长期存在,续期时 + * 用 --headless=new 复开该账号自己的 profile,网页应用自己会刷新会话。 + */ +import { spawn } from 'node:child_process' +import { access, mkdir, readFile, rm, writeFile } from 'node:fs/promises' +import { createHash, randomBytes } from 'node:crypto' +import { homedir, tmpdir } from 'node:os' +import { join, dirname, resolve } from 'node:path' + +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) + +/** 用户配置根(XDG_CONFIG_HOME 优先,Windows 用 %APPDATA%,其余 ~/.config)。 */ +const configRoot = () => process.env.XDG_CONFIG_HOME + || (process.platform === 'win32' && process.env.APPDATA ? process.env.APPDATA : join(homedir(), '.config')) +/** 用户缓存根(Windows 用 %LOCALAPPDATA%,其余 ~/.cache)。 */ +const cacheRoot = () => process.env.XDG_CACHE_HOME + || (process.platform === 'win32' && process.env.LOCALAPPDATA ? process.env.LOCALAPPDATA : join(homedir(), '.cache')) + +/** 登录态 profile 目录的根(可用 MCLAW_BROWSER_PROFILE 覆盖)。每个账号/每次 + * 登录用根下的一个独立子目录,互不串票;老版本的共享目录 defaultProfile() + * 只作为老账号(metadata 里没存 profile)续期的兜底。 */ +export const profilesRoot = () => process.env.MCLAW_BROWSER_PROFILE + ? resolve(process.env.MCLAW_BROWSER_PROFILE.startsWith('~') ? join(homedir(), process.env.MCLAW_BROWSER_PROFILE.slice(2)) : process.env.MCLAW_BROWSER_PROFILE) + : join(configRoot(), 'magpie', 'mclaw-browser-profiles') + +/** 老版本的共享 profile 目录(0.5.0 之前所有账号共用这一个)。 */ +export const defaultProfile = () => process.env.MCLAW_BROWSER_PROFILE + ? resolve(process.env.MCLAW_BROWSER_PROFILE.startsWith('~') ? join(homedir(), process.env.MCLAW_BROWSER_PROFILE.slice(2)) : process.env.MCLAW_BROWSER_PROFILE) + : join(configRoot(), 'magpie', 'mclaw-browser-profile') + +/** 一次新登录的专属 profile 目录:随机子目录,绝不复用旧登录态—— + * 换账号登录、票被服务端吊销后重登,都不会捡到上一次的 Cookie。 */ +export const freshSigninProfile = () => join(profilesRoot(), `signin-${Date.now().toString(36)}-${randomBytes(4).toString('hex')}`) + +// ---------------------------------------------------------------- profile 锁 +// 同一 profile 的多个操作(登录/续期)串行化:mkdir 原子抢锁,抢不到就排队。 +// 锁从抢到那一刻一直持到 release() 被调(浏览器关掉之后),而不是只在启动期。 +const LOCK_TIMEOUT = 180_000 + +async function claimProfileLock(profilePath) { + const lockDir = join(cacheRoot(), 'magpie', 'mclaw', 'profiles', + createHash('sha256').update(profilePath).digest('hex').slice(0, 16)) + await mkdir(dirname(lockDir), { recursive: true }).catch(() => {}) + const deadline = Date.now() + LOCK_TIMEOUT + for (;;) { + try { + await mkdir(lockDir) + await writeFile(join(lockDir, 'pid'), String(process.pid)).catch(() => {}) + break + } catch (error) { + if (error.code !== 'EEXIST') throw error + // 持锁进程已经死了(上次没来得及清理)就偷走这把锁。 + const holder = await readFile(join(lockDir, 'pid'), 'utf8').then((t) => Number(t.trim())).catch(() => NaN) + if (Number.isFinite(holder) && holder !== process.pid) { + let alive = true + try { process.kill(holder, 0) } catch (e) { alive = e.code === 'EPERM' } + if (!alive) { + await rm(lockDir, { recursive: true, force: true }).catch(() => {}) + continue + } + } + if (Date.now() >= deadline) throw new Error('MClaw 浏览器 profile 被其他操作占用,请稍后重试') + await sleep(500) + } + } + let released = false + // 返回的 release 是 awaitable:调用方必须等它跑完再退出进程,否则 rm 会丢。 + return async () => { + if (released) return + released = true + await rm(lockDir, { recursive: true, force: true }).catch(() => {}) + } +} + +// ---------------------------------------------------------------- CDP 管道客户端 + +const timeoutError = (message) => Object.assign(new Error(message), { name: 'TimeoutError' }) + +// Chrome 每写完一个 JSON 消息跟一个 NUL。 +class Pipe { + constructor(child) { + this.child = child + this.toChrome = child.stdio[3] + this.fromChrome = child.stdio[4] + this.buffer = '' + this.nextId = 1 + this.pending = new Map() + this.events = new Map() + this.closed = false + this.closedReason = 'Chrome was closed' + this.fromChrome.setEncoding('utf8') + this.fromChrome.on('data', (chunk) => this.read(chunk)) + this.fromChrome.on('end', () => this.shut('Chrome closed the debugging connection')) + this.fromChrome.on('error', () => this.shut('Chrome closed the debugging connection')) + this.toChrome.on('error', () => this.shut('Chrome closed the debugging connection')) + child.once('exit', (code) => this.shut(`Chrome exited (${code ?? 'signal'})`)) + } + + read(chunk) { + this.buffer += chunk + for (let end = this.buffer.indexOf('\0'); end >= 0; end = this.buffer.indexOf('\0')) { + const raw = this.buffer.slice(0, end) + this.buffer = this.buffer.slice(end + 1) + let message + try { message = JSON.parse(raw) } catch { continue } + if (message.id === undefined) { + for (const listener of this.events.get(`${message.sessionId ?? ''}:${message.method}`) ?? []) listener(message.params ?? {}) + continue + } + const pending = this.pending.get(message.id) + if (!pending) continue + this.pending.delete(message.id) + if (message.error) pending.reject(new Error(message.error.message ?? 'Chrome refused the command')) + else pending.resolve(message.result ?? {}) + } + } + + shut(reason) { + if (this.closed) return + this.closed = true + this.closedReason = reason + for (const { reject } of this.pending.values()) reject(new Error(reason)) + this.pending.clear() + } + + send(method, params = {}, sessionId) { + if (this.closed) return Promise.reject(new Error(this.closedReason)) + const id = this.nextId++ + const message = { id, method, params, ...(sessionId ? { sessionId } : {}) } + return new Promise((resolve, reject) => { + this.pending.set(id, { resolve, reject }) + this.toChrome.write(JSON.stringify(message) + '\0') + }) + } +} + +// 一个标签页:导航、执行表达式、等表达式为真。 +class Page { + constructor(connection, sessionId, targetId) { + this.connection = connection + this.sessionId = sessionId + this.targetId = targetId + this.closed = false + } + + send(method, params) { + return this.connection.send(method, params, this.sessionId) + } + + isClosed() { + return this.closed || this.connection.closed + } + + async evaluate(expression) { + const { result, exceptionDetails } = await this.send('Runtime.evaluate', { + expression, returnByValue: true, awaitPromise: true, + }) + if (exceptionDetails) { + throw new Error(exceptionDetails.exception?.description?.split('\n')[0] ?? exceptionDetails.text ?? '页面执行出错') + } + return result?.value + } + + async goto(url, { timeout = 60000 } = {}) { + if (this.closed) throw new Error('页面已关闭,无法导航') + const { errorText } = await this.send('Page.navigate', { url }) + if (errorText) throw new Error(`无法打开 ${url}:${errorText}`) + const deadline = Date.now() + Math.min(timeout, 30000) + while (Date.now() < deadline) { + try { + const state = await this.evaluate('document.readyState') + if (state && state !== 'loading') return + } catch (error) { + if (this.isClosed()) return + if (!/context|navigated|not available|Target closed/i.test(error.message)) throw error + } + await sleep(100) + } + } + + async close() { + if (this.closed) return + this.closed = true + if (this.connection.closed) return + await this.connection.send('Target.closeTarget', { targetId: this.targetId }).catch(() => {}) + } +} + +export class Browser { + constructor(child, connection) { + this.child = child + this.connection = connection + this.pages = new Set() + } + + async newPage(url = 'about:blank') { + const { targetId } = await this.connection.send('Target.createTarget', { url }) + const { sessionId } = await this.connection.send('Target.attachToTarget', { targetId, flatten: true }) + const page = new Page(this.connection, sessionId, targetId) + this.pages.add(page) + page.send('Page.enable').catch(() => {}) + return page + } + + async firstPage(timeout = 15000) { + const deadline = Date.now() + timeout + while (Date.now() < deadline) { + const { targetInfos = [] } = await this.connection.send('Target.getTargets').catch(() => ({})) + const found = targetInfos.find((target) => target.type === 'page') + if (found) { + const { sessionId } = await this.connection.send('Target.attachToTarget', { targetId: found.targetId, flatten: true }) + const page = new Page(this.connection, sessionId, found.targetId) + this.pages.add(page) + page.send('Page.enable').catch(() => {}) + return page + } + if (this.connection.closed) throw new Error(this.connection.closedReason) + await sleep(100) + } + throw new Error('Chrome 没有打开页面') + } + + // 关进程 = 收掉 profile 会话:Cookie 留在磁盘上,也不会留下无主 Chrome。 + // Promise 在进程退出后才 settle,持锁方因此能确定下一个 Chrome 不会叠上来。 + async close() { + for (const page of this.pages) page.closed = true + const exited = new Promise((resolve) => { + if (this.child.exitCode !== null || this.child.signalCode !== null) resolve() + else this.child.once('exit', resolve) + }) + await this.connection.send('Browser.close').catch(() => {}) + this.connection.shut('Chrome was closed') + const gone = await Promise.race([ + exited.then(() => true), + sleep(5000).then(() => false), + ]) + if (!gone) { + this.child.kill('SIGTERM') + const stopped = await Promise.race([exited.then(() => true), sleep(3000).then(() => false)]) + if (!stopped) { + this.child.kill('SIGKILL') + await Promise.race([exited, sleep(2000)]) + } + } + } +} + +function launch(executable, args, { timeout = 30000 } = {}) { + const child = spawn(executable, [...args, '--remote-debugging-pipe'], { + stdio: ['ignore', 'ignore', 'ignore', 'pipe', 'pipe'], + detached: false, + }) + const connection = new Pipe(child) + const failed = new Promise((_, reject) => { + child.once('error', (error) => { + connection.shut('Chrome could not be started') + reject(error.code === 'ENOENT' + ? new Error('找不到 Chrome;请安装 Google Chrome 或用 MCLAW_CHROME_PATH 指到可执行文件') + : new Error(`Chrome 无法启动:${error.message}`)) + }) + child.once('exit', (code) => { + connection.shut(`Chrome exited (${code ?? 'signal'})`) + }) + }) + failed.catch(() => {}) + const browser = new Browser(child, connection) + // profile 已被别的 Chrome 占用时,第二次启动会立刻退出(表现为管道关闭)。 + return Promise.race([browser.firstPage(timeout).then((page) => ({ browser, page })), failed]) +} + +// ---------------------------------------------------------------- Chrome 定位 + +export async function chromeExecutable() { + const override = process.env.MCLAW_CHROME_PATH + if (override) return resolve(override.startsWith('~') ? join(homedir(), override.slice(2)) : override) + const candidates = process.platform === 'win32' + ? [ + process.env.PROGRAMFILES && join(process.env.PROGRAMFILES, 'Google', 'Chrome', 'Application', 'chrome.exe'), + process.env['PROGRAMFILES(X86)'] && join(process.env['PROGRAMFILES(X86)'], 'Google', 'Chrome', 'Application', 'chrome.exe'), + process.env.LOCALAPPDATA && join(process.env.LOCALAPPDATA, 'Google', 'Chrome', 'Application', 'chrome.exe'), + process.env.LOCALAPPDATA && join(process.env.LOCALAPPDATA, 'Chromium', 'Application', 'chrome.exe'), + ].filter(Boolean) + : process.platform === 'darwin' + ? ['/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', join(homedir(), 'Applications', 'Google Chrome.app', 'Contents', 'MacOS', 'Google Chrome')] + : ['/usr/bin/google-chrome', '/usr/bin/google-chrome-stable', '/usr/bin/chromium', '/usr/bin/chromium-browser', '/snap/bin/chromium'] + for (const path of candidates) { + try { await access(path); return path } catch {} + } + throw new Error('找不到 Chrome;请安装 Google Chrome 或用 MCLAW_CHROME_PATH 指到可执行文件') +} + +// ---------------------------------------------------------------- 打开/收割 + +/** 用专属 profile 开 Chrome。登录用 headless: false(用户手动操作窗口), + * 续期用 headless: true(后台跑完就关)。profilePath 缺省用老共享目录 + * (只服务于 metadata 里没存 profile 的老账号续期)。返回 { browser, page, + * profilePath, release }:release() 在浏览器 close() 之后调用才放锁。 */ +export async function openMclawBrowser({ headless = true, startUrl = 'about:blank', profilePath } = {}) { + profilePath ||= defaultProfile() + const release = await claimProfileLock(profilePath) + try { + await mkdir(profilePath, { recursive: true, mode: 0o700 }) + const args = [ + `--user-data-dir=${profilePath}`, + '--no-first-run', '--no-default-browser-check', + '--disable-background-networking', '--disable-sync', '--disable-default-apps', + '--disable-component-update', '--disable-client-side-phishing-detection', + '--disable-domain-reliability', + '--disable-features=Translate,OptimizationHints,MediaRouter,DialMediaRouteProvider', + '--metrics-recording-only', '--no-service-autorun', + // Cookie 存储用 mock keychain,不碰 macOS 钥匙串 / Linux keyring。 + ...(process.platform === 'darwin' ? ['--use-mock-keychain'] : process.platform === 'linux' ? ['--password-store=basic'] : []), + '--window-size=1280,900', + ...(headless ? ['--headless=new', '--disable-gpu'] : []), + '--crash-dumps-dir=' + tmpdir(), + startUrl, + ] + const started = await launch(await chromeExecutable(), args) + return { ...started, profilePath, release } + } catch (error) { + release() + throw error + } +} + +/** 读移动云登录 Cookie(含 httpOnly;CDP 直读浏览器 Cookie 库)。 + * 返回 { name, value, expiresMs }(expiresMs 为 0 表示会话 Cookie)。 */ +export async function harvestYunAuth(browser) { + const { cookies = [] } = await browser.connection.send('Storage.getCookies').catch(() => ({})) + const hits = cookies.filter((c) => c?.name === 'authorization' && /(^|\.)yun\.139\.com$/i.test(String(c?.domain ?? ''))) + const pick = hits.find((c) => c?.value) ?? hits[0] + if (!pick?.value) return undefined + return { + name: pick.name, + value: pick.value, + expiresMs: Number.isFinite(pick.expires) && pick.expires > 0 ? pick.expires * 1000 : 0, + } +} + +/** 浏览器登录全流程:有头 Chrome(新登录用全新 profile,绝不带旧票)→ 用户 + * 在窗口里完成移动云登录 → 收割 authorization Cookie。 + * 返回 { promise, abort }:promise resolve { cookie, profilePath, release, + * close }。abort() 随时可调(宿主取消):Chrome 还没开起来时先记标记,开出来 + * 立即收尾;已开出则关浏览器、放锁。失败/取消/超时的路径还会删掉 profile 目录 + * ——没人认领的登录态不该留在盘上(成功则归账号所有,绝不删)。 */ +export function startBrowserHarvest({ deadlineMs = 600_000, profilePath = freshSigninProfile() } = {}) { + const session = { promise: undefined, abort: async () => {} } + session.promise = (async () => { + let aborted = false + let opened // { browser, release }:Chrome 开出后持有,成功时移交 callback + let resolved = false + session.abort = async () => { + if (aborted) return + aborted = true + if (opened) { + await opened.browser.close().catch(() => {}) + await opened.release() + } + } + try { + const { browser, page, profilePath: used, release } = await openMclawBrowser({ + headless: false, startUrl: 'https://yun.139.com/', profilePath, + }) + opened = { browser, release } + if (aborted) throw new Error('登录已取消') + const deadline = Date.now() + deadlineMs + for (;;) { + if (aborted) throw new Error('登录已取消') + if (browser.connection.closed) throw new Error('浏览器被关闭,登录中断') + const cookie = await harvestYunAuth(browser).catch(() => undefined) + if (cookie?.value) { + resolved = true // 目录归账号所有(metadata.profile),abort 不许删 + return { cookie, profilePath: used, release, close: () => browser.close() } + } + if (Date.now() >= deadline) throw timeoutError(`登录超时(${Math.round(deadlineMs / 60000)} 分钟内没有检测到移动云登录)`) + await sleep(1500) + } + } catch (error) { + if (opened) { + await opened.browser.close().catch(() => {}) + await opened.release() + } + if (!resolved) await rm(profilePath, { recursive: true, force: true }).catch(() => {}) + throw error + } + })() + return session +} + +/** 续期:headless 复开账号自己的 profile(metadata.profile)首页,等网页应用 + * 刷新会话后收割 Cookie。页面加载后多等 settleMs,给 tokenRefresh 留时间。 */ +export async function browserRefreshHarvest({ profilePath, settleMs = 12_000, timeoutMs = 60_000 } = {}) { + const { browser, page, profilePath: used, release } = await openMclawBrowser({ + headless: true, startUrl: 'https://yun.139.com/', profilePath, + }) + try { + const deadline = Date.now() + timeoutMs + let cookie = await harvestYunAuth(browser).catch(() => undefined) + if (!cookie) { + await page.goto('https://yun.139.com/', { timeout: 30000 }).catch(() => {}) + } + // 等 settle 窗口(页面应用启动 + 可能的 tokenRefresh),Cookie 有变化就用新的。 + const first = cookie?.value + const settleDeadline = Math.min(Date.now() + settleMs, deadline) + while (Date.now() < settleDeadline) { + await sleep(2000) + const next = await harvestYunAuth(browser).catch(() => undefined) + if (next?.value && next.value !== first) { cookie = next; break } + cookie = next ?? cookie + if (browser.connection.closed) break + } + if (!cookie?.value) throw new Error('profile 里没有移动云登录态(请先完成浏览器登录)') + return { cookie, profilePath: used } + } finally { + await browser.close().catch(() => {}) + await release() + } +} diff --git a/packages/mclaw/chat.test.mjs b/packages/mclaw/chat.test.mjs new file mode 100644 index 0000000..4ae9a68 --- /dev/null +++ b/packages/mclaw/chat.test.mjs @@ -0,0 +1,74 @@ +// normalizeChatResponse:网关以 HTTP 200 包裸 JSON 错误、正常 JSON、SSE 流、 +// 空响应、超过旧 1MB 截断的大回复——全部本地构造,不碰网络。 +import './nonet.mjs' +import { expect, test } from 'bun:test' +import { _internal } from './index.mjs' + +const { normalizeChatResponse } = _internal + +const sseResponse = (chunks) => new Response( + new ReadableStream({ + start(controller) { + for (const chunk of chunks) controller.enqueue(new TextEncoder().encode(chunk)) + controller.close() + }, + }), + { status: 200, headers: { 'content-type': 'text/event-stream' } }, +) + +test('HTTP 200 + 裸 JSON 错误 01000002 → 401,标记登录失效', async () => { + const out = await normalizeChatResponse(Response.json({ error: { code: '01000002', message: '无效的ApiKey' } })) + expect(out.status).toBe(401) + expect(out.headers.get('x-magpie-sign-in')).toBe('expired') + const body = await out.json() + expect(body.error.code).toBe('01000002') + expect(body.error.message).toBe('无效的ApiKey') +}) + +test('HTTP 200 + 裸 JSON 错误(其他 code)→ 502,登录保持', async () => { + const out = await normalizeChatResponse(Response.json({ error: { code: '01000005', message: '资源不存在' } })) + expect(out.status).toBe(502) + expect(out.headers.get('x-magpie-sign-in')).toBe('kept') +}) + +test('HTTP 200 + success:false → 502', async () => { + const out = await normalizeChatResponse(Response.json({ success: false, code: 'X', message: 'nope' })) + expect(out.status).toBe(502) + expect((await out.json()).error.message).toBe('nope') +}) + +test('正常 JSON 回复原样透出', async () => { + const payload = { choices: [{ message: { role: 'assistant', content: 'hi' } }], usage: { total_tokens: 1 } } + const out = await normalizeChatResponse(Response.json(payload)) + expect(out.status).toBe(200) + expect(await out.json()).toEqual(payload) +}) + +test('超过 1MB 的合法 JSON 回复不再被截断成 502', async () => { + const payload = { choices: [{ message: { role: 'assistant', content: 'x'.repeat(2 * 1024 * 1024) } }] } + const out = await normalizeChatResponse(Response.json(payload)) + expect(out.status).toBe(200) + const body = await out.json() + expect(body.choices[0].message.content.length).toBe(2 * 1024 * 1024) +}) + +test('SSE 流透传:检查过的首字节重放,其余照序', async () => { + const chunks = ['data: {"id":"1","cho', 'ices":[{"delta":{"content":"你"}}]}\n\n', 'data: [DONE]\n\n'] + const out = await normalizeChatResponse(sseResponse(chunks)) + expect(out.status).toBe(200) + expect(out.headers.get('content-type')).toBe('text/event-stream') + const text = await out.text() + expect(text).toBe(chunks.join('')) +}) + +test('空响应体 → 502 empty_response', async () => { + const out = await normalizeChatResponse(new Response('', { status: 200 })) + expect(out.status).toBe(502) + expect((await out.json()).error.code).toBe('empty_response') +}) + +test('JSON 但既非错误也非对话响应 → 502 invalid_response', async () => { + const out = await normalizeChatResponse(Response.json({ foo: 'bar' })) + expect(out.status).toBe(502) + expect((await out.json()).error.code).toBe('invalid_response') +}) diff --git a/packages/mclaw/fake-browser.mjs b/packages/mclaw/fake-browser.mjs new file mode 100644 index 0000000..2f8fa17 --- /dev/null +++ b/packages/mclaw/fake-browser.mjs @@ -0,0 +1,67 @@ +// 浏览器替身:startBrowserHarvest / browserRefreshHarvest 的可控 fake。 +// ticket 就是 fake 收割出的 authorization Cookie 值(与真实流程一致:整段 +// "Basic " 票,fake.mjs 的 TICKET_A/TICKET_B)。closed/released 记录 +// 收尾是否发生(取消收尾的断言用)。 +export function fakeBrowserModule({ ticket } = {}) { + const state = { + harvests: 0, + refreshes: 0, + openedProfiles: [], + refreshProfiles: [], + closed: 0, + released: 0, + aborted: false, + // 测试用例按需覆盖:harvestError 让收割失败;holdHarvest 让 promise 挂起, + // 再用 deliverHarvest() 放行(取消收尾的时序测试用)。 + harvestError: undefined, + refreshCookie: ticket, + } + let deliverHarvestNow = undefined + const module = { + startBrowserHarvest({ profilePath } = {}) { + const session = { promise: undefined, abort: async () => {} } + state.harvests++ + const profile = profilePath ?? 'fake-profile-signin' + state.openedProfiles.push(profile) + session.promise = new Promise((resolve, reject) => { + session.abort = async () => { + if (state.aborted) return + state.aborted = true + state.closed++ + state.released++ + reject(new Error('登录已取消')) + } + const deliver = () => { + if (state.harvestError) { + state.closed++ + state.released++ + reject(state.harvestError) + return + } + resolve({ + cookie: { value: ticket, expiresMs: 0 }, + profilePath: profile, + release: async () => { state.released++ }, + close: async () => { state.closed++ }, + }) + } + if (state.harvestError) queueMicrotask(deliver) + else deliverHarvestNow = deliver + }) + session.promise.catch(() => {}) + return session + }, + deliverHarvest() { + deliverHarvestNow?.() + deliverHarvestNow = undefined + }, + async browserRefreshHarvest({ profilePath } = {}) { + state.refreshes++ + state.refreshProfiles.push(profilePath) + if (state.harvestError) throw state.harvestError + if (!state.refreshCookie) throw new Error('profile 里没有移动云登录态(请先完成浏览器登录)') + return { cookie: { value: state.refreshCookie, expiresMs: 0 }, profilePath: profilePath ?? 'fake-profile-legacy' } + }, + } + return { module, state } +} diff --git a/packages/mclaw/fake.mjs b/packages/mclaw/fake.mjs new file mode 100644 index 0000000..0c04e48 --- /dev/null +++ b/packages/mclaw/fake.mjs @@ -0,0 +1,85 @@ +// 上游的本地 fake:一个 Bun.serve 站着 ai.yun.139.com(openclaw)、 +// ypqy.mcloud.139.com(benefit)和 vip.yun.139.com(vip)——fakeUpstream() +// 把 _internal.HOSTS 三个 origin 都指到本地,按路径路由(三台上游的路径 +// 互不重叠)。route("POST /api/llm/apikey/get", handler) 追加/覆盖处理器; +// seen 记录每个请求(方法、路径、头、body),供断言。close() 还原 HOSTS。 +import { _internal } from './index.mjs' + +export function fakeUpstream() { + const routes = new Map() + const seen = [] + const server = Bun.serve({ + port: 0, + hostname: '127.0.0.1', + async fetch(req) { + const url = new URL(req.url) + const text = await req.text() + const r = { method: req.method, path: url.pathname, headers: req.headers, text } + if (text) try { r.json = JSON.parse(text) } catch {} + seen.push(r) + const handler = routes.get(`${req.method} ${url.pathname}`) + if (!handler) return new Response('no route ' + req.method + ' ' + url.pathname, { status: 404 }) + return handler(r) + }, + }) + const origin = `http://127.0.0.1:${server.port}` + const was = { ..._internal.HOSTS } + _internal.HOSTS.openclaw = origin + _internal.HOSTS.benefit = origin + _internal.HOSTS.vip = origin + _internal.HOSTS.userNjs = origin + const f = { + origin, + seen, + route: (key, handler) => routes.set(key, handler), + close() { + server.stop(true) + Object.assign(_internal.HOSTS, was) + }, + } + // 上游三条数据面的默认应答:agent/list(实例 + 可用模型)、apikey/get v1 + // (key + 倍率)、aitokens 权益池。用例里 route() 同名覆盖。 + f.route('POST /api/adapter/assistant/agent/list', () => json({ + success: true, + data: { agentList: [{ agentType: 'mclaw', agentId: 'oclaw-1', modelList: ['blian_qwen38_flash', 'huoshan_glm_5_3'].map((code) => ({ modelCode: code, description: code })) }] }, + })) + f.route('POST /api/llm/apikey/get', () => json({ + success: true, + data: { apikey: 'na-test-key', modelUrl: 'x', modelList: [ + { modelCode: 'blian_qwen38_flash', modelName: 'Qwen3.8-Flash', tokenRatio: 0.18 }, + { modelCode: 'huoshan_glm_5_3', modelName: 'GLM-5.3', tokenRatio: 3.5 }, + ] }, + })) + f.route('POST /isbo2/openApi/queryAvailableBenefitV2', () => json({ + result: { resultCode: '0', resultDesc: 'SUCCESS' }, + userAvailableBenefitList: [{ benefitNo: 'RHR135', benefitName: 'aitokens', benefitValue: '30500000', benefitUsed: '11375000' }], + })) + // SSO 换票链默认应答:出票 + ssoLogin 下发 6 个 mc_* cookie(.139.com,24h, + // mc_at/mc_pat 是 httpOnly——和真实抓包一致;插件从 getSetCookie() 整段收)。 + f.route('POST /user/querySpecTokenV2', () => json({ + success: true, code: '0000', message: '请求成功', data: { token: 'YZsid-fake-ticket', resultCode: '104000' }, + })) + f.route('POST /m4c/login/ssoLogin', () => new Response(JSON.stringify({ resultCode: '0', resultDesc: 'SUCCESS' }), { + headers: { + 'content-type': 'application/json', + 'set-cookie': [ + 'mc_at=fake-at; Domain=.139.com; Path=/; HttpOnly; Expires=Wed, 06 Nov 2026 00:00:00 GMT', + 'mc_bt=fake-bt; Domain=.139.com; Path=/; Expires=Wed, 06 Nov 2026 00:00:00 GMT', + 'mc_pat=fake-pat; Domain=.139.com; Path=/; HttpOnly; Expires=Wed, 06 Nov 2026 00:00:00 GMT', + 'mc_pbt=fake-pbt; Domain=.139.com; Path=/; Expires=Wed, 06 Nov 2026 00:00:00 GMT', + 'mc_ac=fake-ac; Domain=.139.com; Path=/; Expires=Wed, 06 Nov 2026 00:00:00 GMT', + 'mc_pac=fake-pac; Domain=.139.com; Path=/; Expires=Wed, 06 Nov 2026 00:00:00 GMT', + ], + }, + })) + return f +} + +export const json = (value, status = 200) => new Response(JSON.stringify(value), { status, headers: { 'content-type': 'application/json' } }) + +// 两张 pc: Basic 票(浏览器登录收割的形态):掩码手机号不同,票文本内嵌 +// 13 位到期 ms(basicExpiryMs 读的就是它)。值即 authorization Cookie/头。 +export const TICKET_A = 'Basic ' + Buffer.from(`pc:13112349239:x|1|RCS|${Date.now() + 30 * 86400e3}|sig`, 'utf8').toString('base64') +export const TICKET_B = 'Basic ' + Buffer.from(`pc:18687654321:y|1|RCS|${Date.now() + 30 * 86400e3}|sig`, 'utf8').toString('base64') +export const PHONE_A = '131****9239' +export const PHONE_B = '186****4321' diff --git a/packages/mclaw/icon.png b/packages/mclaw/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..ff3e3fe7c37195a13b73212d8d90cdc54b883684 GIT binary patch literal 2728 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…,开放接口 key) + * base 默认 https://ai.yun.139.com/api/llm/102001 + * ⚠️ 网关会以 HTTP 200 返回裸 JSON 错误(如 {"error":{"code":"01000002"}}), + * normalizeChatResponse 会把这种响应转成明确的失败。 + * + * models POST https://ai.yun.139.com/api/adapter/assistant/agent/list + * Authorization: Basic base64("mobile:<手机号>:")(App 抓包凭证) + * 或 base64("pc:<手机号>:")(网页登录票,等价) + * headers: x-yun-app-channel: 101, x-yun-api-version: v1, + * Origin: mcloudlocal://yun.139.com + * body: {"sourceChannel":"101","sceneType":"homePage"}(免 userId) + * → agentList[] 里 agentType=mclaw 的 agentId 即 openclawId, + * 其 modelList 是账号实际可用的模型。 + * + * key+倍率 POST https://ai.yun.139.com/api/llm/apikey/get + * Authorization: Basic <同上>(mobile: / pc: 均可,实测) + * headers: x-yun-api-version: v1 ← 必须 v1;v2 会返回另一个 + * 不能直连 chat 的 key 且要求 userId + * body: {"channelId":"102001"} + * → data: { apikey(真正的 llm key), modelUrl, + * modelList[{modelCode, modelName, ability, tokenRatio}] } + * 一次拿全:chat key + 带倍率的模型表,无需手动粘贴 key。 + * + * usage POST https://ypqy.mcloud.139.com/isbo2/openApi/queryAvailableBenefitV2 + * Authorization: Basic <同上>(此接口可空账号,无需 userId) + * body: {"account":{"userDomainId":""}} + * → userAvailableBenefitList[] 里 benefitNo=RHR135 的 + * benefitValue(总额)/benefitUsed(已用),即 aitokens 池。 + * + * 明细 POST https://vip.yun.139.com/m4c/benefit/getAiTokenConsumptionRecords + * Cookie: (网页版会话,可自动换取) + * body: {"pageNum":1,"pageSize":3,"action":["1","4"]} + * → 每条:modelCode/modelName/benefitNum(消耗)/coefficient(倍率)/recordTime + * /endTime(当前周期权威重置点) + * + * 换票链 POST https://user-njs.yun.139.com/user/querySpecTokenV2 + * Authorization: Basic <票> body: {"toSourceId":"001005"} + * ⚠️ 必须 001005(App vip 会员中心 H5 的 app.js 自配值);001003/001221 + * 会被 USER_DOMAIN 拒 200050409。 + * → data.token(YZsid 临时票) + * POST https://vip.yun.139.com/m4c/login/ssoLogin + * body: {"ticket":"YZsid…","source":"503016","channelSrc":""} + * → Set-Cookie 下发 6 个(mc_at/mc_bt/mc_pat/mc_pbt/mc_ac/mc_pac, + * .139.com 域,24h;mc_at/mc_pat httpOnly),getSetCookie() 整段收全 + * → 拼 Cookie 串查明细。pc:/mobile: 票均可。 + * + * 两套凭证互不通用(实测对照过):llm key 只管 chat;Basic 票只管 + * models/usage/key发放。Basic 票格式 "<渠道>:<手机号>:<…>|RCS|<到期ms>|<…>" + * (渠道 = mobile: App 票 / pc: 网页票),到期时间可从票文本里读出。 + * config/get(倍率)只认 mobile: 票 → 网页票的倍率走 apikey/get。 + * + * 浏览器登录(v0.4.0):yun.139.com 网页登录一次(方式不限),CDP(--remote- + * debugging-pipe,每次登录一个全新 profile)收割 authorization Cookie = + * pc: 票,apikey/get v1 自动取 chat key + 倍率;profile 目录存进账号 + * metadata,续期 = headless 复开该账号自己的 profile,网页应用自己刷新 + * 会话后重新收割(收割的票会校验是不是这个账号的)。见 browser.mjs。 + * + * Options (magpie plugin options mclaw '{"…"}'): + * { "base": "https://ai.yun.139.com/api/llm/102001" } + * 环境变量:MCLAW_CHROME_PATH(Chrome 路径)、MCLAW_BROWSER_PROFILE(登录 + * profile 目录的根,每个账号是它下面的一个子目录) + */ +import { randomUUID } from 'node:crypto' +import * as browserDefault from './browser.mjs' + +const PROVIDER = 'mclaw' +const DEFAULT_BASE = 'https://ai.yun.139.com/api/llm/102001' +// 测试通过 _internal.HOSTS 重定向到本地 fake(见 *.test.mjs)。 +const HOSTS = { + openclaw: 'https://ai.yun.139.com', + benefit: 'https://ypqy.mcloud.139.com', + vip: 'https://vip.yun.139.com', + userNjs: 'https://user-njs.yun.139.com', +} +const APP_UA = 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) AIModeHome MCloudApp/13.2.5 iPhone AppLanguage/zh-CN' + +// 每进程稳定的伪设备标识(App 侧头,服务端用来路由,内容不敏感) +const TID = randomUUID() +const DEVICE_ID = randomUUID() +const CLIENT_INFO = `||2|13.2.5||iPhone|${DEVICE_ID}||ios 18.7|||||` +const DEVICE_INFO = `||36|13.2.5||iPhone|${DEVICE_ID}||ios 18.7|||||` + +// 模型目录(2026-11-04 config/get 抓包快照;配置了 App 凭证后由账号实际目录覆盖)。 +// rate = tokenRatio(积分倍率,App 计费口径,非美元价)。 +const MODELS = { + 'blian_qwen38_flash': { + name: 'Qwen3.8-Flash', + limit: { context: 200000, output: 32000 }, + reasoning: true, + tool_call: true, + rate: 0.18, + }, + 'blian_qwen38_max': { + name: 'Qwen3.8-Max', + limit: { context: 200000, output: 32000 }, + reasoning: true, + tool_call: true, + rate: 1.5, + }, + 'huoshan_glm_5_3': { + name: 'GLM-5.3', + limit: { context: 200000, output: 32000 }, + reasoning: true, + tool_call: true, + rate: 3.5, + }, + 'blian_qwen37_plus': { + name: 'Qwen3.7-Plus', + limit: { context: 200000, output: 32000 }, + reasoning: true, + tool_call: true, + rate: 1.5, + }, + 'blian_qwen36_plus': { + name: 'Qwen3.6-Plus', + limit: { context: 200000, output: 32000 }, + tool_call: true, + rate: 1.0, + }, + 'blian_qwen35_plus': { + name: 'Qwen3.5-Plus', + limit: { context: 200000, output: 32000 }, + tool_call: true, + modalities: { input: ['text', 'image'] }, + rate: 0.6, + }, + 'blian_deepseek_v4_pro': { + name: 'DeepSeek-V4-Pro', + limit: { context: 200000, output: 32000 }, + reasoning: true, + tool_call: true, + rate: 2.5, + }, + 'vlm_huoshan_2_0_lite_thinking_vision': { + name: 'Seed-2.0-Lite', + limit: { context: 200000, output: 32000 }, + reasoning: true, + tool_call: true, + modalities: { input: ['text', 'image'] }, + rate: 1.0, + }, + 'vlm_huoshan_2_0_mini_thinking_vision': { + name: 'Seed-2.0-Mini', + limit: { context: 200000, output: 32000 }, + reasoning: true, + tool_call: true, + modalities: { input: ['text', 'image'] }, + rate: 0.3, + }, + 'huoshan_deepseek_v4_1_flash': { + name: 'DeepSeek-V4.1-Flash', + limit: { context: 200000, output: 32000 }, + reasoning: true, + tool_call: true, + // config/get 的计费表里没有它,倍率未知 + }, +} + +// ---------------------------------------------------------------- helpers +// (辅助函数不导出为模块级函数:插件宿主会把每个导出的函数当插件调用。 +// 测试面统一走 _internal 对象。) + +const fmt = (value) => new Intl.NumberFormat('en-US', { maximumFractionDigits: 0 }).format(value) + +/** App 侧(openclaw)公共请求头。 */ +function appHeaders(appAuth) { + return { + 'content-type': 'application/json', + accept: '*/*', + authorization: appAuth, + 'x-yun-app-channel': '101', + 'x-yun-api-version': 'v1', + 'x-yun-client-info': CLIENT_INFO, + 'x-deviceinfo': DEVICE_INFO, + 'x-yun-tid': TID, + origin: 'mcloudlocal://yun.139.com', + 'user-agent': APP_UA, + } +} + +function expired(message) { + return Object.assign(new Error(message), { signIn: 'expired' }) +} + +/** 统一解析 JSON API 响应,识别凭证失效。 */ +async function readJson(response, label) { + const json = await response.json().catch(() => null) + if (response.status === 401) throw expired(`${label} 登录已失效,请重新抓取凭证`) + if (!json) throw new Error(`${label} 返回非 JSON 响应(HTTP ${response.status})`) + return json +} + +/** MClaw 实例(openclawId)自动发现 + 账号实际模型清单。 + * agent/list 免 userId:agentList 里 agentType=mclaw 的 agentId 即 openclawId。 */ +async function fetchAgentList(appAuth) { + let response + try { + response = await fetch(`${HOSTS.openclaw}/api/adapter/assistant/agent/list`, { + method: 'POST', + headers: appHeaders(appAuth), + body: JSON.stringify({ sourceChannel: '101', sceneType: 'homePage' }), + signal: AbortSignal.timeout(15_000), + }) + } catch { + throw new Error('MClaw agent 列表查询网络失败或超时') + } + const json = await readJson(response, 'MClaw agent 列表') + const agents = json?.data?.agentList + if (json?.success !== true || !Array.isArray(agents)) { + const code = json?.code ?? response.status + if (String(code) === '01000002' || response.status === 401) { + throw expired('MClaw App 凭证已失效,请重新抓取') + } + throw new Error(`MClaw agent 列表查询失败(code ${code}:${json?.message ?? '未知错误'})`) + } + const agent = agents.find((a) => a?.agentType === 'mclaw') ?? + agents.find((a) => /claw/i.test(`${a?.agentType ?? ''}${a?.applicationName ?? ''}`)) + if (!agent?.agentId) throw new Error('agent 列表里没有 MClaw 实例') + return { + agentId: String(agent.agentId), + // 账号实际可用的模型(modelCode + 描述);config/get 给倍率 + models: Array.isArray(agent.modelList) + ? agent.modelList.map((m) => ({ code: m?.modelCode, name: m?.description })) + : [], + } +} + +/** 模型目录(openclaw config/get),给每个模型的积分倍率。 */ +async function fetchModelCatalogue(appAuth, openclawId) { + let response + try { + response = await fetch(`${HOSTS.openclaw}/api/openclaw/config/get`, { + method: 'POST', + headers: appHeaders(appAuth), + body: JSON.stringify({ sourceChannel: '101', openclawId }), + signal: AbortSignal.timeout(15_000), + }) + } catch { + throw new Error('MClaw 模型目录查询网络失败或超时') + } + const json = await readJson(response, 'MClaw 模型目录') + if (json?.success !== true || !Array.isArray(json?.data?.modelList)) { + const code = json?.code ?? response.status + if (String(code) === '01000002' || response.status === 401) { + throw expired('MClaw App 凭证已失效,请重新抓取') + } + throw new Error(`MClaw 模型目录查询失败(code ${code}:${json?.message ?? '未知错误'})`) + } + return json.data.modelList +} + +/** llm 渠道号(从 base 里推导,默认 102001)。 */ +function llmChannelId() { + return activeBase.match(/\/api\/llm\/(\d+)/)?.[1] ?? '102001' +} + +/** apikey/get v1:Basic 票(mobile:/pc: 均可,实测)一次拿全 llm key + 带倍率模型表。 + * ⚠️ 必须 x-yun-api-version: v1——v2 返回另一个不能直连 chat 的 key,且要求 userId。 */ +async function fetchLlmKeyAndRates(appAuth, channelId = '102001') { + let response + try { + response = await fetch(`${HOSTS.openclaw}/api/llm/apikey/get`, { + method: 'POST', + headers: { + 'content-type': 'application/json', + authorization: appAuth, + 'x-yun-api-version': 'v1', + 'user-agent': APP_UA, + }, + body: JSON.stringify({ channelId }), + signal: AbortSignal.timeout(15_000), + }) + } catch { + throw new Error('MClaw key/倍率查询网络失败或超时') + } + const json = await readJson(response, 'MClaw key/倍率') + const data = json?.data + if (json?.success !== true || !data?.apikey) { + const code = json?.code ?? response.status + if (String(code) === '01000002' || response.status === 401) { + throw expired('MClaw Basic 票已失效,请重新登录') + } + throw new Error(`MClaw key/倍率查询失败(code ${code}:${json?.message ?? '未知错误'})`) + } + return data +} + +/** 两种存储形态的 Basic 票:oauth 型(浏览器登录)在 access;api 型(0.4.1 已移除的 + * 手动粘贴方式)的老账号在 metadata.appAuth,登录方式删了,老登录态仍兼容。 */ +function appAuthOf(auth) { + const raw = auth?.access ?? auth?.metadata?.appAuth + return typeof raw === 'string' && raw.trim() ? raw.trim() : undefined +} + +/** aitokens 权益池(总量/已用)。空账号即可,无需 userId。 */ +async function fetchBenefit(appAuth) { + let response + try { + response = await fetch(`${HOSTS.benefit}/isbo2/openApi/queryAvailableBenefitV2`, { + method: 'POST', + headers: { + 'content-type': 'application/json', + authorization: appAuth, + 'user-agent': APP_UA, + }, + body: JSON.stringify({ account: { userDomainId: '' } }), + signal: AbortSignal.timeout(15_000), + }) + } catch { + throw new Error('MClaw 用量查询网络失败或超时') + } + const json = await readJson(response, 'MClaw 用量') + const list = json?.userAvailableBenefitList + if (json?.result?.resultCode !== '0' || !Array.isArray(list)) { + const desc = json?.result?.resultDesc ?? `HTTP ${response.status}` + if (/授权|登录|token/i.test(desc)) throw expired('MClaw App 凭证已失效,请重新抓取') + throw new Error(`MClaw 用量查询失败(${desc})`) + } + return list.find((item) => item?.benefitNo === 'RHR135') ?? + list.find((item) => /token/i.test(`${item?.benefitName ?? ''}${item?.benefitDesc ?? ''}`)) +} + +/** 逐条消耗明细(vip 网页会话 Cookie,可选)。 */ +async function fetchRecords(vipCookie) { + let response + try { + response = await fetch(`${HOSTS.vip}/m4c/benefit/getAiTokenConsumptionRecords`, { + method: 'POST', + headers: { + 'content-type': 'application/json', + cookie: vipCookie, + origin: HOSTS.vip, + referer: `${HOSTS.vip}/vip/consumptionDetail?sourceid=503016`, + 'user-agent': APP_UA, + }, + body: JSON.stringify({ pageNum: 1, pageSize: 3, action: ['1', '4'] }), + signal: AbortSignal.timeout(15_000), + }) + } catch { + throw new Error('MClaw 明细查询网络失败或超时') + } + const json = await response.json().catch(() => null) + if (json?.resultCode !== '0') { + const desc = json?.resultDesc ?? `HTTP ${response.status}` + if (/授权|401/.test(desc)) throw expired('vip 会话 Cookie 已失效') + throw new Error(`MClaw 明细查询失败(${desc})`) + } + return json?.data?.aiTokenConsumptionRecordList ?? [] +} + +/** 从 Basic 票里解出掩码手机号(mobile:/pc: 前缀均可),解不出返回空。 */ +function nameFromAppAuth(appAuth) { + try { + const raw = Buffer.from(appAuth.replace(/^Basic\s+/i, ''), 'base64').toString('utf8') + const phone = raw.match(/(?:mobile|pc):(\d{11})/)?.[1] + return phone ? `${phone.slice(0, 3)}****${phone.slice(7)}` : undefined + } catch { + return undefined + } +} + +/** 记录里的 endTime("2026-11-11 15:20:47",北京时间)→ ms。 */ +function endTimeMs(text) { + if (typeof text !== 'string' || !/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(text)) return undefined + const ms = new Date(`${text.replace(' ', 'T')}+08:00`).getTime() + return Number.isFinite(ms) && ms > 0 ? ms : undefined +} + +/** App Basic 凭证内嵌的到期时间(mobile:…|1|RCS|<到期ms>|…)。 */ +function basicExpiryMs(appAuth) { + try { + const raw = Buffer.from(appAuth.replace(/^Basic\s+/i, ''), 'base64').toString('utf8') + const ms = Number(raw.split('|').find((part) => /^\d{13}$/.test(part))) + return Number.isFinite(ms) && ms > 0 ? ms : undefined + } catch { + return undefined + } +} + +/** 周期起点(近似):从权威 endTime 回退一个日历月(北京时间的年月日时分秒 + * 原样前移一个月,小月会滚到下月 1 日)。上游不给周期起止,这只在有了该账号 + * 自己的权威 endTime 时才用于 startsAt/span,绝不凭空猜一个周期。endMs 是 + * +08:00 解析出的 epoch,先 +8h 让 UTC 分量还原成北京墙钟再取。 */ +function cycleStartMs(endMs) { + const d = new Date(endMs + 8 * 3600e3) + let year = d.getUTCFullYear() + let month = d.getUTCMonth() + 1 // 1-based(此刻的 UTC 分量即北京墙钟) + month -= 1 + if (month === 0) { month = 12; year -= 1 } + const pad = (n) => String(n).padStart(2, '0') + return new Date(`${year}-${pad(month)}-${pad(d.getUTCDate())}T${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}:${pad(d.getUTCSeconds())}+08:00`).getTime() +} + +// vip 会话 Cookie 的进程内缓存与换票失败冷却(宿主进程长驻,缓存跨请求有效) +const cookieCache = new Map() +const ssoFailedAt = new Map() +const SSO_COOLDOWN = 30 * 60e3 + +/** SSO 换票链:Basic 票 → user-njs querySpecTokenV2 → 出 YZsid 临时票 → + * vip ssoLogin 换 vip 会话 Cookie。toSourceId 必须是 **001005**(App vip 会员 + * 中心 H5 的 app.js 自配值;001003/001221 会被 USER_DOMAIN 拒 200050409)。 + * ssoLogin 的 Set-Cookie 一次下发 6 个(mc_at/mc_bt/mc_pat/mc_pbt/mc_ac/ + * mc_pac,.139.com 域,24h;mc_at/mc_pat 是 httpOnly)——必须从 getSetCookie() + * 整段收全,curl 式 cookie jar 会漏。pc: 和 mobile: 票都认(实测)。 */ +async function ssoCookie(appAuth) { + const last = ssoFailedAt.get(appAuth) + if (last && Date.now() - last < SSO_COOLDOWN) return undefined + try { + const mint = await fetch(`${HOSTS.userNjs}/user/querySpecTokenV2`, { + method: 'POST', + headers: { 'content-type': 'application/json', authorization: appAuth, 'user-agent': APP_UA }, + body: JSON.stringify({ toSourceId: '001005' }), + signal: AbortSignal.timeout(15_000), + }).then((r) => r.json()) + const ticket = mint?.data?.token + if (typeof ticket !== 'string' || !ticket) throw new Error('出票失败') + const response = await fetch(`${HOSTS.vip}/m4c/login/ssoLogin`, { + method: 'POST', + headers: { + 'content-type': 'application/json', + origin: HOSTS.vip, + referer: `${HOSTS.vip}/vip/consumptionDetail?sourceid=503016`, + 'user-agent': APP_UA, + }, + body: JSON.stringify({ ticket, source: '503016', channelSrc: '' }), + signal: AbortSignal.timeout(15_000), + }) + const json = await response.json().catch(() => null) + if (json?.resultCode !== '0') throw new Error(json?.resultDesc ?? `HTTP ${response.status}`) + const raw = response.headers.getSetCookie?.() ?? [] + const lines = [] + for (const entry of Array.isArray(raw) ? raw : [raw]) { + // Bun 会把多条 Set-Cookie 折叠成一条(逗号连接),而 Expires 日期里本身 + // 就有逗号——只在「逗号后紧跟 名字=」的边界切开,日期逗号保持原样。 + for (const piece of String(entry).split(/,(?=\s*[-\w]+=)/)) { + const pair = piece.trim().split(';')[0] + if (pair) lines.push(pair) + } + } + const cookies = [...new Set(lines)] + if (!cookies.length) throw new Error('ssoLogin 未下发会话 Cookie') + const cookie = cookies.join('; ') + cookieCache.set(appAuth, cookie) + return cookie + } catch { + ssoFailedAt.set(appAuth, Date.now()) + return undefined + } +} + +/** 清 SSO 缓存与冷却(测试用)。 */ +function resetSsoState() { + cookieCache.clear() + ssoFailedAt.clear() +} + +/** 清模型/key 进程内缓存(测试用)。 */ +function resetModelCache() { + llKeyRatesCache = undefined + openclawIdCache = undefined +} + +// ---------------------------------------------------------------- chat 响应守卫 +// (移植自 kasisama/magpie-joycode 的 normalizeChatResponse,MIT) + +function chatError(status, code, message) { + return Response.json({ error: { type: 'upstream_error', code, message } }, { + status, + headers: { 'x-magpie-sign-in': status === 401 ? 'expired' : 'kept' }, + }) +} + +async function normalizeChatResponse(response) { + if (!response.ok) { + const headers = new Headers(response.headers) + headers.set('x-magpie-sign-in', response.status === 401 ? 'expired' : 'kept') + return new Response(response.body, { status: response.status, headers }) + } + if (!response.body) return chatError(502, 'empty_response', 'MClaw 返回空响应') + const reader = response.body.getReader() + const buffered = [] + const decoder = new TextDecoder() + let prefix = '' + let bytes = 0 + // 网关可能以 HTTP 200 + SSE 响应头返回裸 JSON 错误,先看前缀再放行。 + while (!prefix.trim() && bytes <= 65536) { + const next = await reader.read() + if (next.done) break + buffered.push(next.value) + bytes += next.value.byteLength + prefix += decoder.decode(next.value, { stream: true }) + } + if (!prefix.trim()) { + await reader.cancel() + return chatError(502, 'empty_response', 'MClaw 返回空响应') + } + if (prefix.trimStart().startsWith('{')) { + // JSON(含 200 裸 JSON 错误):读到结尾再判。错误体很小;正常的 JSON + // 回复可能远超 1MB,不设上限(流式回复走下面的透传分支)。 + for (;;) { + const next = await reader.read() + if (next.done) break + bytes += next.value.byteLength + prefix += decoder.decode(next.value, { stream: true }) + } + prefix += decoder.decode() + let json + try { json = JSON.parse(prefix) } catch {} + if (json?.error || json?.success === false || + (json?.code !== undefined && json?.code !== '0000' && !json?.choices)) { + const code = json.error?.code ?? json.code + const message = json.error?.message ?? json.message + const status = String(code) === '01000002' ? 401 : 502 + return chatError(status, code, typeof message === 'string' + ? message.slice(0, 500) + : 'MClaw 请求被拒绝') + } + if (json?.choices) return Response.json(json) + return chatError(502, 'invalid_response', 'MClaw 未返回有效的对话响应') + } + // 把检查过的字节重放后正常透传流,保留工具调用增量。 + const headers = new Headers(response.headers) + headers.delete('content-length') + headers.delete('content-encoding') + return new Response(new ReadableStream({ + async pull(controller) { + if (buffered.length) { controller.enqueue(buffered.shift()); return } + try { + const next = await reader.read() + if (next.done) controller.close() + else controller.enqueue(next.value) + } catch (error) { controller.error(error) } + }, + cancel(reason) { return reader.cancel(reason) }, + }), { status: response.status, headers }) +} + +// ---------------------------------------------------------------- 账号模型目录 + +function visionByCode(code) { + return code.startsWith('vlm_') || code.includes('vision') || code.includes('qwen35') +} + +// MClaw 实例 id 的进程内缓存(agent/list 免 userId,可随时重发现) +let openclawIdCache +// 插件装载时的 llm 基址(accountModels 在模块层,读不到插件闭包的 options) +let activeBase = DEFAULT_BASE + +// apikey/get v1 的进程内缓存(5 分钟):models() 调用频繁,key+倍率不用每次拉 +let llKeyRatesCache +const LLMKEY_TTL = 5 * 60e3 + +async function llmKeyAndRates(appAuth) { + const cached = llKeyRatesCache + if (cached && cached.appAuth === appAuth && Date.now() - cached.at < LLMKEY_TTL) return cached.data + const data = await fetchLlmKeyAndRates(appAuth, llmChannelId()) + llKeyRatesCache = { appAuth, data, at: Date.now() } + return data +} + +/** 账号实际模型目录:agent/list(实例 id + 可用模型)× apikey/get v1(key+倍率, + * mobile:/pc: 票通用)× config/get(兜底,仅 mobile: 票)。 + * ⚠️ 宿主传给钩子的 provider 是它归一化过的对象(自定义字段会被剥掉), + * 所以这里只用闭包值,绝不读 provider 参数上的 base/openclawId。 */ +async function accountModels(provider, { auth } = {}) { + const appAuth = appAuthOf(auth) + if (!appAuth) return provider.models + let agentList + try { + agentList = await fetchAgentList(appAuth) + openclawIdCache = agentList.agentId + } catch (error) { + if (error.signIn === 'expired') throw error + if (!openclawIdCache) return provider.models // 连实例 id 都拿不到时保留静态目录 + agentList = { agentId: openclawIdCache, models: [] } + } + let rates = new Map() + let names = new Map() + try { + // 首选 apikey/get v1:一张票拿全 key + 倍率,网页票(pc:)也认 + const data = await llmKeyAndRates(appAuth) + if (Array.isArray(data.modelList)) { + rates = new Map(data.modelList.map((m) => [m?.modelCode, Number(m?.tokenRatio)])) + names = new Map(data.modelList.map((m) => [m?.modelCode, m?.modelName])) + } + } catch (error) { + if (error.signIn === 'expired') throw error + // 兜底 config/get(App 渠道票专用);再失败就只剩 agent 列表(无倍率) + try { + const catalogue = await fetchModelCatalogue(appAuth, agentList.agentId) + rates = new Map(catalogue.map((m) => [m?.code, Number(m?.tokenRatio)])) + names = new Map(catalogue.map((m) => [m?.code, m?.name])) + } catch (fallbackError) { + if (fallbackError.signIn === 'expired') throw fallbackError + } + } + const models = {} + const source = agentList.models.length + ? agentList.models + : [...names].map(([code, name]) => ({ code, name })) + for (const am of source) { + const id = am?.code + if (typeof id !== 'string' || !id) continue + const base = provider.models?.[id] ?? {} + const rate = rates.get(id) + const image = visionByCode(id) + models[id] = { + ...base, + id, + name: names.get(id) || am.name || base.name || id, + api: { id, url: `${activeBase}/v1`, npm: '@ai-sdk/openai-compatible' }, + limit: { ...base.limit, context: 200000, output: 32000 }, + tool_call: true, + ...(id.includes('max') || id.includes('glm') || id.includes('deepseek') || id.includes('qwen37') + ? { reasoning: true } : {}), + modalities: { input: image ? ['text', 'image'] : ['text'] }, + ...(Number.isFinite(rate) && rate > 0 ? { rate } : {}), + } + } + return Object.keys(models).length ? models : provider.models +} + +// ---------------------------------------------------------------- plugin + +export const MclawAuthPlugin = async (_input, options) => { + const base = String(options?.base ?? DEFAULT_BASE).replace(/\/+$/, '') + activeBase = base + // 测试缝:fake browser 从 options.browserModule 进(宿主不会传)。 + const browser = options?.browserModule ?? browserDefault + // 宿主取消登录(callback 没被调)后的收尾时限:到点关浏览器、放 profile 锁, + // 不然锁被宿主 pid 占着,后续登录/续期全要等 LOCK_TIMEOUT。 + const signinAbortMs = Number(options?.signinAbortMs) > 0 ? Number(options.signinAbortMs) : 300_000 + + return { + // 未登录也能看到的供应商与静态模型目录。 + config: async (cfg) => { + cfg.provider ??= {} + cfg.provider[PROVIDER] ??= { + name: 'MClaw', + npm: '@ai-sdk/openai-compatible', // chat completions + api: `${base}/v1`, + models: MODELS, + } + }, + + // 配置了 App 凭证后按账号拉取实际模型目录与倍率。 + provider: { id: PROVIDER, models: accountModels }, + + auth: { + provider: PROVIDER, + methods: [ + { + type: 'oauth', + label: '浏览器登录(登录一次,凭证全自动)', + // 没有 prompts:登录全程只有「在弹出的 Chrome 里登录」一个动作。 + // llm key 由 apikey/get v1 自动取;vip 会话由 SSO 换票链自动维持 + // (0.5.0 前老账号手动粘过的 metadata.vipCookie 仍优先、失效自动换新)。 + + // 流程:宿主契约要求 authorize 立即返回 { url, opened, instructions, + // method, callback }(参照 sensenova/joycode),Chrome 由 authorize 弹出、 + // 收割等登录放进宿主随后调的 callback()。每次登录用全新 profile 的 + // Chrome(CDP 管道驱动,不占端口),绝不带旧票:换账号登录、票被吊销 + // 后重登都不会捡到上一次的 Cookie。用户在窗口里完成移动云登录(网页 + // 支持验证码、密码、扫码等多种方式)→ 插件收割 authorization Cookie + // (= pc: 票)→ apikey/get v1 自动取 llm key → profile 目录与手机号 + // 存进 metadata,存为 oauth 型 { refresh:'browser', access, expires, + // metadata },到期前宿主调 refresh 钩子 headless 续期(复开该账号 + // 自己的 profile)。 + async authorize(inputs = {}, { signal } = {}) { + // 不 await:Chrome 立即弹出;若宿主取消(callback 没被调),定时器 + // 到点 abort——关浏览器、放 profile 锁;挂个空 catch 免得 abort 后 + // 的拒绝刷 unhandled rejection。 + const harvesting = browser.startBrowserHarvest() + harvesting.promise.catch(() => {}) + const cleanup = setTimeout(() => { harvesting.abort().catch(() => {}) }, signinAbortMs) + // magpie 式取消:宿主在 authorize 之后立刻调 callback(undefined, { signal }), + // 用户关掉面板/登录超时就 abort 这个 signal。两个入口都接上它——abort + // 一到立即收尾(关浏览器、放锁、删孤儿 profile),不等到 10 分钟 deadline。 + const onAbort = () => { harvesting.abort().catch(() => {}) } + if (signal?.aborted) onAbort() + else if (typeof signal?.addEventListener === 'function') signal.addEventListener('abort', onAbort, { once: true }) + return { + url: '', + opened: true, // Chrome 已由本插件弹出,宿主不要再开 url + instructions: '已弹出专用 Chrome 窗口:请在里面登录移动云(yun.139.com,网页支持多种登录方式),登录成功后本流程自动继续并收走全部凭证', + method: 'auto', + async callback(_code, { signal: callbackSignal } = {}) { + clearTimeout(cleanup) + if (callbackSignal?.aborted) onAbort() + else if (typeof callbackSignal?.addEventListener === 'function') callbackSignal.addEventListener('abort', onAbort, { once: true }) + let release, close + try { + const { cookie, profilePath, release: r, close: c } = await harvesting.promise + release = r + close = c + const token = cookie.value + const expires = basicExpiryMs(token) ?? (cookie.expiresMs || undefined) + // 票校验 + 自动取 key(顺带拿到倍率表,缓存给 models 用) + let apiKey + try { + apiKey = (await llmKeyAndRates(token)).apikey + } catch (error) { + if (error.signIn === 'expired') { + return { type: 'failed', error: `登录票校验失败:${error.message}` } + } + apiKey = undefined // 网络抖动:见下 + } + if (!apiKey) { + return { type: 'failed', error: '登录成功但 llm key 自动获取失败(网络抖动),请重新登录重试' } + } + const metadata = { apiKey, profile: profilePath } + const email = nameFromAppAuth(token) + if (email) metadata.email = email + return { type: 'success', refresh: 'browser', access: token, expires, metadata } + } catch (error) { + return { type: 'failed', error: error?.message ?? String(error) } + } finally { + await close?.().catch(() => {}) + await release?.() + } + }, + } + }, + }, + ], + + // 每个账号请求所带的凭证。chat key 两种存储形态都认: + // api 型在 auth.key,oauth 型(浏览器登录自动获取的)在 metadata.apiKey。 + loader: async (getAuth) => { + const auth = await getAuth() + const key = String(auth?.type === 'oauth' ? auth?.metadata?.apiKey : auth?.key ?? '').trim() + if (!key) return {} + return { + baseURL: `${base}/v1`, + + async fetch(input, init) { + const headers = new Headers(init?.headers) + headers.set('authorization', `Bearer ${key}`) + const response = await fetch(input, { ...init, headers }) + return normalizeChatResponse(response) + }, + } + }, + + async usage(getAuth) { + const auth = await getAuth() + const appAuth = appAuthOf(auth) + if (!appAuth) return { windows: [] } // 未配 Basic 票,无用量可查 + try { + const item = await fetchBenefit(appAuth) + if (!item) return { error: '权益列表里没有 aitokens(RHR135)', windows: [] } + const total = Number(item.benefitValue) + const used = Number(item.benefitUsed) + const window = { + // 权益识别走 benefitNo(RHR135),卡片名不带编号。 + name: 'MClaw tokens', + used: total > 0 ? (used / total) * 100 : 0, + amount: used, + limit: total, + unit: 'tokens', + display: `已用 ${fmt(used)} / ${fmt(total)} · 剩余 ${fmt(Math.max(total - used, 0))}`, + } + const expiry = basicExpiryMs(appAuth) + if (expiry) { + const d = new Date(expiry) + window.display += ` · 凭证至 ${d.getMonth() + 1}/${d.getDate()}${expiry < Date.now() ? '(已过期,请重新抓取)' : ''}` + } + // 最近明细 + 权威重置时间需要 vip 会话:优先账号配置的 Cookie,其次 + // 进程内缓存的换票成果;缺失或失效走 SSO 换票链自动补。明细只是 + // 加料:任何失败(超时、Cookie 失效、换票不成)都不影响池窗口本身。 + const cached = cookieCache.get(appAuth) + const configured = auth.metadata?.vipCookie?.trim() + let vipCookie = cached ?? configured + let records = vipCookie ? await fetchRecords(vipCookie).catch(() => undefined) : undefined + if (!records && cached) cookieCache.delete(appAuth) // 缓存的那张死了 + if (!records) { + const fresh = await ssoCookie(appAuth) + if (fresh) records = await fetchRecords(fresh).catch(() => undefined) + } + const latest = records?.[0] + const end = endTimeMs(latest?.endTime) + // 「重置于」只认该账号明细里的权威 endTime(当前周期的终点)。 + // 上游不给周期起止,也没有可外推的通用锚点——别家账号的周期起点 + // 各不相同,没有权威 endTime 就不显示,绝不猜一个。 + const resetsAt = end && end > Date.now() ? end : undefined + if (resetsAt) { + // 窗口形态带上 startsAt + span(周期起点 = endTime 回退一个日历月, + // 近似)。当前 magpie(0.1.2906)的插件桥会把这两个量剥掉(startsAt + // 留给自家网关窗口),「按此速度,预计…」由宿主自己的历史采样 + // (≥3 点且 ≥1h)另算;宿主哪天不剥了即生效。 + const start = cycleStartMs(resetsAt) + window.resetsAt = new Date(resetsAt).toISOString() + if (start > 0 && start < resetsAt) { + window.startsAt = new Date(start).toISOString() + window.span = (resetsAt - start) / 1000 + } + } + const reset = resetsAt + ? ` · 重置于 ${new Date(resetsAt).toLocaleString('zh-CN', { month: 'numeric', day: 'numeric', hour: '2-digit', minute: '2-digit' })}` + : '' + window.display += reset + if (latest) { + window.display += ` · 最近 ${latest.recordTime ?? ''} ${latest.comments ?? ''} -${fmt(Number(latest.benefitNum) || 0)}tok(${latest.modelName || latest.modelCode || ''}${latest.coefficient ? ` ${latest.coefficient}×` : ''})` + } + return { windows: [window] } + } catch (error) { + return { + error: error.message, + windows: [], + signIn: error.signIn === 'expired' ? 'expired' : 'kept', + } + } + }, + + // 浏览器登录账号(refresh === 'browser')的自动续期:headless 复开该账号 + // 自己的 profile(metadata.profile;0.5.0 前的老账号退回老共享目录,收割 + // 成功后把目录钉进 metadata),网页应用自己刷新会话后重新收割 + // authorization Cookie;票换了就顺手刷新 metadata.apiKey。到期前 + // refreshLead 触发;其他形态原样返回。 + refreshLead: 3 * 24 * 3600e3, + async refresh(auth) { + if (auth?.refresh !== 'browser' || !auth?.access) return {} + const { cookie, profilePath } = await browser.browserRefreshHarvest({ profilePath: auth?.metadata?.profile }) + const token = cookie.value + // 收割到的票必须是这个账号的:最后一个登录的是别的账号时绝不能 + // 张冠李戴(B 的票 + B 的 key 存到 A 名下)。 + const who = nameFromAppAuth(token) + if (auth?.metadata?.email && who && who !== auth.metadata.email) { + throw expired(`续期收割到的是另一账号(${who})的票,已放弃;请重新登录`) + } + const expires = basicExpiryMs(token) ?? (cookie.expiresMs || auth.expires) + const metadata = { ...(auth.metadata ?? {}) } + if (!metadata.profile && profilePath) metadata.profile = profilePath + if (token !== auth.access) { + try { + metadata.apiKey = (await llmKeyAndRates(token)).apikey + } catch {} // key 拉不到就保留旧值,chat 不一定受影响 + } + return { access: token, expires, metadata } + }, + }, + } +} + +// 测试面(node --test / bun test)。除插件本身外不要导出别的函数。 +export const _internal = { + MODELS, appHeaders, visionByCode, nameFromAppAuth, endTimeMs, basicExpiryMs, + appAuthOf, llmChannelId, cycleStartMs, normalizeChatResponse, accountModels, HOSTS, + resetSsoState, resetModelCache, +} + +// OpenCode v1 形态:默认导出 { id, server },宿主只取 server。 +export default { id: PROVIDER, server: MclawAuthPlugin } diff --git a/packages/mclaw/login.test.mjs b/packages/mclaw/login.test.mjs new file mode 100644 index 0000000..3ad852c --- /dev/null +++ b/packages/mclaw/login.test.mjs @@ -0,0 +1,150 @@ +// 登录 / 续期:浏览器替身(fake-browser.mjs)+ 本地 fake 上游。覆盖:登录成功 +// 存 profile 与手机号;取消(callback 没被调)后定时器收尾关浏览器、放锁; +// 续期只开账号自己的 profile 且校验票的归属,别人的票拒写。 +import './nonet.mjs' +import { beforeEach, afterEach, expect, test } from 'bun:test' +import { MclawAuthPlugin, _internal } from './index.mjs' +import { fakeUpstream, TICKET_A, TICKET_B, PHONE_A, PHONE_B } from './fake.mjs' +import { fakeBrowserModule } from './fake-browser.mjs' + +let f +let fb +afterEach(() => { + f?.close() + f = undefined +}) +beforeEach(() => _internal.resetModelCache()) + +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)) + +const oauthMethod = (plugin) => plugin.auth.methods[0] + +test('登录成功:收割票 + 自动取 key,profile 与掩码手机号进 metadata', async () => { + f = fakeUpstream() + fb = fakeBrowserModule({ ticket: TICKET_A }) + const plugin = await MclawAuthPlugin({}, { browserModule: fb.module, signinAbortMs: 60_000 }) + const flow = await oauthMethod(plugin).authorize({}) + expect(flow.opened).toBe(true) + expect(flow.method).toBe('auto') + fb.module.deliverHarvest() + const result = await flow.callback() + expect(result.type).toBe('success') + expect(result.access).toBe(TICKET_A) + expect(result.refresh).toBe('browser') + expect(result.metadata.apiKey).toBe('na-test-key') + expect(result.metadata.email).toBe(PHONE_A) + expect(result.metadata.profile).toBe(fb.state.openedProfiles[0]) + // 正常收尾:callback 自己关浏览器、放锁,abort 定时器不再动它 + expect(fb.state.closed).toBe(1) + expect(fb.state.released).toBe(1) +}) + +test('宿主取消(callback 没被调)→ 定时器到点关浏览器、放 profile 锁', async () => { + f = fakeUpstream() + fb = fakeBrowserModule({ ticket: TICKET_A }) + const plugin = await MclawAuthPlugin({}, { browserModule: fb.module, signinAbortMs: 30 }) + await oauthMethod(plugin).authorize({}) + // 收割一直挂着(用户没登录完),宿主已经取消:定时器到点应 abort + await sleep(120) + expect(fb.state.aborted).toBe(true) + expect(fb.state.closed).toBeGreaterThanOrEqual(1) + expect(fb.state.released).toBeGreaterThanOrEqual(1) +}) + +test('续期:只开账号自己的 profile;票换了 key 跟着刷', async () => { + f = fakeUpstream() + fb = fakeBrowserModule({ ticket: TICKET_A }) + const plugin = await MclawAuthPlugin({}, { browserModule: fb.module }) + const auth = { type: 'oauth', refresh: 'browser', access: 'Basic old', expires: Date.now() - 1000, metadata: { apiKey: 'na-old', email: PHONE_A, profile: 'profile-of-A' } } + const out = await plugin.auth.refresh(auth) + expect(fb.state.refreshProfiles).toEqual(['profile-of-A']) + expect(out.access).toBe(TICKET_A) + expect(out.metadata.apiKey).toBe('na-test-key') + expect(out.metadata.profile).toBe('profile-of-A') +}) + +test('续期收割到别人的票 → 拒写(expired),绝不张冠李戴', async () => { + f = fakeUpstream() + fb = fakeBrowserModule({ ticket: TICKET_B }) + const plugin = await MclawAuthPlugin({}, { browserModule: fb.module }) + const auth = { type: 'oauth', refresh: 'browser', access: TICKET_A, expires: Date.now() - 1000, metadata: { apiKey: 'na-a', email: PHONE_A, profile: 'profile-of-A' } } + let caught + try { + await plugin.auth.refresh(auth) + } catch (error) { + caught = error + } + expect(caught?.signIn).toBe('expired') + expect(caught?.message).toContain(PHONE_B) +}) + +test('0.5.0 前的老账号(metadata 无 profile):退回老共享目录续期,成功后钉进 metadata', async () => { + f = fakeUpstream() + fb = fakeBrowserModule({ ticket: TICKET_B }) + const plugin = await MclawAuthPlugin({}, { browserModule: fb.module }) + const auth = { type: 'oauth', refresh: 'browser', access: TICKET_B, expires: Date.now() - 1000, metadata: { apiKey: 'na-b', email: PHONE_B } } + const out = await plugin.auth.refresh(auth) + expect(fb.state.refreshProfiles).toEqual([undefined]) // fake 的缺省路径 + expect(out.metadata.profile).toBe('fake-profile-legacy') + expect(out.metadata.email).toBe(PHONE_B) +}) + +test('llm key 自动获取失败(网络抖动)→ 登录失败并提示重试,收尾照常', async () => { + f = fakeUpstream() + f.route('POST /api/llm/apikey/get', () => new Response('boom', { status: 500 })) + fb = fakeBrowserModule({ ticket: TICKET_A }) + const plugin = await MclawAuthPlugin({}, { browserModule: fb.module, signinAbortMs: 60_000 }) + const flow = await oauthMethod(plugin).authorize({}) + fb.module.deliverHarvest() + const result = await flow.callback() + expect(result.type).toBe('failed') + expect(result.error).toContain('重新登录') + expect(fb.state.closed).toBe(1) + expect(fb.state.released).toBe(1) +}) + +test('authorize 不需要任何输入:无 prompts,直接开登', async () => { + f = fakeUpstream() + fb = fakeBrowserModule({ ticket: TICKET_A }) + const plugin = await MclawAuthPlugin({}, { browserModule: fb.module, signinAbortMs: 60_000 }) + const method = oauthMethod(plugin) + expect(method.prompts).toBeUndefined() + const flow = await method.authorize() + expect(flow.opened).toBe(true) + fb.module.deliverHarvest() + const result = await flow.callback() + expect(result.type).toBe('success') + expect(result.metadata.email).toBe(PHONE_A) +}) + +test('magpie 式取消:callback 立即被调 + signal abort → 立即收尾', async () => { + f = fakeUpstream() + fb = fakeBrowserModule({ ticket: TICKET_A }) + const plugin = await MclawAuthPlugin({}, { browserModule: fb.module, signinAbortMs: 60_000 }) + const controller = new AbortController() + // magpie 的时序:authorize 一返回就调 callback(undefined, { signal }), + // 用户取消/登录超时时 abort signal——收尾必须立刻发生,不等 5 分钟定时器 + const flow = await oauthMethod(plugin).authorize({}, { signal: controller.signal }) + const done = flow.callback(undefined, { signal: controller.signal }) + await sleep(10) + expect(fb.state.aborted).toBe(false) + controller.abort() + const result = await done + expect(result.type).toBe('failed') + expect(fb.state.aborted).toBe(true) + expect(fb.state.closed).toBeGreaterThanOrEqual(1) + expect(fb.state.released).toBeGreaterThanOrEqual(1) +}) + +test('authorize 时 signal 已是 aborted → 直接收尾不开流程', async () => { + f = fakeUpstream() + fb = fakeBrowserModule({ ticket: TICKET_A }) + const plugin = await MclawAuthPlugin({}, { browserModule: fb.module, signinAbortMs: 60_000 }) + const controller = new AbortController() + controller.abort() + await oauthMethod(plugin).authorize({}, { signal: controller.signal }) + await sleep(10) + expect(fb.state.aborted).toBe(true) + expect(fb.state.closed).toBeGreaterThanOrEqual(1) + expect(fb.state.released).toBeGreaterThanOrEqual(1) +}) diff --git a/packages/mclaw/models.test.mjs b/packages/mclaw/models.test.mjs new file mode 100644 index 0000000..c322a25 --- /dev/null +++ b/packages/mclaw/models.test.mjs @@ -0,0 +1,57 @@ +// 账号模型目录:agent/list × apikey/get v1 的合并(倍率、名字)、票过期向外抛、 +// 无凭证时静态目录原样返回。全部走本地 fake。 +import './nonet.mjs' +import { beforeEach, afterEach, expect, test } from 'bun:test' +import { MclawAuthPlugin, _internal } from './index.mjs' +import { fakeUpstream, json, TICKET_A, TICKET_B } from './fake.mjs' + +let f +afterEach(() => f?.close()) +beforeEach(() => _internal.resetModelCache()) + +const authOf = (ticket) => ({ + type: 'oauth', refresh: 'browser', access: ticket, expires: Date.now() + 86400e3, + metadata: { apiKey: 'na-test-key', email: '131****9239' }, +}) + +test('agent/list × apikey/get 合并出账号目录与倍率', async () => { + f = fakeUpstream() + const p = await MclawAuthPlugin({}, {}) + const models = await p.provider.models({ models: {} }, { auth: authOf(TICKET_A) }) + expect(Object.keys(models).sort()).toEqual(['blian_qwen38_flash', 'huoshan_glm_5_3']) + expect(models.blian_qwen38_flash.rate).toBe(0.18) + expect(models.huoshan_glm_5_3.rate).toBe(3.5) + expect(models.blian_qwen38_flash.api.url).toContain('/api/llm/102001/v1') + expect(models.blian_qwen38_flash.tool_call).toBe(true) + expect(models.huoshan_glm_5_3.reasoning).toBe(true) +}) + +test('票过期(01000002)向外抛 expired', async () => { + f = fakeUpstream() + f.route('POST /api/adapter/assistant/agent/list', () => json({ success: false, code: '01000002', message: '无效的凭证' })) + const p = await MclawAuthPlugin({}, {}) + let caught + try { + await p.provider.models({ models: {} }, { auth: authOf(TICKET_B) }) + } catch (error) { + caught = error + } + expect(caught?.signIn).toBe('expired') +}) + +test('倍率接口挂了、config/get 兜底也不可用 → 仍有目录(无倍率)', async () => { + f = fakeUpstream() + f.route('POST /api/llm/apikey/get', () => new Response('boom', { status: 500 })) + f.route('POST /api/openclaw/config/get', () => new Response('boom', { status: 500 })) + const p = await MclawAuthPlugin({}, {}) + const models = await p.provider.models({ models: {} }, { auth: authOf(TICKET_B) }) + expect(models.blian_qwen38_flash).toBeTruthy() + expect(models.blian_qwen38_flash.rate).toBeUndefined() +}) + +test('无凭证 → 静态目录原样返回,不发请求', async () => { + const p = await MclawAuthPlugin({}, {}) + const staticModels = { static_model: { name: 'S' } } + const models = await p.provider.models({ models: staticModels }, { auth: undefined }) + expect(models).toBe(staticModels) +}) diff --git a/packages/mclaw/nonet.mjs b/packages/mclaw/nonet.mjs new file mode 100644 index 0000000..878eb31 --- /dev/null +++ b/packages/mclaw/nonet.mjs @@ -0,0 +1,10 @@ +// 每个测试文件最先 import 它:测试跑不到真网络。fetch 只放行本机(127.0.0.1/ +// localhost/[::1]),其余一律抛错——哪个测试忘了装 fake,请求就发不出去, +// 凭证(Basic 票、llm key、vip Cookie)不可能漏到 yun.139.com / mcloud.139.com。 +const local = (u) => /^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:\d+)?(\/|$|\?)/.test(u) +const realFetch = globalThis.fetch +globalThis.fetch = async (input, init) => { + const u = typeof input === 'string' ? input : input instanceof URL ? input.href : input.url + if (!local(u)) throw new Error('a test asked ' + u + ' with no fake in place') + return realFetch(input, init) +} diff --git a/packages/mclaw/opencode.mjs b/packages/mclaw/opencode.mjs new file mode 100644 index 0000000..737ef1d --- /dev/null +++ b/packages/mclaw/opencode.mjs @@ -0,0 +1,5 @@ +// The package's OpenCode 1.x plugins, as OpenCode 1.x and magpie's host +// load them: its plugin functions and nothing else (1.x refuses a +// package whose exports include anything but plugins). OpenCode 2.x +// loads opencode2.mjs, which runs these. +export { MclawAuthPlugin } from "./index.mjs" diff --git a/packages/mclaw/opencode2.mjs b/packages/mclaw/opencode2.mjs new file mode 100644 index 0000000..7aa300b --- /dev/null +++ b/packages/mclaw/opencode2.mjs @@ -0,0 +1,594 @@ +// The OpenCode 2.x face of a package whose plugins are written for +// OpenCode 1.x (and magpie's plugin host). +// +// OpenCode 2.x loads a package's `exports["."]` and wants its default to be +// {id, setup(ctx)}; it has no fallback for a 1.x plugin's named functions +// (plugins#657). This file is that default. It runs each 1.x plugin the +// package's opencode.mjs exports and hands 2.x what the plugin's hooks say: +// +// auth.methods → the integration's sign-in methods +// config() → the provider, its package, base URL and models +// provider.models → the signed-in account's own model list +// auth.loader → each request's base URL, key, headers and fetch +// +// What 2.x has no place for is left out: chat.headers and chat.params +// (2.x's sdk hook doesn't carry the session), magpie's usage and checkin, +// tools and events. +// +// scripts/opencode2.mjs is the one copy that is edited. Every package that +// has it carries the same bytes as packages//opencode2.mjs, and +// scripts/check.mjs fails when a copy differs. + +import { readFileSync } from "node:fs" +import * as v1 from "./opencode.mjs" + +const pkg = JSON.parse(readFileSync(new URL("./package.json", import.meta.url), "utf8")) + +// The key the SDK is made with: the account's own goes on each request in +// its place (see wrapFetch), so a key read when the SDK was made can't go +// out after the account changed. +const PLACEHOLDER = "opencode2-v1-key" + +// The SDK package a 1.x npm name runs as on 2.x. A version keeps 2.x from +// swapping @ai-sdk/* for its native providers, which never call the sdk +// hook below; openai-compatible's is the one 2.x ships, the others are AI +// SDK v6's dist-tag, the line 2.x's bridge runs. +export function packageOf(npm) { + const name = npm || "@ai-sdk/openai-compatible" + if (name === "@ai-sdk/openai-compatible") return "aisdk:@ai-sdk/openai-compatible@2.0.41" + if (/^@ai-sdk\/[^/@]+$/.test(name)) return `aisdk:${name}@ai-v6` + return `aisdk:${name}` +} + +// The plugins a 1.x module exports, as magpie's host and OpenCode 1.x read +// them: a default {server} is the one plugin, else every function export +// and every {server} object. +export function pluginsOf(mod) { + const d = mod?.default + if (d && typeof d === "object" && ("server" in d || "id" in d || "tui" in d)) + return typeof d.server === "function" ? [d.server] : [] + const out = [] + for (const value of Object.values(mod ?? {})) { + const fn = typeof value === "function" ? value : value && typeof value === "object" && typeof value.server === "function" ? value.server : null + if (fn && !out.includes(fn)) out.push(fn) + } + return out +} + +const int = (n, fallback = 0) => { + const v = Math.trunc(Number(n)) + return Number.isFinite(v) && v >= 0 ? v : fallback +} +const money = (n) => (Number.isFinite(Number(n)) && Number(n) >= 0 ? Number(n) : 0) +const record = (v) => (v && typeof v === "object" && !Array.isArray(v) ? v : {}) +const json = (v) => { + try { + return JSON.parse(JSON.stringify(v ?? null)) + } catch { + return null + } +} +const strings = (v) => Object.fromEntries(Object.entries(record(v)).filter(([, s]) => typeof s === "string")) +const nonEmpty = (o) => (Object.keys(o).length ? o : undefined) + +// connKey names a connection the way 2.x does. +const connKey = (c) => (!c ? "" : c.type === "credential" ? `credential:${c.id}` : `env:${c.name}`) + +// ---- sign-in ------------------------------------------------------------ + +// fields is a 1.x method's prompts as a 2.x form. +export function fieldsOf(prompts) { + const out = [] + for (const p of prompts ?? []) { + if (!p?.key) continue + const f = { key: String(p.key), type: "string", title: String(p.message ?? p.key) } + if (p.placeholder) f.placeholder = String(p.placeholder) + if (p.type === "select" && Array.isArray(p.options)) + f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) })) + // a prompt shown only when another answer says so can't be required + if (!p.condition) f.required = true + out.push(f) + } + return out.length ? out : undefined +} + +// v1Saved is what a 1.x sign-in's success is saved as, the way 1.x writes +// auth.json: the result without its type and provider. +function v1Saved(r) { + const { type: _t, provider: _p, ...rest } = r + if ("key" in r) return { type: "api", ...rest } + return { type: "oauth", ...rest } +} + +// credentialOf is a 1.x sign-in's success as a 2.x credential: OAuth for +// both kinds, the 1.x auth kept whole in its metadata. No refresh is +// registered, so 2.x hands the credential over as it is and the plugin's +// own loader renews it, as it does on 1.x. +export function credentialOf(methodID, r) { + if (!r || r.type !== "success") throw new Error(r?.error || r?.message || "the sign-in failed") + const saved = json(v1Saved(r)) + if (saved.type === "api") + return { type: "oauth", methodID, access: String(saved.key ?? ""), refresh: "", expires: 0, metadata: { v1: saved } } + return { + type: "oauth", + methodID, + access: String(saved.access ?? ""), + refresh: String(saved.refresh ?? ""), + expires: int(saved.expires), + metadata: { v1: saved }, + } +} + +// authOfValue is the 1.x auth a 2.x credential stands for. +export function authOfValue(value) { + if (!value) return null + if (value.type === "oauth") { + const v1 = record(value.metadata).v1 + if (v1 && typeof v1 === "object") return v1 + return { type: "oauth", access: value.access, refresh: value.refresh, expires: value.expires } + } + if (value.type === "key") { + const meta = value.metadata && Object.keys(value.metadata).length ? { metadata: value.metadata } : {} + return { type: "api", key: value.key, ...meta } + } + return null +} + +const fingerprint = (a) => JSON.stringify([a?.type, a?.access ?? a?.key ?? "", a?.refresh ?? ""]) + +// ---- models ------------------------------------------------------------- + +const MODALITIES = ["text", "audio", "image", "video", "pdf"] + +// internalOf is a config model as 1.x hands it to provider.models: what +// fromModelsDevModel makes of it, with the config's own variants. +export function internalOf(providerID, conf, key, m) { + const mods = record(m.modalities) + const has = (list, k) => Array.isArray(list) && list.includes(k) + const cost = record(m.cost) + return { + ...m, + id: key, + providerID, + name: m.name ?? key, + api: { id: m.id ?? key, url: m.provider?.api ?? conf.api ?? conf.options?.baseURL ?? "", npm: m.provider?.npm ?? conf.npm ?? "@ai-sdk/openai-compatible" }, + status: m.status ?? "active", + headers: m.headers ?? {}, + options: m.options ?? {}, + cost: { input: money(cost.input), output: money(cost.output), cache: { read: money(cost.cache_read), write: money(cost.cache_write) } }, + limit: { context: int(m.limit?.context), input: m.limit?.input, output: int(m.limit?.output) }, + capabilities: { + temperature: m.temperature ?? false, + reasoning: m.reasoning ?? false, + attachment: m.attachment ?? false, + toolcall: m.tool_call ?? true, + input: Object.fromEntries(MODALITIES.map((k) => [k, mods.input ? has(mods.input, k) : k === "text"])), + output: Object.fromEntries(MODALITIES.map((k) => [k, mods.output ? has(mods.output, k) : k === "text"])), + interleaved: m.interleaved ?? false, + }, + release_date: m.release_date ?? "", + variants: record(m.variants), + } +} + +// modelOf is a 1.x model, in config or internal form, as a 2.x Model.Info. +export function modelOf(providerID, provider, key, m) { + const caps = record(m.capabilities) + const listFrom = (obj, list) => { + if (obj && typeof obj === "object") return MODALITIES.filter((k) => obj[k]) + if (Array.isArray(list)) return list.map(String) + return ["text"] + } + const input = listFrom(caps.input, m.modalities?.input) + const output = listFrom(caps.output, m.modalities?.output) + const c = record(m.cost) + const cache = record(c.cache) + const npm = m.api?.npm ?? m.provider?.npm + const url = m.api?.url ?? m.provider?.api + const settings = { ...record(json(m.options)) } + if (url && url !== provider.baseURL) settings.baseURL = url + const variants = Object.entries(record(m.variants)) + .filter(([, v]) => !record(v).disabled) + .map(([id, v]) => { + const { disabled: _d, ...rest } = record(json(v)) + return nonEmpty(rest) ? { id, settings: rest } : { id } + }) + const status = ["alpha", "beta", "deprecated", "active"].includes(m.status) ? m.status : "active" + const out = { + id: key, + modelID: String(m.api?.id ?? m.id ?? key), + providerID, + name: String(m.name ?? key), + capabilities: { + tools: caps.toolcall ?? m.tool_call ?? true, + input: input.length ? input : ["text"], + output: output.length ? output : ["text"], + ...(typeof (caps.temperature ?? m.temperature) === "boolean" ? { temperature: caps.temperature ?? m.temperature } : {}), + }, + variants, + time: { released: Date.parse(m.release_date ?? "") || 0 }, + cost: [{ input: money(c.input), output: money(c.output), cache: { read: money(cache.read ?? c.cache_read), write: money(cache.write ?? c.cache_write) } }], + status, + enabled: true, + limit: { context: int(m.limit?.context, 128000) || 128000, output: int(m.limit?.output, 8192) || 8192 }, + } + if (m.limit?.input) out.limit.input = int(m.limit.input) + if (npm && npm !== provider.npm) out.package = packageOf(npm) + if (nonEmpty(settings)) out.settings = settings + const headers = strings(m.headers) + if (nonEmpty(headers)) out.headers = headers + return out +} + +// ---- requests ----------------------------------------------------------- + +const urlOf = (input) => (typeof input === "string" ? input : input instanceof URL ? input.href : input?.url ?? String(input)) + +// wrapFetch sends a request the SDK made from the provider's settings the +// way 1.x would have sent it with the loader's options: the loader's base +// URL in place of the configured one, the account's key in place of the +// placeholder, the loader's headers added, through the loader's fetch. +export function wrapFetch(next, base, options) { + return async (input, init = {}) => { + const o = await options() + let url = urlOf(input) + const from = String(base ?? "").replace(/\/+$/, "") + const to = o.baseURL ? String(o.baseURL).replace(/\/+$/, "") : "" + if (from && to && from !== to && url.startsWith(from)) url = to + url.slice(from.length) + const req = input instanceof Request ? input : null + const headers = new Headers(init.headers ?? req?.headers ?? undefined) + for (const [k, v] of [...headers.entries()]) { + if (!v.includes(PLACEHOLDER)) continue + if (o.key) headers.set(k, v.replaceAll(PLACEHOLDER, o.key)) + else headers.delete(k) + } + for (const [k, v] of Object.entries(strings(o.headers))) headers.set(k, v) + const send = typeof o.fetch === "function" ? o.fetch : next ?? fetch + if (req && init.body === undefined) { + const body = req.method === "GET" || req.method === "HEAD" ? undefined : await req.text() + return send(url, { method: req.method, headers, body, signal: init.signal ?? req.signal }) + } + return send(url, { ...init, headers }) + } +} + +// ---- one plugin --------------------------------------------------------- + +async function setupPlugin(ctx, fn, live) { + const directory = ctx?.location?.directory ?? process.cwd() + // the active account each provider was last read for, and the renewed + // auth a plugin saved for it (2.x has no way for a plugin to write a + // credential back, so it is kept in the plugin's storage, under the + // credential it renews and the token it was renewed from) + const current = new Map() + const saved = new Map() + const signingIn = new Map() + const storeKey = (id, key) => `v1auth/${id}/${key}` + + const client = { + auth: { + async set(arg) { + const id = arg?.path?.id + const body = json(arg?.body) + const cur = id && current.get(id) + // a sign-in's own saves belong to the credential it is about to + // make, not the one that was active when it started + if (!cur || !body || signingIn.get(id) > 0) return { data: true } + const entry = { fp: cur.fp, auth: body } + saved.set(storeKey(id, cur.key), entry) + await Promise.resolve() + .then(() => ctx.storage?.set?.(storeKey(id, cur.key), entry)) + .catch(() => {}) + return { data: true } + }, + async get() { + return { data: undefined } + }, + }, + app: { log: async () => ({ data: true }) }, + } + + const hooks = (await fn({ client, directory, worktree: directory, project: {}, serverUrl: undefined, $: undefined }, {})) ?? {} + const cfg = { provider: {} } + try { + await hooks.config?.(cfg) + } catch {} + const auth = hooks.auth + const authID = auth?.provider ? String(auth.provider) : undefined + const providers = record(cfg.provider) + + // getAuth reads the active account: the credential 2.x holds, or what the + // plugin last saved renewing it. + const getAuth = async (id) => { + const connection = await ctx.integration.connection.active(id).catch(() => undefined) + if (!connection) { + current.delete(id) + return undefined + } + const value = await ctx.integration.connection.resolve(connection).catch(() => undefined) + const base = authOfValue(value) + if (!base) { + current.delete(id) + return undefined + } + const key = connKey(connection) + const fp = fingerprint(base) + // ours: a credential one of this plugin's own sign-ins made + const ours = value?.type === "oauth" && !!record(value.metadata).v1 + current.set(id, { key, fp, ours }) + const sk = storeKey(id, key) + let entry = saved.get(sk) + if (!entry) { + entry = await Promise.resolve() + .then(() => ctx.storage?.get?.(sk)) + .catch(() => undefined) + if (entry) saved.set(sk, entry) + } + return entry && entry.fp === fp && entry.auth ? entry.auth : base + } + + // the sign-in methods + if (authID && Array.isArray(auth.methods) && auth.methods.length) { + const label = (c) => { + const a = authOfValue(c) + const name = a?.name ?? a?.email ?? a?.metadata?.name ?? a?.metadata?.email ?? a?.account + return typeof name === "string" && name ? name : undefined + } + const begin = () => signingIn.set(authID, (signingIn.get(authID) ?? 0) + 1) + const end = () => signingIn.set(authID, Math.max(0, (signingIn.get(authID) ?? 1) - 1)) + const title = record(providers[authID]).name + // 2.x runs a transform again on every reload, from nothing + await ctx.integration.transform((editor) => { + let keyed = false + // the integration 2.x makes for an id it doesn't know is named by the + // id; the provider's own name reads better in the sign-in list + if (typeof title === "string" && title) + try { + editor.update?.(authID, (i) => { + if (i && (!i.name || i.name === authID)) i.name = title + }) + } catch {} + auth.methods.forEach((m, i) => { + if (!m) return + const methodID = `v1-${i}` + const form = fieldsOf(m.prompts) + if (m.type === "api" && typeof m.authorize !== "function") { + if (keyed) return + keyed = true + editor.method.update({ integrationID: authID, method: { type: "key", label: String(m.label ?? "API key"), ...(form ? { form } : {}) } }) + return + } + if (typeof m.authorize !== "function") return + editor.method.update({ + integrationID: authID, + method: { id: methodID, type: "oauth", label: String(m.label ?? authID), ...(form ? { form } : {}) }, + async authorize(answer) { + begin() + let ended = false + const done = () => { + if (!ended) end() + ended = true + } + try { + const inputs = Object.fromEntries(Object.entries(record(answer)).map(([k, v]) => [k, String(v)])) + const r = await m.authorize(inputs) + if (m.type === "api") { + done() + return { url: "", instructions: "", mode: "auto", callback: Promise.resolve().then(() => credentialOf(methodID, r)) } + } + if (r?.method === "code") + return { + url: String(r.url ?? ""), + instructions: String(r.instructions ?? ""), + mode: "code", + callback: async (code) => { + try { + return credentialOf(methodID, await r.callback(code)) + } finally { + done() + } + }, + } + const callback = Promise.resolve() + .then(() => r.callback()) + .then((res) => credentialOf(methodID, res)) + .finally(done) + callback.catch(() => {}) + return { url: String(r?.url ?? ""), instructions: String(r?.instructions ?? ""), mode: "auto", callback } + } catch (e) { + done() + throw e + } + }, + label, + }) + }) + }) + } + + // the loader's options for the account signed in now, read again when + // the account changes + let loaded = null + const loaderOptions = async (id) => { + if (id !== authID || typeof auth?.loader !== "function") { + const a = authID === id ? await getAuth(id) : undefined + return { key: a?.type === "api" ? a.key : undefined } + } + const a = await getAuth(id) + if (!a) return {} + const fp = current.get(id)?.key + "\0" + fingerprint(a) + if (loaded?.fp !== fp) { + const p = Promise.resolve() + .then(() => auth.loader(() => getAuth(id), providerOf(id))) + .then((o) => record(o)) + loaded = { fp, p } + p.catch(() => { + if (loaded?.fp === fp) loaded = null + }) + } + const o = await loaded.p + const key = typeof o.apiKey === "string" && o.apiKey ? o.apiKey : a.type === "api" ? a.key : undefined + return { baseURL: o.baseURL, key, headers: o.headers, fetch: o.fetch } + } + + // the providers, with the list the account's own read last gave each + const source = new Map() + // providerOf is a provider as 1.x hands it to provider.models and + // auth.loader + const providerOf = (id) => { + const conf = record(providers[id]) + const models = Object.fromEntries(Object.entries(record(conf.models)).map(([k, m]) => [k, internalOf(id, conf, k, record(m))])) + return { id, name: conf.name ?? id, source: "config", env: [], options: record(conf.options), models } + } + const listed = new Set() + for (const [id, conf0] of Object.entries(providers)) { + const conf = record(conf0) + // a provider entry that only names the sign-in (no package, no models) + // is not a provider of models + if (!conf.npm && !Object.keys(record(conf.models)).length) continue + const options = record(conf.options) + const { apiKey: _k, baseURL: _b, fetch: _f, headers: optHeaders, ...rest } = options + // with no base URL the config leaves it to the loader: a name that + // can't resolve stands in for it, and each request swaps in the + // loader's (wrapFetch) + const baseURL = options.baseURL ?? conf.api ?? `https://${id.replace(/[^a-z0-9-]/gi, "-")}.opencode2-v1.invalid` + const npm = conf.npm ?? "@ai-sdk/openai-compatible" + const info = { + id, + ...(id === authID ? { integrationID: id } : {}), + name: String(conf.name ?? id), + activation: "auto", + package: packageOf(npm), + settings: { ...record(json(rest)), ...(baseURL ? { baseURL: String(baseURL) } : {}) }, + } + const headers = { ...strings(conf.headers), ...strings(optHeaders) } + if (nonEmpty(headers)) info.headers = headers + const prov = { baseURL, npm } + const fromConfig = () => + Object.entries(record(conf.models)).map(([key, m]) => modelOf(id, prov, key, internalOf(id, conf, key, record(m)))) + listed.add(id) + await ctx.provider.transform((editor) => { + const s = source.get(id) + editor.add({ info, models: s?.models ?? fromConfig(), sourceConnection: s?.connection }) + }) + source.set(id, { conf, prov, models: null, connection: undefined }) + } + + // each request: the placeholder key, and the fetch that swaps in the + // account's. A provider the package doesn't list (one 2.x has built in + // that the plugin only signs in to) is left to 2.x unless the plugin's + // loader serves it and one of the plugin's own sign-ins is active. + const own = authID && !listed.has(authID) && typeof auth?.loader === "function" ? [authID] : [] + for (const id of new Set([...listed, ...own])) { + const base = source.get(id)?.prov.baseURL + await ctx.aisdk.hook( + "sdk", + async (evt) => { + const opts = evt.options + if (!opts || opts.__opencode2) return + if (!listed.has(id)) { + await getAuth(id) + if (!current.get(id)?.ours) return + } + opts.__opencode2 = true + opts.apiKey = PLACEHOLDER + opts.fetch = wrapFetch(opts.fetch, opts.baseURL ?? base, () => loaderOptions(id)) + }, + { providerID: id }, + ) + } + + // refresh reads the account's own list after a sign-in or a switch + const listID = hooks.provider?.id ? String(hooks.provider.id) : undefined + let refreshing = null + let again = false + // the account the list was last read for: a credential.updated that + // leaves it as it was reads nothing again + let readFor = null + const stateOf = async () => { + const c = await ctx.integration.connection.active(authID).catch(() => undefined) + const a = c ? await getAuth(authID) : undefined + return connKey(c) + "\0" + (a ? fingerprint(a) : "") + } + const refresh = () => { + if (refreshing) { + again = true + return refreshing + } + refreshing = (async () => { + try { + if (!authID || !source.has(authID)) return + const s = source.get(authID) + const connection = await ctx.integration.connection.active(authID).catch(() => undefined) + const a = connection ? await getAuth(authID) : undefined + readFor = connKey(connection) + "\0" + (a ? fingerprint(a) : "") + if (!a || listID !== authID || typeof hooks.provider?.models !== "function") { + if (s.connection || s.models) { + s.connection = undefined + s.models = null + await ctx.provider.reload() + } + return + } + const provider = providerOf(authID) + let got + try { + got = await hooks.provider.models(provider, { auth: a }) + } catch { + got = null + } + if (connKey(await ctx.integration.connection.active(authID).catch(() => undefined)) !== connKey(connection)) { + again = true + return + } + s.connection = connection + s.models = got && typeof got === "object" ? Object.entries(got).map(([k, m]) => modelOf(authID, s.prov, k, record(m))) : null + await ctx.provider.reload() + await ctx.model?.reload?.() + } finally { + refreshing = null + if (again && live.on) { + again = false + void refresh() + } + } + })() + return refreshing + } + + if (authID && ctx.event?.subscribe) + void (async () => { + try { + // a switch names the integration; an update (a sign-in, a removal) + // names nothing, so it reads again only when this account changed + const types = ["credential.switched", "credential.updated"] + for await (const event of ctx.event.subscribe({ types })) { + if (!live.on) return + if (event?.type === "credential.switched" && event?.data?.integrationID === authID) { + loaded = null + await refresh() + } else if (event?.type === "credential.updated" && (await stateOf()) !== readFor) { + await refresh() + } + } + } catch {} + })() + void refresh() +} + +export async function setup(ctx, mod = v1) { + const live = { on: true } + for (const fn of pluginsOf(mod)) { + try { + await setupPlugin(ctx, fn, live) + } catch (e) { + // one plugin failing to start leaves the package's others working + console.error(`${pkg.name}: ${e?.message ?? e}`) + } + } + return () => { + live.on = false + } +} + +export default { id: pkg.name, setup: (ctx) => setup(ctx) } diff --git a/packages/mclaw/package.json b/packages/mclaw/package.json new file mode 100644 index 0000000..f0755a7 --- /dev/null +++ b/packages/mclaw/package.json @@ -0,0 +1,36 @@ +{ + "name": "@magpie-community/opencode-mclaw-auth", + "version": "0.5.2", + "description": "OpenCode provider plugin: MClaw (中国移动云 MClaw, ai.yun.139.com)", + "type": "module", + "main": "./opencode.mjs", + "exports": { + ".": "./opencode2.mjs" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/joey-41/opencode-mclaw-auth.git" + }, + "scripts": { + "test": "bun test" + }, + "files": [ + "index.mjs", + "browser.mjs", + "opencode.mjs", + "opencode2.mjs", + "README.md", + "CHANGELOG.md", + "icon.png" + ], + "keywords": [ + "opencode", + "opencode-plugin", + "mclaw" + ], + "license": "MIT", + "magpie": { + "maxConcurrency": 4, + "icon": "data:image/png;base64,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" + } +} \ No newline at end of file diff --git a/packages/mclaw/usage.test.mjs b/packages/mclaw/usage.test.mjs new file mode 100644 index 0000000..bbf38ca --- /dev/null +++ b/packages/mclaw/usage.test.mjs @@ -0,0 +1,158 @@ +// 用量窗口:aitokens 池数学、无 RHR135、票过期、明细只是加料(失败不连坐)、 +// 重置时间只认账号自己的权威 endTime、SSO 换票链自动补 vip 会话。全部走本地 fake。 +import './nonet.mjs' +import { afterEach, beforeEach, expect, test } from 'bun:test' +import { MclawAuthPlugin, _internal } from './index.mjs' +import { fakeUpstream, json, TICKET_A } from './fake.mjs' + +let f +afterEach(() => f?.close()) +beforeEach(() => _internal.resetSsoState()) // SSO 缓存/冷却是模块级的,用例间隔离 + +const authOf = (ticket, extra) => ({ + type: 'oauth', refresh: 'browser', access: ticket, expires: Date.now() + 86400e3, + metadata: { apiKey: 'na-test-key', email: '131****9239', ...(extra ?? {}) }, +}) + +const plugin = async () => MclawAuthPlugin({}, {}) + +test('aitokens 池数学:amount/limit/used%,名字不带权益编号', async () => { + f = fakeUpstream() + const p = await plugin() + const out = await p.auth.usage(async () => authOf(TICKET_A)) + expect(out.windows).toHaveLength(1) + const w = out.windows[0] + expect(w.name).toBe('MClaw tokens') + expect(w.amount).toBe(11375000) + expect(w.limit).toBe(30500000) + expect(w.used).toBeCloseTo((11375000 / 30500000) * 100, 6) + expect(w.display).toContain('凭证至') + // 没配 vip Cookie:没有权威 endTime,就不给「重置于」 + expect(w.resetsAt).toBeUndefined() + expect(w.display).not.toContain('重置于') +}) + +test('权益列表里没有 aitokens → 明确报错', async () => { + f = fakeUpstream() + f.route('POST /isbo2/openApi/queryAvailableBenefitV2', () => json({ + result: { resultCode: '0', resultDesc: 'SUCCESS' }, + userAvailableBenefitList: [{ benefitNo: 'RHR077', benefitName: '一键成片VIP模板', benefitValue: '1', benefitUsed: '0' }], + })) + const p = await plugin() + const out = await p.auth.usage(async () => authOf(TICKET_A)) + expect(out.error).toContain('aitokens') + expect(out.windows).toEqual([]) +}) + +test('票被上游拒绝(授权)→ signIn expired', async () => { + f = fakeUpstream() + f.route('POST /isbo2/openApi/queryAvailableBenefitV2', () => json({ + result: { resultCode: '1', resultDesc: '授权失败' }, + })) + const p = await plugin() + const out = await p.auth.usage(async () => authOf(TICKET_A)) + expect(out.signIn).toBe('expired') + expect(out.windows).toEqual([]) +}) + +test('vip 明细挂了不连坐:池窗口照常,只是没有重置时间', async () => { + f = fakeUpstream() + f.route('POST /m4c/benefit/getAiTokenConsumptionRecords', () => new Response('boom', { status: 500 })) + const p = await plugin() + const out = await p.auth.usage(async () => authOf(TICKET_A, { vipCookie: 'mc_at=x; mc_bt=y' })) + expect(out.error).toBeUndefined() + expect(out.windows).toHaveLength(1) + expect(out.windows[0].resetsAt).toBeUndefined() +}) + +test('权威 endTime → resetsAt/startsAt/span,重置时间进 display', async () => { + f = fakeUpstream() + // 未来 10 天的北京时间墙钟(endTime 按 +08:00 解析,UTC 分量即北京墙钟) + const t = new Date(Date.now() + 10 * 86400e3 + 8 * 3600e3) + const pad = (n) => String(n).padStart(2, '0') + const endTimeText = `${t.getUTCFullYear()}-${pad(t.getUTCMonth() + 1)}-${pad(t.getUTCDate())} ${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad(t.getUTCSeconds())}` + f.route('POST /m4c/benefit/getAiTokenConsumptionRecords', () => json({ + resultCode: '0', + data: { aiTokenConsumptionRecordList: [{ recordTime: '2026-11-05 09:00:00', endTime: endTimeText, benefitNum: '123456', modelName: 'Qwen3.8-Flash', coefficient: '0.18', comments: '对话' }] }, + })) + const p = await plugin() + const out = await p.auth.usage(async () => authOf(TICKET_A, { vipCookie: 'mc_at=x; mc_bt=y' })) + const w = out.windows[0] + const expectedReset = _internal.endTimeMs(endTimeText) + expect(new Date(w.resetsAt).getTime()).toBe(expectedReset) + expect(new Date(w.startsAt).getTime()).toBe(_internal.cycleStartMs(expectedReset)) + expect(w.span).toBeGreaterThan(28 * 86400) + expect(w.span).toBeLessThan(32 * 86400) + expect(w.display).toContain('重置于') + expect(w.display).toContain('最近 2026-11-05 09:00:00') +}) + +test('明细里的 endTime 是上轮周期的(已过去)→ 不显示重置时间', async () => { + f = fakeUpstream() + f.route('POST /m4c/benefit/getAiTokenConsumptionRecords', () => json({ + resultCode: '0', + data: { aiTokenConsumptionRecordList: [{ recordTime: '2026-10-01 09:00:00', endTime: '2026-10-11 15:20:47', benefitNum: '1', modelName: 'x' }] }, + })) + const p = await plugin() + const out = await p.auth.usage(async () => authOf(TICKET_A, { vipCookie: 'mc_at=x; mc_bt=y' })) + expect(out.windows[0].resetsAt).toBeUndefined() + expect(out.windows[0].display).not.toContain('重置于') +}) + +// 未来 10 天的北京时间墙钟 → 明细接口的 endTime 文本 +const futureEndTime = () => { + const t = new Date(Date.now() + 10 * 86400e3 + 8 * 3600e3) + const pad = (n) => String(n).padStart(2, '0') + return `${t.getUTCFullYear()}-${pad(t.getUTCMonth() + 1)}-${pad(t.getUTCDate())} ${pad(t.getUTCHours())}:${pad(t.getUTCMinutes())}:${pad(t.getUTCSeconds())}` +} + +test('没配 vip Cookie:SSO 链自动换票,明细与重置时间全自动', async () => { + f = fakeUpstream() + const end = futureEndTime() + f.route('POST /m4c/benefit/getAiTokenConsumptionRecords', () => json({ + resultCode: '0', + data: { aiTokenConsumptionRecordList: [{ recordTime: '2026-11-05 09:00:00', endTime: end, benefitNum: '1000', modelName: 'Qwen3.8-Flash' }] }, + })) + const p = await plugin() + const out = await p.auth.usage(async () => authOf(TICKET_A)) // metadata 里没有 vipCookie + const paths = f.seen.map((r) => r.path) + expect(paths).toContain('/user/querySpecTokenV2') + expect(paths).toContain('/m4c/login/ssoLogin') + // 出票的渠道号必须是 001005(001003/001221 会被 USER_DOMAIN 拒) + const mint = f.seen.find((r) => r.path === '/user/querySpecTokenV2') + expect(mint.json.toSourceId).toBe('001005') + // 明细请求带上了全部 6 个 cookie,含 httpOnly 的 mc_at/mc_pat(curl jar 会漏) + const recordsReq = f.seen.find((r) => r.path === '/m4c/benefit/getAiTokenConsumptionRecords') + expect(recordsReq.headers.get('cookie')).toContain('mc_at=fake-at') + expect(recordsReq.headers.get('cookie')).toContain('mc_pat=fake-pat') + expect(recordsReq.headers.get('cookie')).toContain('mc_pac=fake-pac') + const w = out.windows[0] + expect(new Date(w.resetsAt).getTime()).toBe(_internal.endTimeMs(end)) + expect(w.display).toContain('重置于') +}) + +test('SSO 换票失败有冷却:两次 usage 只出一次票', async () => { + f = fakeUpstream() + f.route('POST /m4c/login/ssoLogin', () => json({ resultCode: '500400', resultDesc: '统一通信证临时票据验证失败' })) + const p = await plugin() + const out1 = await p.auth.usage(async () => authOf(TICKET_A)) + const out2 = await p.auth.usage(async () => authOf(TICKET_A)) + const mints = f.seen.filter((r) => r.path === '/user/querySpecTokenV2').length + expect(mints).toBe(1) + expect(out1.windows[0].resetsAt).toBeUndefined() + expect(out2.windows[0].resetsAt).toBeUndefined() + expect(out1.error).toBeUndefined() // 换票不成也不连坐池窗口 +}) + +test('配置的 vip Cookie 有效 → 不打换票链', async () => { + f = fakeUpstream() + const end = futureEndTime() + f.route('POST /m4c/benefit/getAiTokenConsumptionRecords', () => json({ + resultCode: '0', + data: { aiTokenConsumptionRecordList: [{ recordTime: '2026-11-05 09:00:00', endTime: end, benefitNum: '1000', modelName: 'x' }] }, + })) + const p = await plugin() + const out = await p.auth.usage(async () => authOf(TICKET_A, { vipCookie: 'mc_at=mine; mc_bt=mine' })) + expect(f.seen.map((r) => r.path)).not.toContain('/user/querySpecTokenV2') + expect(out.windows[0].resetsAt).toBeTruthy() +}) diff --git a/registry.json b/registry.json index 516f1b7..8ee3669 100644 --- a/registry.json +++ b/registry.json @@ -220,6 +220,8 @@ "summary": { "en": "Unofficial Tabbit (web.tabbit.com) provider: reuse the Tabbit Browser sign-in on this computer to serve its chat models, with the account's live catalog, cycle usage and the daily check-in. No browser automation: a turn is Tabbit's own room → run → event-stream calls. Client tool calls are not available (Tabbit's tools are its own).", "zh": "非官方 Tabbit(web.tabbit.com)插件:复用本机 Tabbit 浏览器的登录态接入它的聊天模型,含账号实时模型目录、周期用量与每日签到。不走浏览器自动化:一轮对话就是 Tabbit 自己的 建房间 → 发起 → 事件流。不支持客户端工具调用(Tabbit 的工具是它自己的)。" } }, { "package": "magpie-plugin-codar", "name": "Codar (科搭)", "icon": "https://codar.speedai.com/assets/codar-icon.png", "providers": ["codar"], "community": true, "summary": { "en": "Codar (科搭), SpeedAI's research desktop app: its 17 models (the auto router plus the DeepSeek, GLM, GPT and Claude families) over OpenAI Chat and Anthropic Messages, with the model list refreshed live from the vendor. Signs in by reading the desktop app's token file on this machine (read-only) or by pasting an access token; the daily check-in reports the claim and carries the next claim time; the card shows general and agent points and any running free-model activity.", "zh": "科搭(Codar,SpeedAI 出品的研究桌面应用):17 个模型(auto 路由 + DeepSeek、GLM、GPT、Claude 各系),走 OpenAI Chat 与 Anthropic Messages,模型列表从厂商实时刷新。登录可读取本机桌面端令牌(只读)或粘贴访问令牌;每日签到报告领取结果并带上下次可领时间;卡片显示通用与 Agent 点数及进行中的免费模型活动。" } }, - {"package": "@magpie-community/gateway-agentcompass", "name": "AgentCompass", "kind": "middleware", "community": true, "summary": {"en": "AgentCompass routing for Magpie: picks : from candidateModels by task intent, Model DNA and session continuity, orders pool seats by subscription quota, and optionally serves /v1/systemone for Routing Groups.", "zh": "AgentCompass 路由插件:按任务意图、模型能力与会话连续性从 candidateModels 选出 :,按订阅配额排号池席位,并可选作为路由组 /v1/systemone 分类器。"}, "icon": "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA2NCA2NCIgZmlsbD0ibm9uZSI+PGNpcmNsZSBjeD0iMzIiIGN5PSIzMiIgcj0iMjgiIHN0cm9rZT0iIzNCODJGNiIgc3Ryb2tlLXdpZHRoPSI0IiBmaWxsPSIjMEYxNzJBIi8+PGNpcmNsZSBjeD0iMzIiIGN5PSIzMiIgcj0iMjIiIHN0cm9rZT0iIzYwQTVGQSIgc3Ryb2tlLXdpZHRoPSIxLjUiIHN0cm9rZS1kYXNoYXJyYXk9IjMgMyIvPjxwb2x5Z29uIHBvaW50cz0iMzIsMTIgMzgsMzIgMzIsMjggMjYsMzIiIGZpbGw9IiNFRjQ0NDQiLz48cG9seWdvbiBwb2ludHM9IjMyLDUyIDM4LDMyIDMyLDM2IDI2LDMyIiBmaWxsPSIjRTJFOEYwIi8+PGNpcmNsZSBjeD0iMzIiIGN5PSIzMiIgcj0iMy41IiBmaWxsPSIjRjhGQUZDIi8+PC9zdmc+"} + {"package": "@magpie-community/gateway-agentcompass", "name": "AgentCompass", "kind": "middleware", "community": true, "summary": {"en": "AgentCompass routing for Magpie: picks : from candidateModels by task intent, Model DNA and session continuity, orders pool seats by subscription quota, and optionally serves /v1/systemone for Routing Groups.", "zh": "AgentCompass 路由插件:按任务意图、模型能力与会话连续性从 candidateModels 选出 :,按订阅配额排号池席位,并可选作为路由组 /v1/systemone 分类器。"}, "icon": "data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCA2NCA2NCIgZmlsbD0ibm9uZSI+PGNpcmNsZSBjeD0iMzIiIGN5PSIzMiIgcj0iMjgiIHN0cm9rZT0iIzNCODJGNiIgc3Ryb2tlLXdpZHRoPSI0IiBmaWxsPSIjMEYxNzJBIi8+PGNpcmNsZSBjeD0iMzIiIGN5PSIzMiIgcj0iMjIiIHN0cm9rZT0iIzYwQTVGQSIgc3Ryb2tlLXdpZHRoPSIxLjUiIHN0cm9rZS1kYXNoYXJyYXk9IjMgMyIvPjxwb2x5Z29uIHBvaW50cz0iMzIsMTIgMzgsMzIgMzIsMjggMjYsMzIiIGZpbGw9IiNFRjQ0NDQiLz48cG9seWdvbiBwb2ludHM9IjMyLDUyIDM4LDMyIDMyLDM2IDI2LDMyIiBmaWxsPSIjRTJFOEYwIi8+PGNpcmNsZSBjeD0iMzIiIGN5PSIzMiIgcj0iMy41IiBmaWxsPSIjRjhGQUZDIi8+PC9zdmc+"}, + { "package": "@magpie-community/opencode-mclaw-auth", "name": "MClaw", "icon": "https://yun.139.com/w/static/img/LOGO.png", "providers": ["mclaw"], "community": true, + "summary": { "en": "Unofficial MClaw provider: China Mobile Cloud's MClaw agent (ai.yun.139.com) with an OpenAI-compatible endpoint — the browser sign-in harvests the ticket by itself, auto-fetches the llm key and the token multipliers, serves the live model catalogue and the aitokens pool usage, and renews the ticket before it expires.", "zh": "非官方 MClaw 插件:中国移动云 MClaw 智能体(ai.yun.139.com),OpenAI 兼容接口——浏览器登录一次自动收票、自动取 llm key 与积分倍率,动态模型目录与 aitokens 池用量,凭证到期前自动续期。" } } ] }