diff --git a/packages/trae/README.md b/packages/trae/README.md index 540aab9..17a7c87 100644 --- a/packages/trae/README.md +++ b/packages/trae/README.md @@ -107,6 +107,10 @@ agent's `POST https://trae-api-cn.mchost.guru/api/agent/v3/llm_utils_chat`: Text under `message`, `delta` or an event with no name is the answer's too. - `token_usage`, `done` and `error` mark usage, the end and failures. + What `token_usage` says the prompt cache read and wrote + (`cache_read_input_tokens`, `cache_creation_input_tokens`) goes on under + those names, and `reasoning_tokens` as + `completion_tokens_details.reasoning_tokens`. `done`'s `finish_reason` `length`/`max_tokens` is OpenAI's `length`. - Queue events are ignored. - A `{"reasoning_content": …}` object written into the text is reasoning, diff --git a/packages/trae/cache.test.mjs b/packages/trae/cache.test.mjs new file mode 100644 index 0000000..fb07b9b --- /dev/null +++ b/packages/trae/cache.test.mjs @@ -0,0 +1,68 @@ +// What Trae's token_usage says the prompt cache read and wrote reaches +// magpie (01huadalang on magpie's Discord: K3, 53 calls, every one 0 hits). +// The event's fields are TRAE SOLO CN's own TokenUsageEvent (its ai-agent's +// serde names): name, prompt_tokens, completion_tokens, total_tokens, +// reasoning_tokens, cache_creation_input_tokens, cache_read_input_tokens, +// prompt_tokens_total, completion_tokens_total. +import "./nonet.mjs" +import { afterEach, expect, test } from "bun:test" +import { TraeCNAuthPlugin } from "./index.mjs" +import { fakeTrae, signedIn, sse } from "./fake.mjs" + +let f +afterEach(() => f?.close()) + +async function ask(body) { + const hooks = await TraeCNAuthPlugin({ client: {} }) + const opts = await hooks.auth.loader(async () => signedIn()) + return opts.fetch(opts.baseURL + "/chat/completions", { method: "POST", body: JSON.stringify(body) }) +} + +const USAGE = { + name: "kimi-k3", + prompt_tokens: 12000, + completion_tokens: 300, + total_tokens: 12300, + reasoning_tokens: 120, + cache_creation_input_tokens: 0, + cache_read_input_tokens: 11264, + prompt_tokens_total: 12000, + completion_tokens_total: 300, +} + +const want = { + prompt_tokens: 12000, + completion_tokens: 300, + total_tokens: 12300, + cache_read_input_tokens: 11264, + completion_tokens_details: { reasoning_tokens: 120 }, +} + +test("a stream's token_usage keeps what the cache read", async () => { + f = fakeTrae() + f.route("POST /api/agent/v3/llm_utils_chat", () => sse([["output", { response: "ok" }], ["token_usage", USAGE], ["done", { finish_reason: "stop" }]])) + const res = await ask({ model: "glm-5", stream: true, messages: [{ role: "user", content: "hi" }] }) + const last = (await res.text()).split("\n").filter((l) => l.startsWith("data: {")).map((l) => JSON.parse(l.slice(6))).at(-1) + expect(last.usage).toEqual(want) +}) + +test("a single answer keeps it too, and what the cache wrote", async () => { + f = fakeTrae() + f.route("POST /api/agent/v3/llm_utils_chat", () => sse([["output", { response: "ok" }], ["token_usage", { usage: { ...USAGE, cache_creation_input_tokens: 500 } }], ["done", {}]])) + const res = await ask({ model: "glm-5", messages: [{ role: "user", content: "hi" }] }) + expect((await res.json()).usage).toEqual({ ...want, cache_creation_input_tokens: 500 }) +}) + +test("OpenAI's own cache count is kept as it came", async () => { + f = fakeTrae() + f.route("POST /api/agent/v3/llm_utils_chat", () => sse([["output", { response: "ok" }], ["done", { usage: { prompt_tokens: 100, completion_tokens: 5, prompt_tokens_details: { cached_tokens: 64 } } }]])) + const res = await ask({ model: "glm-5", messages: [{ role: "user", content: "hi" }] }) + expect((await res.json()).usage).toEqual({ prompt_tokens: 100, completion_tokens: 5, total_tokens: 105, prompt_tokens_details: { cached_tokens: 64 } }) +}) + +test("no cache count adds no field", async () => { + f = fakeTrae() + f.route("POST /api/agent/v3/llm_utils_chat", () => sse([["output", { response: "ok" }], ["token_usage", { prompt_tokens: 10, completion_tokens: 5, cache_read_input_tokens: 0 }], ["done", {}]])) + const res = await ask({ model: "glm-5", messages: [{ role: "user", content: "hi" }] }) + expect((await res.json()).usage).toEqual({ prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 }) +}) diff --git a/packages/trae/index.mjs b/packages/trae/index.mjs index fb7a925..7010bae 100644 --- a/packages/trae/index.mjs +++ b/packages/trae/index.mjs @@ -992,13 +992,35 @@ const eventName = (s) => .toLowerCase() .replace(/^_|_$/g, "") -// usageOf maps Trae's token counts to OpenAI's +// tokensOf maps Trae's token counts to OpenAI's. Trae's token_usage event +// (TRAE SOLO CN's ai-agent, TokenUsageEvent: name, prompt_tokens, +// completion_tokens, total_tokens, reasoning_tokens, +// cache_creation_input_tokens, cache_read_input_tokens, +// prompt_tokens_total, completion_tokens_total) says what the prompt cache +// read and wrote under Anthropic's names. They go on under those names, +// which magpie reads beside prompt_tokens as it reads a relay's in front of +// Claude (whether prompt_tokens counts them too is judged there, by +// whether it is at least as big); without them every request read as no +// cache hit (01huadalang on magpie's Discord: K3, 53 calls, all 0) function tokensOf(u) { if (!u || typeof u !== "object") return null - const p = Number(u.prompt_tokens ?? u.input_tokens ?? u.promptTokens ?? u.inputTokens ?? 0) || 0 - const c = Number(u.completion_tokens ?? u.output_tokens ?? u.completionTokens ?? u.outputTokens ?? 0) || 0 + const n = (...v) => Number(v.find((x) => x != null) ?? 0) || 0 + const p = n(u.prompt_tokens, u.input_tokens, u.promptTokens, u.inputTokens) + const c = n(u.completion_tokens, u.output_tokens, u.completionTokens, u.outputTokens) if (!p && !c) return null - return { prompt_tokens: p, completion_tokens: c, total_tokens: Number(u.total_tokens ?? u.totalTokens) || p + c } + const out = { prompt_tokens: p, completion_tokens: c, total_tokens: n(u.total_tokens, u.totalTokens) || p + c } + const read = n(u.prompt_tokens_details?.cached_tokens) + const write = n(u.prompt_tokens_details?.cache_write_tokens) + if (read || write) out.prompt_tokens_details = { cached_tokens: read, ...(write ? { cache_write_tokens: write } : {}) } + else { + const r = n(u.cache_read_input_tokens, u.cacheReadInputTokens) + const w = n(u.cache_creation_input_tokens, u.cacheCreationInputTokens) + if (r) out.cache_read_input_tokens = r + if (w) out.cache_creation_input_tokens = w + } + const thought = n(u.reasoning_tokens, u.completion_tokens_details?.reasoning_tokens) + if (thought) out.completion_tokens_details = { reasoning_tokens: thought } + return out } let callSeq = 0 diff --git a/packages/trae/package.json b/packages/trae/package.json index 4bb7aab..b8b2f36 100644 --- a/packages/trae/package.json +++ b/packages/trae/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-trae-auth", - "version": "0.2.11", + "version": "0.2.12", "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",