catpaw: add the Meituan CatPaw plugin (#174)

Adds packages/catpaw (Meituan CatPaw): sign-in, paste-token sign-in, models, chat and usage. Hosts: ai.catpaw.meituan.com and catx.nocode.cn only; no dependencies or scripts; captures redacted.

Answers the 10-17 review: the request body's source/mode is CatPawCLI/CLI, matching the captured CLI round (testdata/captured-round.json, captured-turn.json) and enforced by the fake; the non-stream usage block that wasn't in the capture is gone; a no-credit error keeps the sign-in; the paste method returns a callback as the host calls it.

Run at 475979a (PR head 71f36ce with origin/main merged, loomy #175 included; registry.json conflict resolved keeping both entries), on mote with a sandbox HOME:
- bun test packages/catpaw: 24 pass, 0 fail
- bun scripts/check.mjs: exit 0 (catpaw ✓); bun test scripts: 3 pass, 0 fail
- Broken by hand, then restored: identity reverted to CatX/CATX_APP (8 fail), paste callback reverted (1 fail). The no-credit signIn:"kept" has no test (removing it stays green).

Not tried: a real CatPaw account. Not on npm yet: served from the dist branch until the first version is published by hand.
This commit is contained in:
lin2670
2026-10-29 21:12:00 +08:00
committed by GitHub
parent 6a9c528a5c
commit eeb344f174
9 changed files with 1430 additions and 0 deletions
+1
View File
@@ -11,6 +11,7 @@ subscription and makes its requests. The packages work in OpenCode and in
| Package | Signs in to | Provider id |
|---|---|---|
| [catpaw](packages/catpaw) | Meituan's 妙手 CatPaw (ai.catpaw.meituan.com), with a browser web sign-in or the desktop client's saved credentials | `catpaw` |
| [cline](packages/cline) | Cline (cline.bot): usage-billed models, ClinePass's and Cline's free ones, with Cline's device sign-in or an API key | `cline` |
| [codearts](packages/codearts) | Huawei Cloud CodeArts (码道) coding plans (Trial, personal and enterprise credits), with Huawei Cloud OAuth sign-in (unofficial) | `codearts` |
| [commandcode](packages/commandcode) | Command Code plans (Pro, GOAT, Max, Ultra, Go, Teams Pro) | `commandcode-plan` |
+54
View File
@@ -0,0 +1,54 @@
# @magpie-community/opencode-catpaw-auth
[OpenCode](https://opencode.ai) / [magpie](https://usemagpie.ai) provider 插件:**妙手(CatPaw,美团 `ai.catpaw.meituan.com`)**——登录、模型清单、聊天转发、余额查询。
请求形态按妙手桌面客户端 2026-10-09 的真实抓包移植(`round → event(running) → turn(SSE)` 简化链路,无跨请求会话复用):请求头、`permissionMode` 均为客户端原样取值,脱敏抓包存于 `testdata/captured-*.json`,测试逐键比对。
## 安装
```
magpie plugin add @magpie-community/opencode-catpaw-auth
magpie plugin login catpaw # 选「网页登录」/「妙手桌面端登录态」/「手动粘贴 token」
```
## 能力
- **登录**:
- `网页登录`:插件问 `login-config` 取官方登录页,浏览器完成登录后,插件按官方客户端同款 **poll-token 通道**每秒轮询 `?sid` 直接拿 token——服务端对服务端,无监听端口、不受浏览器私有网络检查(PNA)影响;再问一次 `current-user` 补 uid/昵称(失败不影响登录)。
- `妙手桌面端登录态`:每次请求前实时读 `~/.meituan-catpaw/auth.json`(mtime 缓存 5 分钟内;重开妙手即自动刷新)。
- `手动粘贴 token`。
- **无续期接口**:token 过期后 401,网页登录重新发起一次即可;桌面端登录态则在妙手里重新登录(下一请求自动读新 token)。
- **聊天**:`round → event → turn` 三步会话机;上游 SSE 帧为累积式,插件做差分转 OpenAI delta(`content` + `reasoning_content`),流式与非流式都支持。
- **模型**:妙手桌面端的 9 个模型(longcat-2.0 / glm-5.3 系列 / deepseek-v4 系列 / minimax-m3 / kimi-k3 / auto),静态表(无远程目录接口)。不声明各模型的上下文/输出窗口(客户端未公布,不编造数字),也不声明图片输入(见下)。
- **工具与图片**:会话协议只收一段扁平文本 prompt,工具定义、工具结果与图片都无法送达——带这些的请求以 **400 明确拒绝**(而不是悄悄丢掉后答错)。
- **余额(usage)**:`GET https://catx.nocode.cn/api/gateway/credit/balance`,鉴权头是 **`X-Auth-Token: <accessToken>`**。
- ⚠️ 这个接口与聊天网关**不是同一个鉴权头**:它只认 `X-Auth-Token`,把聊天用的 `Cookie: X-Passport-Token` 发到这里会稳定 401(body `code 4010`)。magpie 把 usage 的 401 当作「登录态失效」,所以鉴权头必须分开核对。
- 读成功后**不带 `signIn` 字段**:magpie 以此把「已退出登录」的标记撤掉。
- **无签到**:CatPaw 没有每日签到活动。
## 协议细节
- 请求头(客户端抓包原样):`m-appkey: com.sankuai.mcopilot.cli`、`m-debug: true`、`User-Agent: axios/1.19.0`、`m-traceid`/`x-request-id`/`x-trace-id` 每请求随机、`x-agent-version: 1.2.0-beta.6`、`Cookie: X-Passport-Token=...`(聊天网关 `ai.catpaw.meituan.com`);抓包里的 `m-host` 是客户端本机局域网 IP,插件不发这个头。
- 请求体(客户端抓包原样):`source: CatX`、`mode: CATX_APP`、`permissionMode: "unsafeBypassPermissions"`、`toolVersion: 2.0.2`。
- **注意**:上表是**聊天网关**的头;**余额接口**(`catx.nocode.cn`)改用 `X-Auth-Token`(见上)。
- turn SSE 总超时:15 分钟(带工具循环的长回答全程在推流,更短会把长回答掐断)。
## 环境变量(测试 / 镜像用)
| 变量 | 默认 |
|---|---|
| `CATPAW_AUTH_PATH` | `~/.meituan-catpaw/auth.json`(妙手桌面端登录态) |
| `CATPAW_BALANCE_URL` | `https://catx.nocode.cn/api/gateway/credit/balance`(余额接口,测试用) |
| `CATPAW_PASSPORT_BASE` | `https://catx.nocode.cn`(网页登录的 passport 域,测试用) |
## 测试
```
bun test packages/catpaw
```
测试打到本地假上游(`fake.mjs`),不触网、不使用真实 token。
## 许可
MIT。
+118
View File
@@ -0,0 +1,118 @@
// the fake 妙手 (CatPaw) upstream: the round/event/turn conversation machine
// on a local port, with cumulative SSE frames as the real gateway sends.
const json = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } })
export function fakeCatPaw() {
const state = {
token: "cat-token-1",
conversations: [],
rounds: 0,
events: 0,
turns: 0,
turnError: null, // "sse-error" makes the turn stream send an error frame
balanceCalls: 0,
// the web sign-in: sids awaiting their token, like the real vendor
webSids: new Map(), // sid -> token to hand out
webTokens: new Set(), // tokens poll-token has handed out (current-user accepts these)
pollCalls: 0,
currentUserCalls: 0,
reset() {
state.conversations = []
state.rounds = 0
state.events = 0
state.turns = 0
state.turnError = null
state.balanceCalls = 0
state.webSids = new Map()
state.webTokens = new Set()
state.pollCalls = 0
state.currentUserCalls = 0
},
}
const server = Bun.serve({
port: 0,
async fetch(req) {
const url = new URL(req.url)
// the credit balance lives on its own host in the real vendor and takes
// `X-Auth-Token`; the cookie the conversation gateway wants is refused
// here with the real body (401 / code 4010)
if (url.pathname === "/api/gateway/credit/balance") {
state.balanceCalls++
if (req.headers.get("x-auth-token") !== state.token && !state.webTokens?.has(req.headers.get("x-auth-token"))) return json(401, { code: 4010, message: "Authentication token is required", data: null, errorCode: null })
return json(200, {
code: 0,
message: "success",
data: { availableCredits: "1134.67", userPlan: { planId: "plan_free", planName: "体验版", pro: false, status: "active" } },
errorCode: null,
})
}
// the web sign-in: login-config → poll-token → current-user
// (no auth on any of them; poll-token hands the token once the sid
// was "claimed" by a browser login the fake cannot have, so tests
// arm it via state.webSids)
if (url.pathname === "/api/gateway/passport/login-config") {
return json(200, { code: 0, message: "success", data: { loginEntryUrl: `${url.origin}/passport/login-entry` }, errorCode: null })
}
if (url.pathname === "/api/gateway/passport/poll-token") {
state.pollCalls++
const sid = url.searchParams.get("sid") ?? ""
const issued = state.webSids.get(sid)
if (!issued) return json(200, { code: 0, data: null, errorCode: null })
state.webSids.delete(sid)
state.webTokens ??= new Set()
state.webTokens.add(issued)
return json(200, { code: 0, data: issued, errorCode: null })
}
if (url.pathname === "/api/gateway/passport/current-user") {
state.currentUserCalls++
if (req.headers.get("x-auth-token") !== state.token && !state.webTokens?.has(req.headers.get("x-auth-token")))
return json(401, { code: 401, message: "token refused", data: null, errorCode: null })
return json(200, { code: 0, message: "success", data: { userId: 42, userName: "网页用户" }, errorCode: null })
}
const token = (req.headers.get("cookie") ?? "").match(/X-Passport-Token=(.+)/)?.[1] ?? ""
// any valid login state passes: the desktop file's, and any token the
// web sign-in handed out (the real vendor accepts both alike)
if (token !== state.token && !state.webTokens?.has(token)) return json(401, { code: 401, msg: "token refused" })
if (req.headers.get("m-appkey") !== "com.sankuai.mcopilot.cli") return json(400, { code: 400, msg: "m-appkey missing" })
const body = await req.json().catch(() => ({}))
if (url.pathname === "/api/agent/conversation/round") {
state.rounds++
if (body.source !== "CatPawCLI" || body.mode !== "CLI") return json(400, { code: 400, msg: `source/mode wrong: ${body.source}/${body.mode}` })
state.conversations.push({ id: body.conversationId, modelType: body.modelType, prompt: body.message?.content?.[0]?.text ?? "", token: (req.headers.get("cookie") ?? "").match(/X-Passport-Token=([^;]+)/)?.[1] ?? "", permissionMode: body.permissionMode, source: body.source, mode: body.mode })
return json(200, { code: 0, data: { conversationId: body.conversationId } })
}
if (url.pathname === "/api/agent/conversation/event") {
state.events++
if (body.conversationId !== state.conversations.at(-1)?.id) return json(400, { code: 400, msg: "event for unknown conversation" })
return json(200, { code: 0 })
}
if (url.pathname === "/api/agent/conversation/turn") {
state.turns++
const conv = state.conversations.at(-1)
if (body.conversationId !== conv?.id) return json(400, { code: 400, msg: "turn for unknown conversation" })
if (state.turnError === "sse-error")
return new Response(`data: ${JSON.stringify({ error: { code: 500, message: "vendor broke" } })}\n\n`, { headers: { "content-type": "text/event-stream" } })
// cumulative frames: each carries the whole text so far (as the real gateway does)
const frames = [
{ message: { content: [{ type: "text", text: "你", reasoningContent: "思" }] } },
{ message: { content: [{ type: "text", text: "你好", reasoningContent: "思考" }] } },
{ message: { content: [{ type: "text", text: "你好,", reasoningContent: "思考" }] } },
{ message: { content: [{ type: "text", text: "你好,收到", reasoningContent: "思考" }] }, finished: true },
]
const sse = frames.map((f) => `data: ${JSON.stringify(f)}\n\n`).join("") + "data: [DONE]\n\n"
return new Response(sse, { headers: { "content-type": "text/event-stream" } })
}
return json(404, { code: 404, msg: "no such route" })
},
})
return { server, state, url: `http://127.0.0.1:${server.port}` }
}
+631
View File
@@ -0,0 +1,631 @@
// @magpie-community/opencode-catpaw-auth — the 妙手 (CatPaw, Meituan)
// provider plugin for OpenCode and magpie.
//
// Signs in with a browser web login or the CatPaw desktop client's saved
// credentials, then runs each chat completion through its conversation
// protocol: round → event(running) → turn(SSE). The SSE frames are
// cumulative, so each is diffed against the last to make OpenAI deltas.
// The request shapes are the desktop client's own, captured 2026-10-09
// (testdata/captured-*.json; the simplified chain was first verified in
// catpaw-proxy.mjs the same day); conversation reuse and tool continuation
// are phase 2.
const ID = "catpaw"
const NAME = "妙手 CatPaw"
const ORIGIN = "https://ai.catpaw.meituan.com"
// the credit balance endpoint. A different host *and* a different auth header
// from the conversation gateway: it takes `X-Auth-Token` and rejects
// `X-Passport-Token` / `Cookie` / `Authorization` with 401 code 4010 (see
// usage() — sending the cookie here marks the account signed out).
const balanceUrl = () => process.env.CATPAW_BALANCE_URL || "https://catx.nocode.cn/api/gateway/credit/balance"
// the passport domain the web sign-in runs on (login-config / poll-token /
// current-user, none of them authenticated; the vendor serves them from
// catx.nocode.cn while the conversation gateway is ai.catpaw.meituan.com)
const passportBase = () => process.env.CATPAW_PASSPORT_BASE || "https://catx.nocode.cn"
// how long a read of the desktop client's auth.json is trusted before being
// read again (the proxy's 5-minute cache)
const AUTH_TTL = 5 * 60_000
// ── the desktop client's model table (the proxy's MODEL_MAP, deduped) ──────
const MODELS = {
"longcat-2.0": { name: "LongCat-2.0 (限时免费)", type: 77, image: true },
"glm-5.3-flashx": { name: "GLM-5.3-FlashX", type: 98, image: true },
"glm-5.3-flash": { name: "GLM-5.3-Flash", type: 91, image: true },
"glm-5.3": { name: "GLM-5.3", type: 89, image: false },
"deepseek-v4-flash": { name: "DeepSeek-V4-Flash", type: 63, image: false },
"deepseek-v4-pro": { name: "DeepSeek-V4-Pro", type: 64, image: false },
"minimax-m3": { name: "MiniMax-M3", type: 70, image: true },
"kimi-k3": { name: "Kimi-K3", type: 83, image: true },
auto: { name: "Auto (自动选择)", type: 0, image: false },
}
const DEFAULT_MODEL_TYPE = 77
const modelTypeOf = (id) => MODELS[id]?.type ?? DEFAULT_MODEL_TYPE
// no modalities (the conversation prompt is text-only — see the 400s above)
// and no `limit` (the client publishes no per-model context or output
// window; an invented number would lie to the agent sizing its prompts)
const configModel = (id, m) => ({
name: m.name,
})
// ── small helpers ──────────────────────────────────────────────────────────
const errorResponse = (status, message) =>
new Response(JSON.stringify({ error: { message } }), { status, headers: { "content-type": "application/json" } })
async function bodyText(input, init) {
const b = init.body ?? (input instanceof Request ? await input.clone().text() : undefined)
return typeof b === "string" ? b : new TextDecoder().decode(b)
}
// ── credentials: the desktop client's file, read live ─────────────────────
const fs = await import("node:fs")
const os = await import("node:os")
const path = await import("node:path")
function authPath() {
return process.env.CATPAW_AUTH_PATH || path.join(os.homedir(), ".meituan-catpaw", "auth.json")
}
// readAuth reads the desktop client's auth.json — every time, so a re-login
// in 妙手 is picked up without restarting magpie. mtime-checked to skip
// re-reading an unchanged file.
let cachedAuth = null
let cachedAt = 0
function readAuth() {
const p = authPath()
let mtime = 0
try {
mtime = fs.statSync(p).mtimeMs
} catch {
throw new SignedOut(`未找到妙手登录态文件 ${p}:请安装并登录妙手桌面端,或改用"手动粘贴 token"登录`)
}
if (cachedAuth && cachedAt === mtime) return cachedAuth
const file = JSON.parse(fs.readFileSync(p, "utf8"))
const token = file?.auth?.accessToken
if (!token) throw new SignedOut(`妙手登录态文件里没有 accessToken(${p}):请在妙手桌面端重新登录`)
cachedAuth = { token, uid: String(file?.account?.uid ?? "") }
cachedAt = mtime
return cachedAuth
}
class SignedOut extends Error {}
const expired = (message) => Object.assign(new Error(message), { signIn: "expired" })
// the auth.json account name, for the sign-in's display
function authAccount() {
try {
return JSON.parse(fs.readFileSync(authPath(), "utf8"))?.account?.name || "妙手桌面端账号"
} catch {
return "妙手桌面端账号"
}
}
// ── the gateway ────────────────────────────────────────────────────────────
// gatewayHeaders is what every CatPaw request carries. Every value is what
// the official desktop client itself puts on the wire — captured 2026-10-09
// from the client talking to its own gateway (002…round.json / 004…turn.json
// in the capture set): the axios UA, m-debug: true, the m-appkey, the trace
// ids. The capture's m-host carried the client machine's LAN IP; that is not
// a value we can truthfully send from somewhere else, so the header is left
// off entirely rather than invented.
function gatewayHeaders(token, extra = {}) {
const traceId = crypto.randomUUID().replace(/-/g, "")
return {
"Content-Type": "application/json",
Cookie: `X-Passport-Token=${token}`,
"User-Agent": "axios/1.19.0",
"m-appkey": "com.sankuai.mcopilot.cli",
"m-debug": "true",
"m-traceid": traceId,
"x-request-id": crypto.randomUUID(),
"x-trace-id": traceId,
"x-agent-version": "1.2.0-beta.6",
...extra,
}
}
async function gatewayPost(pathname, body, token, extraHeaders, signal) {
const res = await fetch(ORIGIN + pathname, {
method: "POST",
headers: gatewayHeaders(token, extraHeaders),
body: JSON.stringify(body),
signal: signal ?? AbortSignal.timeout(30_000),
})
const text = await res.text()
return { status: res.status, text }
}
// buildPrompt flattens the messages into the one text the conversation
// protocol carries (the proxy's buildPrompt)
function buildPrompt(messages) {
const parts = []
for (const msg of messages) {
const role = msg.role || "user"
const content =
typeof msg.content === "string"
? msg.content
: Array.isArray(msg.content)
? msg.content.map((c) => c.text || "").join("")
: ""
if (role === "system") parts.push(`[System Instructions]\n${content}`)
else if (role === "user") parts.push(`[User]\n${content}`)
else if (role === "assistant") parts.push(`[Assistant]\n${content}`)
}
if (messages.length === 1 && messages[0].role === "user") {
const m = messages[0]
return typeof m.content === "string"
? m.content
: Array.isArray(m.content)
? m.content.map((c) => c.text || "").join("")
: ""
}
return parts.join("\n\n")
}
// runConversation: round → event(running) → turn(SSE), yielding OpenAI-shaped
// deltas from the cumulative frames (the proxy's catpawComplete, as a stream)
async function* runConversation(token, chat, signal) {
const modelType = modelTypeOf(chat.model)
const convId = crypto.randomUUID()
const msgId = crypto.randomUUID()
const turnId = crypto.randomUUID()
const prompt = buildPrompt(chat.messages ?? [])
// ① round: create the conversation
const r1 = await gatewayPost(
"/api/agent/conversation/round",
{
conversationId: convId,
message: { type: "user", messageId: msgId, content: [{ type: "text", text: prompt }], finished: true },
modelType,
// the client's own round body (testdata/captured-round.json): CLI
// identity end to end — these source/mode values ride the same
// captured request as the CLI headers gatewayHeaders sends
source: "CatPawCLI",
mode: "CLI",
// the client's own round/turn bodies carry this exact value (captured
// 2026-10-09, both requests) — the client's default, not ours
permissionMode: "unsafeBypassPermissions",
toolVersion: "2.0.2",
repositories: [],
},
token,
{ "m-spanid": "0.2", "m-spanname": "conversation.round" },
signal,
)
const r1j = JSON.parse(r1.text || "{}")
if (r1.status !== 200 || r1j.code !== 0)
throw new Error(`妙手 round 失败:HTTP ${r1.status} code=${r1j.code ?? "?"} msg=${r1j.msg ?? r1j.message ?? ""}`)
// ② event: mark the conversation as running
const r2 = await gatewayPost(
"/api/agent/conversation/event",
{ conversationId: convId, eventType: "conversation", data: { status: "running" } },
token,
{ "m-spanid": "0.3", "m-spanname": "conversation.event" },
signal,
)
if (r2.status !== 200) throw new Error(`妙手 event 失败:HTTP ${r2.status}`)
// ③ turn: the SSE answer. Every frame's content is the whole text so far,
// so each is diffed against the last; the reply is yielded as deltas.
const turnBody = JSON.stringify({
conversationId: convId,
turnRequestId: turnId,
message: { type: "user", messageId: msgId, content: [{ type: "text", text: prompt }], finished: true },
modelType,
// the client's own turn body (testdata/captured-turn.json): CLI identity
source: "CatPawCLI",
mode: "CLI",
// the client's own round/turn bodies carry this exact value (captured
// 2026-10-09, both requests) — the client's default, not ours
permissionMode: "unsafeBypassPermissions",
toolConfigs: [],
toolVersion: "2.0.2",
})
const res = await fetch(ORIGIN + "/api/agent/conversation/turn", {
method: "POST",
headers: gatewayHeaders(token, {
Accept: "text/event-stream",
enableheartbeat: "true",
"m-spanid": "0.4.1",
"m-spanname": "conversation.turn",
}),
body: turnBody,
// a total timeout over the whole response, as the reference's
// SSE_TIMEOUT_MS = 15min: long tool-loop answers stream the whole time,
// a shorter cap would cut them off mid-answer
signal: signal ?? AbortSignal.timeout(15 * 60e3),
})
if (res.status !== 200) throw new Error(`妙手 turn 失败:HTTP ${res.status} ${(await res.text().catch(() => "")).slice(0, 500)}`)
if (!res.body) throw new Error("妙手 turn 返回了空流")
const decoder = new TextDecoder()
const reader = res.body.getReader()
let buffered = ""
let prevText = ""
let prevReasoning = ""
let finalText = ""
let finalReasoning = ""
let frameCount = 0
for (;;) {
const { done, value } = await reader.read()
if (done) break
buffered += decoder.decode(value, { stream: true })
const lines = buffered.split("\n")
buffered = lines.pop() ?? ""
for (const line of lines) {
if (!line.startsWith("data:")) continue
const data = line.slice(5).trim()
if (data === "[DONE]") {
yield { done: true, text: finalText, reasoning: finalReasoning }
return
}
let frame
try {
frame = JSON.parse(data)
} catch {
continue
}
frameCount++
if (frame.error) throw new Error(`妙手 SSE 错误:code=${frame.error.code} msg=${frame.error.message || ""}`)
const msg = frame.message
if (!msg || !Array.isArray(msg.content)) continue
for (const c of msg.content) {
if (c.type !== "text") continue
const curText = c.text || ""
if (curText.length > prevText.length) {
yield { delta: curText.slice(prevText.length) }
prevText = curText
}
finalText = curText
const curReasoning = c.reasoningContent || ""
if (curReasoning.length > prevReasoning.length) {
yield { reasoningDelta: curReasoning.slice(prevReasoning.length) }
prevReasoning = curReasoning
}
finalReasoning = curReasoning
}
}
}
// the stream ended without [DONE]
if (finalText === "" && frameCount === 0) throw new Error("妙手 SSE 流结束但没有任何帧")
yield { done: true, text: finalText, reasoning: finalReasoning }
}
// ── the plugin ─────────────────────────────────────────────────────────────
export async function CatPawAuthPlugin({ client } = {}) {
return {
auth: {
provider: ID,
// CatPaw has no refresh: the sign-in lives in the desktop client's
// auth.json and is re-read before every request (mtime-checked), so
// an "expiry" is just the next read finding a new file
async loader(getAuth) {
const a = await getAuth()
return {
baseURL: ORIGIN,
apiKey: "catpaw",
async fetch(input, init = {}) {
const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url
if (!/\/chat\/completions$/.test(new URL(url).pathname))
return errorResponse(404, "only chat completions are served")
const raw = await bodyText(input, init)
let chat
try {
chat = JSON.parse(raw)
} catch {
return errorResponse(400, "a request that isn't JSON")
}
if (!Array.isArray(chat.messages) || chat.messages.length === 0)
return errorResponse(400, "messages is required")
if (!(chat.model in MODELS) && String(chat.model).trim() !== "")
return errorResponse(400, `unknown model "${chat.model}" (known: ${Object.keys(MODELS).join(", ")})`)
// the flattened one-text prompt the conversation protocol carries
// has no room for tool schemas, tool results or image parts: a
// request carrying any of them would get an answer that never
// calls a tool and never sees the image, with nothing saying why
// — refuse it instead (tool continuation is a later phase)
if (Array.isArray(chat.tools) && chat.tools.length > 0)
return errorResponse(400, "this provider cannot run tools: the conversation protocol takes one flattened text prompt, so tool definitions would be silently dropped (refused rather than answered wrongly)")
if (chat.messages.some((m) => m.role === "tool" || (Array.isArray(m.content) && m.content.some((c) => c?.type === "tool_call" || c?.type === "tool_use" || c?.type === "tool_result"))))
return errorResponse(400, "this provider cannot continue a tool call: the conversation protocol takes one flattened text prompt, so tool results would be silently dropped (refused rather than answered wrongly)")
// image_url is what @ai-sdk/openai-compatible actually sends
// ({"type":"image_url","image_url":{…}}); input_image is the
// responses-API shape some clients carry over
if (chat.messages.some((m) => Array.isArray(m.content) && m.content.some((c) => c?.type === "image" || c?.type === "image_url" || c?.type === "input_image" || (typeof c?.text === "string" && c.text.startsWith("data:image/")))))
return errorResponse(400, "this provider cannot take images through the text-only conversation prompt (refused rather than silently dropped)")
// the token: only the desktop method's credentials live in the
// client's auth.json — a web sign-in or a paste carries its own
// token in the account record, and a request made in account A's
// name must never be spent on whatever account the desktop app
// happens to hold
let token
let accountName
const a = await getAuth()
if (a?.type === "oauth" && a.access && a.source !== "desktop") {
token = a.access
accountName = a.name || a.accountId || (a.source === "web" ? "妙手网页登录" : "手动粘贴")
} else {
try {
const file = readAuth()
token = file.token
accountName = authAccount()
} catch (e) {
return errorResponse(e instanceof SignedOut ? 401 : 502, String(e?.message ?? e))
}
}
if (!token) return errorResponse(401, "妙手登录态缺失:请登录妙手桌面端或手动粘贴 token")
// the answer as an OpenAI Response, streaming or not
const model = chat.model || "longcat-2.0"
const id = `chatcmpl-${crypto.randomUUID().replace(/-/g, "").slice(0, 24)}`
const created = Math.floor(Date.now() / 1000)
if (chat.stream) {
const encoder = new TextEncoder()
const chunk = (delta, finish, reasoningDelta) => {
const choices = [{ index: 0, delta: {}, finish_reason: finish ?? null }]
if (delta) choices[0].delta.content = delta
if (reasoningDelta) choices[0].delta.reasoning_content = reasoningDelta
return encoder.encode(
`data: ${JSON.stringify({ id, object: "chat.completion.chunk", created, model, choices })}\n\n`,
)
}
const stream = new ReadableStream({
async start(controller) {
controller.enqueue(chunk(null, null)) // the role frame
try {
for await (const ev of runConversation(token, chat, init.signal)) {
if (ev.delta) controller.enqueue(chunk(ev.delta, null))
if (ev.reasoningDelta) controller.enqueue(chunk(null, null, ev.reasoningDelta))
if (ev.done) {
controller.enqueue(chunk(null, "stop"))
controller.enqueue(encoder.encode("data: [DONE]\n\n"))
}
}
} catch (e) {
controller.enqueue(
encoder.encode(`data: ${JSON.stringify({ error: { message: String(e?.message ?? e) } })}\n\n`),
)
controller.enqueue(encoder.encode("data: [DONE]\n\n"))
}
controller.close()
},
})
return new Response(stream, { status: 200, headers: { "content-type": "text/event-stream" } })
}
let text = ""
let reasoning = ""
try {
for await (const ev of runConversation(token, chat, init.signal)) {
if (ev.done) {
text = ev.text
reasoning = ev.reasoning
}
}
} catch (e) {
return errorResponse(e?.message?.includes("401") ? 401 : 502, String(e?.message ?? e))
}
return new Response(
JSON.stringify({
id,
object: "chat.completion",
created,
model,
choices: [{ index: 0, message: { role: "assistant", content: text, ...(reasoning ? { reasoning_content: reasoning } : {}) }, finish_reason: "stop" }],
// no usage block: the conversation protocol returns no token
// counts, and zeros would read as real ones
}),
{ status: 200, headers: { "content-type": "application/json" } },
)
},
}
},
// the credit balance the desktop client's own gateway API serves.
//
// ⚠️ This endpoint's auth header is `X-Auth-Token`, **not** the
// conversation gateway's `Cookie: X-Passport-Token` — the same
// accessToken either way, but the cookie here answers 401 code 4010
// ("Authentication token is required"). Getting that wrong is not a
// cosmetic bug: a 401 from usage is how magpie learns an account's
// sign-in is gone, so the wrong header marks a live account as signed
// out on its card (`lapsed` in logins.json).
async usage(getAuth) {
const a = await getAuth()
let token
// same split as the loader: only the desktop method reads the
// client's auth.json; every stored account spends its own token
if (a?.type === "oauth" && a.access && a.source !== "desktop") token = a.access
else {
try {
token = readAuth().token
} catch (e) {
return { error: String(e?.message ?? e), signIn: "kept" }
}
}
let res
try {
res = await fetch(balanceUrl(), {
headers: {
Accept: "application/json",
"X-Auth-Token": token,
// the client's own marker; not required, but its real shape
"gray-set": "new-agent-sdk",
},
signal: AbortSignal.timeout(20_000),
})
} catch (e) {
return { error: String(e?.message ?? e), signIn: "kept" }
}
const payload = await res.json().catch(() => null)
const code = typeof payload?.code === "number" ? payload.code : null
// two credential paths: HTTP 401, and the body's 4010 (no token) /
// 4011 (token refused)
if (res.status === 401 || code === 4010 || code === 4011)
return { error: "妙手登录态已过期,请在妙手桌面端重新登录", signIn: "expired" }
if (!res.ok) return { error: `妙手余额查询返回 HTTP ${res.status}`, signIn: "kept" }
if (!payload) return { error: "妙手余额响应无法解析", signIn: "kept" }
if (code !== 0) return { error: `妙手余额查询返回异常 code=${code ?? "null"}`, signIn: "kept" }
const data = payload.data
if (!data || typeof data !== "object") return { error: "妙手余额响应缺少 data", signIn: "kept" }
const credit = data.availableCredits ?? data.credit ?? data.balance ?? data.available
const plan = data.userPlan ?? {}
if (credit == null) return { error: `余额接口没有返回积分数额(${JSON.stringify(data).slice(0, 120)})`, signIn: "kept" }
// no `signIn` on a clean read: magpie reads that as "the sign-in is
// fine" and takes the expired mark back off the account. Saying
// "kept" here instead would leave a lapse — this read's or an
// earlier transient 401's — on the card until a manual re-login.
return {
plan: plan.planName || (plan.pro ? "妙手 CatPaw Pro" : NAME),
user: a?.type === "oauth" && a.source !== "desktop" ? a.name || a.accountId || "妙手网页登录" : authAccount(),
windows: [{ name: "可用积分", used: 0, display: `${credit} credit`, aside: true }],
}
},
// CatPaw has no check-in (confirmed: no such activity in its client)
methods: [
{
type: "oauth",
label: "网页登录(妙手官方授权页,Web sign-in)",
authorize: async () => {
// the vendor's own two-channel web login, the poll channel only:
// login-config names the entry URL, the browser login claims the
// sid, and GET poll-token?sid hands the token straight to us —
// server-to-server, no loopback listener, immune to the browser's
// private-network check that breaks the vendor's own POST channel
// (agent2api login/catpaw.rs, the official client's Promise.race)
const state = crypto.randomUUID().replace(/-/g, "")
const sid = crypto.randomUUID().replace(/-/g, "")
let entry
try {
const res = await fetch(`${passportBase()}/api/gateway/passport/login-config`, {
headers: { Accept: "application/json" },
signal: AbortSignal.timeout(10_000),
})
const payload = await res.json().catch(() => null)
entry = payload?.data?.loginEntryUrl
} catch (e) {
return { type: "failed", error: `无法连接妙手登录服务: ${e?.message ?? e}` }
}
if (!entry) return { type: "failed", error: "妙手登录服务未返回登录入口地址" }
const url = new URL(entry)
url.searchParams.set("state", state)
url.searchParams.set("sid", sid)
url.searchParams.set("redirect", `http://127.0.0.1:9/catpaw-callback`)
return {
url: url.href,
instructions:
"浏览器打开上面的妙手登录页并完成登录。登录成功后本插件会自动拿到登录态(约几秒),无需手动输入任何东西;若长时间停在完成页,请回到 magpie 重试一次。",
method: "auto",
callback: async () => {
// poll-token every second until the browser login claims the
// sid (data: null = not yet), 3 minutes overall like agent2api
const deadline = Date.now() + 180_000
let token
while (Date.now() < deadline) {
await new Promise((r) => setTimeout(r, 1000))
try {
const res = await fetch(`${passportBase()}/api/gateway/passport/poll-token?sid=${sid}`, {
headers: { Accept: "application/json" },
signal: AbortSignal.timeout(5_000),
})
const payload = await res.json().catch(() => null)
const t = typeof payload?.data === "string" ? payload.data.trim() : ""
if (t) {
token = t
break
}
} catch {
// a single failed poll is skipped, like the vendor's client
}
}
if (!token) return { type: "failed", error: "网页登录超时(3 分钟内未取到登录态),请重试" }
// current-user fills uid/name; failing it does not fail the
// sign-in (the token itself is already in hand)
let accountId = "妙手网页登录"
let uid = ""
try {
const res = await fetch(`${passportBase()}/api/gateway/passport/current-user`, {
headers: { Accept: "application/json", "X-Auth-Token": token },
signal: AbortSignal.timeout(10_000),
})
const payload = await res.json().catch(() => null)
const data = payload?.data
if (data) {
uid = String(data.userId ?? "") === "null" ? "" : String(data.userId ?? "")
if (data.userName) accountId = data.userName
}
} catch {}
return { type: "success", refresh: "", access: token, expires: 0, accountId, ...(uid ? { uid } : {}), source: "web" }
},
}
},
},
{
type: "oauth",
label: "妙手桌面端登录态(CatPaw desktop sign-in)",
authorize: () => ({
url: "",
instructions: "使用本机妙手桌面端已保存的登录态(每次请求前实时读取,重开妙手即自动刷新)。",
method: "auto",
callback: async () => {
try {
const auth = readAuth()
// refresh is present-but-empty: magpie's host only keeps a
// sign-in whose result has a refresh field, and CatPaw has
// no refresh to give (the token lives in the desktop file)
return { type: "success", refresh: "", access: auth.token, expires: 0, accountId: authAccount(), uid: auth.uid, source: "desktop" }
} catch (e) {
return { type: "failed", error: String(e?.message ?? e) }
}
},
}),
},
{
type: "oauth",
label: "手动粘贴 token(Paste token)",
prompts: [{ type: "text", key: "token", message: "accessToken(X-Passport-Token 的值)", validate: (v) => (v && v.trim() ? undefined : "必填") }],
// an oauth authorize() hands back {url, method, instructions,
// callback} and the host finishes the sign-in by calling
// callback() — returning the account directly leaves the host
// waiting on a callback that doesn't exist
authorize: async (inputs) => {
const token = String(inputs?.token ?? "").trim()
if (!token) return { type: "failed", error: "token 必填" }
return {
url: "",
instructions: "已取到粘贴的 token,确认即完成登录。",
method: "auto",
callback: async () => ({ type: "success", refresh: "", access: token, expires: 0, accountId: "手动粘贴", source: "manual" }),
}
},
},
],
},
async config(config) {
config.provider ??= {}
const was = config.provider[ID] ?? {}
config.provider[ID] = {
name: NAME,
npm: "@ai-sdk/openai-compatible",
api: ORIGIN,
...was,
models: { ...Object.fromEntries(Object.entries(MODELS).map(([id, m]) => [id, configModel(id, m)])), ...(was.models ?? {}) },
}
},
}
}
// for tests
export const _internal = { ID, NAME, MODELS, modelTypeOf, buildPrompt, gatewayHeaders, gatewayHeadersForTest: gatewayHeaders, readAuth, authPath, configModel }
+420
View File
@@ -0,0 +1,420 @@
import { describe, test, expect, beforeAll, afterAll, beforeEach } from "bun:test"
import { mkdirSync, rmSync, writeFileSync, mkdtempSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { readFileSync } from "node:fs"
import { CatPawAuthPlugin, _internal } from "./index.mjs"
import { fakeCatPaw } from "./fake.mjs"
import capturedRound from "./testdata/captured-round.json"
import capturedTurn from "./testdata/captured-turn.json"
// every test runs against the fake upstream in fake.mjs: no network, no real
// token ever leaves this process. The upstream base is monkey-patched because
// CatPaw's is a module constant (the origin is fixed by the vendor).
let fake
let plugin
let saved = {}
let tmpDir
const client = { auth: { set: async ({ body }) => (saved = body) } }
const getAuth = async () => saved
beforeAll(async () => {
fake = fakeCatPaw()
tmpDir = mkdtempSync(join(tmpdir(), "catpaw-auth-test-"))
// point the desktop auth path at a fake auth.json
const authPath = join(tmpDir, "auth.json")
writeFileSync(authPath, JSON.stringify({ auth: { accessToken: fake.state.token }, account: { uid: "u1", name: "Tester" } }))
process.env.CATPAW_AUTH_PATH = authPath
// the credit balance is a separate host in the vendor; point it at the fake
process.env.CATPAW_BALANCE_URL = `${fake.url}/api/gateway/credit/balance`
// replace the origin with the fake server
// the plugin reads ORIGIN at call time only inside gatewayHeaders/fetch, so
// monkey-patching the global fetch to route to the fake works: we swap the
// global fetch for one that rewrites the URL host to the fake server
const realFetch = globalThis.fetch
globalThis.fetch = (input, init) => {
const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url
const patched = url.replace("https://ai.catpaw.meituan.com", fake.url).replace("https://catx.nocode.cn", fake.url)
return realFetch(patched, init)
}
plugin = await CatPawAuthPlugin({ client })
})
afterAll(() => {
fake.server.stop(true)
rmSync(tmpDir, { recursive: true, force: true })
})
beforeEach(() => {
fake.state.reset()
saved = { type: "oauth", access: fake.state.token, expires: 0, source: "desktop", accountId: "Tester" }
})
describe("config", () => {
test("lists the desktop client's models", async () => {
const cfg = {}
await plugin.config(cfg)
expect(cfg.provider.catpaw.name).toBe("妙手 CatPaw")
const ids = Object.keys(cfg.provider.catpaw.models)
expect(ids).toContain("longcat-2.0")
expect(ids).toContain("kimi-k3")
expect(ids).toContain("glm-5.3-flash")
// no modalities and no invented limit: the text-only conversation prompt
// takes no images, and the client publishes no per-model windows
expect(cfg.provider.catpaw.models["longcat-2.0"].modalities).toBeUndefined()
expect(cfg.provider.catpaw.models["longcat-2.0"].limit).toBeUndefined()
})
})
describe("sign-in methods", () => {
test("reads the desktop client's auth.json live", async () => {
const method = plugin.auth.methods.find((m) => m.label.includes("桌面端"))
expect(method).toBeTruthy()
const flow = method.authorize()
expect(flow.method).toBe("auto")
const result = await flow.callback()
expect(result.type).toBe("success")
expect(result.access).toBe(fake.state.token)
expect(result.source).toBe("desktop")
expect(result.uid).toBe("u1")
})
test("manual paste works through the host's authorize → callback contract", async () => {
const method = plugin.auth.methods.find((m) => m.label.includes("Paste"))
const flow = await method.authorize({ token: "pasted-token" })
expect(flow.method).toBe("auto")
expect(typeof flow.callback).toBe("function")
const result = await flow.callback()
expect(result.type).toBe("success")
expect(result.access).toBe("pasted-token")
expect(await method.authorize({ token: "" })).toMatchObject({ type: "failed" })
})
test("web sign-in: login-config names the entry, poll-token hands the token once claimed", async () => {
const method = plugin.auth.methods.find((m) => m.label.includes("Web sign-in"))
expect(method).toBeTruthy()
const flow = await method.authorize()
expect(flow.method).toBe("auto")
expect(flow.url).toContain("state=")
expect(flow.url).toContain("sid=")
expect(flow.url).toContain("redirect=")
// the sid is not claimed yet: arm it one poll in (the callback polls
// every second, so the token appears on its second pass)
const sid = new URL(flow.url).searchParams.get("sid")
const cb = flow.callback()
await new Promise((r) => setTimeout(r, 1200))
fake.state.webSids.set(sid, "web-cat-token")
const result = await cb
expect(result.type).toBe("success")
expect(result.access).toBe("web-cat-token")
expect(result.source).toBe("web")
expect(result.accountId).toBe("网页用户")
expect(result.uid).toBe("42")
expect(fake.state.pollCalls).toBeGreaterThanOrEqual(2)
expect(fake.state.currentUserCalls).toBe(1)
})
})
describe("chat", () => {
test("round → event → turn, cumulative frames diffed to deltas", async () => {
const loader = await plugin.auth.loader(getAuth)
const res = await loader.fetch("https://ai.catpaw.meituan.com/v1/chat/completions", {
method: "POST",
body: JSON.stringify({ model: "longcat-2.0", stream: true, messages: [{ role: "user", content: "hi" }] }),
})
expect(res.status).toBe(200)
const text = await res.text()
// the deltas build up the answer
expect(text).toContain('"content":"你"')
expect(text).toContain('"content":"好"')
expect(text).toContain('"content":","')
expect(text).toContain('"content":"收到"')
// reasoning is diffed too
expect(text).toContain('"reasoning_content":"思"')
expect(text).toContain('"reasoning_content":"考"')
// the stream ends with stop + [DONE]
expect(text).toContain('"finish_reason":"stop"')
expect(text).toContain("data: [DONE]")
// the conversation machine ran all three steps in order
expect(fake.state.rounds).toBe(1)
expect(fake.state.events).toBe(1)
expect(fake.state.turns).toBe(1)
expect(fake.state.conversations[0].prompt).toBe("hi")
expect(fake.state.conversations[0].modelType).toBe(77)
})
test("non-stream returns the full answer", async () => {
const loader = await plugin.auth.loader(getAuth)
const res = await loader.fetch("https://ai.catpaw.meituan.com/v1/chat/completions", {
method: "POST",
body: JSON.stringify({ model: "kimi-k3", stream: false, messages: [{ role: "user", content: "hi" }] }),
})
const answer = await res.json()
expect(answer.model).toBe("kimi-k3")
expect(answer.choices[0].message.content).toBe("你好,收到")
expect(answer.choices[0].message.reasoning_content).toBe("思考")
expect(answer.choices[0].finish_reason).toBe("stop")
expect(fake.state.conversations[0].modelType).toBe(83)
})
test("multi-turn messages flatten into one prompt", async () => {
const loader = await plugin.auth.loader(getAuth)
await loader.fetch("https://ai.catpaw.meituan.com/v1/chat/completions", {
method: "POST",
body: JSON.stringify({
model: "longcat-2.0",
stream: false,
messages: [
{ role: "system", content: "be terse" },
{ role: "user", content: "q1" },
{ role: "assistant", content: "a1" },
{ role: "user", content: "q2" },
],
}),
})
expect(fake.state.conversations[0].prompt).toContain("[System Instructions]\nbe terse")
expect(fake.state.conversations[0].prompt).toContain("[User]\nq1")
expect(fake.state.conversations[0].prompt).toContain("[Assistant]\na1")
expect(fake.state.conversations[0].prompt).toContain("[User]\nq2")
})
test("a single user message passes as-is", async () => {
const loader = await plugin.auth.loader(getAuth)
await loader.fetch("https://ai.catpaw.meituan.com/v1/chat/completions", {
method: "POST",
body: JSON.stringify({ model: "auto", stream: false, messages: [{ role: "user", content: "just this" }] }),
})
expect(fake.state.conversations[0].prompt).toBe("just this")
expect(fake.state.conversations[0].modelType).toBe(0)
})
test("an SSE error frame surfaces as an error chunk", async () => {
fake.state.turnError = "sse-error"
const loader = await plugin.auth.loader(getAuth)
const res = await loader.fetch("https://ai.catpaw.meituan.com/v1/chat/completions", {
method: "POST",
body: JSON.stringify({ model: "longcat-2.0", stream: true, messages: [{ role: "user", content: "hi" }] }),
})
const text = await res.text()
expect(text).toContain('"error"')
expect(text).toContain("vendor broke")
})
test("a request carrying tools is refused with a clear 400", async () => {
const loader = await plugin.auth.loader(getAuth)
const res = await loader.fetch(`${fake.url}/api/agent/chat/completions`, {
method: "POST",
body: JSON.stringify({ model: "longcat-2.0", messages: [{ role: "user", content: "hi" }], tools: [{ type: "function", function: { name: "f" } }] }),
})
expect(res.status).toBe(400)
const body = await res.json()
expect(body.error.message).toContain("cannot run tools")
})
test("a request carrying tool results is refused, images are refused", async () => {
const loader = await plugin.auth.loader(getAuth)
const toolRes = await loader.fetch(`${fake.url}/api/agent/chat/completions`, {
method: "POST",
body: JSON.stringify({ model: "longcat-2.0", messages: [{ role: "user", content: "hi" }, { role: "tool", content: "result" }] }),
})
expect(toolRes.status).toBe(400)
expect((await toolRes.json()).error.message).toContain("cannot continue a tool call")
const imgRes = await loader.fetch(`${fake.url}/api/agent/chat/completions`, {
method: "POST",
body: JSON.stringify({ model: "longcat-2.0", messages: [{ role: "user", content: [{ type: "image", image_url: { url: "data:image/png;base64,AAAA" } }] }] }),
})
expect(imgRes.status).toBe(400)
expect((await imgRes.json()).error.message).toContain("cannot take images")
})
test("the OpenAI image shapes (image_url, input_image) are refused too", async () => {
const loader = await plugin.auth.loader(getAuth)
for (const type of ["image_url", "input_image"]) {
const res = await loader.fetch(`${fake.url}/api/agent/chat/completions`, {
method: "POST",
body: JSON.stringify({
model: "longcat-2.0",
messages: [{ role: "user", content: [{ type: "text", text: "看这张图" }, { type, image_url: { url: "https://example.com/x.png" } }] }],
}),
})
expect(res.status).toBe(400)
expect((await res.json()).error.message).toContain("cannot take images")
}
})
test("unknown model is rejected", async () => {
const loader = await plugin.auth.loader(getAuth)
const res = await loader.fetch("https://ai.catpaw.meituan.com/v1/chat/completions", {
method: "POST",
body: JSON.stringify({ model: "not-a-model", stream: false, messages: [{ role: "user", content: "hi" }] }),
})
expect(res.status).toBe(400)
})
test("a web sign-in spends its own token, without any auth.json on the machine", async () => {
// the desktop file moves away entirely: the web sign-in must not need it
const was = process.env.CATPAW_AUTH_PATH
process.env.CATPAW_AUTH_PATH = join(tmpDir, "absent-web-test.json")
// sign in through the web flow itself: the sid is claimed, poll-token
// hands out its token, and that account is what chats
const webMethod = plugin.auth.methods.find((m) => m.label.includes("Web sign-in"))
const flow = await webMethod.authorize()
const sid = new URL(flow.url).searchParams.get("sid")
fake.state.webSids.set(sid, "web-tok-1")
const signedIn = await flow.callback()
expect(signedIn.type).toBe("success")
saved = { type: "oauth", access: signedIn.access, refresh: "", expires: 0, accountId: signedIn.accountId, name: signedIn.accountId, source: "web" }
try {
const loader = await plugin.auth.loader(getAuth)
const res = await loader.fetch("https://ai.catpaw.meituan.com/v1/chat/completions", {
method: "POST",
body: JSON.stringify({ model: "longcat-2.0", stream: false, messages: [{ role: "user", content: "hi" }] }),
})
expect(res.status).toBe(200)
// the request went out under the web account's token, not the
// desktop file's, and the card shows the web account's name
expect(fake.state.conversations[0].token).toBe("web-tok-1")
// the conversation body fields are the client's captured protocol
expect(fake.state.conversations[0].permissionMode).toBe(capturedRound.bodyProtocol.permissionMode)
const usage = await plugin.auth.usage(getAuth)
expect(usage.error).toBeUndefined()
expect(usage.user).toBe("网页用户")
expect(usage.windows[0].display).toContain("credit")
} finally {
process.env.CATPAW_AUTH_PATH = was
}
})
test("the desktop account and a web account never cross: A's request is not spent on B", async () => {
// the desktop file holds the fake's own token; account A signed in on
// the web with a different one — A's chat must carry A's token
const webMethod = plugin.auth.methods.find((m) => m.label.includes("Web sign-in"))
const flow = await webMethod.authorize()
const sid = new URL(flow.url).searchParams.get("sid")
fake.state.webSids.set(sid, "acct-A-token")
const signedIn = await flow.callback()
expect(signedIn.type).toBe("success")
saved = { type: "oauth", access: signedIn.access, refresh: "", expires: 0, accountId: signedIn.accountId, name: signedIn.accountId, source: "web" }
const loader = await plugin.auth.loader(getAuth)
await loader.fetch("https://ai.catpaw.meituan.com/v1/chat/completions", {
method: "POST",
body: JSON.stringify({ model: "longcat-2.0", stream: false, messages: [{ role: "user", content: "hi" }] }),
})
expect(fake.state.conversations[0].token).toBe("acct-A-token")
})
test("a refused token says 401", async () => {
saved = { type: "oauth", access: "gone", expires: 0, source: "manual" }
const loader = await plugin.auth.loader(getAuth)
const res = await loader.fetch("https://ai.catpaw.meituan.com/v1/chat/completions", {
method: "POST",
body: JSON.stringify({ model: "longcat-2.0", stream: false, messages: [{ role: "user", content: "hi" }] }),
})
expect(res.status).toBe(401)
const answer = await res.json().catch(() => null)
expect(answer?.error?.message ?? "").toMatch(/round 失败/)
})
test("only chat completions are served", async () => {
const loader = await plugin.auth.loader(getAuth)
const res = await loader.fetch("https://ai.catpaw.meituan.com/v1/embeddings", { method: "POST", body: "{}" })
expect(res.status).toBe(404)
})
})
describe("usage", () => {
// the credit endpoint takes `X-Auth-Token`, not the conversation gateway's
// `Cookie: X-Passport-Token`: sending the cookie there answers 401 / code
// 4010, which magpie reads as the sign-in having expired
test("reads the credit balance with X-Auth-Token", async () => {
const usage = await plugin.auth.usage(getAuth)
// a clean read says nothing about the sign-in: that absence is what lets
// magpie clear a lapse (a "kept" here would leave the mark on forever)
expect(usage.signIn).toBeUndefined()
expect(usage.windows[0].display).toBe("1134.67 credit")
expect(usage.plan).toBe("体验版")
expect(fake.state.balanceCalls).toBe(1)
})
test("a refused token says the sign-in expired", async () => {
saved = { type: "oauth", access: "not-the-token", expires: 0, source: "manual" }
const usage = await plugin.auth.usage(getAuth)
expect(usage.signIn).toBe("expired")
expect(usage.error).toContain("重新登录")
})
test("a missing desktop file is not the sign-in expiring", async () => {
const was = process.env.CATPAW_AUTH_PATH
process.env.CATPAW_AUTH_PATH = join(tmpDir, "absent.json")
try {
const usage = await plugin.auth.usage(getAuth)
expect(usage.signIn).toBe("kept")
expect(usage.error).toContain("未找到妙手登录态文件")
} finally {
process.env.CATPAW_AUTH_PATH = was
}
})
})
describe("captured protocol", () => {
test("gatewayHeaders matches the captured client headers key for key", () => {
// _internal doesn't expose gatewayHeaders directly; build one through
// the only place its shape is fully visible — reconstruct from source is
// fragile, so compare against the exported header set instead
const captured = capturedRound.headers
const ours = _internal.gatewayHeadersForTest("tok")
// every header the client sent, our request sends too — with the same
// value where the value is a constant, and the same shape where it is
// per-request random (the trace ids)
// the base set (what gatewayHeaders returns) plus what fetch adds and
// what the round route's extraHeaders carry — together they must cover
// every header the client sent
const roundExtras = { "m-spanid": "0.2", "m-spanname": "conversation.round" }
const combined = { accept: "application/json, text/plain, */*", ...ours, ...roundExtras }
for (const [key, value] of Object.entries(captured)) {
const lower = key.toLowerCase()
if (lower === "m-host") {
// the client machine's LAN IP: deliberately not sent (see index.mjs)
expect(ours).not.toHaveProperty("m-host")
continue
}
if (["accept-encoding", "content-length"].includes(lower)) continue // transport-level
const oursKey = Object.keys(combined).find((k) => k.toLowerCase() === lower)
expect(oursKey, key).toBeTruthy()
if (["m-traceid", "x-request-id", "x-trace-id"].includes(lower)) {
expect(String(combined[key])).toMatch(/^[0-9a-f-]{32,36}$/)
} else {
expect(String(combined[oursKey]), key).toBe(String(value))
}
}
expect(ours["m-traceid"]).toBe(ours["x-trace-id"])
})
test("the round body carries the captured protocol fields", async () => {
const loader = await plugin.auth.loader(getAuth)
await loader.fetch("https://ai.catpaw.meituan.com/v1/chat/completions", {
method: "POST",
body: JSON.stringify({ model: "longcat-2.0", stream: false, messages: [{ role: "user", content: "hi" }] }),
})
const sent = fake.state.conversations[0]
expect(sent.permissionMode).toBe(capturedRound.bodyProtocol.permissionMode)
// one client identity end to end: the body's source/mode are the same
// captured request's values as the headers are
expect(sent.source).toBe(capturedRound.bodyProtocol.source)
expect(sent.mode).toBe(capturedRound.bodyProtocol.mode)
})
test("the captured turn request carries the same permissionMode", () => {
expect(capturedTurn.bodyProtocol.permissionMode).toBe(capturedRound.bodyProtocol.permissionMode)
expect(capturedRound.headers["user-agent"]).toBe(capturedTurn.headers["user-agent"])
})
})
describe("helpers", () => {
test("model type mapping", () => {
expect(_internal.modelTypeOf("longcat-2.0")).toBe(77)
expect(_internal.modelTypeOf("kimi-k3")).toBe(83)
expect(_internal.modelTypeOf("unknown")).toBe(77)
})
})
+26
View File
@@ -0,0 +1,26 @@
{
"name": "@magpie-community/opencode-catpaw-auth",
"version": "0.1.0",
"description": "OpenCode & Magpie provider plugin for Meituan's 妙手 CatPaw (ai.catpaw.meituan.com): web sign-in or the desktop client's saved credentials, chat through the round/event/turn protocol, models and credit balance",
"type": "module",
"main": "./index.mjs",
"exports": "./index.mjs",
"files": [
"index.mjs",
"README.md"
],
"keywords": [
"opencode",
"opencode-plugin",
"magpie",
"catpaw",
"meituan",
"妙手"
],
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/magpie-community/plugins.git",
"directory": "packages/catpaw"
}
}
+42
View File
@@ -0,0 +1,42 @@
{
"note": "Captured 2026-10-09 from the official desktop client talking to its own gateway. Cookies, host and message text redacted; header keys, values and body protocol fields verbatim. See packages/catpaw/index.mjs gatewayHeaders and runConversation.",
"path": "/api/agent/conversation/round",
"headers": {
"accept": "application/json, text/plain, */*",
"accept-encoding": "gzip, compress, deflate, br",
"content-type": "application/json",
"user-agent": "axios/1.19.0",
"m-appkey": "com.sankuai.mcopilot.cli",
"m-debug": "true",
"m-host": "<client machine LAN IP — redacted>",
"m-spanid": "0.2",
"m-spanname": "conversation.round",
"m-traceid": "e66f2791065a78b22f6975d7726f30b7",
"x-request-id": "0e51db8a-9eae-44d0-b580-cec10f9a2154",
"x-trace-id": "e66f2791065a78b22f6975d7726f30b7",
"content-length": "1897"
},
"bodyProtocol": {
"agentType": "main",
"conversationId": "<redacted>",
"dxNoticeEnable": false,
"enableTodos": true,
"mcpServers": [],
"mode": "CLI",
"modelType": 30,
"permissionMode": "unsafeBypassPermissions",
"repositories": [],
"rulesMessage": "",
"source": "CatPawCLI",
"toolVersion": "2.0.2",
"goal": null,
"userPromptContext": {}
},
"headerless_message_shape": {
"type": "user",
"content_types": [
"text"
],
"finished": true
}
}
+135
View File
@@ -0,0 +1,135 @@
{
"note": "Captured 2026-10-09 from the official desktop client talking to its own gateway. Cookies, host and message text redacted; header keys, values and body protocol fields verbatim. See packages/catpaw/index.mjs gatewayHeaders and runConversation.",
"path": "/api/agent/conversation/turn",
"headers": {
"accept": "application/json, text/plain, */*",
"accept-encoding": "gzip, compress, deflate, br",
"content-type": "application/json",
"user-agent": "axios/1.19.0",
"enableheartbeat": "true",
"m-appkey": "com.sankuai.mcopilot.cli",
"m-debug": "true",
"m-host": "<client machine LAN IP — redacted>",
"m-spanid": "0.4.1",
"m-spanname": "conversation.turn",
"m-traceid": "e66f2791065a78b22f6975d7726f30b7",
"x-agent-version": "1.2.0-beta.6",
"x-request-id": "2bee144e-8e91-4531-8e63-4c98747802fa",
"x-trace-id": "e66f2791065a78b22f6975d7726f30b7",
"content-length": "3140"
},
"bodyProtocol": {
"conversationId": "<redacted>",
"mode": "CLI",
"modelType": 30,
"permissionMode": "unsafeBypassPermissions",
"rulesMessage": "",
"source": "CatPawCLI",
"toolVersion": "2.0.2",
"toolConfigs": [
{
"name": "delete_file",
"enable": true
},
{
"name": "glob_file_search",
"enable": true
},
{
"name": "list_dir",
"enable": true
},
{
"name": "read_file",
"enable": true
},
{
"name": "read_lints",
"enable": true
},
{
"name": "write",
"enable": true
},
{
"name": "fetch_rules",
"enable": true
},
{
"name": "bash",
"enable": true
},
{
"name": "task_stop",
"enable": true
},
{
"name": "string_replace",
"enable": true
},
{
"name": "multi_edit",
"enable": true
},
{
"name": "grep",
"enable": true
},
{
"name": "docs_search",
"enable": true
},
{
"name": "fetch_docs",
"enable": true
},
{
"name": "km_search",
"enable": true
},
{
"name": "web_fetch",
"enable": true
},
{
"name": "web_search",
"enable": true
},
{
"name": "todo_write",
"enable": true
},
{
"name": "get_goal",
"enable": true,
"description": "Get the current goal for this thread, including status, budgets, token and elapsed-time usage, and remaining turn budget."
},
{
"name": "create_goal",
"enable": true,
"description": "Create a goal only when explicitly requested by the user or system/developer instructions; do not infer goals from ordinary tasks.\nSet turn_budget only when an explicit turn budget is requested. Fails if an unfinished goal exists; use update_goal only for status."
},
{
"name": "update_goal",
"enable": true,
"description": "Update the existing goal.\nUse this tool only to mark the goal achieved or genuinely blocked.\nSet status to `complete` only when the objective has actually been achieved and no required work remains.\nSet status to `blocked` only when the same blocking condition has repeated for at least three consecutive goal turns, counting the original/user-triggered turn and any automatic continuations, and the agent cannot make meaningful progress without user input or an external-state change.\nIf the user resumes a goal that was previously marked `blocked`, treat the resumed run as a fresh blocked audit. If the same blocking condition then repeats for at least three consecutive resumed goal turns, set status to `blocked` again.\nOnce the blocked threshold is satisfied, do not keep reporting that you are still blocked while leaving the goal active; set status to `blocked`.\nDo not use `blocked` merely because the work is hard, slow, uncertain, incomplete, or would benefit from clarification.\nDo not mark a goal complete merely because its budget is nearly exhausted or because you are stopping work.\nYou cannot use this tool to pause, resume, turn-limit, or usage-limit a goal; those status changes are controlled by the user or system.\nWhen marking a turn-budgeted goal achieved with status `complete`, report the final turn usage from the tool result to the user."
},
{
"name": "powershell",
"enable": true
}
],
"turnRequestId": "dacd35b1-6c36-4ea6-93fc-3fcd496633b5",
"goal": null,
"userPromptContext": {
"userTextInput": "say hi"
}
},
"headerless_message_shape": {
"type": "user",
"content_types": [
"text"
],
"finished": true
}
}
+3
View File
@@ -38,6 +38,9 @@
"summary": { "en": "Trae CN (trae.cn) and Trae international (trae.ai) models with your own account, free tier included — Trae's own browser sign-in. Experimental.", "zh": "用 Trae CN(trae.cn)与 Trae 国际版(trae.ai)账号使用各自的模型,含免费版,使用 Trae 自己的浏览器登录。实验性。" } },
{ "package": "@magpie-community/opencode-opendesign-auth", "name": "Open Design", "providers": ["opendesign"], "community": true,
"summary": { "en": "Open Design Cloud's Design Plan (open-design.ai): the account's device sign-in, the models the plan entitles it to, and the plan's 5-hour and 7-day allowance and wallet balance.", "zh": "Open Design Cloud 的 Design Plan(open-design.ai):账号设备登录、套餐可用的模型,以及 5 小时与 7 天额度、钱包余额。" } },
{ "package": "@magpie-community/opencode-catpaw-auth", "name": "CatPaw", "providers": ["catpaw"], "community": true,
"summary": { "en": "Meituan's 妙手 CatPaw (ai.catpaw.meituan.com): a browser web sign-in or the desktop client's saved credentials, chat through its round/event/turn conversation protocol, models and credit balance.",
"zh": "美团妙手 CatPaw(ai.catpaw.meituan.com):浏览器网页登录或妙手桌面端已保存的登录态,经其 round/event/turn 会话协议对话,含模型与积分余额。" } },
{ "package": "@magpie-community/opencode-loomy-auth", "name": "Loomy", "providers": ["loomy"], "community": true,
"summary": { "en": "iFlytek's Loomy (loomyad.xunfei.cn): SMS sign-in, OpenAI-compatible chat with reasoning-effort folding and image markers, the live model catalog, two point wallets and the daily first-login grant.",
"zh": "讯飞 Loomy(loomyad.xunfei.cn):短信验证码登录,OpenAI 兼容对话(思考档折叠与图片标记适配),实时模型目录、双积分钱包与每日首登赠送。" } },