From 5d679712f0d604196c2e513e915798fb62e5efd3 Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 3 Nov 2026 23:59:58 +0800 Subject: [PATCH] catpaw 0.1.3: models the vendor adds appear without a release (LongCat 2.5) star21321321124 (Discord, magpie v0.1.2862, catpaw 0.1.0/0.1.1): the vendor added LongCat 2.5 and the plugin did not list it. The plugin's model list was a hard-coded copy of an old proxy's table (9 models, each with its modelType number). The desktop client keeps no such table: its main process POSTs /api/agent/maas/model-types with {tenant: "CatDesk", scene: "CATX_APP", env: "EXTERNAL"} on the gateway, caches the list 5 minutes, and sends a model's modelTypeId as the round/turn body's modelType (read from the 2026.1016.0032 client's dist-electron/main and catpawEnv chunks; items carry modelTypeId, modelTypeName, provider, supportImage). - index.mjs: provider.models reads that list with the account's own token (desktop file or the stored web/paste token, as usage does) and adds what the table lacks; a listed model whose type the table has keeps the table's id and name, any other gets its modelTypeName lower-cased (LongCat-2.5 -> longcat-2.5). Negative ids / USER_CUSTOM (the user's own models) are left out. A chat on a table model costs no request; a chat on any other id looks it up in the list and sends that modelType; an id in neither is still a 400 naming what is known. A failed read leaves the table. The headers are the plugin's gatewayHeaders, unchanged. - fake.mjs: the list endpoint. 7 new tests: the request body, the extra model offered, custom model left out, modelType sent on a chat, no request for a table model, one read per 5 minutes, a failed read. - README, version 0.1.3. Run on mote at this tree: bun test packages/catpaw 35 pass 0 fail; bun scripts/check.mjs exit 0; HOME=$(mktemp -d) bun test (root) 5303 pass, 19 skip, 0 fail. Broken by hand, then restored: the lookup of an unlisted id returning null: 3 fail; provider.models ignoring the list: 2 fail. Not tried: a real CatPaw account (none here), so the real response is untested; the shape comes from the client's code. The id of LongCat 2.5 is whatever the vendor's modelTypeName is; if it differs from "LongCat-2.5" the id will differ from longcat-2.5. Not the lists of the Windows client. --- packages/catpaw/README.md | 2 +- packages/catpaw/fake.mjs | 23 ++++++++ packages/catpaw/index.mjs | 105 ++++++++++++++++++++++++++++++--- packages/catpaw/index.test.mjs | 62 +++++++++++++++++++ packages/catpaw/package.json | 2 +- 5 files changed, 185 insertions(+), 9 deletions(-) diff --git a/packages/catpaw/README.md b/packages/catpaw/README.md index 6df2b02..36c029e 100644 --- a/packages/catpaw/README.md +++ b/packages/catpaw/README.md @@ -19,7 +19,7 @@ magpie plugin login catpaw # 选「网页登录」/「妙手桌面端登录 - `手动粘贴 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),静态表(无远程目录接口)。不声明各模型的上下文/输出窗口(客户端未公布,不编造数字),也不声明图片输入(见下)。 +- **模型**:妙手桌面端的 9 个模型(longcat-2.0 / glm-5.3 系列 / deepseek-v4 系列 / minimax-m3 / kimi-k3 / auto),静态表打底,再按妙手桌面端的做法向网关取账号的模型清单(`POST /api/agent/maas/model-types`,缓存 5 分钟),官方新增的模型(如 LongCat 2.5)无需发版即出现;取不到清单时用静态表。不声明各模型的上下文/输出窗口(客户端未公布,不编造数字),也不声明图片输入(见下)。 - **工具与图片**:会话协议只收一段扁平文本 prompt,工具定义、工具结果与图片都无法送达——带这些的请求以 **400 明确拒绝**(而不是悄悄丢掉后答错)。 - **余额(usage)**:`GET https://catx.nocode.cn/api/gateway/credit/balance`,鉴权头是 **`X-Auth-Token: `**。 - ⚠️ 这个接口与聊天网关**不是同一个鉴权头**:它只认 `X-Auth-Token`,把聊天用的 `Cookie: X-Passport-Token` 发到这里会稳定 401(body `code 4010`)。magpie 把 usage 的 401 当作「登录态失效」,所以鉴权头必须分开核对。 diff --git a/packages/catpaw/fake.mjs b/packages/catpaw/fake.mjs index 3743707..951cb73 100644 --- a/packages/catpaw/fake.mjs +++ b/packages/catpaw/fake.mjs @@ -3,6 +3,13 @@ const json = (status, body) => new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } }) +const defaultModelTypes = () => [ + { modelTypeId: 77, modelTypeName: "LongCat-2.0", provider: "CATPAW", supportImage: true }, + { modelTypeId: 83, modelTypeName: "Kimi-K3", provider: "CATPAW", supportImage: true }, + { modelTypeId: 120, modelTypeName: "LongCat-2.5", provider: "CATPAW", supportImage: true }, + { modelTypeId: -3, modelTypeName: "my-own-model", provider: "USER_CUSTOM", supportImage: false }, +] + export function fakeCatPaw() { const state = { token: "cat-token-1", @@ -17,6 +24,13 @@ export function fakeCatPaw() { disabledSources: new Set(["CatPawCLI"]), turnBodies: [], balanceCalls: 0, + // POST /api/agent/maas/model-types, the list the desktop client asks for + // (items as its renderer reads them: modelTypeId, modelTypeName, provider, + // supportImage). The ids here are the table's own, plus one the table has + // never heard of (type 120 is a fixture, not the vendor's number). + modelTypes: defaultModelTypes(), + modelTypeCalls: [], + modelTypesFail: false, // 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) @@ -31,6 +45,9 @@ export function fakeCatPaw() { state.disabledSources = new Set(["CatPawCLI"]) state.turnBodies = [] state.balanceCalls = 0 + state.modelTypes = defaultModelTypes() + state.modelTypeCalls = [] + state.modelTypesFail = false state.webSids = new Map() state.webTokens = new Set() state.pollCalls = 0 @@ -88,6 +105,12 @@ export function fakeCatPaw() { const body = await req.json().catch(() => ({})) + if (url.pathname === "/api/agent/maas/model-types") { + state.modelTypeCalls.push(body) + if (state.modelTypesFail) return json(500, { code: 500, msg: "boom" }) + return json(200, { code: 0, message: "success", data: state.modelTypes, errorCode: null }) + } + if (url.pathname === "/api/agent/conversation/round") { state.rounds++ if (state.disabledSources.has(body.source)) return json(200, { code: 400, msg: `source 不存在或未启用: ${body.source}` }) diff --git a/packages/catpaw/index.mjs b/packages/catpaw/index.mjs index bf30e33..82025b7 100644 --- a/packages/catpaw/index.mjs +++ b/packages/catpaw/index.mjs @@ -46,6 +46,70 @@ const MODELS = { const DEFAULT_MODEL_TYPE = 77 const modelTypeOf = (id) => MODELS[id]?.type ?? DEFAULT_MODEL_TYPE +// The desktop client does not keep a model table of its own: it asks the +// gateway for one (POST /api/agent/maas/model-types with {tenant: "CatDesk", +// scene: "CATX_APP", env: "EXTERNAL"}, read from the 2026.1016 client's +// main process, 5 minutes cached) and sends a model's modelTypeId as the +// round and turn body's modelType. MODELS above is only what that list held +// when the plugin was written; a model the vendor adds later (LongCat 2.5, +// 2026-11-03) is in the list and not in the table. The list is read with the +// account's own token, and a failed read leaves the table. +const LIVE_TTL = 5 * 60_000 +const liveLists = new Map() // token -> { at, models } + +// a listed model's id: the table's id when the table has its type, else the +// vendor's modelTypeName as a lower-cased slug ("LongCat-2.5" -> "longcat-2.5") +function liveModels(rows) { + const out = {} + const byType = new Map(Object.entries(MODELS).map(([id, m]) => [m.type, id])) + for (const r of Array.isArray(rows) ? rows : []) { + const type = r?.modelTypeId + // a negative id is the user's own custom model (it needs its own key and + // base URL); the gateway does not serve it + if (!Number.isInteger(type) || type < 0 || r.provider === "USER_CUSTOM") continue + const name = typeof r.modelTypeName === "string" ? r.modelTypeName.trim() : "" + const id = byType.get(type) ?? name.toLowerCase().replace(/\s+/g, "-") + if (!id || id in out) continue + out[id] = { name: MODELS[id]?.name ?? name, type, image: r.supportImage === true } + } + return out +} + +async function fetchLiveModels(token, signal) { + const res = await fetch(ORIGIN + "/api/agent/maas/model-types", { + method: "POST", + headers: gatewayHeaders(token), + body: JSON.stringify({ tenant: "CatDesk", scene: "CATX_APP", env: "EXTERNAL" }), + signal: signal ?? AbortSignal.timeout(15_000), + }) + if (res.status === 401) throw Object.assign(new Error("妙手登录态已过期,请在妙手桌面端重新登录"), { signIn: "expired" }) + const body = await res.json().catch(() => null) + if (!res.ok || (body && typeof body.code === "number" && body.code !== 0 && body.code !== 200)) throw new Error(`妙手模型列表返回 HTTP ${res.status}`) + const rows = Array.isArray(body) ? body : body?.data + if (!Array.isArray(rows)) throw new Error("妙手模型列表无法解析") + return liveModels(rows) +} + +// the account's list, 5 minutes cached; null when it cannot be read (the +// table is then all there is) +async function liveListFor(token, signal) { + const hit = liveLists.get(token) + if (hit && Date.now() - hit.at < LIVE_TTL) return hit.models + try { + const models = await fetchLiveModels(token, signal) + liveLists.set(token, { at: Date.now(), models }) + return models + } catch { + return hit?.models ?? null + } +} + +// a model by id: the table first (no request), then the account's list +async function specOf(token, id, signal) { + if (MODELS[id]) return MODELS[id] + return (await liveListFor(token, signal))?.[id] ?? null +} + // 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) @@ -182,8 +246,7 @@ function buildPrompt(messages) { // 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) +async function* runConversation(token, chat, signal, modelType = modelTypeOf(chat.model)) { const convId = crypto.randomUUID() const msgId = crypto.randomUUID() const turnId = crypto.randomUUID() @@ -334,8 +397,6 @@ export async function CatPawAuthPlugin({ client } = {}) { } 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 @@ -373,6 +434,17 @@ export async function CatPawAuthPlugin({ client } = {}) { } if (!token) return errorResponse(401, "妙手登录态缺失:请登录妙手桌面端或手动粘贴 token") + // the model: the table's, or one the vendor added since (its own + // list, read with this account's token) + let spec = null + if (String(chat.model ?? "").trim() !== "") { + spec = await specOf(token, chat.model, init.signal) + if (!spec) { + const known = Object.keys({ ...MODELS, ...(liveLists.get(token)?.models ?? {}) }) + return errorResponse(400, `unknown model "${chat.model}" (known: ${known.join(", ")})`) + } + } + // 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)}` @@ -392,7 +464,7 @@ export async function CatPawAuthPlugin({ client } = {}) { async start(controller) { controller.enqueue(chunk(null, null)) // the role frame try { - for await (const ev of runConversation(token, chat, init.signal)) { + for await (const ev of runConversation(token, chat, init.signal, spec?.type)) { if (ev.delta) controller.enqueue(chunk(ev.delta, null)) if (ev.reasoningDelta) controller.enqueue(chunk(null, null, ev.reasoningDelta)) if (ev.done) { @@ -415,7 +487,7 @@ export async function CatPawAuthPlugin({ client } = {}) { let text = "" let reasoning = "" try { - for await (const ev of runConversation(token, chat, init.signal)) { + for await (const ev of runConversation(token, chat, init.signal, spec?.type)) { if (ev.done) { text = ev.text reasoning = ev.reasoning @@ -619,6 +691,25 @@ export async function CatPawAuthPlugin({ client } = {}) { }, ], }, + // the account's own list: the table plus what the vendor serves now + provider: { + id: ID, + async models(provider, { auth } = {}) { + let token + if (auth?.type === "oauth" && auth.access && auth.source !== "desktop") token = auth.access + else { + try { + token = readAuth().token + } catch { + return provider?.models ?? {} + } + } + const live = await liveListFor(token) + if (!live) return provider?.models ?? {} + const extra = Object.fromEntries(Object.entries(live).filter(([id]) => !(id in (provider?.models ?? {}))).map(([id, m]) => [id, configModel(id, m)])) + return { ...(provider?.models ?? {}), ...extra } + }, + }, async config(config) { config.provider ??= {} const was = config.provider[ID] ?? {} @@ -634,4 +725,4 @@ export async function CatPawAuthPlugin({ client } = {}) { } // for tests -export const _internal = { ID, BODY_IDENTITY, NAME, MODELS, modelTypeOf, buildPrompt, gatewayHeaders, gatewayHeadersForTest: gatewayHeaders, readAuth, authPath, configModel } +export const _internal = { ID, BODY_IDENTITY, NAME, MODELS, modelTypeOf, buildPrompt, gatewayHeaders, gatewayHeadersForTest: gatewayHeaders, readAuth, authPath, configModel, liveModels, liveListFor, forgetLive: () => liveLists.clear() } diff --git a/packages/catpaw/index.test.mjs b/packages/catpaw/index.test.mjs index 8360914..f27f63f 100644 --- a/packages/catpaw/index.test.mjs +++ b/packages/catpaw/index.test.mjs @@ -466,6 +466,68 @@ describe("source (plugins#605)", () => { }) }) +describe("models the vendor added (the desktop client asks the gateway for its list)", () => { + const chatWith = async (model) => { + const loader = await plugin.auth.loader(getAuth) + return loader.fetch("https://ai.catpaw.meituan.com/v1/chat/completions", { + method: "POST", + body: JSON.stringify({ model, stream: false, messages: [{ role: "user", content: "hi" }] }), + }) + } + beforeEach(() => _internal.forgetLive()) + + test("the list is asked the way the client asks it", async () => { + await plugin.provider.models({ models: {} }, { auth: saved }) + expect(fake.state.modelTypeCalls).toEqual([{ tenant: "CatDesk", scene: "CATX_APP", env: "EXTERNAL" }]) + }) + + test("a listed model the table lacks is offered, under its table id when it has one", async () => { + const cfg = {} + await plugin.config(cfg) + const got = await plugin.provider.models({ models: cfg.provider.catpaw.models }, { auth: saved }) + expect(got["longcat-2.5"]).toEqual({ name: "LongCat-2.5" }) + expect(Object.keys(got)).toContain("longcat-2.0") + expect(got["longcat-2.0"].name).toBe("LongCat-2.0 (限时免费)") + // the user's own custom model (negative id) is not the gateway's to serve + expect(Object.keys(got)).not.toContain("my-own-model") + }) + + test("a chat on the new model sends the listed modelType", async () => { + const res = await chatWith("longcat-2.5") + expect(res.status).toBe(200) + expect(fake.state.conversations.at(-1).modelType).toBe(120) + }) + + test("a table model costs no list request", async () => { + const res = await chatWith("kimi-k3") + expect(res.status).toBe(200) + expect(fake.state.modelTypeCalls).toEqual([]) + expect(fake.state.conversations.at(-1).modelType).toBe(83) + }) + + test("the list is read once in five minutes", async () => { + await chatWith("longcat-2.5") + await chatWith("longcat-2.5") + expect(fake.state.modelTypeCalls.length).toBe(1) + }) + + test("a model neither the table nor the list has is still refused, naming what is known", async () => { + const res = await chatWith("not-a-model") + expect(res.status).toBe(400) + expect((await res.json()).error.message).toContain("longcat-2.5") + }) + + test("when the list cannot be read the table stands", async () => { + fake.state.modelTypesFail = true + const cfg = {} + await plugin.config(cfg) + const got = await plugin.provider.models({ models: cfg.provider.catpaw.models }, { auth: saved }) + expect(Object.keys(got).sort()).toEqual(Object.keys(cfg.provider.catpaw.models).sort()) + expect((await chatWith("longcat-2.5")).status).toBe(400) + expect((await chatWith("glm-5.3")).status).toBe(200) + }) +}) + describe("helpers", () => { test("model type mapping", () => { expect(_internal.modelTypeOf("longcat-2.0")).toBe(77) diff --git a/packages/catpaw/package.json b/packages/catpaw/package.json index a59c314..8f9c1c5 100644 --- a/packages/catpaw/package.json +++ b/packages/catpaw/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-catpaw-auth", - "version": "0.1.2", + "version": "0.1.3", "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": "./opencode.mjs",