diff --git a/packages/trae/README.md b/packages/trae/README.md index 769a8ab..a40ecc9 100644 --- a/packages/trae/README.md +++ b/packages/trae/README.md @@ -69,6 +69,18 @@ agent's `POST https://trae-api-cn.mchost.guru/api/agent/v3/llm_utils_chat`: `solo_work_lite`, SOLO's Work mode; `solo_agent`, the TRAE agent's; `solo_agent_lite`). If Trae answers 4001, 4023 or 1005, the plugin tries the others once and remembers which one worked. + - `session_id` is the conversation's, as the IDE keeps one per conversation: + the session magpie (or OpenCode) names the request by, else the chat's + first user message, which every later turn repeats, together with the + account the request is made as. Trae counts a conversation by it, so a + fresh one per request made one user send that takes several steps (a tool + result sent back, a retry, another function answering) count as a + conversation of its own — several rows in the usage detail, each under no + title. One conversation answered by two accounts (magpie failing over, or + rotating, inside it) is named twice then, as two conversations, so Trae + never reads one account's conversation as another's; that costs the two + halves of such a conversation their single row. `request_id` is the + request's own, fresh on every one. - **Headers:** TRAE SOLO CN 0.1.69's (`x-ide-version`/`x-app-version` 0.1.69, version code 20260917; Trae offers a model only to clients new enough for it): `Authorization: Cloud-IDE-JWT …`, `X-Cloudide-Token`, diff --git a/packages/trae/conversation.test.mjs b/packages/trae/conversation.test.mjs new file mode 100644 index 0000000..9b72410 --- /dev/null +++ b/packages/trae/conversation.test.mjs @@ -0,0 +1,120 @@ +// One conversation keeps one session_id: Trae counts a conversation by the +// session its requests name, so a request naming a new session each time is +// counted as a conversation of its own — one user send that takes several +// steps shows up in the usage detail as several rows, each under no title. +// The session comes from magpie's (or OpenCode's) session for the request +// when it names one, else from the chat's first user message. +import "./nonet.mjs" +import { afterEach, expect, test } from "bun:test" +import { TraeCNAuthPlugin, _internal } from "./index.mjs" +import { fakeTrae, sse, signedIn } from "./fake.mjs" + +let f +afterEach(() => f?.close()) + +const { SESSION } = _internal + +// ask sends a chat as magpie's host does: the chat.headers hook is told the +// session, then the loader's fetch with what it added, and the request Trae +// was sent is read back. auth is the sign-in the loader asks for, which is +// what a group of accounts answers with, one of them per request. +async function ask(chat, { session = "", provider = "trae-cn", auth = signedIn() } = {}) { + const hooks = await TraeCNAuthPlugin({ client: {} }) + const out = { headers: {} } + await hooks["chat.headers"]({ sessionID: session, model: { providerID: provider, id: "glm-5" }, provider: { info: { id: provider } } }, out) + const opts = await hooks.auth.loader(async () => auth) + const res = await opts.fetch(opts.baseURL + "/chat/completions", { + method: "POST", + headers: new Headers(out.headers), + body: JSON.stringify(chat), + }) + expect(res.status).toBe(200) + return { sent: f.seen.at(-1), out } +} + +const chat = (...messages) => ({ model: "glm-5", stream: true, messages }) +const user = (t) => ({ role: "user", content: [{ type: "text", text: t }] }) +const assistant = (t) => ({ role: "assistant", content: [{ type: "text", text: t }] }) +const call = { role: "assistant", content: [], tool_calls: [{ id: "c1", type: "function", function: { name: "read", arguments: "{}" } }] } +const result = { role: "tool", tool_call_id: "c1", content: "a.go" } +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/ +const serve = () => { + f = fakeTrae() + f.route("POST /api/agent/v3/llm_utils_chat", () => sse([["output", { response: "ok" }], ["done", {}]])) +} + +test("one send's steps carry one session_id; each request still has its own", async () => { + serve() + const first = await ask(chat(user("fix the bug"))) + const called = await ask(chat(user("fix the bug"), call)) + const answered = await ask(chat(user("fix the bug"), call, result)) + const ids = [first, called, answered].map((x) => x.sent.json.session_id) + expect(ids[0]).toMatch(UUID) + expect(new Set(ids).size).toBe(1) + // request_id is the request's own: each step has one of its own + const reqs = [first, called, answered].map((x) => x.sent.json.request_id) + expect(new Set(reqs).size).toBe(3) + for (const r of reqs) expect(r).toMatch(UUID) + // the session header itself goes no further + for (const x of [first, called, answered]) expect(x.sent.headers.get(SESSION)).toBe(null) +}) + +test("the next user message and another conversation are other sessions", async () => { + serve() + const first = await ask(chat(user("fix the bug"))) + const next = await ask(chat(user("fix the bug"), assistant("ok"), user("and then?"))) + expect(next.sent.json.session_id).toBe(first.sent.json.session_id) + const other = await ask(chat(user("something else"))) + expect(other.sent.json.session_id).not.toBe(first.sent.json.session_id) +}) + +test("the session magpie names wins over the chat's own first message", async () => { + serve() + const named = await ask(chat(user("hi")), { session: "ses_1" }) + const again = await ask(chat(user("hi"), assistant("ok"), user("more")), { session: "ses_1" }) + expect(again.sent.json.session_id).toBe(named.sent.json.session_id) + // the same words under another session are another conversation + const other = await ask(chat(user("hi")), { session: "ses_2" }) + expect(other.sent.json.session_id).not.toBe(named.sent.json.session_id) + // and the session header is not sent to Trae + expect(named.sent.headers.get(SESSION)).toBe(null) +}) + +test("nothing names a conversation: a fresh session per request, as before", async () => { + serve() + const one = await ask(chat({ role: "system", content: "be brief" })) + const two = await ask(chat({ role: "system", content: "be brief" })) + expect(one.sent.json.session_id).not.toBe(two.sent.json.session_id) +}) + +test("two accounts of one conversation are two conversations to Trae", async () => { + serve() + const named = await ask(chat(user("hi")), { session: "ses_1", auth: signedIn() }) + const other = await ask(chat(user("hi")), { session: "ses_1", auth: signedIn({ uid: "u-2", accountId: "Bob" }) }) + expect(other.sent.json.session_id).not.toBe(named.sent.json.session_id) + // each account's own conversation keeps its own id, so failing over + // back mid-conversation doesn't split it + const again = await ask(chat(user("hi"), assistant("ok"), user("more")), { session: "ses_1", auth: signedIn() }) + expect(again.sent.json.session_id).toBe(named.sent.json.session_id) + // and the same holds when the conversation is named by the chat itself + const first = await ask(chat(user("fix the bug")), { auth: signedIn() }) + const onOther = await ask(chat(user("fix the bug")), { auth: signedIn({ uid: "u-2", accountId: "Bob" }) }) + expect(onOther.sent.json.session_id).not.toBe(first.sent.json.session_id) + // an account named by its name alone (no uid) is one of its own too + const namedOnly = await ask(chat(user("hi")), { session: "ses_1", auth: signedIn({ uid: "", accountId: "Bob" }) }) + expect(namedOnly.sent.json.session_id).not.toBe(named.sent.json.session_id) +}) + +test("one account's two conversations stay two", async () => { + serve() + const one = await ask(chat(user("fix the bug")), { session: "ses_1" }) + const two = await ask(chat(user("fix the bug")), { session: "ses_2" }) + expect(two.sent.json.session_id).not.toBe(one.sent.json.session_id) +}) + +test("the hook leaves other providers' requests alone", async () => { + const hooks = await TraeCNAuthPlugin({ client: {} }) + const out = { headers: {} } + await hooks["chat.headers"]({ sessionID: "ses_1", model: { providerID: "trae-global" }, provider: { info: { id: "trae-global" } } }, out) + expect(out.headers).toEqual({}) +}) diff --git a/packages/trae/index.mjs b/packages/trae/index.mjs index 36c82c1..8e1bb77 100644 --- a/packages/trae/index.mjs +++ b/packages/trae/index.mjs @@ -9,7 +9,7 @@ // The account's fetch also sends Trae CN's own pages on api.trae.cn // (/trae/api/…) as the account, for magpie's daily check-in (每日签到: // /trae/api/v2/ug/checkin_credits/status, then /claim). -import { generateKeyPairSync, randomBytes, randomUUID, randomInt, sign } from "node:crypto" +import { createHash, generateKeyPairSync, randomBytes, randomUUID, randomInt, sign } from "node:crypto" import { createServer, STATUS_CODES } from "node:http" const SITES = { @@ -767,14 +767,72 @@ const nativeTools = (tools) => return { type: "function", function: { name: f.name, description: f.description ?? "", parameters: typeof f.parameters === "string" ? f.parameters : JSON.stringify(f.parameters ?? {}) } } }) +// SESSION carries the conversation magpie (or OpenCode) names a request by, +// from the chat.headers hook to the loader's fetch. It goes no further. +const SESSION = "x-magpie-trae-session" + +// SALT is what the id is derived with, so it says nothing of the words it was +// made from. New in each process, as Trae's own session ids are one session's +// own within a run. +const SALT = randomBytes(16).toString("hex") + +// conversationID is the conversation a chat belongs to, as the UUID the +// request's session_id wants: the session magpie or OpenCode names (its +// chat.headers hook), else the chat's first user message, which every later +// turn of the conversation repeats. "" when neither names one — a body that +// isn't a chat, or one with no user message in it — and the caller then makes +// a fresh id per request, as before: a made-up conversation of the request's +// own is the very splitting this is here to end. +// +// who is the account the request is made as (its uid, else its name), and it +// is part of what the id is made of, so one conversation answered by two +// accounts (magpie failing over, or rotating, inside it) is two conversations +// as Trae is concerned — an id a fresh random one never linked, and one that +// would let Trae read one conversation as another's. The cost is that such a +// conversation's two halves are counted apart again, which is what it did +// before this named one at all. +function conversationID(chat, session, who = "") { + const account = String(who ?? "").trim() + if (session) return uuidOf("magpie-trae-session|" + account + "|" + session) + const first = (Array.isArray(chat?.messages) ? chat.messages : []).find((m) => m?.role === "user") + const text = partText(first?.content ?? "") + return text.trim() ? uuidOf("magpie-trae-first|" + account + "|" + text) : "" +} + +// uuidOf is a version 4 UUID made of a hash's first 16 bytes: the shape +// randomUUID() returns, since that is what session_id carried before. +function uuidOf(s) { + const b = Buffer.from(createHash("sha256").update(SALT + "|" + s).digest().subarray(0, 16)) + b[6] = (b[6] & 0x0f) | 0x40 + b[8] = (b[8] & 0x3f) | 0x80 + const h = b.toString("hex") + return `${h.slice(0, 8)}-${h.slice(8, 12)}-${h.slice(12, 16)}-${h.slice(16, 20)}-${h.slice(20)}` +} + +// sessionOf takes the session a chat.headers hook named off the headers, with +// the header: it goes no further than here. Its length is capped as magpie's +// own session ids are, the id being derived from it anyway. +function sessionOf(headers) { + const s = String(headers.get(SESSION) ?? "").trim() + headers.delete(SESSION) + return s.slice(0, 128) +} + // chatBody is the request for llm_utils_chat; modelName is the model the // function's list names for the config (its __dev one), when it named one, // and most the max_tokens it gives that model (0: none given), which a // request asking more is held to. A Max model (max: {base, window}) asks // the config base by its __max model, max_tokens always set, and gives // the prompt the room the window has beside it, as the IDE's Max mode does. -function chatBody(req, fn, modelName, most = 0, max = null) { - const session = randomUUID() +// +// session is the conversation's id, made by conversationID, so every request +// of one conversation carries one: Trae counts a conversation by the session +// the requests name, and a request naming a new session each time is counted +// as a conversation of its own — one user send that takes several steps (a +// 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 = "") { const config = max?.base ?? req.model const body = { messages: traeMessages(req), @@ -783,8 +841,8 @@ function chatBody(req, fn, modelName, most = 0, max = null) { model: config, ...(modelName ? { model_name: modelName } : {}), stream: true, // Trae answers in SSE either way - request_id: session, - session_id: session, + request_id: randomUUID(), + session_id: session || randomUUID(), } const asked = req.max_completion_tokens ?? req.max_tokens if (Number.isFinite(asked) && asked > 0) body.max_tokens = most > 0 ? Math.min(Math.floor(asked), most) : Math.floor(asked) @@ -2078,6 +2136,14 @@ const makePlugin = (site) => async ({ client }) => { models: { ...site.models, ...(was.models ?? {}) }, } }, + // the conversation's id, which the requests below carry as their + // session_id: magpie's (or OpenCode's) session for this request, when it + // names one + "chat.headers": async (input, output) => { + const id = input?.model?.providerID ?? input?.provider?.info?.id + if (id !== site.id || !input?.sessionID) return + output.headers[SESSION] = String(input.sessionID).slice(0, 128) + }, provider: { id: site.id, // the account's own list, when Trae answers; else the list above @@ -2156,11 +2222,16 @@ const makePlugin = (site) => async ({ client }) => { if (outer.aborted) ac.abort() else outer.addEventListener("abort", () => ac.abort(), { once: true }) } + // the conversation this request belongs to, from the chat.headers + // hook (magpie's session) or the chat's own first user message, as + // the account answering it, so a failover inside one conversation + // is not one Trae reads as another's + const session = conversationID(req, sessionOf(new Headers(init.headers ?? r0?.headers ?? {})), who) for (const fn of [...new Set(fns)]) { 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)), + body: JSON.stringify(chatBody(req, fn, named?.fn === fn || max ? named.name : "", named?.fn === fn || max ? named.most : 0, max, session)), signal: ac.signal, }) if (!res.ok) { @@ -2211,4 +2282,4 @@ const makePlugin = (site) => async ({ client }) => { export const TraeCNAuthPlugin = makePlugin(SITES["trae-cn"]) export const TraeGlobalAuthPlugin = makePlugin(SITES["trae-global"]) -export const _internal = { HOSTS: SITES["trae-cn"].hosts, MODELS: SITES["trae-cn"].models, TextTools, NativeCalls, looseJSON, glmCall, toolNamed, traeMessages, chatBody, credits, dollarUsageOf, whenOf, newDevice, proofOf, SITES } +export const _internal = { HOSTS: SITES["trae-cn"].hosts, MODELS: SITES["trae-cn"].models, TextTools, NativeCalls, looseJSON, glmCall, toolNamed, traeMessages, chatBody, credits, dollarUsageOf, whenOf, newDevice, proofOf, SITES, SESSION, conversationID } diff --git a/packages/trae/package.json b/packages/trae/package.json index f594dc8..e2590b2 100644 --- a/packages/trae/package.json +++ b/packages/trae/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-trae-auth", - "version": "0.2.5", + "version": "0.2.6", "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",