From ea805ecc921feab3fac34f37560a5be87124f20e Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 19 Nov 2026 13:57:20 +0800 Subject: [PATCH] trae 0.2.45: an enterprise chat names its limit where Trae's client does, and a cut reply says length @liuyuexue2020 on X (0.2.44, Trae CN enterprise seat): their own request, volc/deepseek-v4-1-flash with max_tokens 4096, temperature 0, stream false, asking for 120 long lines. Four enterprise models (AI/deekseek-v4.1-flash, volc/deepseek-v4-1-flash, AI/deekseek-v4-flash-0731, AI/GLM-5.3-Flash) each answered exactly 2000 completion tokens, finish_reason "stop", mid-answer (24, 27 and 52 of 120 lines; deekseek-v4.1-flash no content at all). What 0.2.44 sent: top-level max_tokens = min(4096, the detail's max_tokens), so 4096 unless the list gives the model less. magpie's gateway only lowers a limit (the user's Max output, withMaxOutput) and fills one in on the Anthropic API only (askedOutput); it has no 2000. The plugin passes Trae's completion_tokens and finish_reason through, and reads the stream to Trae's done event; it doesn't cut it. Cause (inferred, no enterprise seat to measure): Trae CN 3.4.22's own client never sends llm_utils_chat a max_tokens (its request struct in libharness has none), and its agent task carries an enterprise model's limit as enterprise_custom_hyper_params {max_tokens, prompt_max_tokens, multimodal} beside config_source and is_custom_model (AgentSpec, CreateTaskRequest). So Trae most likely ignores the top-level max_tokens for an enterprise model and gives it 2000, and says "stop" when it cuts. The other reading, the list giving these models max_tokens 2000, would show as 2000 output in /v1/models; the reporter is asked for it. Now: - an enterprise model's chat also sends enterprise_custom_hyper_params (max_tokens as sent, the detail's prompt_max_tokens, multimodal from the list) when a limit is known; the top-level max_tokens stays. A preset gets nothing new. - a reply Trae ends with "stop" or no reason, having used every token it was let have (the max_tokens sent, or 2000 for an enterprise model), finishes "length" in a body and in a stream, so the agent knows it was cut. Tool calls, content_filter and shorter replies are unchanged; a preset's 2000 isn't taken for a cut. Tests (entmodels.test.mjs), from the reporter's request: a fake Trae that reads the limit from enterprise_custom_hyper_params only and cuts at 2000 with "stop". On 0.2.44's index.mjs all three new tests are red (3100 expected, 2000 received; "length" expected, "stop" received). Not tried: a real enterprise seat (none here). Whether Trae honours enterprise_custom_hyper_params on llm_utils_chat is read from the binary, not measured; if it doesn't, the reply is still cut at 2000 but now says length. Siblings: Trae CN and Trae international share chatBody and openai(); SOLO functions too. Run (mica, HOME=$(mktemp -d), this tree on 67fb1258; mote was over its cores): packages/trae bun test: 290 pass, 0 fail (24 files); bun scripts/check.mjs trae: ok; root bun test: 9060 pass, 3 fail, 20 skip (636 files, 533s). The 3 reds are in untouched packages and pass alone at once (agent-office jump.test 12/12, doubao-work 59/59): agent-office's jumpRequest is #642, doubao-work's two are filed as #1350. Broken by hand: 0.2.44's index.mjs with these tests, 3 of 13 red in entmodels.test.mjs (above). --- packages/trae/README.md | 10 ++++- packages/trae/entmodels.test.mjs | 70 ++++++++++++++++++++++++++++++++ packages/trae/index.mjs | 47 ++++++++++++++++++--- packages/trae/package.json | 2 +- 4 files changed, 121 insertions(+), 8 deletions(-) diff --git a/packages/trae/README.md b/packages/trae/README.md index 98b2b14..8276c27 100644 --- a/packages/trae/README.md +++ b/packages/trae/README.md @@ -259,7 +259,15 @@ output the `__dev` model's `max_tokens` (an enterprise model's own detail's, since 0.2.44). That `max_tokens` is sent with every chat, the agent's limit held to it and it sent when the agent names none, as Trae's own client sends the model's `max_tokens` with each model: asked with none, an -enterprise seat's replies stopped at exactly 2000 output tokens (0.2.43). A model with a `__max` model and +enterprise seat's replies stopped at exactly 2000 output tokens (0.2.43). +They still did on 0.2.44 with `max_tokens` 4096 asked, so since 0.2.45 an +enterprise model's limit also goes in `enterprise_custom_hyper_params` +(`max_tokens`, the detail's `prompt_max_tokens`, `multimodal`), where Trae +CN 3.4.22's own agent task puts it — read from the binary, **not verified +with a real enterprise seat**. A reply Trae ends with "stop" (or no reason) +after using every token it was let have — the `max_tokens` sent, or 2000 +for an enterprise model — ends with `finish_reason: "length"`, so an agent +knows it was cut. 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 `max_tokens`; the two can come from different functions' lists (chat_v3 diff --git a/packages/trae/entmodels.test.mjs b/packages/trae/entmodels.test.mjs index 99295c3..f83005d 100644 --- a/packages/trae/entmodels.test.mjs +++ b/packages/trae/entmodels.test.mjs @@ -188,3 +188,73 @@ test("a preset asked with no limit is sent its __dev max_tokens, as Trae's clien // a function whose list doesn't name the model's __dev detail: nothing known, nothing sent expect("max_tokens" in _internal.chatBody(req, "solo_agent", "", 0, null, "s", false, null, preset)).toBe(false) }) + +// the reporter's next case (@liuyuexue2020 on X, 0.2.44), their own request: +// volc/deepseek-v4-1-flash asked for 120 long lines with max_tokens 4096 and +// stream false. Four enterprise models each answered exactly 2000 +// completion tokens with finish_reason "stop", mid-answer. The fake is Trae +// as inferred from its client (libharness 3.4.22): an enterprise model's +// limit is read from enterprise_custom_hyper_params, a top-level max_tokens +// is not, and a reply cut at the limit still says "stop". +const LINE = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" +const theirAsk = { model: "volc/deepseek-v4-1-flash", messages: [{ role: "user", content: `Generate exactly 120 numbered lines. Each line must be in this format: LINE-001: ${LINE}. Continue through LINE-120. Do not summarize, do not explain, and do not stop early.` }], max_tokens: 4096, temperature: 0, stream: false } +const cutAt = (r) => r.json.enterprise_custom_hyper_params?.max_tokens || 2000 +const answer = (out, finish = "stop") => sse([["output", { response: "LINE-001: " + LINE }], ["done", { finish_reason: finish, usage: { prompt_tokens: 80, completion_tokens: out } }]]) + +test("an enterprise model's chat names its limit in enterprise_custom_hyper_params, as Trae's client does", async () => { + const hooks = await plugin([preset, ...listed.map((m) => ({ ...m, multimodal: false, model_detail_list: m.model_detail_list.map((d) => ({ ...d, prompt_max_tokens: 120000 })) }))]) + await hooks.provider.models({ models: {} }, { auth: signedIn() }) + f.route("POST /api/agent/v3/llm_utils_chat", (r) => answer(Math.min(cutAt(r), 3100))) + const opts = await hooks.auth.loader(async () => signedIn()) + const res = await opts.fetch(opts.baseURL + "/chat/completions", { method: "POST", body: JSON.stringify(theirAsk) }) + expect(res.status).toBe(200) + const b = await res.json() + expect(b.usage.completion_tokens).toBe(3100) + expect(b.choices[0].finish_reason).toBe("stop") + const sent = f.seen.filter((r) => r.path === "/api/agent/v3/llm_utils_chat").at(-1).json + expect(sent.max_tokens).toBe(4096) + expect(sent.enterprise_custom_hyper_params).toEqual({ max_tokens: 4096, prompt_max_tokens: 120000, multimodal: false }) + // a preset is sent no enterprise params + expect("enterprise_custom_hyper_params" in _internal.chatBody({ model: "glm-5", messages: [], max_tokens: 4096 }, "chat_v3", "glm-5__dev", 32000, null, "s", false, null, preset)).toBe(false) + // nor an enterprise model with no limit known + const bare = { ...listed[0], model_detail_list: [{ model_name: "deekseek-v4.1-flash", provider: "AI" }] } + expect("enterprise_custom_hyper_params" in _internal.chatBody({ model: bare.config_name, messages: [] }, "chat_v3", "", 0, null, "s", false, null, bare)).toBe(false) +}) + +test("a reply Trae cut at its limit ends for length, not stop, in a body and in a stream", async () => { + const hooks = await plugin([preset, ...listed]) + await hooks.provider.models({ models: {} }, { auth: signedIn() }) + let out = 2000 + f.route("POST /api/agent/v3/llm_utils_chat", () => answer(out)) + const opts = await hooks.auth.loader(async () => signedIn()) + const ask = async (extra) => { + const res = await opts.fetch(opts.baseURL + "/chat/completions", { method: "POST", body: JSON.stringify({ ...theirAsk, ...extra }) }) + expect(res.status).toBe(200) + if (!extra.stream) return (await res.json()).choices[0].finish_reason + const lines = (await res.text()).split("\n").filter((l) => l.startsWith("data: ") && l !== "data: [DONE]").map((l) => JSON.parse(l.slice(6))) + return lines.map((x) => x.choices?.[0]?.finish_reason).filter(Boolean) + } + // Trae's own 2000, whatever was asked + expect(await ask({})).toBe("length") + expect(await ask({ stream: true })).toEqual(["length"]) + // the limit sent, used up + out = 1000 + expect(await ask({ max_tokens: 1000 })).toBe("length") + // a reply that ended short of both is whole + out = 1999 + expect(await ask({})).toBe("stop") + expect(await ask({ stream: true })).toEqual(["stop"]) + // a preset's reply of exactly 2000 under a bigger limit was not seen cut + out = 2000 + expect(await ask({ model: "glm-5" })).toBe("stop") +}) + +test("cutFinish keeps what Trae said of a reply it didn't cut", () => { + const u = (c) => ({ completion_tokens: c }) + expect(_internal.cutFinish("stop", u(2000), 4096, _internal.TRAE_CUT)).toBe("length") + expect(_internal.cutFinish("", u(2000), 4096, _internal.TRAE_CUT)).toBe("length") + expect(_internal.cutFinish("stop", u(2000), 4096, 0)).toBe("stop") + expect(_internal.cutFinish("content_filter", u(2000), 4096, _internal.TRAE_CUT)).toBe("content_filter") + expect(_internal.cutFinish("stop", u(4096), 4096, 0)).toBe("length") + expect(_internal.cutFinish("stop", null, 4096, _internal.TRAE_CUT)).toBe("stop") +}) diff --git a/packages/trae/index.mjs b/packages/trae/index.mjs index 5969ffb..47a06ae 100644 --- a/packages/trae/index.mjs +++ b/packages/trae/index.mjs @@ -1676,6 +1676,22 @@ function chatBody(req, fn, modelName, most = 0, max = null, session = "", sees = if (!body.model_name && detail?.model_name) body.model_name = String(detail.model_name) const provider = entry.provider || detail?.provider if (provider) body.provider = String(provider) + // the reply limit again, where Trae's own client puts it for an + // enterprise model: its agent task (libharness 3.4.22, AgentSpec and + // CreateTaskRequest) carries enterprise_custom_hyper_params + // {max_tokens, prompt_max_tokens, multimodal} beside config_source and + // is_custom_model, and no top-level max_tokens. 0.2.44 sent the top-level + // one only, and the reporter's seat still stopped at exactly 2000 with + // max_tokens 4096 asked, on four models (@liuyuexue2020 on X). Inferred + // from the binary, not measured: no enterprise seat to try it on. + if (body.max_tokens > 0) { + const hyper = { max_tokens: body.max_tokens } + const prompt = Number(detail?.prompt_max_tokens) || 0 + if (prompt > 0) hyper.prompt_max_tokens = prompt + const sees = seesOf(entry) + if (sees !== null) hyper.multimodal = sees + body.enterprise_custom_hyper_params = hyper + } } if (typeof req.temperature === "number") body.temperature = req.temperature if (Array.isArray(req.tools) && req.tools.length && req.tool_choice !== "none") { @@ -2863,6 +2879,24 @@ function done(a) { // any other is queueing, metadata or timing const ANSWER = new Set(["", "output", "message", "delta", "content", "text", "answer", "chunk", "output_delta", "message_delta"]) +// TRAE_CUT is the reply length Trae stops an enterprise model's chat at +// whatever limit it is asked for: four models of one seat each answered +// exactly 2000 completion tokens, finish_reason "stop", mid-sentence, with +// max_tokens 4096 asked (@liuyuexue2020 on X, 0.2.44) +const TRAE_CUT = 2000 + +// cutFinish is the finish an answer that came to its limit ends with: Trae +// says "stop" (or nothing) of a reply it cut, so an agent took a half +// answer for a whole one. A reply that used every token it was let have +// (limit, the max_tokens sent; or cut, Trae's own TRAE_CUT for an +// enterprise model, 0 for a preset, which wasn't seen cut) ended for length. +function cutFinish(finish, usage, limit, cut = 0) { + if (finish && finish !== "stop") return finish + const c = Number(usage?.completion_tokens) || 0 + if (c > 0 && ((limit > 0 && c >= limit) || (cut > 0 && c === cut))) return "length" + return finish +} + // finishOf is OpenAI's finish_reason for the one Trae's last event gives, // "" for none it says or one it has no word for function finishOf(d) { @@ -3006,7 +3040,7 @@ function failure(site, status, code, message, ctx = "") { // moment the agent goes away (a tool call made, a request cancelled): a // generator's return can't break a read that is already waiting, so the // fetch itself is what has to be stopped -async function openai(req, it, abort, site) { +async function openai(req, it, abort, site, limit = 0, cut = 0) { const id = "chatcmpl-" + randomBytes(12).toString("hex") const created = Math.floor(Date.now() / 1000) const model = req.model @@ -3027,7 +3061,7 @@ async function openai(req, it, abort, site) { const message = { role: "assistant", content: text || (calls.length ? null : "") } if (reasoning) message.reasoning_content = reasoning if (calls.length) message.tool_calls = calls.map((c) => ({ id: c.id, type: "function", function: { name: c.name, arguments: c.arguments } })) - const body = { id, object: "chat.completion", created, model, choices: [{ index: 0, message, finish_reason: calls.length ? "tool_calls" : finish || "stop" }] } + const body = { id, object: "chat.completion", created, model, choices: [{ index: 0, message, finish_reason: calls.length ? "tool_calls" : cutFinish(finish, usage, limit, cut) || "stop" }] } if (usage) body.usage = usage return new Response(JSON.stringify(body), { status: 200, headers: { "content-type": "application/json" } }) } @@ -3065,7 +3099,7 @@ async function openai(req, it, abort, site) { if (p.finish) finish = p.finish } if (!failed) { - put(chunk({}, calls ? "tool_calls" : finish || "stop")) + put(chunk({}, calls ? "tool_calls" : cutFinish(finish, usage, limit, cut) || "stop")) if (usage) put(enc.encode(`data: ${JSON.stringify({ id, object: "chat.completion.chunk", created, model, choices: [], usage })}\n\n`)) } } catch (e) { @@ -4285,10 +4319,11 @@ const makePlugin = (site) => async ({ client }) => { let refused = false for (const fn of [...new Set(fns)]) { tried.push(fn) + const sent = chatBody(req, fn, named?.fn === fn || max ? named.name : "", named?.fn === fn || max ? named.most : 0, max, session, sees, levels, entry) 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, entry)), + body: JSON.stringify(sent), signal: ac.signal, }) if (!res.ok) { @@ -4332,7 +4367,7 @@ const makePlugin = (site) => async ({ client }) => { break } fnOf.set(who, fn) - const out = await openai(req, done ? held : chain(held, it), () => ac.abort(), site) + const out = await openai(req, done ? held : chain(held, it), () => ac.abort(), site, sent.max_tokens || 0, enterpriseModel(entry) ? TRAE_CUT : 0) out.headers.set("X-Magpie-Sign-In", signIn) return out } @@ -4357,4 +4392,4 @@ const makePlugin = (site) => async ({ client }) => { export const TraeCNAuthPlugin = makePlugin(SITES["trae-cn"]) export const TraeGlobalAuthPlugin = makePlugin(SITES["trae-global"]) -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 } +export const _internal = { chatModel, cutFinish, TRAE_CUT, 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 3abc3b7..affe229 100644 --- a/packages/trae/package.json +++ b/packages/trae/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-trae-auth", - "version": "0.2.44", + "version": "0.2.45", "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",