Add Trae Global (trae.ai) plugin - trae-global provider (#22)
* Add Trae Global (trae.ai) plugin — trae-global provider Trae international (trae.ai, ByteDance's AI IDE international build) as a provider plugin: sign in with Trae's own browser flow, free tier included, models served through the international llm_utils_chat gateway. Same plugin contract and request/response machinery as the Trae CN plugin (packages/trae), a separate deployment: different domains, OAuth client, model catalog, plus a US region (coreva) routed by the account's AIRegion. The usage card reads the dollar billing's entitlements (basic+bonus allowance) from the pay host, with the Free plan's /month allowance riding it. bun test: 41 pass; bun scripts/check.mjs trae-global: ok * trae-global: a stream the agent walks away from closes Trae's connection The bug: an answer whose tool call the agent acts on is cancelled mid-read, and the read to Trae was left hanging. A generator's return cannot break a read that is already waiting on reader.read(), so the SSE reader kept its half of the connection open, and the host the next ask reused was one Trae had dropped — a stream that runs, then dies, exactly around tool calls. The fix: the answer's fetch is what gets stopped. The loader builds one AbortController per request, follows the caller's abort signal into it, and openai() aborts it when the stream is cancelled. sse() also lets its reader go in a finally, for the paths that end the generator rather than the fetch. stream.test.mjs: the agent reads, then cancels with nothing more coming, so only aborting Trae's fetch can release the read — red before, green after. bun test (42 pass); bun scripts/check.mjs trae-global: ok * trae-global: the review's three blockers — planLocked, the 0.1.15 Max, usage's error code planLocked is gone. It read display_contact_config's identity_list and assumed every account is Free (identity 0), so a paying account lost exactly the models it pays for — gpt-5.5, the gpt-5.6 family, gpt-6, glm-5.2 — and could never pick them. The plugin is never told the account's own identity (not at sign-in, not in the entitlement answer), so nothing is filtered on identity now: the list is the account's own, the IDE greys out what the plan locks, and a locked model answers Trae's own 1005 when asked. The picker's invisible entries (paygo/auto twins, search agents) stay out, as before. maxModel takes the 0.1.15 fix: a model's Max is found across every list that names it, not just the one entry the model is listed through — chat_v3 can name the __max model while the SOLO list names only __dev, and the window can be another entry's again. Without it the same "no -max model" bug the CN plugin fixed in 0.1.15 comes back here. maxes holds each model's Max for the models hook, as CN's does. usage: a 200 carrying an error code (e.code !== "0") now says Trae's own message instead of "no entitlement pack in the answer", as CN's does. README: the verification range is stated honestly — one Free account, SG realm, no Pro and no US account tried; paid-account behaviour is implemented from the interface's shape, not confirmed on a live one. registry.json marks Trae Global experimental, as Trae CN is. usage.test.mjs: the locked-model test now asserts the paying account's list, and a new one asks a paid account's gpt-5.5 through the gateway. stream.test.mjs: a Max split across lists is listed and asked where its __max model is named. Each red before its fix, green after. bun test (46 pass); bun scripts/check.mjs trae-global: ok
This commit is contained in:
@@ -20,6 +20,7 @@ subscription and makes its requests. The packages work in OpenCode and in
|
||||
| [qoder](packages/qoder) | Qoder subscription (qoder.com), with Qoder's device sign-in | `qoder` |
|
||||
| [qoder](packages/qoder) | Qoder CN subscription (qoder.cn), with Qoder CN's device sign-in | `qoder-cn` |
|
||||
| [trae](packages/trae) | Trae CN (trae.cn), free tier included, with Trae's browser sign-in (experimental) | `trae-cn` |
|
||||
| [trae-global](packages/trae-global) | Trae international (trae.ai), free tier included, with Trae's browser sign-in | `trae-global` |
|
||||
| [workbuddy](packages/workbuddy) | WorkBuddy (China build, CodeBuddy plan) | `workbuddy` |
|
||||
| [workbuddy](packages/workbuddy) | WorkBuddy (international build) | `workbuddy-ai` |
|
||||
| [zcode](packages/zcode) | ZCode: Z.ai / BigModel (智谱) GLM Coding Plan, team seats, Start Plan | `zcode` |
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
# Trae Global (trae.ai) for OpenCode / magpie
|
||||
|
||||
Trae 国际版(trae.ai,ByteDance 的 AI IDE 国际部署)作为 OpenCode provider 插件:
|
||||
用 Trae 国际版 IDE 自己的浏览器登录流程签入你的账号,免费额度可用,
|
||||
模型走国际版的 `llm_utils_chat` 网关。
|
||||
|
||||
与 `@magpie-community/opencode-trae-auth`(Trae CN)的关系:**同一套插件契约与
|
||||
同一套请求/应答机制,另一套部署**。国际版与国内版是完全独立的服务(不同域名、
|
||||
不同 client 生态、模型目录几乎不重叠),所以是一个独立插件,不是配置项。机制
|
||||
部分(工具调用解析、流收尾、max 档位、reply limit)跟随 CN 0.1.15。
|
||||
|
||||
## 验证范围
|
||||
|
||||
本插件目前只在**一个 Free 账号**上实测过(SG realm)。未在 Pro / 付费账号上
|
||||
验证,也未验证 US realm 的账号。付费账号相关的行为(模型列表里付费模型的可用性、
|
||||
付费额度的显示)依据 Trae 接口的结构实现,未经真机确认。故 registry 标
|
||||
**实验性**,与 Trae CN 一致。
|
||||
|
||||
计划:把国际版并入 `packages/trae`,一个包用两个 provider id
|
||||
(`trae-cn` + `trae-global`),按 realm 分表(hosts、client、版本号、usage 页面、
|
||||
兜底模型、错误码)。那样每个请求 / 流 / 工具调用的修复会同时作用于两个版本,
|
||||
也消除两份代码的漂移。
|
||||
|
||||
## 端点(与 CN 版的差异)
|
||||
|
||||
| 项 | Trae CN | Trae Global (本插件) |
|
||||
| --- | --- | --- |
|
||||
| 授权页 | `https://www.trae.cn` | `https://www.trae.ai` |
|
||||
| token/账号/积分 | `https://api.trae.cn` | `https://growsg-normal.trae.ai` |
|
||||
| 模型网关(SG) | `https://trae-api-cn.mchost.guru` | `https://coresg-normal.trae.ai` |
|
||||
| 模型网关(US) | — | `https://coreva-normal.trae.ai`(按账号 region 自动路由) |
|
||||
| OAuth ClientID | SOLO: `en1oxy7wnw8j9n` / IDE: `ono9krqynydwx5` | 两者同: `ono9krqynydwx5` |
|
||||
| IDE 版本 | 3.3.x | 3.5.x |
|
||||
|
||||
依据:wangqi233/trae2api 的 realm 表(cn/sg 双区域实测),本插件按 SG realm 配置。
|
||||
|
||||
## 登录
|
||||
|
||||
`auth.login` 选 **Trae Global account (browser)**:本插件起一个 127.0.0.1 回调,
|
||||
打开 trae.ai 的授权页,你在浏览器里登录国际版 Trae 账号并允许,页面会把
|
||||
token 送回本机,签入自动完成。token 过期前插件自动续期(ExchangeToken)。
|
||||
|
||||
前提:你的账号是 **trae.ai(国际版)** 的账号。trae.cn 的账号签不进 trae.ai。
|
||||
|
||||
美区账号:回调的 `AIRegion` 为 US(或 Host 是 `api-us-east.trae.ai` 这类认证
|
||||
主机)时,模型请求自动走 `coreva-normal.trae.ai`;SG 账号不受影响。
|
||||
|
||||
## 模型
|
||||
|
||||
签入后模型列表从国际版网关实时拉取(`get_detail_param` / `batch_get_detail_param`,
|
||||
跨 `chat_v3`、`solo_work_lite`、`solo_agent`、`solo_agent_lite` 四个 function 合并)。
|
||||
国际版常见模型是 GPT / Gemini / Kimi / MiniMax / DeepSeek-V3 系列(与 CN 版的
|
||||
GLM/Qwen/Doubao/Kimi-K2.7 几乎不重叠)。未签入时显示内置的静态表。
|
||||
|
||||
一个模型在清单里带 `__max` 条目和更大的 `context_window_tokens.max` 时,会作为
|
||||
第二个模型列出(`<id>-max`,名字加 "(Max)",窗口与输出上限取 max 档的):
|
||||
请求它时改发该模型的 `__max`,并按 IDE 的 Max 模式带上
|
||||
`user_message_context.model_info.prompt_max_tokens`(max 窗口 − max_tokens)。
|
||||
|
||||
模型的回复上限取清单给的 `__dev` 条目的 `max_tokens`;清单没给的就是没有(0),
|
||||
magpie 会从 models.dev 补,插件不编一个数。
|
||||
|
||||
## 工具调用
|
||||
|
||||
Trae 的 chat 没有原生 tool-call 轮次:工具原生带给它、也写进系统提示词,模型
|
||||
可能以 `<tool_call>{...}</tool_call>` 文本块(含 GLM 的 `arg_key/arg_value`
|
||||
模板、DeepSeek 的 DSML 标签收尾)或原生分片事件回复,两种都解析成 OpenAI 的
|
||||
tool calls;写在正文里的 `{"reasoning_content":...}` JSON 是思维链不是回答;
|
||||
未命名/错名事件里的正文不丢;失败的回复以错误和 `[DONE]` 收尾,不谎报 stop。
|
||||
|
||||
## 思考强度(reasoning effort)
|
||||
|
||||
Trae 的请求不接收思考强度:本插件不给模型声明任何档位,客户端的思考档选择
|
||||
对 Trae 无效(选了也照常回答)。dev/max 是上下文档位,不是思考档。
|
||||
|
||||
## 用量
|
||||
|
||||
用法卡片显示账号的 **Dollar Usage**(美元额度,2026-02 起国际版的计费方式):
|
||||
各 entitlement pack 的额度(`basic_usage_limit` + `bonus_usage_limit`)与已用
|
||||
(`basic_usage_amount` + `bonus_usage_amount`),在 Credits 式的窗口行里按
|
||||
百分比展示。免费计划是 $1/月的额度池(另有 10 次快速 + 50 次慢速 + 1000 次
|
||||
高级模型的请求次数限制,插件暂不展示次数)。
|
||||
|
||||
接口走 `api-sg-central.trae.ai`(美区账号走 `api-us-east.trae.ai`)的
|
||||
`/trae/api/v1/pay/user_current_entitlement_list`——认证主机自己的
|
||||
`/cloudide/api/v2/pay/*` 对插件 scope 返回 403 Api Scope Forbidden。
|
||||
|
||||
## 图标
|
||||
|
||||
`package.json` 的 `magpie.icon` 是 Trae 官网的 favicon(`lf16-web-neutral.traecdn.ai`
|
||||
的 48×48 PNG)以 data URI 内嵌——与 MiMo 插件同一做法,magpie 直接取用,不联网抓图。
|
||||
|
||||
## 本地开发
|
||||
|
||||
```sh
|
||||
bun test # 全部测试(fake 掉所有 Trae 主机,不出网)
|
||||
```
|
||||
|
||||
改完源码接入本机 magpie 验证时(`file:` 依赖是 copyfile 安装,必须重跑):
|
||||
|
||||
```sh
|
||||
bun install --cwd ~/.config/magpie/plugins --backend=copyfile --force
|
||||
```
|
||||
|
||||
然后完全重启 magpie(插件模块被进程缓存)。
|
||||
@@ -0,0 +1,49 @@
|
||||
// A fake of Trae Global for the tests: one local server standing in for
|
||||
// trae.ai's authorization page host, the SG auth host and the model host,
|
||||
// which the plugin's HOSTS are pointed at. route(method, path) answers a
|
||||
// request; seen lists what came.
|
||||
import { _internal } from "./index.mjs"
|
||||
|
||||
export function fakeTrae() {
|
||||
const routes = new Map()
|
||||
const seen = []
|
||||
const server = Bun.serve({
|
||||
port: 0,
|
||||
hostname: "127.0.0.1",
|
||||
async fetch(req) {
|
||||
const url = new URL(req.url)
|
||||
const text = await req.text()
|
||||
const r = { method: req.method, path: url.pathname, query: url.searchParams, headers: req.headers, text }
|
||||
if (text) try { r.json = JSON.parse(text) } catch {}
|
||||
seen.push(r)
|
||||
const h = routes.get(req.method + " " + url.pathname)
|
||||
if (!h) return new Response("no route " + req.method + " " + url.pathname, { status: 404 })
|
||||
return h(r)
|
||||
},
|
||||
})
|
||||
const origin = `http://127.0.0.1:${server.port}`
|
||||
const was = { ..._internal.HOSTS }
|
||||
Object.assign(_internal.HOSTS, { web: origin, auth: origin, api: origin, us: origin, usPay: origin, pay: origin })
|
||||
return {
|
||||
origin,
|
||||
seen,
|
||||
route: (key, h) => routes.set(key, h),
|
||||
close() {
|
||||
server.stop(true)
|
||||
Object.assign(_internal.HOSTS, was)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export const json = (v, status = 200) => new Response(JSON.stringify(v), { status, headers: { "content-type": "application/json" } })
|
||||
|
||||
// sse is an answer in Trae's events: [event, data] pairs
|
||||
export const sse = (events, status = 200) =>
|
||||
new Response(events.map(([e, d]) => `event: ${e}\ndata: ${typeof d === "string" ? d : JSON.stringify(d)}\n\n`).join(""), { status, headers: { "content-type": "text/event-stream" } })
|
||||
|
||||
export const jwtOf = (claims) => ["e30", Buffer.from(JSON.stringify(claims)).toString("base64url"), "sig"].join(".")
|
||||
|
||||
export const signedIn = (over = {}) => ({
|
||||
type: "oauth", access: "jwt-1", refresh: "r-1", expires: Date.now() + 3600_000, accountId: "Ann", uid: "u-1",
|
||||
clientId: "ono9krqynydwx5", deviceId: "1234567890123456789", machineId: "ab".repeat(16), ...over,
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,18 @@
|
||||
// Imported first by every test here: nothing a test runs reaches Trae.
|
||||
// fetch and HTTP/2 go to this machine (a test's fake) or fail, so a test
|
||||
// left without its fake, or work still going after it, can't send a token
|
||||
// to trae.ai or any other of Trae's hosts.
|
||||
import http2 from "node:http2"
|
||||
|
||||
const local = (u) => /^https?:\/\/(127\.0\.0\.1|localhost|\[::1\])(:\d+)?(\/|$)/.test(u)
|
||||
const realFetch = globalThis.fetch
|
||||
globalThis.fetch = async (input, init) => {
|
||||
const u = typeof input === "string" ? input : input instanceof URL ? input.href : input.url
|
||||
if (!local(u)) throw new Error("a test asked " + u + " with no fake in place")
|
||||
return realFetch(input, init)
|
||||
}
|
||||
const connect = http2.connect
|
||||
http2.connect = (origin, ...rest) => {
|
||||
if (!local(String(origin))) throw new Error("a test connected to " + origin)
|
||||
return connect(origin, ...rest)
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-trae-global-auth",
|
||||
"version": "0.2.3",
|
||||
"description": "OpenCode provider plugin for Trae international (trae.ai): your Trae international account's models, free tier included, with Trae's own browser sign-in",
|
||||
"type": "module",
|
||||
"main": "./index.mjs",
|
||||
"exports": "./index.mjs",
|
||||
"files": [
|
||||
"index.mjs",
|
||||
"README.md"
|
||||
],
|
||||
"keywords": [
|
||||
"opencode",
|
||||
"opencode-plugin",
|
||||
"trae",
|
||||
"trae.ai",
|
||||
"bytedance"
|
||||
],
|
||||
"license": "MIT",
|
||||
"repository": { "type": "git", "url": "git+https://github.com/magpie-community/plugins.git", "directory": "packages/trae-global" },
|
||||
"magpie": {
|
||||
"icon": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAF9SURBVHgB7Zm9SsNQFMf/EYWiVB2KKGLBScHFN9BJurmoa0dn9QGqD1CdHbtWFzd10jfQQdBJqIgKGYw4VCR+nGD0ptqmsSectD0/CKXpbXJ+3HvOyYfVP5B+RxvTgzZHBaRRAWlUQBoVkEYFpOkNGzC0MgtJnPJZw99DBcZ2FiFJmIDmgDSdn8S1PB9d4aFwiDgY2cwhnZuK9J/IAq5TxevNI+Lg7amKqGgO/DrgYIplTNPnAyN9E8OYPF5FZmOu7hgKPrufZ+svkXOgHhR8di/vfWbW5719dvE0MMYPPjUz6m3E3doBWoFlBszgfUjCnAkzeB+6TGl1JuJNYuOJk/W1ccMiQGW1slwKlFe7eAJ7+2cJuZ8lsrJUwsvF/fc+us5JxBIiTIna4H1MCY7gCbYkJij464Xdhg3Jl3D/0bT+gj0HmummXMET2omlCc2By/GtwHeq3dO3BSQFXULSdN8dGdV6p3yOpGDpOzJhVEAaFZBGBaRRAWlUQJoPEeV5RYlN/QYAAAAASUVORK5CYII="
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
// Renewing the JWT with the refresh token, once at a time (Trae spends a
|
||||
// refresh token once): magpie's auth.refresh, and the check before a
|
||||
// request.
|
||||
import "./nonet.mjs"
|
||||
import { afterEach, expect, test } from "bun:test"
|
||||
import { TraeGlobalAuthPlugin } from "./index.mjs"
|
||||
import { fakeTrae, json, signedIn, sse } from "./fake.mjs"
|
||||
|
||||
let f
|
||||
afterEach(() => f?.close())
|
||||
|
||||
test("auth.refresh exchanges the refresh token, once for two asking", async () => {
|
||||
f = fakeTrae()
|
||||
let n = 0
|
||||
f.route("POST /cloudide/api/v3/trae/oauth/ExchangeToken", async () => {
|
||||
n++
|
||||
await Bun.sleep(20)
|
||||
return json({ Result: { Token: "jwt-2", RefreshToken: "r-2", TokenExpireAt: 2000000000 } })
|
||||
})
|
||||
const hooks = await TraeGlobalAuthPlugin({ client: {} })
|
||||
expect(hooks.auth.refreshLead).toBe(10 * 60 * 1000)
|
||||
const auth = signedIn({ expires: Date.now() + 60_000 })
|
||||
const [x, y] = await Promise.all([hooks.auth.refresh(auth), hooks.auth.refresh(auth)])
|
||||
expect(n).toBe(1)
|
||||
expect(x).toEqual({ access: "jwt-2", refresh: "r-2", expires: 2000000000 * 1000 })
|
||||
expect(y).toEqual(x)
|
||||
// asked again with the sign-in from before, it gives the one it got
|
||||
expect(await hooks.auth.refresh(auth)).toEqual(x)
|
||||
expect(n).toBe(1)
|
||||
})
|
||||
|
||||
test("a refresh token Trae turns away is signIn expired", async () => {
|
||||
f = fakeTrae()
|
||||
f.route("POST /cloudide/api/v3/trae/oauth/ExchangeToken", () => json({ ResponseMetadata: { Error: { Code: "10101", Message: "refresh token is not matched to the client" } } }, 400))
|
||||
const hooks = await TraeGlobalAuthPlugin({ client: {} })
|
||||
const e = await hooks.auth.refresh(signedIn()).catch((e) => e)
|
||||
expect(e.signIn).toBe("expired")
|
||||
expect(e.message).toContain("not matched")
|
||||
})
|
||||
|
||||
test("a request with a token about to end renews it first and saves it", async () => {
|
||||
f = fakeTrae()
|
||||
f.route("POST /cloudide/api/v3/trae/oauth/ExchangeToken", () => json({ Result: { Token: "jwt-2", RefreshToken: "r-2", TokenExpireAt: Date.now() + 7200_000 } }))
|
||||
let auth = null
|
||||
f.route("POST /api/agent/v3/llm_utils_chat", (r) => {
|
||||
auth = r.headers.get("authorization")
|
||||
return sse([["output", { response: "hi" }], ["done", {}]])
|
||||
})
|
||||
const saved = []
|
||||
const hooks = await TraeGlobalAuthPlugin({ client: { auth: { set: async (x) => saved.push(x) } } })
|
||||
const opts = await hooks.auth.loader(async () => signedIn({ expires: Date.now() + 30_000 }))
|
||||
const res = await opts.fetch(opts.baseURL + "/chat/completions", { method: "POST", body: JSON.stringify({ model: "gpt-5.4", messages: [{ role: "user", content: "hi" }] }) })
|
||||
expect(res.status).toBe(200)
|
||||
expect(auth).toBe("Cloud-IDE-JWT jwt-2")
|
||||
expect(saved[0].body.access).toBe("jwt-2")
|
||||
})
|
||||
@@ -0,0 +1,237 @@
|
||||
// Model requests: OpenAI chat completions translated for the IDE agent's
|
||||
// llm_utils_chat, and its SSE events back into an OpenAI answer.
|
||||
import "./nonet.mjs"
|
||||
import { afterEach, expect, test } from "bun:test"
|
||||
import { TraeGlobalAuthPlugin, _internal } from "./index.mjs"
|
||||
import { fakeTrae, json, signedIn, sse } from "./fake.mjs"
|
||||
|
||||
let f
|
||||
afterEach(() => f?.close())
|
||||
|
||||
async function ask(body, auth = signedIn()) {
|
||||
const hooks = await TraeGlobalAuthPlugin({ client: {} })
|
||||
const opts = await hooks.auth.loader(async () => auth)
|
||||
return opts.fetch(opts.baseURL + "/chat/completions", { method: "POST", body: JSON.stringify(body) })
|
||||
}
|
||||
|
||||
async function chunks(res) {
|
||||
const out = []
|
||||
for (const line of (await res.text()).split("\n")) {
|
||||
if (!line.startsWith("data: ")) continue
|
||||
const d = line.slice(6)
|
||||
out.push(d === "[DONE]" ? d : JSON.parse(d))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const TOOLS = [{ type: "function", function: { name: "read", description: "Read a file", parameters: { type: "object", properties: { path: { type: "string" } } } } }]
|
||||
|
||||
test("the request is the IDE's: its headers, the device, text parts, the tools natively and in the prompt", async () => {
|
||||
f = fakeTrae()
|
||||
f.route("POST /api/agent/v3/llm_utils_chat", () => sse([["output", { response: "ok" }], ["done", {}]]))
|
||||
await ask({ model: "gpt-5.4", max_tokens: 100, tools: TOOLS, messages: [{ role: "system", content: "be brief" }, { role: "user", content: [{ type: "text", text: "hi" }] }] })
|
||||
const r = f.seen[0]
|
||||
expect(r.headers.get("authorization")).toBe("Cloud-IDE-JWT jwt-1")
|
||||
expect(r.headers.get("x-cloudide-token")).toBe("jwt-1")
|
||||
expect(r.headers.get("x-device-id")).toBe("1234567890123456789")
|
||||
expect(r.headers.get("x-machine-id")).toBe("ab".repeat(16))
|
||||
expect(r.headers.get("x-uid")).toBe("u-1")
|
||||
expect(r.headers.get("accept")).toBe("text/event-stream")
|
||||
const b = r.json
|
||||
expect(b.function).toBe("chat_v3")
|
||||
expect(b.config_name).toBe("gpt-5.4")
|
||||
expect(b.model).toBe("gpt-5.4")
|
||||
expect(b.max_tokens).toBe(100)
|
||||
expect(b.stream).toBe(true)
|
||||
expect(b.messages.map((m) => m.role)).toEqual(["system", "system", "user"])
|
||||
expect(b.messages[0].content[0].text).toContain("<tool_call>")
|
||||
expect(b.messages[2].content).toEqual([{ type: "text", text: "hi" }])
|
||||
expect(b.tools[0].function.name).toBe("read")
|
||||
expect(typeof b.tools[0].function.parameters).toBe("string")
|
||||
})
|
||||
|
||||
test("a US account's request goes to the US chat host", async () => {
|
||||
f = fakeTrae()
|
||||
f.route("POST /api/agent/v3/llm_utils_chat", () => sse([["output", { response: "us" }], ["done", {}]]))
|
||||
const hooks = await TraeGlobalAuthPlugin({ client: {} })
|
||||
const opts = await hooks.auth.loader(async () => signedIn({ region: "US-East" }))
|
||||
expect(opts.baseURL).toBe(f.origin + "/v1") // the US host, which the fake stands in for
|
||||
const res = await opts.fetch(opts.baseURL + "/chat/completions", { method: "POST", body: JSON.stringify({ model: "gpt-5.4", messages: [{ role: "user", content: "hi" }] }) })
|
||||
expect((await res.json()).choices[0].message.content).toBe("us")
|
||||
})
|
||||
|
||||
test("tool history goes in as text", () => {
|
||||
const m = _internal.traeMessages({ messages: [
|
||||
{ role: "user", content: "read a" },
|
||||
{ role: "assistant", content: null, tool_calls: [{ id: "c1", type: "function", function: { name: "read", arguments: "{\"path\":\"a\"}" } }] },
|
||||
{ role: "tool", tool_call_id: "c1", content: "AAA" },
|
||||
{ role: "tool", tool_call_id: "c2", content: "BBB" },
|
||||
] })
|
||||
expect(m.map((x) => x.role)).toEqual(["user", "assistant", "user"])
|
||||
expect(m[1].content[0].text).toBe('<tool_call>{"name":"read","arguments":{"path":"a"}}</tool_call>')
|
||||
expect(m[2].content[0].text).toContain("Result of read (call c1):\nAAA")
|
||||
expect(m[2].content[0].text).toContain("BBB")
|
||||
})
|
||||
|
||||
test("a stream: text, reasoning, a tool block split across events, a native call, usage", async () => {
|
||||
f = fakeTrae()
|
||||
f.route("POST /api/agent/v3/llm_utils_chat", () => sse([
|
||||
["request_wait_in_queue", { position: 3 }],
|
||||
["output", { reasoning_content: "think" }],
|
||||
["output", { response: "Let me look. <tool" }],
|
||||
["output", { response: '_call>{"name":"read","arguments":{"path":"a"}}</tool_call>' }],
|
||||
["output", { tool_calls: [{ id: "n1", function: { name: "read", arguments: { path: "b" } } }] }],
|
||||
["token_usage", { usage: { prompt_tokens: 10, completion_tokens: 5 } }],
|
||||
["done", { finish_reason: "stop" }],
|
||||
]))
|
||||
const res = await ask({ model: "gpt-5.4", stream: true, tools: TOOLS, messages: [{ role: "user", content: "hi" }] })
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get("content-type")).toBe("text/event-stream")
|
||||
expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept")
|
||||
const c = await chunks(res)
|
||||
const deltas = c.filter((x) => x !== "[DONE]" && x.choices?.length).map((x) => x.choices[0].delta)
|
||||
expect(deltas.map((d) => d.content ?? "").join("")).toBe("Let me look. ")
|
||||
expect(deltas.find((d) => d.reasoning_content).reasoning_content).toBe("think")
|
||||
const calls = deltas.flatMap((d) => d.tool_calls ?? [])
|
||||
expect(calls.map((t) => [t.index, t.function.name, t.function.arguments])).toEqual([[0, "read", '{"path":"a"}'], [1, "read", '{"path":"b"}']])
|
||||
expect(calls[1].id).toBe("n1")
|
||||
expect(c.at(-3).choices[0].finish_reason).toBe("tool_calls")
|
||||
expect(c.at(-2).usage).toEqual({ prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 })
|
||||
expect(c.at(-1)).toBe("[DONE]")
|
||||
})
|
||||
|
||||
test("a native call streamed over several events goes on whole (#799)", async () => {
|
||||
f = fakeTrae()
|
||||
f.route("POST /api/agent/v3/llm_utils_chat", () => sse([
|
||||
// the arguments so far, each event
|
||||
["output", { tool_calls: [{ id: "b1", index: 0, function: { name: "bash", arguments: "" } }] }],
|
||||
["output", { tool_calls: [{ id: "b1", index: 0, function: { name: "bash", arguments: '{"command":"echo \\"T' } }] }],
|
||||
["output", { tool_calls: [{ id: "b1", index: 0, function: { name: "bash", arguments: '{"command":"echo \\"Trae\\""}' } }] }],
|
||||
// only the new piece, the name only at first
|
||||
["output", { tool_calls: [{ id: "r1", index: 1, function: { name: "read", arguments: '{"filePath":"C:/Users/j' } }] }],
|
||||
["output", { tool_calls: [{ index: 1, function: { arguments: 'oe/a.txt"}' } }] }],
|
||||
// a whole call sent again
|
||||
["output", { tool_calls: [{ id: "r1", index: 1, function: { name: "read", arguments: '{"filePath":"C:/Users/joe/a.txt"}' } }] }],
|
||||
["done", {}],
|
||||
]))
|
||||
const res = await ask({ model: "gpt-5.4", stream: true, tools: TOOLS, messages: [{ role: "user", content: "hi" }] })
|
||||
const c = await chunks(res)
|
||||
const calls = c.filter((x) => x !== "[DONE]" && x.choices?.length).flatMap((x) => x.choices[0].delta.tool_calls ?? [])
|
||||
expect(calls.map((t) => [t.id, t.function.name, JSON.parse(t.function.arguments)])).toEqual([
|
||||
["b1", "bash", { command: 'echo "Trae"' }],
|
||||
["r1", "read", { filePath: "C:/Users/joe/a.txt" }],
|
||||
])
|
||||
})
|
||||
|
||||
test("no stream asked: one chat completion", async () => {
|
||||
f = fakeTrae()
|
||||
f.route("POST /api/agent/v3/llm_utils_chat", () => sse([["output", { content: "Hel" }], ["output", { content: "lo" }], ["done", {}]]))
|
||||
const res = await ask({ model: "gpt-5.4", messages: [{ role: "user", content: "hi" }] })
|
||||
const b = await res.json()
|
||||
expect(b.object).toBe("chat.completion")
|
||||
expect(b.choices[0].message).toEqual({ role: "assistant", content: "Hello" })
|
||||
expect(b.choices[0].finish_reason).toBe("stop")
|
||||
})
|
||||
|
||||
test("a text like a tag that isn't one goes through whole", () => {
|
||||
const t = new _internal.TextTools()
|
||||
expect(t.push("a <to").text).toBe("a ")
|
||||
expect(t.push("p> b").text).toBe("<top> b")
|
||||
expect(t.push("", true).text).toBe("")
|
||||
})
|
||||
|
||||
test("a model chat_v3 doesn't know is asked of SOLO's function, which is kept for the account", async () => {
|
||||
f = fakeTrae()
|
||||
f.route("POST /api/agent/v3/llm_utils_chat", (r) => (r.json.function === "chat_v3"
|
||||
? sse([["error", { code: 4023, message: "model is unknown" }]])
|
||||
: sse([["output", { response: "solo" }], ["done", {}]])))
|
||||
const hooks = await TraeGlobalAuthPlugin({ client: {} })
|
||||
const opts = await hooks.auth.loader(async () => signedIn())
|
||||
const body = JSON.stringify({ model: "gemini-3.1-pro", messages: [{ role: "user", content: "hi" }] })
|
||||
const res = await opts.fetch(opts.baseURL + "/chat/completions", { method: "POST", body })
|
||||
expect((await res.json()).choices[0].message.content).toBe("solo")
|
||||
expect(f.seen.map((r) => r.json.function)).toEqual(["chat_v3", "solo_work_lite"])
|
||||
await opts.fetch(opts.baseURL + "/chat/completions", { method: "POST", body })
|
||||
expect(f.seen.at(-1).json.function).toBe("solo_work_lite")
|
||||
})
|
||||
|
||||
test("a function that doesn't take the model leaves its read behind with it", async () => {
|
||||
// chat_v3 answers "unknown model" and would keep the stream open:
|
||||
// the plugin moves to solo_work_lite, and chat_v3's read must close
|
||||
// with it, or the connection it left is one Trae has to drop
|
||||
let cancelled = false
|
||||
f = fakeTrae()
|
||||
f.route("POST /api/agent/v3/llm_utils_chat", (r) => {
|
||||
if (r.json.function !== "chat_v3") return sse([["output", { response: "solo" }], ["done", {}]])
|
||||
let n = 0
|
||||
const body = new ReadableStream({
|
||||
async pull(ctl) {
|
||||
if (n++ === 0) return ctl.enqueue(new TextEncoder().encode('event: error\ndata: {"code":4023,"message":"model is unknown"}\n\n'))
|
||||
await new Promise((r) => setTimeout(r, 10_000)) // the stream would stay open
|
||||
},
|
||||
cancel() { cancelled = true },
|
||||
})
|
||||
return new Response(body, { headers: { "content-type": "text/event-stream" } })
|
||||
})
|
||||
const hooks = await TraeGlobalAuthPlugin({ client: {} })
|
||||
const opts = await hooks.auth.loader(async () => signedIn())
|
||||
const res = await opts.fetch(opts.baseURL + "/chat/completions", { method: "POST", body: JSON.stringify({ model: "gemini-3.1-pro", messages: [{ role: "user", content: "hi" }] }) })
|
||||
expect((await res.json()).choices[0].message.content).toBe("solo")
|
||||
await new Promise((r) => setTimeout(r, 50))
|
||||
expect(cancelled).toBe(true)
|
||||
})
|
||||
|
||||
test("signed out (1001, or a 401) is a 401 that marks the account", async () => {
|
||||
f = fakeTrae()
|
||||
f.route("POST /api/agent/v3/llm_utils_chat", () => sse([["error", { code: 1001, message: "not login" }]]))
|
||||
let res = await ask({ model: "gpt-5.4", messages: [{ role: "user", content: "hi" }] })
|
||||
expect(res.status).toBe(401)
|
||||
expect(res.headers.get("X-Magpie-Sign-In")).toBe("expired")
|
||||
expect((await res.json()).error.message).toContain("sign in again")
|
||||
f.route("POST /api/agent/v3/llm_utils_chat", () => json({ code: 401, message: "unauthorized" }, 401))
|
||||
res = await ask({ model: "gpt-5.4", messages: [{ role: "user", content: "hi" }] })
|
||||
expect(res.status).toBe(401)
|
||||
expect(res.headers.get("X-Magpie-Sign-In")).toBe("expired")
|
||||
})
|
||||
|
||||
test("out of quota (4008) is a 429, the account kept", async () => {
|
||||
f = fakeTrae()
|
||||
f.route("POST /api/agent/v3/llm_utils_chat", () => sse([["error", { code: 4008, message: "quota exceeded" }]]))
|
||||
const res = await ask({ model: "gpt-5.4", stream: true, messages: [{ role: "user", content: "hi" }] })
|
||||
expect(res.status).toBe(429)
|
||||
expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept")
|
||||
expect((await res.json()).error.message).toBe("Trae Global: quota exceeded")
|
||||
})
|
||||
|
||||
test("a tool block with a file's content written out raw, or its arguments beside the name, goes on whole (#799)", async () => {
|
||||
f = fakeTrae()
|
||||
const block = '<tool_call>{"name":"write","arguments":{"path":"a.py","content":"import sys\n\tprint(\\"hi\\")\n"}}</tool_call>'
|
||||
f.route("POST /api/agent/v3/llm_utils_chat", () => sse([
|
||||
["output", { response: "Writing it. " + block }],
|
||||
["output", { response: '<tool_call>{"name":"read","path":"a.py"}</tool_call>' }],
|
||||
["done", {}],
|
||||
]))
|
||||
const res = await ask({ model: "gpt-5.4", stream: true, tools: TOOLS, messages: [{ role: "user", content: "hi" }] })
|
||||
const c = await chunks(res)
|
||||
const deltas = c.filter((x) => x !== "[DONE]" && x.choices?.length).map((x) => x.choices[0].delta)
|
||||
expect(deltas.map((d) => d.content ?? "").join("")).toBe("Writing it. ")
|
||||
const calls = deltas.flatMap((d) => d.tool_calls ?? [])
|
||||
expect(calls.map((t) => [t.function.name, JSON.parse(t.function.arguments)])).toEqual([
|
||||
["write", { path: "a.py", content: 'import sys\n\tprint("hi")\n' }],
|
||||
["read", { path: "a.py" }],
|
||||
])
|
||||
})
|
||||
|
||||
test("a native call's pieces that say neither id nor name join the call being written (#799)", () => {
|
||||
const nc = new _internal.NativeCalls()
|
||||
nc.push({ id: "w1", function: { name: "write", arguments: '{"path":"a.py",' } })
|
||||
nc.push({ index: 0, function: { arguments: '"content":"x\ny"' } })
|
||||
nc.push({ function: { arguments: "}" } })
|
||||
expect(nc.take().map((t) => [t.id, t.name, JSON.parse(t.arguments)])).toEqual([["w1", "write", { path: "a.py", content: "x\ny" }]])
|
||||
})
|
||||
|
||||
test("looseJSON reads raw control characters in strings only", () => {
|
||||
expect(_internal.looseJSON('{"a":"x\ny","b":"\\"q\\""}')).toEqual({ a: "x\ny", b: '"q"' })
|
||||
expect(_internal.looseJSON('{"a":\n1}')).toEqual({ a: 1 })
|
||||
expect(_internal.looseJSON('{"a":"x')).toBe(null)
|
||||
})
|
||||
@@ -0,0 +1,106 @@
|
||||
// Signing in as the IDE does: trae.ai's authorization page sends the
|
||||
// browser back to the callback on 127.0.0.1 with the token pair and the
|
||||
// account, or, from its older page, a refresh token to exchange.
|
||||
import "./nonet.mjs"
|
||||
import { afterEach, expect, test } from "bun:test"
|
||||
import { TraeGlobalAuthPlugin } from "./index.mjs"
|
||||
import { fakeTrae, json } from "./fake.mjs"
|
||||
|
||||
let f
|
||||
afterEach(() => f?.close())
|
||||
|
||||
async function start() {
|
||||
const hooks = await TraeGlobalAuthPlugin({ client: {} })
|
||||
const [method] = hooks.auth.methods
|
||||
expect(method.type).toBe("oauth")
|
||||
const a = await method.authorize()
|
||||
expect(a.method).toBe("auto")
|
||||
const u = new URL(a.url)
|
||||
// the fake points the plugin's HOSTS.web at itself, so the page is the
|
||||
// fake's; what the sign-in names is trae.ai's, and the query is its
|
||||
expect(u.hostname).toBe(f.origin && new URL(f.origin).hostname)
|
||||
expect(u.pathname).toBe("/authorization")
|
||||
const q = u.searchParams
|
||||
expect(q.get("client_id")).toBe("ono9krqynydwx5")
|
||||
expect(q.get("login_channel")).toBe("native_ide")
|
||||
expect(q.get("device_id")).toMatch(/^\d{19}$/)
|
||||
expect(q.get("x_device_id")).toBe(q.get("device_id"))
|
||||
expect(q.get("machine_id")).toMatch(/^[0-9a-f]{32}$/)
|
||||
const cb = new URL(q.get("auth_callback_url"))
|
||||
expect(cb.hostname).toBe("127.0.0.1")
|
||||
expect(cb.pathname).toBe("/authorize")
|
||||
return { a, cb, q }
|
||||
}
|
||||
|
||||
test("the callback's userJwt and userInfo are the sign-in, with the device the page was told", async () => {
|
||||
f = fakeTrae()
|
||||
const { a, cb, q } = await start()
|
||||
const jwt = { Token: "jwt-1", RefreshToken: "r-1", TokenExpireAt: Math.floor(Date.now() / 1000) + 7200, ClientID: "ono9krqynydwx5" }
|
||||
const info = { UserID: "u-1", ScreenName: "Ann", AIRegion: "SG", Host: "https://coresg-normal.trae.ai" }
|
||||
const url = new URL(cb)
|
||||
url.searchParams.set("userJwt", JSON.stringify(jwt))
|
||||
url.searchParams.set("userInfo", JSON.stringify(info))
|
||||
const res = await fetch(url)
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get("access-control-allow-origin")).toBe("*")
|
||||
expect(await res.text()).toContain("signed in")
|
||||
const got = await a.callback()
|
||||
expect(got.type).toBe("success")
|
||||
expect(got.access).toBe("jwt-1")
|
||||
expect(got.refresh).toBe("r-1")
|
||||
expect(got.accountId).toBe("Ann")
|
||||
expect(got.uid).toBe("u-1")
|
||||
expect(got.expires).toBe(jwt.TokenExpireAt * 1000)
|
||||
expect(got.deviceId).toBe(q.get("device_id"))
|
||||
expect(got.machineId).toBe(q.get("machine_id"))
|
||||
expect(got.region).toBe("SG")
|
||||
expect(got.api).toBe("https://coresg-normal.trae.ai") // the callback's Host, kept; apiOf takes it as the default chat host
|
||||
})
|
||||
|
||||
test("a US callback keeps the region, and its saved auth routes to the US chat host", async () => {
|
||||
f = fakeTrae()
|
||||
const { a, cb } = await start()
|
||||
const jwt = { Token: "jwt-us", RefreshToken: "r-us", TokenExpireAt: Math.floor(Date.now() / 1000) + 7200, ClientID: "ono9krqynydwx5" }
|
||||
// a real US account's Host is api-us-east.trae.ai, an auth host; the
|
||||
// region is what says where it chats
|
||||
const info = { UserID: "u-us", ScreenName: "Bo", AIRegion: "US-East", Host: "https://api-us-east.trae.ai" }
|
||||
const url = new URL(cb)
|
||||
url.searchParams.set("userJwt", JSON.stringify(jwt))
|
||||
url.searchParams.set("userInfo", JSON.stringify(info))
|
||||
await fetch(url)
|
||||
const got = await a.callback()
|
||||
expect(got.type).toBe("success")
|
||||
expect(got.region).toBe("US-East")
|
||||
expect(got.api).toBe("https://api-us-east.trae.ai")
|
||||
// as magpie saves the sign-in: the fields but its type
|
||||
const { type, ...saved } = got
|
||||
const hooks = await TraeGlobalAuthPlugin({ client: {} })
|
||||
const opts = await hooks.auth.loader(async () => ({ ...saved, type: "oauth" }))
|
||||
expect(opts.baseURL).toBe(f.origin + "/v1") // the US host, which the fake stands in for
|
||||
})
|
||||
|
||||
test("a refresh token alone is exchanged for the pair", async () => {
|
||||
f = fakeTrae()
|
||||
f.route("POST /cloudide/api/v3/trae/oauth/ExchangeToken", () => json({ Result: {
|
||||
Token: "jwt-2", RefreshToken: "r-2", TokenExpireAt: Date.now() + 7200_000, UserInfo: JSON.stringify({ UserID: "u-2", ScreenName: "Bo" }),
|
||||
} }))
|
||||
const { a, cb } = await start()
|
||||
const url = new URL(cb)
|
||||
url.searchParams.set("refreshToken", "r-old")
|
||||
await fetch(url)
|
||||
const got = await a.callback()
|
||||
expect(got.type).toBe("success")
|
||||
expect(got.access).toBe("jwt-2")
|
||||
expect(got.refresh).toBe("r-2")
|
||||
expect(got.accountId).toBe("Bo")
|
||||
expect(f.seen[0].json).toEqual({ ClientID: "ono9krqynydwx5", RefreshToken: "r-old", ClientSecret: "-", UserID: "" })
|
||||
})
|
||||
|
||||
test("a callback with an error fails the sign-in", async () => {
|
||||
f = fakeTrae()
|
||||
const { a, cb } = await start()
|
||||
const url = new URL(cb)
|
||||
url.searchParams.set("error", "access_denied")
|
||||
await fetch(url)
|
||||
expect(await a.callback()).toEqual({ type: "failed", error: "access_denied" })
|
||||
})
|
||||
@@ -0,0 +1,238 @@
|
||||
// What 歧路亡羊 found on magpie's Discord (2026-10-05) and the CN plugin
|
||||
// fixed in 0.1.9–0.1.14, the international plugin taking the same machinery:
|
||||
// GLM's own tool-call tags, a call written into a native call's name, answer
|
||||
// text under an event the stream didn't name as output, reasoning written
|
||||
// into the text or sent twice, the finish of a reply that failed or was cut
|
||||
// at its limit, and Trae's Max context.
|
||||
import "./nonet.mjs"
|
||||
import { afterEach, expect, test } from "bun:test"
|
||||
import { TraeGlobalAuthPlugin, _internal } from "./index.mjs"
|
||||
import { fakeTrae, json, signedIn, sse } from "./fake.mjs"
|
||||
|
||||
let f
|
||||
afterEach(() => f?.close())
|
||||
|
||||
async function ask(body, auth = signedIn()) {
|
||||
const hooks = await TraeGlobalAuthPlugin({ client: {} })
|
||||
const opts = await hooks.auth.loader(async () => auth)
|
||||
return opts.fetch(opts.baseURL + "/chat/completions", { method: "POST", body: JSON.stringify(body) })
|
||||
}
|
||||
|
||||
async function chunks(res) {
|
||||
const out = []
|
||||
for (const line of (await res.text()).split("\n")) {
|
||||
if (!line.startsWith("data: ")) continue
|
||||
const d = line.slice(6)
|
||||
out.push(d === "[DONE]" ? d : JSON.parse(d))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
const deltasOf = (c) => c.filter((x) => x !== "[DONE]" && x.choices?.length).map((x) => x.choices[0].delta)
|
||||
const callsOf = (c) => deltasOf(c).flatMap((d) => d.tool_calls ?? []).map((t) => [t.function.name, JSON.parse(t.function.arguments)])
|
||||
const textOf = (c) => deltasOf(c).map((d) => d.content ?? "").join("")
|
||||
const reasoningOf = (c) => deltasOf(c).map((d) => d.reasoning_content ?? "").join("")
|
||||
const finishOf = (c) => c.filter((x) => x !== "[DONE]" && x.choices?.[0]?.finish_reason).map((x) => x.choices[0].finish_reason)
|
||||
|
||||
const TOOLS = [
|
||||
{ type: "function", function: { name: "read", parameters: { type: "object", properties: { path: { type: "string" }, limit: { type: "number" } } } } },
|
||||
{ type: "function", function: { name: "bash", parameters: { type: "object", properties: { command: { type: "string" } } } } },
|
||||
]
|
||||
|
||||
const stream = (events) => {
|
||||
f?.close()
|
||||
f = fakeTrae()
|
||||
f.route("POST /api/agent/v3/llm_utils_chat", () => sse(events))
|
||||
}
|
||||
|
||||
test("GLM's own <arg_key>/<arg_value> call is a call, split over events, a string kept as written and a number read as one", async () => {
|
||||
stream([
|
||||
["output", { response: "Reading.\n<tool_call>read\n<arg_key>path</arg_key>\n<arg_va" }],
|
||||
["output", { response: "lue>007.txt</arg_value>\n<arg_key>limit</arg_key>\n<arg_value>20</arg_value>\n</tool_call>" }],
|
||||
["output", { response: '<tool_call>bash<arg_key>command</arg_key><arg_value>echo "a\nb"</arg_value></tool_call>' }],
|
||||
["done", {}],
|
||||
])
|
||||
const c = await chunks(await ask({ model: "gpt-5.4", stream: true, tools: TOOLS, messages: [{ role: "user", content: "hi" }] }))
|
||||
expect(textOf(c)).toBe("Reading.\n")
|
||||
expect(callsOf(c)).toEqual([["read", { path: "007.txt", limit: 20 }], ["bash", { command: 'echo "a\nb"' }]])
|
||||
expect(finishOf(c)).toEqual(["tool_calls"])
|
||||
})
|
||||
|
||||
test("a native call whose name holds the whole call, as JSON or GLM's tags, is that call", async () => {
|
||||
stream([
|
||||
["output", { tool_calls: [{ id: "n1", function: { name: '{"name":"read","arguments":{"path":"a"}}', arguments: "" } }] }],
|
||||
["output", { tool_calls: [{ id: "n2", function: { name: "bash<arg_key>command</arg_key><arg_value>ls</arg_value>", arguments: "{}" } }] }],
|
||||
["done", {}],
|
||||
])
|
||||
const c = await chunks(await ask({ model: "gpt-5.4", stream: true, tools: TOOLS, messages: [{ role: "user", content: "hi" }] }))
|
||||
expect(callsOf(c)).toEqual([["read", { path: "a" }], ["bash", { command: "ls" }]])
|
||||
})
|
||||
|
||||
test("a call to a tool named otherwise than the request's (case, dashes) goes on under the request's name", async () => {
|
||||
stream([["output", { response: '<tool_call>{"name":"Read","arguments":{"path":"a"}}</tool_call>' }], ["done", {}]])
|
||||
const c = await chunks(await ask({ model: "gpt-5.4", stream: true, tools: TOOLS, messages: [{ role: "user", content: "hi" }] }))
|
||||
expect(callsOf(c)).toEqual([["read", { path: "a" }]])
|
||||
})
|
||||
|
||||
test("answer text under an event not named output (delta, or none) is the answer's", async () => {
|
||||
f = fakeTrae()
|
||||
f.route("POST /api/agent/v3/llm_utils_chat", () =>
|
||||
new Response('event: output\ndata: {"response":"He"}\n\nevent: delta\ndata: {"response":"ll"}\n\ndata: {"content":"o"}\n\nevent: request_wait_in_queue\ndata: {"position":1}\n\nevent: done\ndata: {}\n\n', { headers: { "content-type": "text/event-stream" } }))
|
||||
const c = await chunks(await ask({ model: "gpt-5.4", stream: true, messages: [{ role: "user", content: "hi" }] }))
|
||||
expect(textOf(c)).toBe("Hello")
|
||||
})
|
||||
|
||||
test("reasoning written into the text as JSON is reasoning, and reasoning sent again isn't sent twice", async () => {
|
||||
stream([
|
||||
["output", { reasoning_content: "The user wants a greeting, so" }],
|
||||
["output", { reasoning_content: "The user wants a greeting, so" }],
|
||||
["output", { reasoning_content: "The user wants a greeting, so I say hi." }],
|
||||
["output", { response: "Hi there." }],
|
||||
["output", { response: '{"reasoning_' }],
|
||||
["output", { response: 'content":"The user wants a greeting, so I say hi."}' }],
|
||||
["output", { response: '{"reasoning_content":"one more thought"}' }],
|
||||
["done", {}],
|
||||
])
|
||||
const c = await chunks(await ask({ model: "gpt-5.4", stream: true, messages: [{ role: "user", content: "hi" }] }))
|
||||
expect(textOf(c)).toBe("Hi there.")
|
||||
expect(reasoningOf(c)).toBe("The user wants a greeting, so I say hi.one more thought")
|
||||
})
|
||||
|
||||
test("text holding braces that aren't reasoning goes through whole", () => {
|
||||
const t = new _internal.TextTools()
|
||||
const a = t.push('x = {"reasoning": 1} and {"a":')
|
||||
const b = t.push("2}", true)
|
||||
expect(a.text + b.text).toBe('x = {"reasoning": 1} and {"a":2}')
|
||||
})
|
||||
|
||||
test("a reply that fails mid-way ends with the error and [DONE], not a stop", async () => {
|
||||
stream([["output", { response: "partial" }], ["error", { code: 500, message: "server broke" }]])
|
||||
const c = await chunks(await ask({ model: "gpt-5.4", stream: true, messages: [{ role: "user", content: "hi" }] }))
|
||||
expect(textOf(c)).toBe("partial")
|
||||
expect(finishOf(c)).toEqual([])
|
||||
expect(c.at(-2).error.message).toContain("server broke")
|
||||
expect(c.at(-1)).toBe("[DONE]")
|
||||
})
|
||||
|
||||
test("a reply cut at its limit says length", async () => {
|
||||
stream([["output", { response: "a lot" }], ["done", { finish_reason: "length" }]])
|
||||
const c = await chunks(await ask({ model: "gpt-5.4", stream: true, messages: [{ role: "user", content: "hi" }] }))
|
||||
expect(finishOf(c)).toEqual(["length"])
|
||||
stream([["output", { response: "a lot" }], ["done", { finish_reason: "max_tokens" }]])
|
||||
const b = await (await ask({ model: "gpt-5.4", messages: [{ role: "user", content: "hi" }] })).json()
|
||||
expect(b.choices[0].finish_reason).toBe("length")
|
||||
})
|
||||
|
||||
test("a stream that breaks off ends with an error and [DONE]", async () => {
|
||||
f = fakeTrae()
|
||||
f.route("POST /api/agent/v3/llm_utils_chat", () => {
|
||||
let n = 0
|
||||
const body = new ReadableStream({
|
||||
async pull(ctl) {
|
||||
if (n++ === 0) return ctl.enqueue(new TextEncoder().encode('event: output\ndata: {"response":"half"}\n\n'))
|
||||
await new Promise((r) => setTimeout(r, 30)) // the headers and the first event are out
|
||||
ctl.error(new Error("connection reset"))
|
||||
},
|
||||
})
|
||||
return new Response(body, { headers: { "content-type": "text/event-stream" } })
|
||||
})
|
||||
const c = await chunks(await ask({ model: "gpt-5.4", stream: true, messages: [{ role: "user", content: "hi" }] }))
|
||||
expect(textOf(c)).toBe("half")
|
||||
expect(finishOf(c)).toEqual([])
|
||||
expect(c.at(-2).error.message).toContain("Trae Global")
|
||||
expect(c.at(-1)).toBe("[DONE]")
|
||||
})
|
||||
|
||||
// The lists needn't agree (trae 0.1.15, ARNO on magpie's Discord): chat_v3's
|
||||
// entry names the __max model, while the SOLO entry the model is asked
|
||||
// through names only __dev and gives the windows. Its Max is found across
|
||||
// them, and asked through the function that names the __max model.
|
||||
const SPLIT = { function_configs: [
|
||||
{ function: "chat_v3", config_info_list: [
|
||||
{ config_name: "gpt-5.4", usage: "chat_completion", display_config: { display_name: "GPT-5.4 Official" }, model_detail_list: [{ model_name: "gpt-5.4__dev" }, { model_name: "gpt-5.4__max", max_tokens: 128000 }] },
|
||||
{ config_name: "GPT-5.4-Official", usage: "chat_completion", display_config: { display_name: "GPT-5.4 Official" }, model_detail_list: [{ model_name: "GPT-5.4-Official__dev" }] },
|
||||
] },
|
||||
{ function: "solo_work_lite", config_info_list: [
|
||||
{ config_name: "gpt-5.4", usage: "chat_completion", display_config: { display_name: "GPT-5.4" }, context_window_tokens: { dev: 200000, max: 1000000 }, model_detail_list: [{ model_name: "gpt-5.4__dev", max_tokens: 64000 }] },
|
||||
] },
|
||||
] }
|
||||
|
||||
test("a Max the lists split between them is listed, and asked where its __max model is named", async () => {
|
||||
f = fakeTrae()
|
||||
f.route("POST /api/ide/v1/batch_get_detail_param", () => json(SPLIT))
|
||||
f.route("POST /api/agent/v3/llm_utils_chat", () => sse([["output", { response: "ok" }], ["done", {}]]))
|
||||
const hooks = await TraeGlobalAuthPlugin({ client: {} })
|
||||
const p = { models: { ..._internal.MODELS } }
|
||||
const live = await hooks.provider.models(p, { auth: signedIn() })
|
||||
expect(Object.keys(live)).toEqual(["gpt-5.4", "gpt-5.4-max", "GPT-5.4-Official"])
|
||||
expect(live["gpt-5.4"].limit).toEqual({ context: 200000, output: 64000 })
|
||||
expect(live["gpt-5.4"].name).toBe("GPT-5.4")
|
||||
expect(live["gpt-5.4-max"].limit).toEqual({ context: 1000000, output: 128000 })
|
||||
expect(live["gpt-5.4-max"].name).toBe("GPT-5.4 (Max)")
|
||||
const opts = await hooks.auth.loader(async () => signedIn())
|
||||
const send = (body) => opts.fetch(opts.baseURL + "/chat/completions", { method: "POST", body: JSON.stringify({ messages: [{ role: "user", content: "hi" }], ...body }) })
|
||||
await send({ model: "gpt-5.4-max" })
|
||||
const b = f.seen.at(-1).json
|
||||
expect([b.function, b.config_name, b.model_name, b.max_tokens, b.user_message_context.model_info.prompt_max_tokens]).toEqual(["chat_v3", "gpt-5.4", "gpt-5.4__max", 128000, 872000])
|
||||
})
|
||||
|
||||
const BATCH = { function_configs: [
|
||||
{ function: "solo_agent", config_info_list: [
|
||||
{ config_name: "gpt-5.4", usage: "chat_completion", display_config: { display_name: "GPT-5.4" }, context_window_tokens: { dev: 272000, max: 400000 }, model_detail_list: [{ model_name: "gpt-5.4__dev", max_tokens: 32000 }, { model_name: "gpt-5.4__max", max_tokens: 128000 }] },
|
||||
{ config_name: "gemini-3-flash", usage: "chat_completion", context_window_tokens: { dev: 200000 }, model_detail_list: [{ model_name: "gemini-3-flash__dev", max_tokens: 32000 }] },
|
||||
] },
|
||||
] }
|
||||
|
||||
test("a model with a Max context is listed a second time, as its Max, which asks Trae's __max model with the prompt it has room for", async () => {
|
||||
f = fakeTrae()
|
||||
f.route("POST /api/ide/v1/batch_get_detail_param", () => json(BATCH))
|
||||
f.route("POST /api/agent/v3/llm_utils_chat", () => sse([["output", { response: "ok" }], ["done", {}]]))
|
||||
const hooks = await TraeGlobalAuthPlugin({ client: {} })
|
||||
const p = { models: { ..._internal.MODELS } }
|
||||
const live = await hooks.provider.models(p, { auth: signedIn() })
|
||||
expect(Object.keys(live)).toEqual(["gpt-5.4", "gpt-5.4-max", "gemini-3-flash"])
|
||||
expect(live["gpt-5.4"].limit).toEqual({ context: 272000, output: 32000 })
|
||||
expect(live["gpt-5.4-max"].limit).toEqual({ context: 400000, output: 128000 })
|
||||
expect(live["gpt-5.4-max"].name).toBe("GPT-5.4 (Max)")
|
||||
const opts = await hooks.auth.loader(async () => signedIn())
|
||||
const send = (body) => opts.fetch(opts.baseURL + "/chat/completions", { method: "POST", body: JSON.stringify({ messages: [{ role: "user", content: "hi" }], ...body }) })
|
||||
await send({ model: "gpt-5.4-max", max_tokens: 100000 })
|
||||
let b = f.seen.at(-1).json
|
||||
expect([b.function, b.config_name, b.model, b.model_name, b.max_tokens]).toEqual(["solo_agent", "gpt-5.4", "gpt-5.4", "gpt-5.4__max", 100000])
|
||||
expect(b.user_message_context).toEqual({ model_info: { prompt_max_tokens: 400000 - 100000 } })
|
||||
await send({ model: "gpt-5.4-max" })
|
||||
b = f.seen.at(-1).json
|
||||
expect([b.model_name, b.max_tokens, b.user_message_context.model_info.prompt_max_tokens]).toEqual(["gpt-5.4__max", 128000, 272000])
|
||||
// the model itself is asked as before
|
||||
await send({ model: "gpt-5.4" })
|
||||
b = f.seen.at(-1).json
|
||||
expect([b.model_name, b.user_message_context]).toEqual(["gpt-5.4__dev", undefined])
|
||||
})
|
||||
|
||||
test("an answer the agent walks away from lets Trae's connection go", async () => {
|
||||
// the agent reads a tool call's name and leaves the rest of the stream
|
||||
// (pi/magpie cancels it to make the call): the read to Trae must close,
|
||||
// not hang on and leave the reused host one Trae has dropped. The fake
|
||||
// sends nothing more, so only aborting Trae's own fetch can release it —
|
||||
// a generator's return can't break a read already waiting.
|
||||
let cancelled = false
|
||||
f = fakeTrae()
|
||||
f.route("POST /api/agent/v3/llm_utils_chat", () => {
|
||||
let n = 0
|
||||
const body = new ReadableStream({
|
||||
async pull(ctl) {
|
||||
if (n++ === 0) return ctl.enqueue(new TextEncoder().encode('event: output\ndata: {"response":"working on it"}\n\n'))
|
||||
await new Promise((r) => setTimeout(r, 10_000)) // nothing more comes
|
||||
},
|
||||
cancel() { cancelled = true },
|
||||
})
|
||||
return new Response(body, { headers: { "content-type": "text/event-stream" } })
|
||||
})
|
||||
const res = await ask({ model: "gpt-5.4", stream: true, messages: [{ role: "user", content: "hi" }] })
|
||||
const reader = res.body.getReader()
|
||||
await reader.read() // the opening role chunk
|
||||
await reader.read() // "working on it"
|
||||
await reader.cancel() // the agent goes away, as making a tool call does
|
||||
await new Promise((r) => setTimeout(r, 100))
|
||||
expect(cancelled).toBe(true)
|
||||
})
|
||||
@@ -0,0 +1,253 @@
|
||||
// The usage card: the account's credits from its entitlement packs; and
|
||||
// the model list, the account's own when Trae answers.
|
||||
import "./nonet.mjs"
|
||||
import { afterEach, expect, test } from "bun:test"
|
||||
import { TraeGlobalAuthPlugin, _internal } from "./index.mjs"
|
||||
import { fakeTrae, json, signedIn, sse } from "./fake.mjs"
|
||||
|
||||
let f
|
||||
afterEach(() => f?.close())
|
||||
|
||||
test("credits are the packs' limits and what they used", async () => {
|
||||
f = fakeTrae()
|
||||
f.route("POST /trae/api/v1/pay/user_current_entitlement_list", () => json({
|
||||
billing_version: 3, is_dollar_usage_billing: true,
|
||||
user_entitlement_pack_list: [{
|
||||
display_desc: "Free plan",
|
||||
entitlement_base_info: {
|
||||
charge_amount: 0, currency: 0, end_time: 1793491199, ent_status: 0, start_time: 1790812800, user_id: "u-1",
|
||||
quota: { basic_usage_limit: 1, bonus_usage_limit: 0, credits_limit: 0, auto_completion_limit: 5000, advanced_model_request_limit: 1000, premium_model_fast_request_limit: 10, premium_model_slow_request_limit: 50 },
|
||||
},
|
||||
usage: { basic_usage_amount: 0.01692, bonus_usage_amount: 0, credits_amount: 0 },
|
||||
}],
|
||||
}))
|
||||
const hooks = await TraeGlobalAuthPlugin({ client: {} })
|
||||
const u = await hooks.auth.usage(async () => signedIn())
|
||||
expect(f.seen[0].path).toBe("/trae/api/v1/pay/user_current_entitlement_list")
|
||||
expect(f.seen[0].headers.get("authorization")).toBe("Cloud-IDE-JWT jwt-1")
|
||||
expect(u.plan).toBe("Free plan")
|
||||
expect(u.user).toBe("Ann")
|
||||
expect(u.signIn).toBe("kept")
|
||||
// the dollar allowance rides the window: $0.01692 of $1 used
|
||||
expect(u.windows).toEqual([{ name: "Dollar Usage", used: 1.69, amount: 0.02, limit: 1, unit: "usd", resetsAt: new Date(1793491199 * 1000).toISOString() }])
|
||||
})
|
||||
|
||||
test("bonus usage adds to the allowance, a US account asks its own pay host", async () => {
|
||||
f = fakeTrae()
|
||||
f.route("POST /trae/api/v1/pay/user_current_entitlement_list", () => json({
|
||||
user_entitlement_pack_list: [{
|
||||
display_desc: "Pro plan",
|
||||
entitlement_base_info: { end_time: 1793491199, quota: { basic_usage_limit: 20, bonus_usage_limit: 5 } },
|
||||
usage: { basic_usage_amount: 4.5, bonus_usage_amount: 1.5 },
|
||||
}],
|
||||
}))
|
||||
const hooks = await TraeGlobalAuthPlugin({ client: {} })
|
||||
const u = await hooks.auth.usage(async () => signedIn({ region: "US-East", api: "https://api-us-east.trae.ai" }))
|
||||
expect(u.windows).toEqual([{ name: "Dollar Usage", used: 24, amount: 6, limit: 25, unit: "usd", resetsAt: new Date(1793491199 * 1000).toISOString() }])
|
||||
})
|
||||
|
||||
test("a 401 reading usage marks the account", async () => {
|
||||
f = fakeTrae()
|
||||
f.route("POST /trae/api/v1/pay/user_current_entitlement_list", () => json({ code: 1001, message: "not login" }, 401))
|
||||
const hooks = await TraeGlobalAuthPlugin({ client: {} })
|
||||
const u = await hooks.auth.usage(async () => signedIn())
|
||||
expect(u.signIn).toBe("expired")
|
||||
expect(u.error).toContain("sign in again")
|
||||
})
|
||||
|
||||
async function given(hooks) {
|
||||
const cfg = { provider: {} }
|
||||
await hooks.config(cfg)
|
||||
const p = cfg.provider["trae-global"]
|
||||
return { id: "trae-global", models: Object.fromEntries(Object.entries(p.models).map(([id, m]) => [id, { id, ...m }])) }
|
||||
}
|
||||
|
||||
test("the config declares the known models; the live list replaces them", async () => {
|
||||
f = fakeTrae()
|
||||
f.route("POST /api/ide/v1/get_detail_param", () => json({ config_info_list: [
|
||||
{ config_name: "gpt-5.4", display_name: "GPT-5.4", context_window_size: { max: [400000] } },
|
||||
{ config_name: "gemini-3-flash", display_name: "Gemini 3 Flash" },
|
||||
] }))
|
||||
const hooks = await TraeGlobalAuthPlugin({ client: {} })
|
||||
const p = await given(hooks)
|
||||
expect(Object.keys(p.models)).toContain("gpt-5.4")
|
||||
const live = await hooks.provider.models(p, { auth: signedIn() })
|
||||
expect(Object.keys(live)).toEqual(["gpt-5.4", "gemini-3-flash"])
|
||||
expect(live["gpt-5.4"].limit.context).toBe(400000)
|
||||
// no batch list (404 here): one function at a time
|
||||
expect(f.seen[0].path).toBe("/api/ide/v1/batch_get_detail_param")
|
||||
expect(f.seen.slice(1).map((r) => r.json.function).sort()).toEqual(["chat_v3", "solo_agent", "solo_agent_lite", "solo_work_lite"])
|
||||
})
|
||||
|
||||
// what batch_get_detail_param answered TRAE SOLO, cut down: each function's
|
||||
// own list; gpt-5.4 is the TRAE agent's (solo_agent), where it names its
|
||||
// __dev model and its __max one; chat_v3 lists gemini-3-flash without one
|
||||
const BATCH = { function_configs: [
|
||||
{ function: "chat_v3", config_info_list: [
|
||||
{ config_name: "gemini-3-flash", usage: "chat_completion", display_config: { display_name: "Gemini 3 Flash" }, context_window_tokens: { dev: 200000 }, model_detail_list: [{ model_name: "gemini-3-flash__dev", max_tokens: 32000 }] },
|
||||
{ config_name: "summary", usage: "summary" },
|
||||
{ config_name: "custom_model_200k", usage: "chat_completion" },
|
||||
] },
|
||||
{ function: "solo_agent", config_info_list: [
|
||||
{ config_name: "gpt-5.4", usage: "chat_completion", display_config: { display_name: "GPT-5.4" }, context_window_tokens: { dev: 272000, max: 400000 }, model_detail_list: [{ model_name: "gpt-5.4__max", max_tokens: 128000 }, { model_name: "gpt-5.4__dev", max_tokens: 32000 }] },
|
||||
] },
|
||||
{ function: "builder", config_info_list: [{ config_name: "builder-only", usage: "chat_completion" }] },
|
||||
] }
|
||||
|
||||
test("the lists are asked in one batch, as TRAE SOLO asks them, and gpt-5.4's Max is a model of its own", async () => {
|
||||
f = fakeTrae()
|
||||
f.route("POST /api/ide/v1/batch_get_detail_param", () => json(BATCH))
|
||||
f.route("POST /api/agent/v3/llm_utils_chat", (r) => sse([["output", { response: r.json.function + " " + (r.json.model_name ?? "-") }], ["done", {}]]))
|
||||
const hooks = await TraeGlobalAuthPlugin({ client: {} })
|
||||
const p = await given(hooks)
|
||||
const live = await hooks.provider.models(p, { auth: signedIn() })
|
||||
// one ask, the client SOLO is
|
||||
expect(f.seen.map((r) => r.path)).toEqual(["/api/ide/v1/batch_get_detail_param"])
|
||||
const r = f.seen[0]
|
||||
expect(r.json).toEqual({
|
||||
functions: ["chat_v3", "solo_work_lite", "solo_agent", "solo_agent_lite"], agent_type: "", current_config_info: { config_name: "", is_custom_model: false },
|
||||
mode_type: 0, access_type: 0, ab_force_vids: "", ab_autotest_advanced_mode: 0, show_custom_model: true,
|
||||
})
|
||||
expect(r.headers.get("x-ide-version")).toBe("0.1.69")
|
||||
expect(r.headers.get("x-ide-version-code")).toBe("20260917")
|
||||
expect(r.headers.get("x-app-version-code")).toBe("20260917")
|
||||
// the IDE's helpers, custom-model slots, configs switched off and other functions' models aren't models to pick
|
||||
// and gpt-5.4's Max a model of its own (gemini-3-flash names no __max model)
|
||||
expect(Object.keys(live)).toEqual(["gemini-3-flash", "gpt-5.4", "gpt-5.4-max"])
|
||||
expect(live["gpt-5.4-max"].limit).toEqual({ context: 400000, output: 128000 })
|
||||
const m = live["gpt-5.4"]
|
||||
expect(m.name).toBe("GPT-5.4")
|
||||
expect(m.limit).toEqual({ context: 272000, output: 32000 })
|
||||
expect(live["gemini-3-flash"].limit).toEqual({ context: 200000, output: 32000 })
|
||||
const opts = await hooks.auth.loader(async () => signedIn())
|
||||
const ask = async (model) => {
|
||||
const res = await opts.fetch(opts.baseURL + "/chat/completions", { method: "POST", body: JSON.stringify({ model, messages: [{ role: "user", content: "hi" }] }) })
|
||||
return (await res.json()).choices[0].message.content
|
||||
}
|
||||
// asked through the function that serves it, with the model it names there
|
||||
expect(await ask("gpt-5.4")).toBe("solo_agent gpt-5.4__dev")
|
||||
expect(await ask("gemini-3-flash")).toBe("chat_v3 gemini-3-flash__dev")
|
||||
})
|
||||
|
||||
// the account's plan locks models the IDE greys out (a lock in its own
|
||||
// picker, a 1005 on a call): the display's access data names the identities
|
||||
// that may, 0 the Free one. The picker's invisible entries (paygo/auto
|
||||
// twins, the search agents) aren't entries to pick at all.
|
||||
const PLAN = { function_configs: [
|
||||
{ function: "chat_v3", config_info_list: [
|
||||
{ config_name: "gpt-5.4", usage: "chat_completion", display_config: { display_name: "GPT-5.4" }, display_contact_config: JSON.stringify({ access: { data: { identity_list: [0, 5, 4, 1, 2, 3] } } }), model_detail_list: [{ model_name: "gpt-5.4__dev", max_tokens: 32000 }] },
|
||||
{ config_name: "gpt-5.5", usage: "chat_completion", display_config: { display_name: "GPT-5.5" }, display_contact_config: JSON.stringify({ access: { data: { identity_list: [5, 4, 1, 2, 3] } } }), model_detail_list: [{ model_name: "gpt-5.5__dev", max_tokens: 32000 }] },
|
||||
{ config_name: "glm-5.2", usage: "chat_completion", display_config: { display_name: "GLM-5.2" }, model_detail_list: [{ model_name: "glm-5.2__dev", max_tokens: 32000 }] },
|
||||
{ config_name: "gemini-3.1-pro-paygo", usage: "chat_completion", display_config: { display_name: "Gemini 3.1 Pro" }, is_invisible_to_user: true, model_detail_list: [{ model_name: "gemini-3.1-pro-paygo__dev", max_tokens: 32000 }] },
|
||||
{ config_name: "search_agent", usage: "chat_completion", display_config: { display_name: "Search" }, is_invisible_to_user: true, model_detail_list: [{ model_name: "search_agent__dev" }] },
|
||||
] },
|
||||
] }
|
||||
|
||||
test("the plan's locked models are listed too — the account keeps what it pays for — while the picker's invisible ones are not", async () => {
|
||||
f = fakeTrae()
|
||||
f.route("POST /api/ide/v1/batch_get_detail_param", () => json(PLAN))
|
||||
f.route("POST /api/agent/v3/llm_utils_chat", () => sse([["output", { response: "ok" }], ["done", {}]]))
|
||||
const hooks = await TraeGlobalAuthPlugin({ client: {} })
|
||||
const p = await given(hooks)
|
||||
const live = await hooks.provider.models(p, { auth: signedIn() })
|
||||
// gpt-5.4's identities hold the 0 (Free); gpt-5.5's don't, so the IDE
|
||||
// greys it out on Free — but the plugin can't read the account's own
|
||||
// identity, so it lists it: a paying account (identity 1–5) keeps the
|
||||
// models it pays for, and a locked one answers Trae's own 1005 when
|
||||
// asked. glm-5.2 says nothing (nothing guessed); the invisible twins
|
||||
// (paygo/auto routing, search agents) are the picker's, not the list's
|
||||
expect(Object.keys(live)).toEqual(["gpt-5.4", "gpt-5.5", "glm-5.2"])
|
||||
})
|
||||
|
||||
test("a paying account keeps every model its plan has, the locked ones included", async () => {
|
||||
// a Pro / paid account (identity 1–5): the models Free can't pick are the
|
||||
// ones it pays for — gpt-5.5, the gpt-5.6 family, gpt-6, glm-5.2 — and
|
||||
// they must survive the listing, whichever identity the account is
|
||||
f = fakeTrae()
|
||||
f.route("POST /api/ide/v1/batch_get_detail_param", () => json(PLAN))
|
||||
f.route("POST /api/agent/v3/llm_utils_chat", () => sse([["output", { response: "ok" }], ["done", {}]]))
|
||||
const hooks = await TraeGlobalAuthPlugin({ client: {} })
|
||||
const p = await given(hooks)
|
||||
const paid = await hooks.provider.models(p, { auth: signedIn({ accountId: "Pro", uid: "u-pro" }) })
|
||||
expect(Object.keys(paid)).toEqual(["gpt-5.4", "gpt-5.5", "glm-5.2"])
|
||||
// and the paid model is asked as itself, not refused before it goes out
|
||||
const opts = await hooks.auth.loader(async () => signedIn({ accountId: "Pro", uid: "u-pro" }))
|
||||
await opts.fetch(opts.baseURL + "/chat/completions", { method: "POST", body: JSON.stringify({ model: "gpt-5.5", stream: true, messages: [{ role: "user", content: "hi" }] }) })
|
||||
expect(f.seen.at(-1).json.config_name).toBe("gpt-5.5")
|
||||
})
|
||||
|
||||
test("a 200 carrying an error code says Trae's own message, not \"no entitlement pack\"", async () => {
|
||||
f = fakeTrae()
|
||||
f.route("POST /trae/api/v1/pay/user_current_entitlement_list", () => json({ code: 4008, message: "quota exceeded" }))
|
||||
const hooks = await TraeGlobalAuthPlugin({ client: {} })
|
||||
const u = await hooks.auth.usage(async () => signedIn())
|
||||
expect(u.error).toBe("Trae Global usage: quota exceeded")
|
||||
expect(u.signIn).toBe("kept")
|
||||
expect(u.user).toBe("Ann")
|
||||
})
|
||||
|
||||
test("a batch answered with no lists falls back to one function at a time", async () => {
|
||||
f = fakeTrae()
|
||||
f.route("POST /api/ide/v1/batch_get_detail_param", () => json({ code: 0 }))
|
||||
f.route("POST /api/ide/v1/get_detail_param", (r) => json({ config_info_list: r.json.function === "solo_agent" ? [{ config_name: "gpt-5.4" }] : [] }))
|
||||
const hooks = await TraeGlobalAuthPlugin({ client: {} })
|
||||
const p = await given(hooks)
|
||||
expect(Object.keys(await hooks.provider.models(p, { auth: signedIn() }))).toEqual(["gpt-5.4"])
|
||||
})
|
||||
|
||||
test("signed out asking the batch marks the account", async () => {
|
||||
f = fakeTrae()
|
||||
f.route("POST /api/ide/v1/batch_get_detail_param", () => json({ code: 1001, message: "not login" }, 401))
|
||||
const hooks = await TraeGlobalAuthPlugin({ client: {} })
|
||||
const p = await given(hooks)
|
||||
await expect(hooks.provider.models(p, { auth: signedIn() })).rejects.toThrow("sign in again")
|
||||
})
|
||||
|
||||
test("one function's list failing leaves the other's", async () => {
|
||||
f = fakeTrae()
|
||||
f.route("POST /api/ide/v1/get_detail_param", (r) => r.json.function === "chat_v3"
|
||||
? json({ config_info_list: [{ config_name: "gemini-3-flash" }] })
|
||||
: new Response("down", { status: 503 }))
|
||||
const hooks = await TraeGlobalAuthPlugin({ client: {} })
|
||||
const p = await given(hooks)
|
||||
expect(Object.keys(await hooks.provider.models(p, { auth: signedIn() }))).toEqual(["gemini-3-flash"])
|
||||
})
|
||||
|
||||
test("when the list can't be read, the known models stand", async () => {
|
||||
f = fakeTrae()
|
||||
f.route("POST /api/ide/v1/get_detail_param", () => new Response("down", { status: 503 }))
|
||||
const hooks = await TraeGlobalAuthPlugin({ client: {} })
|
||||
const p = await given(hooks)
|
||||
expect(await hooks.provider.models(p, { auth: signedIn() })).toBe(p.models)
|
||||
})
|
||||
|
||||
// ARNO on magpie's Discord: a reply limit Trae never gives is none (0), and
|
||||
// magpie then tells agents models.dev's. One Trae gives is kept, and a
|
||||
// request asking more than it is held to it.
|
||||
test("a reply limit is Trae's own or none, and a request is held to Trae's", async () => {
|
||||
f = fakeTrae()
|
||||
f.route("POST /api/ide/v1/batch_get_detail_param", () => json({ function_configs: [
|
||||
{ function: "chat_v3", config_info_list: [
|
||||
{ config_name: "gpt-5.4", usage: "chat_completion", model_detail_list: [{ model_name: "gpt-5.4__dev", max_tokens: 32000 }] },
|
||||
{ config_name: "gemini-3-flash", usage: "chat_completion", context_window_tokens: { dev: 200000 }, model_detail_list: [{ model_name: "gemini-3-flash__dev" }] },
|
||||
{ config_name: "minimax-m2", usage: "chat_completion" },
|
||||
] },
|
||||
] }))
|
||||
f.route("POST /api/agent/v3/llm_utils_chat", (r) => sse([["output", { response: String(r.json.max_tokens) }], ["done", {}]]))
|
||||
const hooks = await TraeGlobalAuthPlugin({ client: {} })
|
||||
const p = await given(hooks)
|
||||
expect(p.models["minimax-m2"].limit.output).toBe(0)
|
||||
expect(p.models["deepseek-v3.2"].limit.output).toBe(0)
|
||||
const live = await hooks.provider.models(p, { auth: signedIn() })
|
||||
expect(live["gpt-5.4"].limit.output).toBe(32000)
|
||||
expect(live["gemini-3-flash"].limit).toEqual({ context: 200000, output: 0 })
|
||||
expect(live["minimax-m2"].limit.output).toBe(0)
|
||||
const opts = await hooks.auth.loader(async () => signedIn())
|
||||
const ask = async (model, max_tokens) => {
|
||||
const res = await opts.fetch(opts.baseURL + "/chat/completions", { method: "POST", body: JSON.stringify({ model, max_tokens, messages: [{ role: "user", content: "hi" }] }) })
|
||||
return (await res.json()).choices[0].message.content
|
||||
}
|
||||
expect(await ask("gpt-5.4", 131072)).toBe("32000")
|
||||
expect(await ask("gpt-5.4", 8000)).toBe("8000")
|
||||
expect(await ask("gemini-3-flash", 384000)).toBe("384000")
|
||||
})
|
||||
+3
-1
@@ -28,6 +28,8 @@
|
||||
{ "package": "@magpie-community/opencode-cline-auth", "name": "Cline", "icon": "cline", "providers": ["cline"], "community": true,
|
||||
"summary": { "en": "Cline's models on your own Cline account — usage billing, ClinePass and Cline's free models — with Cline's device sign-in or an API key.", "zh": "用自己的 Cline 账号使用 Cline 的模型——用量计费、ClinePass 与免费模型——支持 Cline 设备登录或 API key。" } },
|
||||
{ "package": "@magpie-community/opencode-trae-auth", "name": "Trae CN", "icon": "trae", "providers": ["trae-cn"], "community": true,
|
||||
"summary": { "en": "Trae CN (trae.cn) models with your Trae CN account, free tier included — Trae's own browser sign-in. Experimental.", "zh": "用 Trae CN(trae.cn)账号使用其模型,含免费版,使用 Trae 自己的浏览器登录。实验性。" } }
|
||||
"summary": { "en": "Trae CN (trae.cn) models with your Trae CN account, free tier included — Trae's own browser sign-in. Experimental.", "zh": "用 Trae CN(trae.cn)账号使用其模型,含免费版,使用 Trae 自己的浏览器登录。实验性。" } },
|
||||
{ "package": "@magpie-community/opencode-trae-global-auth", "name": "Trae Global", "icon": "trae", "providers": ["trae-global"], "community": true,
|
||||
"summary": { "en": "Trae international (trae.ai) models with your Trae international account, free tier included — Trae's own browser sign-in. Experimental.", "zh": "用 Trae 国际版(trae.ai)账号使用其模型,含免费版,使用 Trae 自己的浏览器登录。实验性。" } }
|
||||
]
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user