diff --git a/packages/qoder/README.md b/packages/qoder/README.md index 3620295..6749314 100644 --- a/packages/qoder/README.md +++ b/packages/qoder/README.md @@ -209,6 +209,18 @@ name remain independently selectable. The name describes the catalog entry used for the request, not an attestation of the backend that executed it. +A request's `model_config` is built as Qoder's own client builds it +(Qoder CN's CLI 1.1.81, desktop 0.4.3), not sent as the listing entry +(since 0.2.54): `key`, `display_name`, an empty `model`, `format`, +`is_vl`, `is_reasoning` (off when thinking is turned off), empty +`api_key` and `url`, `source` and `max_input_tokens`. The entry's +`minimal_version`, `strategies`, prices and `thinking_config` are not +sent. While the whole entry was sent, Qoder CN billed DeepSeek-Flash +(`dfmodel`, whose entry has a `minimal_version`) as Auto at Auto's rate +(plugins#638); that the entry was the cause has not been confirmed on a +Qoder CN account. A model whose entry has no key of its own, or whose key is +`auto`, is refused with a 400 and nothing is sent, never served as Auto. + The `provider.models` hook reads the account's own list, as Qoder's client asks for it (`/algo/api/v2/model/list`). It keeps the enabled models of the listing's `app` scene, the list Qoder's app shows and the one a request diff --git a/packages/qoder/index.mjs b/packages/qoder/index.mjs index febe42d..05e8a17 100644 --- a/packages/qoder/index.mjs +++ b/packages/qoder/index.mjs @@ -1224,6 +1224,38 @@ function typedUnions(schema) { return root } +// modelConfig is the model_config a request carries for model m, built as +// Qoder's own client builds it (Qoder CN's CLI 1.1.81 and desktop 0.4.3, +// the qoder-agent-sdk worker's model resolution): the listing entry's key, +// name, format, image and reasoning flags, source and input size, with an +// empty model, api_key and url, and is_reasoning off when thinking is. +// Never the listing entry as it came: that also holds minimal_version, +// strategies, prices and thinking_config, which no client sends. While it +// was sent whole, Qoder CN billed DeepSeek-Flash (dfmodel, whose entry +// carries a minimal_version) as Auto at Auto's rate, and Kimi-K3.1-Pro +// (none) as itself (magpie-community/plugins#638, square-235); the entry +// is the likely cause, not confirmed on a Qoder CN account. +// A model with no key of its own is refused: Qoder's worker sends a +// request with none as "auto", which is never what was asked for. +function modelConfig(m, thinking) { + const raw = m.config ?? {} + const key = String(raw.key ?? m.key ?? "").trim() + if (!key || ["auto", "default"].includes(key) || key !== m.key) throw new Error(`no Qoder model key for "${m.key ?? ""}"`) + const max = Number.isInteger(raw.max_input_tokens) && raw.max_input_tokens > 0 ? raw.max_input_tokens : 200_000 + return { + key, + display_name: raw.display_name || key, + ...(raw.outer_provider ? { outer_provider: raw.outer_provider } : { model: "" }), + format: raw.format ?? "openai", + is_vl: !!raw.is_vl, + is_reasoning: !!raw.is_reasoning && thinking, + api_key: "", + url: "", + source: raw.source || "system", + max_input_tokens: max, + } +} + // qoderBody is the plaintext agent_chat_generation takes for a chat // completion request, for model m, in the session the agent named (named, // "" when none) and the task it is a call of (taskOf's, a new one when @@ -1254,7 +1286,7 @@ function qoderBody(chat, m, named = "", task, site) { agent_id: "agent_common", task_id: "common", session_type: site?.sessionType ?? "app", - model_config: m.config, + model_config: modelConfig(m, thinking), system: [sys], messages: [{ role: "system", content: [sys] }, ...cacheMarked(qoderMessages(chat.messages ?? []))], } @@ -3058,7 +3090,12 @@ const makePlugin = (site) => async ({ client }) => { const api = siteOf(site, cred).api const CHAT_URL = api + CHAT_PATH const task = taskOf(sessionOf(chat, named), chat) - const body = qoderBody(chat, m, named, task, siteOf(site, cred)) + let body + try { + body = qoderBody(chat, m, named, task, siteOf(site, cred)) + } catch (e) { + return errorResponse({ status: 400, message: e?.message ?? String(e) }) + } // Qoder's queue is waited out (queueWait) and the request sent again // under the request_set_id the queue knows, with a new request_id and // chat_record_id, as Qoder's client sends it (its o4i before each diff --git a/packages/qoder/model-config.test.mjs b/packages/qoder/model-config.test.mjs new file mode 100644 index 0000000..63c6716 --- /dev/null +++ b/packages/qoder/model-config.test.mjs @@ -0,0 +1,89 @@ +// The model_config a chat sends (plugins#638, square-235): Qoder CN billed +// DeepSeek-Flash (dfmodel) as Auto while the plugin sent the model's listing +// entry whole, with its minimal_version, strategies, prices and +// thinking_config. Qoder's own client (CN CLI 1.1.81, desktop 0.4.3) sends +// only the fields below, in this order. The listings are the real bytes +// Qoder (testdata/listing.json) and Qoder CN (testdata/cn-listing-free-view.json) +// answered. +import { afterEach, expect, test } from "bun:test" +import { readFileSync } from "node:fs" +import { QoderAuthPlugin, QoderCNAuthPlugin, _internal } from "./index.mjs" + +const real = globalThis.fetch +afterEach(() => { globalThis.fetch = real }) + +const CLIENT_KEYS = ["key", "display_name", "model", "format", "is_vl", "is_reasoning", "api_key", "url", "source", "max_input_tokens"] +const read = (f) => JSON.parse(readFileSync(new URL(`./testdata/${f}`, import.meta.url), "utf8")) +// The CN listing was read on a free account, which has every paid model off +// (enable false); the reporter's paid account has them on, so they are +// turned on here and nothing else is changed. +const paid = (listing) => Object.fromEntries(Object.entries(listing).map(([s, v]) => [s, Array.isArray(v) ? v.map((e) => ({ ...e, enable: true })) : v])) + +async function chatOn(create, listing, model, extra = {}) { + const sent = [] + globalThis.fetch = async (url, init) => { + if (new URL(String(url)).pathname.endsWith("/model/list")) return Response.json(listing) + if (String(url).includes("agent_chat_generation")) { + sent.push(JSON.parse(_internal.decodeBody(init.body))) + const chunk = { model: "auto", choices: [{ delta: { content: "OK" }, finish_reason: "stop" }], usage: { prompt_tokens: 1, completion_tokens: 1 } } + return new Response(`data: ${JSON.stringify({ body: JSON.stringify(chunk) })}\n\ndata: ${JSON.stringify({ body: "[DONE]" })}\n\n`, { headers: { "content-type": "text/event-stream" } }) + } + throw new Error(`unexpected upstream ${url}`) + } + const auth = { type: "oauth", access: "t", refresh: "r", expires: Date.now() + 3600000, uid: "u", machineId: "m" } + const hooks = await create({ client: { auth: { set: async () => {} } } }) + const loader = await hooks.auth.loader(async () => auth) + const res = await loader.fetch("https://test.invalid/chat/completions", { method: "POST", body: JSON.stringify({ model, messages: [{ role: "user", content: "hi" }], ...extra }) }) + return { res, sent } +} + +for (const [site, create, file] of [["qoder", QoderAuthPlugin, "listing.json"], ["qoder-cn", QoderCNAuthPlugin, "cn-listing-free-view.json"]]) { + for (const key of ["dfmodel", "kmodel_latest"]) { + test(`${site}: ${key}'s model_config is the client's, not the listing entry`, async () => { + const listing = paid(read(file)) + const entry = Object.values(listing).flat().find((e) => e?.key === key) + expect(entry).toBeTruthy() + const { res, sent } = await chatOn(create, listing, key) + expect(res.status).toBe(200) + const mc = sent.at(-1).model_config + expect(Object.keys(mc)).toEqual(CLIENT_KEYS) + expect(mc).toMatchObject({ key, display_name: entry.display_name, model: "", api_key: "", url: "", format: entry.format, source: entry.source, max_input_tokens: entry.max_input_tokens, is_vl: !!entry.is_vl }) + for (const k of ["minimal_version", "strategies", "price_factor", "thinking_config", "context_config", "enable", "is_default"]) expect(mc).not.toHaveProperty(k) + }) + } +} + +test("dfmodel's listing entries carry a minimal_version, which no client sends", () => { + for (const file of ["listing.json", "cn-listing-free-view.json"]) { + const df = Object.values(read(file)).flat().filter((e) => e?.key === "dfmodel") + expect(df.length).toBeGreaterThan(0) + expect(df.every((e) => e.minimal_version)).toBe(true) + } +}) + +test("is_reasoning is sent off when the request turns thinking off", async () => { + const listing = read("cn-listing-free-view.json") + const thinker = listing.chat.find((e) => e.enable && e.is_reasoning && e.thinking_config?.disabled) + expect(thinker).toBeTruthy() + const { sent } = await chatOn(QoderCNAuthPlugin, listing, thinker.key, { reasoning_effort: "none" }) + expect(sent.at(-1).model_config.is_reasoning).toBe(false) + const on = await chatOn(QoderCNAuthPlugin, listing, thinker.key, { reasoning_effort: "high" }) + expect(on.sent.at(-1).model_config.is_reasoning).toBe(true) +}) + +test("a model with no key of its own is refused, never sent as Auto", () => { + const listing = read("cn-listing-free-view.json") + const df = listing.chat.find((e) => e.key === "dfmodel") + const chat = { model: "dfmodel", messages: [{ role: "user", content: "hi" }] } + for (const config of [{ ...df, key: "" }, { ...df, key: "auto" }, { ...df, key: "kmodel_latest" }]) { + const m = { ..._internal.modelInfo(df), config } + expect(() => _internal.qoderBody(chat, m)).toThrow(/no Qoder model key/) + } + expect(_internal.qoderBody(chat, _internal.modelInfo(df)).model_config.key).toBe("dfmodel") +}) + +test("a model the listing doesn't have is answered 400, with nothing sent", async () => { + const { res, sent } = await chatOn(QoderCNAuthPlugin, read("cn-listing-free-view.json"), "Deepseek-Flash") + expect(res.status).toBe(400) + expect(sent).toHaveLength(0) +}) diff --git a/packages/qoder/package.json b/packages/qoder/package.json index 6fefd92..cf56812 100644 --- a/packages/qoder/package.json +++ b/packages/qoder/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-qoder-auth", - "version": "0.2.53", + "version": "0.2.54", "description": "Qoder and QwenWork (千问办公) subscriptions in OpenCode and magpie: qoder.com, qoder.cn, gateway.qwenwork.cn and the enterprise flagship, VPC and dedicated domains", "type": "module", "main": "./index.mjs",