From 9fd59cf6e83c0f456239b5f3fd605896e77a6859 Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 16 Oct 2026 15:40:40 +0800 Subject: [PATCH] trae 0.2.15: a model Trae's list marks multimodal takes images, and they reach it (#161) Reported on magpie's Discord (#help): through magpie, Trae CN's doubao model said it couldn't read images, while in Trae it reads them. Every model was listed as text-only (MODEL's modalities), and partText put "[an image, which this model can't see]" in every image's place, so no image ever reached Trae. What changed: - Trae's lists mark each entry `multimodal` true or false (config_info_list). A listed model's flag now decides capabilities.input.image, attachment and modalities, over a fallback entry's word. Doubao-Seed, Kimi K3/K2.6, Qwen 3.7 Plus and MiniMax M3 are true; GLM-5.x and DeepSeek V4 are false. - An image sent to a model that takes images goes to llm_utils_chat as an OpenAI image_url part ({url}) after the text part. That is the shape TRAE's ai-agent carries (LLMRawMultiContent/LLMRawChatImageURL, in the ai-agent binary's strings) and what autumnsentiment/Trae2api-cn passes llm_utils_chat unchanged. - A model marked false still gets the placeholder. - The fallback list marks kimi-k2.6 and qwen-3.7-plus as taking images, as Trae's SOLO list does. The list fixture is two entries of a relay's capture of the SOLO list (wangqi233/trae2api scripts/_solo-models-clean.json). Run: - images.test.mjs: 6 pass on this change; 5 of 6 fail on 0.2.14's index.mjs (only the text-only case passes there). - packages/trae: 146 tests, 0 fail. - HOME=$(mktemp -d) bun test across the repo: 1616 pass, 0 fail. - bun scripts/check.mjs: ok. Not tried: a real Trae account. Magpie's owner has none signed in, so no real image request was sent to Trae. --- packages/trae/README.md | 10 +++- packages/trae/images.test.mjs | 90 +++++++++++++++++++++++++++++++++++ packages/trae/index.mjs | 88 +++++++++++++++++++++++++++------- packages/trae/package.json | 2 +- 4 files changed, 170 insertions(+), 20 deletions(-) create mode 100644 packages/trae/images.test.mjs diff --git a/packages/trae/README.md b/packages/trae/README.md index f902233..a26af4f 100644 --- a/packages/trae/README.md +++ b/packages/trae/README.md @@ -151,7 +151,15 @@ agent's `POST https://trae-api-cn.mchost.guru/api/agent/v3/llm_utils_chat`: request's (`read`); any other goes on as written, so the agent can say the tool doesn't exist. - Earlier calls and their results go back in as text. - - Images aren't sent. + - Images: Trae's lists mark each model `multimodal` true or false (the + Doubao-Seed models, Kimi K3 and K2.6, Qwen 3.7 Plus and MiniMax M3 take + images; GLM-5 and DeepSeek V4 don't). A model marked true is listed + as one that takes images, and an image sent to it goes in the + message's content as an OpenAI `image_url` part beside the text, as + TRAE's own agent sends one (plugins#161). A model marked false gets + "[an image, which this model can't see]" in its place. A model whose + list hasn't been read is sent its images, unless the fallback list + says it takes none. The model list is the account's own, from `/api/ide/v1/batch_get_detail_param`, every function's list in one ask, as diff --git a/packages/trae/images.test.mjs b/packages/trae/images.test.mjs new file mode 100644 index 0000000..29f69e8 --- /dev/null +++ b/packages/trae/images.test.mjs @@ -0,0 +1,90 @@ +// Images (magpie's Discord: Trae CN's doubao said it can't read images +// through magpie, while it reads them in Trae). Trae's model lists mark +// each model multimodal true or false; a model marked true is told to +// magpie as one that takes images, and its images go to llm_utils_chat as +// OpenAI image_url parts, the shape TRAE's ai-agent sends +// (LLMRawMultiContent / LLMRawChatImageURL). A model marked false is still +// told there was an image it can't see. +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()) + +// two entries of TRAE SOLO CN's list as Trae sends them (the fields a +// relay's capture of the solo_agent list kept, wangqi233/trae2api +// scripts/_solo-models-clean.json), with the __dev model the request needs +const seed = { config_name: "Doubao-Seed-2.1-Pro", display_name: "Seed-2.1-Pro", capability: "reasoning_model", multimodal: true, ctx_dev: 256000, is_default: false, is_custom_model: false, usage: "chat_completion", model_detail_list: [{ model_name: "Doubao-Seed-2.1-Pro__dev" }] } +const glm = { config_name: "glm-5.3", display_name: "GLM-5.3", capability: "reasoning_model", multimodal: false, ctx_dev: 200000, is_default: false, is_custom_model: false, usage: "chat_completion", model_detail_list: [{ model_name: "glm-5.3__dev" }] } + +// a 1×1 PNG, as an agent attaches a screenshot +const PNG = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==" +const said = (text) => ({ role: "user", content: [{ type: "text", text }, { type: "image_url", image_url: { url: PNG } }] }) + +async function plugin() { + f = fakeTrae() + f.route("POST /api/ide/v1/batch_get_detail_param", () => json({ function_configs: [{ function: "chat_v3", config_info_list: [seed, glm] }] })) + f.route("POST /api/agent/v3/llm_utils_chat", () => sse([["output", { response: "a red dot" }], ["done", {}]])) + return TraeCNAuthPlugin({ client: {} }) +} + +async function ask(hooks, body) { + const opts = await hooks.auth.loader(async () => signedIn()) + const res = await opts.fetch(opts.baseURL + "/chat/completions", { method: "POST", body: JSON.stringify(body) }) + await res.text() + return f.seen.filter((r) => r.path === "/api/agent/v3/llm_utils_chat").at(-1).json +} + +test("a model Trae's list marks multimodal is one that takes images, and one marked otherwise isn't", async () => { + const ms = await (await plugin()).provider.models({ models: {} }, { auth: signedIn() }) + expect(ms["Doubao-Seed-2.1-Pro"].capabilities.input.image).toBe(true) + expect(ms["Doubao-Seed-2.1-Pro"].capabilities.attachment).toBe(true) + expect(ms["Doubao-Seed-2.1-Pro"].modalities.input).toEqual(["text", "image"]) + expect(ms["glm-5.3"].capabilities.input.image).toBe(false) + expect(ms["glm-5.3"].capabilities.attachment).toBe(false) +}) + +test("the list's word wins over a fallback entry's capabilities", async () => { + const was = { capabilities: { reasoning: true, temperature: true, toolcall: true, attachment: false, + input: { text: true, image: false, audio: false, video: false, pdf: false }, + output: { text: true, image: false, audio: false, video: false, pdf: false } } } + const ms = await (await plugin()).provider.models({ models: { "Doubao-Seed-2.1-Pro": was } }, { auth: signedIn() }) + expect(ms["Doubao-Seed-2.1-Pro"].capabilities.input).toEqual({ text: true, image: true, audio: false, video: false, pdf: false }) +}) + +test("a multimodal model's image goes to Trae as an image_url part beside the text", async () => { + const hooks = await plugin() + await hooks.provider.models({ models: {} }, { auth: signedIn() }) + const b = await ask(hooks, { model: "Doubao-Seed-2.1-Pro", stream: true, messages: [said("what is this?")] }) + expect(b.messages).toEqual([{ role: "user", content: [{ type: "text", text: "what is this?" }, { type: "image_url", image_url: { url: PNG } }] }]) + expect(JSON.stringify(b)).not.toContain("can't see") +}) + +test("a model Trae marks text-only is told of the image, not sent it", async () => { + const hooks = await plugin() + await hooks.provider.models({ models: {} }, { auth: signedIn() }) + const b = await ask(hooks, { model: "glm-5.3", stream: true, messages: [said("what is this?")] }) + expect(b.messages).toEqual([{ role: "user", content: [{ type: "text", text: "what is this?\n[an image, which this model can't see]" }] }]) +}) + +test("an image alone, a tool's image and two user turns in a row keep every image in order", () => { + const m = _internal.traeMessages({ messages: [ + { role: "user", content: [{ type: "image_url", image_url: { url: PNG } }] }, + { role: "user", content: [{ type: "text", text: "and this" }, { type: "image_url", image_url: "https://example.invalid/b.png" }] }, + { role: "assistant", content: null, tool_calls: [{ id: "c1", type: "function", function: { name: "shot", arguments: "{}" } }] }, + { role: "tool", tool_call_id: "c1", content: [{ type: "text", text: "taken" }, { type: "image_url", image_url: { url: PNG } }] }, + ] }, true) + expect(m.map((x) => x.role)).toEqual(["user", "assistant", "user"]) + expect(m[0].content).toEqual([{ type: "text", text: "and this" }, { type: "image_url", image_url: { url: PNG } }, { type: "image_url", image_url: { url: "https://example.invalid/b.png" } }]) + expect(m[2].content).toEqual([{ type: "text", text: "Result of shot (call c1):\ntaken" }, { type: "image_url", image_url: { url: PNG } }]) +}) + +test("a fallback model that Trae marks multimodal is sent its images before the list is read", async () => { + f = fakeTrae() + f.route("POST /api/agent/v3/llm_utils_chat", () => sse([["output", { response: "ok" }], ["done", {}]])) + const hooks = await TraeCNAuthPlugin({ client: {} }) + expect((await ask(hooks, { model: "kimi-k2.6", stream: true, messages: [said("see")] })).messages[0].content[1]).toEqual({ type: "image_url", image_url: { url: PNG } }) + expect((await ask(hooks, { model: "glm-5", stream: true, messages: [said("see")] })).messages[0].content).toEqual([{ type: "text", text: "see\n[an image, which this model can't see]" }]) +}) diff --git a/packages/trae/index.mjs b/packages/trae/index.mjs index 74832f1..5703c19 100644 --- a/packages/trae/index.mjs +++ b/packages/trae/index.mjs @@ -15,6 +15,10 @@ import { createServer, STATUS_CODES } from "node:http" import { homedir, release, version as osVersion } from "node:os" import { join } from "node:path" +// SEES is a fallback model that takes images, as Trae's lists mark it +// (multimodal: true) +const SEES = { attachment: true, modalities: { input: ["text", "image"], output: ["text"] } } + const SITES = { // Trae CN (trae.cn): the authorization page sends the browser back to a // callback on 127.0.0.1 with the account's Cloud-IDE-JWT and refresh @@ -74,8 +78,8 @@ const SITES = { models: { "glm-5.2": { name: "GLM-5.2", limit: { context: 200_000, output: 32_000 } }, "glm-5": { name: "GLM-5" }, - "kimi-k2.6": { name: "Kimi K2.6", limit: { context: 256_000, output: 0 } }, - "qwen-3.7-plus": { name: "Qwen 3.7 Plus" }, + "kimi-k2.6": { name: "Kimi K2.6", limit: { context: 256_000, output: 0 }, ...SEES }, + "qwen-3.7-plus": { name: "Qwen 3.7 Plus", ...SEES }, "DeepSeek-V4-Pro": { name: "DeepSeek V4 Pro" }, "DeepSeek-V4-Flash": { name: "DeepSeek V4 Flash" }, }, @@ -915,15 +919,36 @@ const partText = (content) => { .join("\n") } -// traeMessages is the conversation as Trae's chat takes it -function traeMessages(req) { +// imageOf is an image part of a message as Trae's chat takes one: OpenAI's +// image_url part, {url} in it, which is what TRAE's ai-agent sends +// (LLMRawMultiContent's image_url, LLMRawChatImageURL) and what the +// open-source relays pass llm_utils_chat unchanged. null for a part that +// isn't an image, or one with no url. +function imageOf(p) { + if (p?.type !== "image_url" && p?.type !== "input_image") return null + const url = typeof p.image_url === "string" ? p.image_url : p.image_url?.url ?? p.url + return typeof url === "string" && url ? { type: "image_url", image_url: { url } } : null +} + +// partsOf is a message's text and, for a model that sees, its images apart +// from it; a model that doesn't is told in the text that one was there +const partsOf = (content, sees) => { + if (!sees || !Array.isArray(content)) return { text: partText(content), images: [] } + const images = content.map(imageOf).filter(Boolean) + return { text: partText(content.filter((p) => !imageOf(p))), images } +} + +// traeMessages is the conversation as Trae's chat takes it. sees is whether +// the model takes images: Trae's list says so of each model (multimodal), +// and a model it says doesn't is sent the placeholder, not the image. +function traeMessages(req, sees = false) { const tools = Array.isArray(req.tools) && req.tools.length && req.tool_choice !== "none" ? req.tools : [] const names = new Map() const out = [] if (tools.length) out.push({ role: "system", text: toolPrompt(tools, req.tool_choice, req.parallel_tool_calls) }) for (const m of req.messages ?? []) { const role = m.role === "developer" ? "system" : m.role - let text = partText(m.content) + let { text, images } = partsOf(m.content, sees) if (role === "assistant") { const calls = (m.tool_calls ?? []).map((c) => { names.set(c.id, c.function?.name) @@ -936,20 +961,24 @@ function traeMessages(req) { text = [text, ...calls].filter(Boolean).join("\n") out.push({ role: "assistant", text }) } else if (role === "tool") { - out.push({ role: "user", text: `Result of ${names.get(m.tool_call_id) || m.name || "the tool"} (call ${m.tool_call_id ?? "?"}):\n${text}` }) + out.push({ role: "user", text: `Result of ${names.get(m.tool_call_id) || m.name || "the tool"} (call ${m.tool_call_id ?? "?"}):\n${text}`, images }) } else { - out.push({ role: role === "system" ? "system" : "user", text }) + out.push({ role: role === "system" ? "system" : "user", text, images }) } } - // Trae takes no empty message, nor two of one role in a row + // Trae takes no empty message, nor two of one role in a row; a message of + // an image alone is not empty const merged = [] for (const m of out) { - if (!m.text) continue + const images = m.images ?? [] + if (!m.text && !images.length) continue const last = merged.at(-1) - if (last && last.role === m.role && m.role !== "system") last.text += "\n\n" + m.text - else merged.push({ ...m }) + if (last && last.role === m.role && m.role !== "system") { + last.text = [last.text, m.text].filter(Boolean).join("\n\n") + last.images = [...last.images, ...images] + } else merged.push({ role: m.role, text: m.text, images }) } - return merged.map((m) => ({ role: m.role, content: [{ type: "text", text: m.text }] })) + return merged.map((m) => ({ role: m.role, content: [...(m.text ? [{ type: "text", text: m.text }] : []), ...m.images] })) } // nativeTools are the tools as Trae names them: parameters a JSON string @@ -1024,10 +1053,10 @@ function sessionOf(headers) { // tool result sent back, a retry, another function answering) shows up in the // usage detail as several, each under no title at all. request_id stays a // fresh id per request, being that request's own. -function chatBody(req, fn, modelName, most = 0, max = null, session = "") { +function chatBody(req, fn, modelName, most = 0, max = null, session = "", sees = false) { const config = max?.base ?? req.model const body = { - messages: traeMessages(req), + messages: traeMessages(req, sees), function: fn, config_name: config, model: config, @@ -2270,6 +2299,12 @@ function chatModel(m, site) { return true } +// seesOf is whether a list's entry says its model takes images: Trae's +// lists mark each one multimodal true or false (Doubao-Seed, Kimi K3, +// Qwen 3.7 Plus take them; GLM-5 and DeepSeek V4 don't). null when the +// entry doesn't say. +const seesOf = (m) => (typeof m?.multimodal === "boolean" ? m.multimodal : typeof m?.display_config?.multimodal === "boolean" ? m.display_config.multimodal : null) + // devModel is the model an entry serves requests with: its __dev one const devModel = (m) => (Array.isArray(m?.model_detail_list) ? m.model_detail_list : []).find((d) => /__dev$/.test(String(d?.model_name ?? ""))) @@ -2352,6 +2387,8 @@ const makePlugin = (site) => async ({ client }) => { const modelNames = new Map() // the Max each model the list last read has (null: none) const maxes = new Map() + // whether each model the list last read takes images (its multimodal) + const sight = new Map() const save = async (auth) => { try { @@ -2595,6 +2632,9 @@ const makePlugin = (site) => async ({ client }) => { } for (const [id, { m, fn }] of out) { listedBy.set(id, fn) + const sees = seesOf(m) + if (sees === null) sight.delete(id) + else sight.set(id, sees) const dev = devModel(m) if (dev) modelNames.set(id, { fn, name: dev.model_name, most: Number(dev.max_tokens) || 0 }) else modelNames.delete(id) @@ -2633,16 +2673,24 @@ const makePlugin = (site) => async ({ client }) => { const out = Number(devModel(m)?.max_tokens) || was.limit?.output || 0 const name = m.display_config?.display_name || m.display_name || m.display_model_name || was.name || id const input = (k) => (MODEL.modalities?.input ?? []).includes(k) + // the list's multimodal says whether the model takes images, over the + // fallback list's word and MODEL's + const sees = seesOf(m) + const inputs = was.capabilities?.input ?? { text: true, image: input("image"), audio: input("audio"), video: input("video"), pdf: input("pdf") } + const sight = sees === null ? {} : { + modalities: { input: [...new Set([...((was.modalities ?? MODEL.modalities).input ?? ["text"]).filter((k) => k !== "image"), ...(sees ? ["image"] : [])])], output: (was.modalities ?? MODEL.modalities).output ?? ["text"] }, + attachment: sees, + } return { - ...MODEL, ...was, id, providerID: site.id, name: String(name), limit: { context: ctx, output: out }, + ...MODEL, ...was, ...sight, id, providerID: site.id, name: String(name), limit: { context: ctx, output: out }, api: was.api ?? { id, url: site.hosts.api, npm: "@ai-sdk/openai-compatible" }, capabilities: { ...(was.capabilities ?? {}), reasoning: was.capabilities?.reasoning ?? MODEL.reasoning, temperature: was.capabilities?.temperature ?? MODEL.temperature, - attachment: was.capabilities?.attachment ?? MODEL.attachment, + attachment: sees ?? was.capabilities?.attachment ?? MODEL.attachment, toolcall: was.capabilities?.toolcall ?? MODEL.tool_call, - input: was.capabilities?.input ?? { text: true, image: input("image"), audio: input("audio"), video: input("video"), pdf: input("pdf") }, + input: sees === null ? inputs : { ...inputs, image: sees }, output: was.capabilities?.output ?? { text: true, image: false, audio: false, video: false, pdf: false }, }, // Trae's request takes no effort or thinking level, so a model has @@ -2739,6 +2787,10 @@ const makePlugin = (site) => async ({ client }) => { if (named) fns.unshift(named.fn) } const max = named?.max ?? null + // a model the list hasn't said of is sent its images: the agent + // sends them only to a model it was told takes them + const base = max?.base ?? String(req.model) + const sees = sight.get(base) ?? (site.models[base]?.modalities?.input?.includes("image") ?? true) // the answer's own signal: the caller's abort (a cancelled // request) and the stream's cancel both stop Trae's fetch, so // no read is left hanging on a connection the agent walked @@ -2758,7 +2810,7 @@ const makePlugin = (site) => async ({ client }) => { const res = await fetch(apiOf(a, site) + "/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)), + body: JSON.stringify(chatBody(req, fn, named?.fn === fn || max ? named.name : "", named?.fn === fn || max ? named.most : 0, max, session, sees)), signal: ac.signal, }) if (!res.ok) { diff --git a/packages/trae/package.json b/packages/trae/package.json index 99f402a..d490998 100644 --- a/packages/trae/package.json +++ b/packages/trae/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-trae-auth", - "version": "0.2.14", + "version": "0.2.15", "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": "./index.mjs",