From 4858e144a6019dfd87cf018668f37d4bb2136810 Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 17 Nov 2026 17:02:27 +0800 Subject: [PATCH] trae 0.2.41: an enterprise's built-in models are listed and say what failed (#1258) A Trae CN enterprise seat (@liuyuexue2020 on X, magpie v0.1.4288, 0.2.40) didn't see the tenant's own built-in models in magpie's list. A name typed in by hand got a bare 502. Trae CN 3.4.20's client (ai-modules-chat) marks each entry's config_source as Trae 1, Enterprise 2 or Personal 3, and shows the Enterprise ones as "Enterprise-builtin". They aren't presets (is_preset false), so they read as custom models, and chatModel dropped them together with the personal ones (is_custom_model, custom_model* ids). - chatModel keeps config_source 2 entries unless status is false (the IDE's "disabled by the administrator"). Personal custom models stay out. - A chat with one of them carries user_message_context.model_info as the client builds it: config_name, config_source 2, is_preset false, use_remote_service, display_model_name, custom_model_id, provider. A preset's body is unchanged. - A refused chat that isn't a lapse or a quota now names the model, the functions tried and the host. When the account's list doesn't have the model, it says that too; the list is read for this on the failing path only. Run (mica, HOME=$(mktemp -d), at this tree on 8c7e8f66): packages/trae bun test, 281 pass, 0 fail (24 files); bun scripts/check.mjs trae ok. Broken by hand: I turned off the chatModel enterprise branch, the model_info block and the error context. All 4 new tests in entmodels.test.mjs went red, then green again once restored. Not tried: a real enterprise seat. The fields in the list entry and the chat shape come from the client bundle. Nothing has seen them from Trae's server, and #1258 asks the reporter for both. Trae Global's enterprise console isn't covered either. --- packages/trae/README.md | 11 ++++- packages/trae/entmodels.test.mjs | 82 ++++++++++++++++++++++++++++++++ packages/trae/index.mjs | 74 +++++++++++++++++++++++++--- packages/trae/package.json | 2 +- 4 files changed, 160 insertions(+), 9 deletions(-) create mode 100644 packages/trae/entmodels.test.mjs diff --git a/packages/trae/README.md b/packages/trae/README.md index 57c9915..6295934 100644 --- a/packages/trae/README.md +++ b/packages/trae/README.md @@ -241,7 +241,16 @@ function does (`glm-5v-turbo`, `kimi-k2.5`, `minimax-m2.7`, `qwen-3.6-plus`, each answering through `solo_coder`). Left out are the IDE's helpers (`usage` other than `chat_completion`: summary, fast_apply…), configs switched off and the -custom-model slots. Context is the list's `context_window_tokens.dev`, +custom-model slots. An enterprise's own built-in models +(`config_source` 2, "Enterprise-builtin" in Trae CN's picker) are listed +since 0.2.41 (#1258), unless the admin switched one off (`status` false); a +personal custom model (`config_source` 3) is not, its key being in the +user's IDE only. A chat with an enterprise model carries +`user_message_context.model_info` as Trae CN 3.4.20's client builds it +(`config_source`, `is_preset` false, `custom_model_id`, `provider`) — +**not verified with a real enterprise seat**. A refused chat's error names +the model, the functions tried and the host, and says when the account's +list doesn't have the model. Context is the list's `context_window_tokens.dev`, output the `__dev` model's `max_tokens`. A model with a `__max` model and a bigger `context_window_tokens.max` is listed again as its Max, `-max` ("… (Max)"), with that window and the `__max` model's diff --git a/packages/trae/entmodels.test.mjs b/packages/trae/entmodels.test.mjs new file mode 100644 index 0000000..9fcd7c0 --- /dev/null +++ b/packages/trae/entmodels.test.mjs @@ -0,0 +1,82 @@ +// An enterprise's own built-in models (Trae CN's client: config_source 2, +// "Enterprise-builtin" in its picker). They are not Trae's presets, so their +// entries say is_custom_model, and the list dropped them with the personal +// custom models a seat's IDE alone holds the key for. A seat that typed one +// in by hand got a bare 502 with nothing saying what was asked. +import "./nonet.mjs" +import { afterEach, expect, test } from "bun:test" +import { TraeCNAuthPlugin, _internal } from "./index.mjs" +import { fakeTrae, json, signedIn, sse } from "./fake.mjs" + +let f +afterEach(() => f?.close()) + +// an enterprise built-in as the detail lists are expected to carry it: the +// fields Trae CN 3.4.20's client reads of one (not yet seen from a real seat) +const ent = { config_name: "custom_model_acme_qwen", usage: "chat_completion", config_source: 2, is_preset: false, + is_custom_model: true, display_config: { display_name: "Acme Qwen", is_custom_model: true }, + custom_model_id: "cm-42", provider: "volcengine", status: true } +// a personal custom model: its provider key is in the user's IDE only +const own = { config_name: "custom_model_mine", usage: "chat_completion", config_source: 3, is_preset: false, + is_custom_model: true, display_config: { display_name: "My GPT", is_custom_model: true }, custom_model_id: "cm-7" } +const preset = { config_name: "glm-5", usage: "chat_completion", config_source: 1, is_preset: true, display_config: { display_name: "GLM-5" } } + +async function plugin(configs) { + f = fakeTrae() + f.route("POST /api/ide/v1/batch_get_detail_param", () => json({ function_configs: [{ function: "chat_v3", config_info_list: configs }] })) + return TraeCNAuthPlugin({ client: {} }) +} + +test("an enterprise built-in model is listed; a personal custom one and a disabled one are not", async () => { + const hooks = await plugin([preset, ent, own, { ...ent, config_name: "custom_model_off", status: false }]) + const ms = await hooks.provider.models({ models: {} }, { auth: signedIn() }) + expect(Object.keys(ms).sort()).toEqual(["custom_model_acme_qwen", "glm-5"]) + expect(ms.custom_model_acme_qwen.name).toBe("Acme Qwen") +}) + +test("chatModel keeps config_source 2 only", () => { + expect(_internal.chatModel(ent)).toBe(true) + expect(_internal.chatModel(own)).toBe(false) + expect(_internal.chatModel({ ...ent, config_source: 3 })).toBe(false) + expect(_internal.chatModel({ ...ent, usage: "summary" })).toBe(false) + expect(_internal.chatModel(preset)).toBe(true) +}) + +test("a chat with an enterprise model carries its model info; a preset's doesn't", async () => { + const hooks = await plugin([preset, ent]) + await hooks.provider.models({ models: {} }, { auth: signedIn() }) + f.route("POST /api/agent/v3/llm_utils_chat", () => sse([["output", { response: "ok" }], ["done", {}]])) + const opts = await hooks.auth.loader(async () => signedIn()) + for (const model of ["custom_model_acme_qwen", "glm-5"]) { + const res = await opts.fetch(opts.baseURL + "/chat/completions", { method: "POST", body: JSON.stringify({ model, messages: [{ role: "user", content: "hi" }] }) }) + expect(res.status).toBe(200) + } + const chats = f.seen.filter((r) => r.path === "/api/agent/v3/llm_utils_chat") + expect(chats[0].json.model).toBe("custom_model_acme_qwen") + expect(chats[0].json.user_message_context.model_info).toEqual({ config_name: "custom_model_acme_qwen", config_source: 2, is_preset: false, + use_remote_service: true, display_model_name: "Acme Qwen", custom_model_id: "cm-42", provider: "volcengine" }) + expect(chats[1].json.user_message_context).toBeUndefined() +}) + +test("a refused chat names the model, the functions tried and the host", async () => { + const hooks = await plugin([preset, ent]) + await hooks.provider.models({ models: {} }, { auth: signedIn() }) + f.route("POST /api/agent/v3/llm_utils_chat", () => json({ code: 5000, message: "model not found" })) + const opts = await hooks.auth.loader(async () => signedIn()) + const ask = (model) => opts.fetch(opts.baseURL + "/chat/completions", { method: "POST", body: JSON.stringify({ model, messages: [{ role: "user", content: "hi" }] }) }) + + let res = await ask("custom_model_acme_qwen") + expect(res.status).toBe(502) + let msg = (await res.json()).error.message + expect(msg).toContain("model not found (code 5000)") + expect(msg).toContain("enterprise built-in model custom_model_acme_qwen asked through chat_v3") + expect(msg).toContain("127.0.0.1") + expect(msg).not.toContain("doesn't have") + + // typed in by hand: a name the account's list doesn't have + res = await ask("Acme-Qwen-72B") + expect(res.status).toBe(502) + msg = (await res.json()).error.message + expect(msg).toContain("model Acme-Qwen-72B asked through chat_v3") + expect(msg).toContain("this account's model list doesn't have Acme-Qwen-72B") +}) diff --git a/packages/trae/index.mjs b/packages/trae/index.mjs index 905307e..808e8a2 100644 --- a/packages/trae/index.mjs +++ b/packages/trae/index.mjs @@ -1618,7 +1618,7 @@ function sessionOf(headers) { // request asks for is sent as the Trae name that model takes, and left out // when it takes none of that name — Trae rejects a level a model has no entry // for, and serves its default when none is asked. -function chatBody(req, fn, modelName, most = 0, max = null, session = "", sees = false, levels = null) { +function chatBody(req, fn, modelName, most = 0, max = null, session = "", sees = false, levels = null, entry = null) { const config = max?.base ?? req.model const body = { messages: traeMessages(req, sees), @@ -1638,6 +1638,22 @@ function chatBody(req, fn, modelName, most = 0, max = null, session = "", sees = if (!body.max_tokens && most > 0) body.max_tokens = most body.user_message_context = { model_info: { prompt_max_tokens: max.window - (body.max_tokens || 0) } } } + // an enterprise's built-in model goes with the model info Trae CN's own + // client gives it (ai-modules-chat's model info: config_source, is_preset + // false, its custom_model_id, served remotely). Not confirmed against an + // enterprise seat's real request: a Trae preset is sent as before. + if (enterpriseModel(entry)) { + const info = body.user_message_context?.model_info ?? {} + info.config_name = config + info.config_source = ENTERPRISE + info.is_preset = false + info.use_remote_service = true + const shown = entry.display_config?.display_name || entry.display_name + if (shown) info.display_model_name = String(shown) + if (entry.custom_model_id) info.custom_model_id = String(entry.custom_model_id) + if (entry.provider) info.provider = String(entry.provider) + body.user_message_context = { ...body.user_message_context, model_info: info } + } if (typeof req.temperature === "number") body.temperature = req.temperature if (Array.isArray(req.tools) && req.tools.length && req.tool_choice !== "none") { body.tools = nativeTools(req.tools, moonshotModel(config, modelName, req.model)) @@ -2951,13 +2967,15 @@ async function* chain(held, it) { } // failure is the response for an error Trae answered with -function failure(site, status, code, message) { +// ctx, when given, says what was asked: an error that isn't a lapse or a +// quota names it, so a 502 says which model, where and through what +function failure(site, status, code, message, ctx = "") { message = message || statusLine(status) if (status === 401 || lapsedCode(code, site) || (status === 403 && lapsedWords.test(message))) { return errorResponse(401, `${site.realm}'s sign-in has expired (${message}); sign in again`, "expired") } if (status === 429 || quotaCode(code, site) || (status === 403 && quotaWords.test(message))) return errorResponse(429, `${site.realm}: ${message}`) - return errorResponse(status >= 400 ? status : 502, `${site.realm}: ${message}${code ? ` (code ${code})` : ""}`) + return errorResponse(status >= 400 ? status : 502, `${site.realm}: ${message}${code ? ` (code ${code})` : ""}${ctx ? `; ${ctx}` : ""}`) } // openai is the answer as an OpenAI chat completion: a stream, or one body @@ -3055,11 +3073,25 @@ const wrongFunction = (code) => ["4001", "4023", "1005"].includes(String(code)) // The lists also hold the IDE's own helpers (summary, fast_apply, title // generation: usage other than chat_completion), configs switched off, and // the slots of custom models, which need a provider bound in the IDE. +// +// An enterprise's own built-in models are the exception: Trae CN's client +// (3.4.20, ai-modules-chat ModelConfigSource) marks each entry's +// config_source Trae 1, Enterprise 2 or Personal 3, and shows the +// Enterprise ones as "Enterprise-builtin" for every seat of the tenant — +// served by Trae with the tenant's provider, so a seat picks them like its +// own. Not being Trae's presets (is_preset false), they come out as custom +// models (is_custom_model) and were dropped with the personal ones, whose +// provider key lives in the user's IDE only (plugins#1258, 0.2.41). +// One the admin switched off (status false) stays out, as in the IDE. +const ENTERPRISE = 2 +const enterpriseModel = (m) => Number(m?.config_source) === ENTERPRISE function chatModel(m, site) { const id = String(m?.config_name ?? "") - if (!id || /^custom_model/i.test(id)) return false + if (!id) return false if (m.usage && m.usage !== "chat_completion") return false if (m.config_switch === false) return false + if (enterpriseModel(m)) return m.status !== false && !(site?.hidesInvisible && m.is_invisible_to_user === true) + if (/^custom_model/i.test(id)) return false if (m.is_custom_model === true || m.display_config?.is_custom_model === true) return false // the IDE's own picker hides these: Auto-mode routing channels and // pay-as-you-go twins of another entry (gemini-3.1-pro vs -paygo/-auto, @@ -3537,6 +3569,24 @@ const makePlugin = (site) => async ({ client }) => { const onConsole = (host) => !!site.hosts.console && host === site.hosts.console && host !== site.hosts.api const consoleRefuses = (code) => String(code) === "4245" + // askedOf says what a refused chat asked for: the model, the functions + // tried and the host, and whether the account's list has the model at all. + // A model typed in by hand that the list doesn't name is the likeliest + // cause of a refusal, and the list is read for it (once per REREAD_MS) + // only on this failing path. + const askedOf = async (a, id, entry, fns, host) => { + let listed = !!entry && liveEntry.has(id) + if (!listed) { + await readList(a).catch(() => {}) + entry = liveEntry.get(id) ?? null + listed = !!entry + } + const kind = enterpriseModel(entry) ? "enterprise built-in model" : "model" + let out = `${kind} ${id} asked through ${fns.join(", ")} on ${host.replace(/^https?:\/\//, "")}` + if (!listed && liveEntry.size) out += `; this account's model list doesn't have ${id}, so Trae may not serve it under that id` + return out + } + const save = async (auth) => { try { await client?.auth?.set?.({ path: { id: site.id }, body: auth }) @@ -4197,20 +4247,27 @@ const makePlugin = (site) => async ({ client }) => { // marked, kept with its sign-in, and the same request is asked // once more on the consumer gateway; its list is read from there // next. + // what the last refusal was, and where it was asked: the error + // the agent gets names the model, the functions and the host + let why = null + const tried = [] + const entry = liveEntryOf(base) for (let round = 0; round < 2; round++) { const host = hostOf(a) let refused = false for (const fn of [...new Set(fns)]) { + tried.push(fn) const res = await fetch(host + "/api/agent/v3/llm_utils_chat", { method: "POST", headers: ideHeaders(a, site, { Accept: "text/event-stream", "X-Request-ID": randomUUID() }), - body: JSON.stringify(chatBody(req, fn, named?.fn === fn || max ? named.name : "", named?.fn === fn || max ? named.most : 0, max, session, sees, levels)), + body: JSON.stringify(chatBody(req, fn, named?.fn === fn || max ? named.name : "", named?.fn === fn || max ? named.most : 0, max, session, sees, levels, entry)), signal: ac.signal, }) if (!res.ok) { const text = await res.text() const e = errorOf(text) - last = failure(site, res.status, e.code, e.message || text.trim().slice(0, 300)) + why = { status: res.status, code: e.code, message: e.message || text.trim().slice(0, 300), host } + last = failure(site, why.status, why.code, why.message) if (onConsole(host) && consoleRefuses(e.code)) { refused = true; break } if (res.status === 400 && wrongFunction(e.code)) continue break @@ -4219,6 +4276,7 @@ const makePlugin = (site) => async ({ client }) => { if (!ct.includes("event-stream") && ct.includes("json")) { // an answer that isn't a stream is an error in a 200 const e = errorOf(await res.text()) + why = { status: 502, code: e.code, message: e.message, host } last = failure(site, 502, e.code, e.message) if (onConsole(host) && consoleRefuses(e.code)) { refused = true; break } if (wrongFunction(e.code)) continue @@ -4228,6 +4286,7 @@ const makePlugin = (site) => async ({ client }) => { const { held, done } = await first(it) const err = held.find((p) => p.error) if (err) { + why = { status: 502, code: err.code, message: err.error, host } last = failure(site, 502, err.code, err.error) if (onConsole(host) && consoleRefuses(err.code)) { it.return?.() @@ -4255,6 +4314,7 @@ const makePlugin = (site) => async ({ client }) => { await save(toAuth(a, site)) readAt.delete(who) } + if (why && last.status !== 401 && last.status !== 429) last = failure(site, why.status, why.code, why.message, await askedOf(a, base, entry, [...new Set(tried)], why.host)) if (!last.headers.has("X-Magpie-Sign-In")) last.headers.set("X-Magpie-Sign-In", signIn) return last }, @@ -4269,4 +4329,4 @@ const makePlugin = (site) => async ({ client }) => { export const TraeCNAuthPlugin = makePlugin(SITES["trae-cn"]) export const TraeGlobalAuthPlugin = makePlugin(SITES["trae-global"]) -export const _internal = { ownClient, clientStoragePaths, clientDevice, clientProfiles, deviceNote, clientDecode, thisMachine, traeHost, accountOf, HOSTS: SITES["trae-cn"].hosts, MODELS: SITES["trae-cn"].models, TextTools, NativeCalls, looseJSON, glmCall, nameCall, toolNamed, unwrapped, traeMessages, chatBody, nativeTools, moonshotSchema, credits, dollarUsageOf, seatPoolOf, seatSpentOf, entResetOf, isEnterprise, yuan, whenOf, newDevice, ugDevice, proofOf, SITES, SESSION, conversationID, LEVELS, levelsOf, variantsOf, effortOf, offered, traeRateOf } +export const _internal = { chatModel, ownClient, clientStoragePaths, clientDevice, clientProfiles, deviceNote, clientDecode, thisMachine, traeHost, accountOf, HOSTS: SITES["trae-cn"].hosts, MODELS: SITES["trae-cn"].models, TextTools, NativeCalls, looseJSON, glmCall, nameCall, toolNamed, unwrapped, traeMessages, chatBody, nativeTools, moonshotSchema, credits, dollarUsageOf, seatPoolOf, seatSpentOf, entResetOf, isEnterprise, yuan, whenOf, newDevice, ugDevice, proofOf, SITES, SESSION, conversationID, LEVELS, levelsOf, variantsOf, effortOf, offered, traeRateOf } diff --git a/packages/trae/package.json b/packages/trae/package.json index d4c0abe..71a888e 100644 --- a/packages/trae/package.json +++ b/packages/trae/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-trae-auth", - "version": "0.2.40", + "version": "0.2.41", "description": "OpenCode provider plugins for Trae: Trae CN (trae.cn) and Trae Global (trae.ai), free tier included, with Trae's own browser sign-in", "type": "module", "main": "./opencode.mjs",