diff --git a/README.md b/README.md index c84acf9..9aa9a44 100644 --- a/README.md +++ b/README.md @@ -19,8 +19,7 @@ subscription and makes its requests. The packages work in OpenCode and in | [mimo](packages/mimo) | Xiaomi MiMo, with a Xiaomi account | `mimo-app` | | [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` | +| [trae](packages/trae) | Trae CN (trae.cn) and Trae international (trae.ai), free tier included, with Trae's browser sign-in (experimental) | `trae-cn`, `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` | diff --git a/packages/trae-global/README.md b/packages/trae-global/README.md deleted file mode 100644 index 4ef83c5..0000000 --- a/packages/trae-global/README.md +++ /dev/null @@ -1,105 +0,0 @@ -# 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` 时,会作为 -第二个模型列出(`-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 轮次:工具原生带给它、也写进系统提示词,模型 -可能以 `{...}` 文本块(含 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(插件模块被进程缓存)。 diff --git a/packages/trae-global/fake.mjs b/packages/trae-global/fake.mjs deleted file mode 100644 index b8df4d2..0000000 --- a/packages/trae-global/fake.mjs +++ /dev/null @@ -1,49 +0,0 @@ -// 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, -}) diff --git a/packages/trae-global/index.mjs b/packages/trae-global/index.mjs deleted file mode 100644 index f3e919e..0000000 --- a/packages/trae-global/index.mjs +++ /dev/null @@ -1,1586 +0,0 @@ -// Trae Global (trae.ai), ByteDance's AI IDE's international deployment, as -// the IDE signs in to it and asks its models: trae.ai's authorization page -// sends the browser back to a callback on 127.0.0.1 with the account's -// Cloud-IDE-JWT and refresh token; the refresh token is exchanged for a new -// JWT at /cloudide/api/v3/trae/oauth/ExchangeToken on the SG auth host; -// model requests go to the IDE agent's /api/agent/v3/llm_utils_chat on the -// SG chat host, which answers in its own SSE events. Worked out from the -// realm table of wangqi233/trae2api (cn/sg dual-region) and the login URL of -// wefew/trae2api; the plugin contract and the request/answer machinery -// follow @magpie-community/opencode-trae-auth (Trae CN) with every -// realm-specific value swapped for the international one. -import { randomBytes, randomUUID, randomInt } from "node:crypto" -import { createServer, STATUS_CODES } from "node:http" - -const ID = "trae-global" -// where each part of Trae Global is served; tests point them at a fake -const HOSTS = { - web: "https://www.trae.ai", // the authorization page - auth: "https://growsg-normal.trae.ai", // tokens, the account - api: "https://coresg-normal.trae.ai", // the models - us: "https://coreva-normal.trae.ai", // the models, the US deployment - usPay: "https://api-us-east.trae.ai", // usage, the US deployment - pay: "https://api-sg-central.trae.ai", // usage -} -// where usage (the dollar billing's entitlements) is asked: the US account -// pays on its own host, the rest on the central one — the auth host's own -// /cloudide/api/v2/pay pages are 403 Api Scope Forbidden here -const payHost = (a) => (/^US(?:[-_ ]|$)/i.test(String(a?.region ?? "")) || /api-us/i.test(String(a?.api ?? "")) ? HOSTS.usPay : HOSTS.pay) -// the international IDE's client; the SG realm table names it for both the -// SOLO and the IDE client (the CN SOLO's en1oxy7wnw8j9n is a CN-only id) -const CLIENT_ID = "ono9krqynydwx5" -const APP_ID = "6eefa01c-1036-4c7e-9ca5-d891f63bfcd8" -const IDE_VERSION = "3.5.51" // named to the international IDE's current build -const IDE_VERSION_CODE = "20260401" -// the client the model host is told it serves: TRAE SOLO (international) as -// its ai-agent names itself. Trae offers a model only to clients new enough -// for it. -const CLIENT_VERSION = "0.1.69" -const CLIENT_VERSION_CODE = "20260917" -const PLUGIN_VERSION = "2.3.62834" -const BRAND = "ASUS TUF Gaming A15 FA507RM_FA507RM" -const SIGN_IN_TIMEOUT = 10 * 60 * 1000 -const EARLY_MS = 2 * 60 * 1000 // a token this close to its end is renewed before a request -const LEAD_MS = 10 * 60 * 1000 // and this close, magpie renews it ahead of time (auth.refresh) -const DAY = 24 * 3600 * 1000 -// the IDE's chat functions: the classic IDE's agent, then SOLO's Work -// mode, then the TRAE agent, then SOLO Lite's agent -const FUNCTIONS = ["chat_v3", "solo_work_lite", "solo_agent", "solo_agent_lite"] - -// a reply limit of 0 is one Trae doesn't say: magpie then takes models.dev's -// for the model (magpie's catalog), where a made-up 32K told agents a far -// smaller one than DeepSeek V4.1 Flash's (ARNO on magpie's Discord) -const MODEL = { attachment: false, tool_call: true, reasoning: true, temperature: true, limit: { context: 128_000, output: 0 }, modalities: { input: ["text"], output: ["text"] } } -// what Trae Global's chat is known to serve (its catalog barely overlaps -// Trae CN's: GPT, Gemini, Kimi, MiniMax, DeepSeek-V3…); the live list -// replaces it -const MODELS = { - "gpt-5.4": { name: "GPT-5.4", ...MODEL }, - "gemini-3-flash": { name: "Gemini 3 Flash", ...MODEL, limit: { context: 1_000_000, output: 0 } }, - "kimi-k2.5": { name: "Kimi K2.5", ...MODEL, limit: { context: 256_000, output: 0 } }, - "minimax-m2": { name: "MiniMax M2", ...MODEL }, - "deepseek-v3.2": { name: "DeepSeek V3.2", ...MODEL }, -} - -const digits = (n) => Array.from({ length: n }, (_, i) => (i === 0 ? randomInt(1, 10) : randomInt(0, 10))).join("") -const statusLine = (status) => `${status} ${STATUS_CODES[status] ?? ""}`.trim() - -// device is the machine an account signs in from, made once at sign-in and -// named to trae.ai's authorization page, then sent with every request: a -// fresh one each time is what the relays saw requests dropped for. -const newDevice = () => ({ deviceId: digits(19), machineId: randomBytes(16).toString("hex") }) - -// whenOf reads one of Trae's expiry times: seconds, milliseconds or ISO -function whenOf(v) { - if (v === undefined || v === null || v === "") return 0 - if (typeof v === "string" && !/^\d+$/.test(v.trim())) { - const t = Date.parse(v) - return isNaN(t) ? 0 : t - } - const n = Number(v) - if (!Number.isFinite(n) || n <= 0) return 0 - return n < 1e11 ? n * 1000 : n -} - -// jwtExp is a JWT's exp, in ms, 0 when it has none -function jwtExp(token) { - try { - const p = JSON.parse(Buffer.from(String(token).split(".")[1], "base64url").toString()) - return whenOf(p?.exp) - } catch { - return 0 - } -} - -const parseJSON = (s) => { - if (s && typeof s === "object") return s - try { - const v = JSON.parse(String(s ?? "")) - return v && typeof v === "object" ? v : {} - } catch { - return {} - } -} - -// ---- the sign-in as kept ------------------------------------------------------ - -// The sign-in is kept as OpenCode keeps an OAuth one: access the -// Cloud-IDE-JWT, refresh the refresh token, expires the JWT's end; beside -// them the account, the client it was issued to, its device and the model -// host its account region names (the US one chats on its own host). -function regionOf(s) { - return String(s?.region ?? s?.aiRegion ?? s?.Region ?? s?.AIRegion ?? "").trim() -} - -function toAuth(s) { - return { - type: "oauth", - access: s.token, - refresh: s.refresh, - expires: s.expires || jwtExp(s.token) || Date.now() + DAY, - accountId: s.name || s.uid, - uid: s.uid, - clientId: s.clientId || CLIENT_ID, - deviceId: s.deviceId, - machineId: s.machineId, - // Keep the account's region and the host named by the sign-in. The - // latter can be an auth host (api-us-east), not the chat host. - ...(regionOf(s) ? { region: regionOf(s) } : {}), - ...(/trae\.ai/i.test(s.api ?? "") ? { api: s.api } : {}), - } -} - -function fromAuth(auth) { - if (auth?.type !== "oauth" || !auth.access) return null - return { - token: auth.access, - refresh: auth.refresh ?? "", - expires: Number(auth.expires) || 0, - uid: String(auth.uid ?? ""), - name: String(auth.accountId ?? ""), - clientId: auth.clientId || CLIENT_ID, - deviceId: auth.deviceId || "", - machineId: auth.machineId || "", - api: auth.api || "", - region: regionOf(auth), - } -} - -// apiOf is the model host for an account. Trae's sign-in may name an auth -// host such as api-us-east.trae.ai, so only known chat hosts are accepted; -// the account region selects the US deployment when no chat host was named. -function apiOf(a) { - const h = String(a?.api ?? "").replace(/\/+$/, "") - const region = regionOf(a).toUpperCase() - if (/coreva/i.test(h) || /api-us(?:[-.]|$)/i.test(h) || /^US(?:[-_ ]|$)/.test(region)) return HOSTS.us - if (/coresg/i.test(h)) return h - return HOSTS.api -} - -// ---- errors -------------------------------------------------------------------- - -class Expired extends Error { - constructor(msg) { - super(msg) - this.signIn = "expired" - } -} - -// errorOf is what Trae said went wrong, from its several shapes: a business -// {code, message}, {error: {code, message}}, or ByteDance's -// {ResponseMetadata: {Error: {Code, Message}}} -function errorOf(v) { - v = parseJSON(v) - const meta = v?.ResponseMetadata?.Error - if (meta && (meta.Code || meta.Message)) return { code: meta.Code ?? "", message: String(meta.Message ?? meta.Code ?? "") } - const e = v?.error && typeof v.error === "object" ? v.error : v - const code = e?.code ?? e?.Code ?? v?.code ?? "" - const message = e?.message ?? e?.msg ?? e?.Message ?? (typeof v?.error === "string" ? v.error : "") ?? "" - return { code, message: String(message || "") } -} - -// lapsed: Trae turned the token away. 1001 is its "not signed in", and the -// SG hosts answer ByteDance's 20101 to a token they won't take -const lapsedCode = (code) => [1001, "1001", 20101, "20101", 401, "401"].includes(code) -const lapsedWords = /not ?log(ged)? ?in|unauthori[sz]ed|token (is )?(expired|invalid)|jwt|not able to authenticate/i -const quotaCode = (code) => [4008, "4008", 1005, "1005", 4011, "4011"].includes(code) -const quotaWords = /quota|credit|insufficient|exceed|limit|额度|积分|次数|上限|用完/i - -// errorResponse is an OpenAI-style error, as the agent reads one -const errorResponse = (status, message, signIn) => { - const headers = { "content-type": "application/json" } - if (signIn) headers["X-Magpie-Sign-In"] = signIn - return new Response(JSON.stringify({ error: { message, type: status === 429 ? "rate_limit_error" : "api_error", code: null } }), { status, headers }) -} - -// ---- tokens ----------------------------------------------------------------------- - -// exchange trades a refresh token for a new Cloud-IDE-JWT, as the IDE does: -// the answer's Result holds the new token pair and the account. Trae issues -// a new refresh token each time and spends the old one. The international -// auth host wraps the pair in Result like the CN one does. - -async function exchange(refresh, clientId, host = HOSTS.auth) { - let res - try { - res = await fetch(host.replace(/\/+$/, "") + "/cloudide/api/v3/trae/oauth/ExchangeToken", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ ClientID: clientId || CLIENT_ID, RefreshToken: refresh, ClientSecret: "-", UserID: "" }), - signal: AbortSignal.timeout(20_000), - }) - } catch (e) { - throw new Error("Trae Global: renewing the sign-in: " + (e?.message ?? e)) - } - const text = await res.text() - const v = parseJSON(text) - const r = v.Result ?? v.result ?? v - const token = r?.Token ?? r?.token ?? "" - if (res.ok && token) { - const info = parseJSON(r.UserInfo ?? r.userInfo) - return { - token, - refresh: r.RefreshToken ?? r.refreshToken ?? refresh, - expires: whenOf(r.TokenExpireAt ?? r.tokenExpireAt) || jwtExp(token), - clientId: r.ClientID ?? r.clientId ?? clientId, - uid: String(info.UserID ?? info.userId ?? r.UserID ?? ""), - name: String(info.ScreenName ?? info.screenName ?? ""), - api: info.Host ?? "", - region: regionOf(info), - } - } - const e = errorOf(text) - const msg = e.message || (text.trim() ? text.trim().slice(0, 200) : statusLine(res.status)) - // a refresh token Trae no longer takes (spent, revoked, past its end, or - // of another client) is a sign-in to make again - if ([400, 401, 403].includes(res.status) || /refresh|expired|invalid|not matched|revoked|unauthori/i.test(msg) || ["10101", "20101"].includes(String(e.code))) { - throw new Expired(`Trae Global's sign-in has expired (${msg}); sign in again`) - } - throw new Error(`Trae Global: renewing the sign-in: ${statusLine(res.status)} ${msg}`.trim()) -} - -// ---- the browser sign-in -------------------------------------------------------- - -const page = (ok, title, text) => `${title} - -

${title}

${String(text).replace(/[<>&]/g, (c) => ({ "<": "<", ">": ">", "&": "&" })[c])}

` - -// signedIn reads trae.ai's callback: userJwt (the token pair) and userInfo -// (the account), or, from its older page, a refresh token alone, which is -// exchanged for the pair. The international callback names the account's -// region TenantID; the Host, when given, is its model host. -async function signedIn(q, device) { - const jwt = parseJSON(q.get("userJwt")) - const info = parseJSON(q.get("userInfo")) - const host = q.get("host") || info.Host || "" - let s = { - token: jwt.Token ?? jwt.token ?? "", - refresh: jwt.RefreshToken ?? jwt.refreshToken ?? q.get("refreshToken") ?? "", - expires: whenOf(jwt.TokenExpireAt ?? jwt.tokenExpireAt), - clientId: jwt.ClientID ?? jwt.clientId ?? q.get("clientId") ?? CLIENT_ID, - uid: String(info.UserID ?? info.userId ?? q.get("userId") ?? ""), - name: String(info.ScreenName ?? info.screenName ?? ""), - api: host, - region: regionOf(info), - } - if (!s.token && s.refresh) { - const x = await exchange(s.refresh, s.clientId) - s = { ...s, ...x, uid: x.uid || s.uid, name: x.name || s.name, api: x.api || s.api, region: x.region || s.region } - } - if (!s.token) throw new Error("trae.ai sent back no token") - if (!s.refresh) throw new Error("trae.ai sent back no refresh token") - return { ...s, ...device } -} - -// browserSignIn is the IDE's sign-in: trae.ai's authorization page, back to -// a callback on 127.0.0.1 (the page takes no other kind) -async function browserSignIn() { - const device = newDevice() - const trace = randomUUID() - let over = false - let settle - const done = new Promise((r) => (settle = r)) - const finish = (result) => { - if (over) return - over = true - settle(result) - } - const server = createServer(async (req, res) => { - // trae.ai's page may call the callback from script as well as open it - const cors = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, OPTIONS", "Access-Control-Allow-Headers": "Content-Type" } - if (req.method === "OPTIONS") return res.writeHead(204, cors).end() - const url = new URL(req.url ?? "/", "http://127.0.0.1") - const html = (body) => { - res.writeHead(200, { ...cors, "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" }) - res.end(body) - } - if (url.pathname !== "/authorize") return res.writeHead(404, cors).end() - const q = url.searchParams - if (over) return html(page(false, "This sign-in is over", "Start it again in magpie.")) - if (q.get("error")) { - const msg = q.get("error_description") || q.get("error") - finish({ type: "failed", error: msg }) - return html(page(false, "Sign-in didn't finish", msg)) - } - if (!q.get("userJwt") && !q.get("refreshToken")) return html(page(false, "Nothing to sign in with", "trae.ai sent no token; start the sign-in again.")) - try { - const s = await signedIn(q, device) - finish({ ...toAuth(s), type: "success" }) - html(page(true, "You're signed in", `${s.name || s.uid || "Your Trae account"} is signed in. You can close this tab.`)) - } catch (e) { - finish({ type: "failed", error: e.message }) - html(page(false, "Sign-in didn't finish", e.message)) - } - }) - await new Promise((resolve, reject) => { - server.once("error", reject) - server.listen(0, "127.0.0.1", resolve) - }) - const callback = `http://127.0.0.1:${server.address().port}/authorize` - const timer = setTimeout(() => finish({ type: "failed", error: "the sign-in timed out" }), SIGN_IN_TIMEOUT) - done.then(() => { - clearTimeout(timer) - setTimeout(() => server.close(), 5_000).unref?.() - }) - const q = new URLSearchParams({ - login_version: "1", - auth_from: "solo", - login_channel: "native_ide", - plugin_version: PLUGIN_VERSION, - auth_type: "local", - client_id: CLIENT_ID, - redirect: "0", - login_trace_id: trace, - auth_callback_url: callback, - machine_id: device.machineId, - device_id: device.deviceId, - x_device_id: device.deviceId, - x_machine_id: device.machineId, - x_device_brand: BRAND, - x_device_type: "windows", - x_os_version: "Windows 10 Pro", - x_env: "", - x_app_version: IDE_VERSION, - x_app_type: "stable", - hide_saas_login: "true", - }) - return { - url: `${HOSTS.web}/authorization?${q}`, - instructions: "Sign in to Trae (trae.ai, the international Trae) in the browser and allow the sign-in. It finishes here by itself. A trae.cn account won't work here — that is the other plugin.", - method: "auto", - callback: () => done, - } -} - -// ---- requests --------------------------------------------------------------------- - -// headers are the IDE's, for the account and its device -function ideHeaders(a, extra = {}) { - return { - "Content-Type": "application/json", - Authorization: `Cloud-IDE-JWT ${a.token}`, - "X-Cloudide-Token": a.token, - "x-ide-token": a.token, - "x-uid": a.uid, - "x-app-id": APP_ID, - "x-device-id": a.deviceId, - "x-machine-id": a.machineId, - "x-request-id": randomUUID(), - "x-app-version": CLIENT_VERSION, - "x-app-version-code": CLIENT_VERSION_CODE, - "x-ide-version": CLIENT_VERSION, - "x-ide-version-code": CLIENT_VERSION_CODE, - "x-ide-version-type": "stable", - "x-device-cpu": "AMD", - "x-device-brand": BRAND, - "x-device-type": "windows", - "x-os-version": "Windows 10", - "x-system-type": "Windows", - ...extra, - } -} - -// Trae's chat takes text only and has no turn for a tool call or its -// result. The agent's tools are named to it natively and in a system -// prompt that asks for each call as a tagged block; earlier calls and -// their results go in as text. A native call in its answer is taken too. -const OPEN = "" -const CLOSE = "" - -function toolPrompt(tools, choice, parallel) { - const defs = tools.map((t) => { - const f = t.function ?? t - return { name: f.name, description: f.description ?? "", parameters: f.parameters ?? {} } - }) - const lines = [ - "You can call the client's tools, listed below as JSON. They run on the user's machine, not on yours: use no built-in or server tool to reach the user's files.", - `To call a tool, write one block per call and nothing after it: ${OPEN}{"name":"tool_name","arguments":{...}}${CLOSE}. Use an exact tool name and fill arguments from its schema. Then stop and wait: the result comes back in the next message.`, - "A call is not done until its result comes back; don't say it is, and don't repeat a call whose result you have.", - ] - if (parallel === false) lines.push("Call at most one tool at a time.") - if (choice === "required") lines.push("Call a tool before answering.") - else if (choice && typeof choice === "object" && (choice.function?.name || choice.name)) lines.push(`Call the tool ${choice.function?.name || choice.name} before answering.`) - lines.push("Tools:", JSON.stringify(defs)) - return lines.join("\n") -} - -const partText = (content) => { - if (typeof content === "string") return content - if (!Array.isArray(content)) return content == null ? "" : String(content) - return content - .map((p) => (typeof p === "string" ? p : p?.type === "text" || p?.type === "input_text" ? p.text ?? "" : p?.type === "image_url" ? "[an image, which this model can't see]" : "")) - .filter(Boolean) - .join("\n") -} - -// traeMessages is the conversation as Trae's chat takes it -function traeMessages(req) { - const tools = Array.isArray(req.tools) && req.tools.length && req.tool_choice !== "none" ? req.tools : [] - const names = new Map() - const out = [] - if (tools.length) out.push({ role: "system", text: toolPrompt(tools, req.tool_choice, req.parallel_tool_calls) }) - for (const m of req.messages ?? []) { - const role = m.role === "developer" ? "system" : m.role - let text = partText(m.content) - if (role === "assistant") { - const calls = (m.tool_calls ?? []).map((c) => { - names.set(c.id, c.function?.name) - let args = c.function?.arguments ?? "{}" - try { - args = JSON.parse(args) - } catch {} - return OPEN + JSON.stringify({ name: c.function?.name, arguments: args }) + CLOSE - }) - text = [text, ...calls].filter(Boolean).join("\n") - out.push({ role: "assistant", text }) - } else if (role === "tool") { - out.push({ role: "user", text: `Result of ${names.get(m.tool_call_id) || m.name || "the tool"} (call ${m.tool_call_id ?? "?"}):\n${text}` }) - } else { - out.push({ role: role === "system" ? "system" : "user", text }) - } - } - // Trae takes no empty message, nor two of one role in a row - const merged = [] - for (const m of out) { - if (!m.text) continue - const last = merged.at(-1) - if (last && last.role === m.role && m.role !== "system") last.text += "\n\n" + m.text - else merged.push({ ...m }) - } - return merged.map((m) => ({ role: m.role, content: [{ type: "text", text: m.text }] })) -} - -// nativeTools are the tools as Trae names them: parameters a JSON string -const nativeTools = (tools) => - tools.map((t) => { - const f = t.function ?? t - return { type: "function", function: { name: f.name, description: f.description ?? "", parameters: typeof f.parameters === "string" ? f.parameters : JSON.stringify(f.parameters ?? {}) } } - }) - -// 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() - const config = max?.base ?? req.model - const body = { - messages: traeMessages(req), - function: fn, - config_name: config, - model: config, - ...(modelName ? { model_name: modelName } : {}), - stream: true, // Trae answers in SSE either way - request_id: session, - session_id: session, - } - 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) - if (max?.window) { - if (!body.max_tokens && most > 0) body.max_tokens = most - body.user_message_context = { model_info: { prompt_max_tokens: max.window - (body.max_tokens || 0) } } - } - if (typeof req.temperature === "number") body.temperature = req.temperature - if (Array.isArray(req.tools) && req.tools.length && req.tool_choice !== "none") { - body.tools = nativeTools(req.tools) - const c = req.tool_choice - if (c && typeof c === "object") body.tool_choice = c.function?.name || c.name || "auto" - else if (typeof c === "string") body.tool_choice = c - if (typeof req.parallel_tool_calls === "boolean") body.parallel_tool_calls = req.parallel_tool_calls - } - return body -} -// sse reads Trae's events: {event, data} for each, data parsed when JSON -async function* sse(stream) { - const reader = stream.getReader() - const dec = new TextDecoder() - let buf = "" - let event = "" - let data = [] - const flush = function* () { - if (!data.length) return - const raw = data.join("\n") - data = [] - let v = raw - try { - v = JSON.parse(raw) - } catch {} - yield { event: event || (v && typeof v === "object" ? String(v.event ?? v.type ?? "") : ""), data: v } - event = "" - } - try { - for (;;) { - const { value, done } = await reader.read() - if (done) break - buf += dec.decode(value, { stream: true }) - let i - while ((i = buf.indexOf("\n")) >= 0) { - const line = buf.slice(0, i).replace(/\r$/, "") - buf = buf.slice(i + 1) - if (!line) { - yield* flush() - continue - } - if (line.startsWith(":")) continue - if (line.startsWith("event:")) { - yield* flush() - event = line.slice(6).trim() - } else if (line.startsWith("data:")) data.push(line.slice(5).trimStart()) - } - } - buf += dec.decode() - if (buf.startsWith("data:")) data.push(buf.slice(5).trimStart()) - yield* flush() - } finally { - // the answer the agent goes away from (a tool call made, a request - // aborted) closes this generator mid-read: let Trae's connection go, - // or the read hangs on and the host the next ask reuses is one Trae - // has dropped — a stream that runs, then dies (#: cancelling) - reader.cancel().catch(() => {}) - } -} - -// normalised event names: "TokenUsage", "token-usage" → token_usage -const eventName = (s) => - String(s ?? "") - .replace(/([a-z0-9])([A-Z])/g, "$1_$2") - .replace(/[^A-Za-z0-9]+/g, "_") - .toLowerCase() - .replace(/^_|_$/g, "") - -// usageOf maps Trae's token counts to OpenAI's -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 - if (!p && !c) return null - return { prompt_tokens: p, completion_tokens: c, total_tokens: Number(u.total_tokens ?? u.totalTokens) || p + c } -} - -let callSeq = 0 -const callId = () => "call_" + randomBytes(12).toString("hex") + (callSeq++).toString(36) - -// TextTools splits the model's text into what the agent sees and the tool -// calls it wrote as blocks, holding back the start of a block until it -// is whole. A block is ours ({…}), its JSON taken -// once whole even when DeepSeek closes it with its own tags in place of -// , or DeepSeek's (<|DSML|invoke name="…">, magpie#823); the -// tags left around a call are dropped. -// -// GLM writes a call as its own template has it, name -// kv, which is read -// too; and a {"reasoning_content": …} object in the text is the model's -// reasoning, not its answer (歧路亡羊 on magpie's Discord). -class TextTools { - constructor(tools = []) { - this.buf = "" - this.after = false - this.tools = tools - } - push(s, end = false) { - this.buf += s - let text = "" - let reasoning = "" - const calls = [] - for (;;) { - if (this.after) { - const m = this.buf.match(LEFTOVER) - if (m) this.buf = this.buf.slice(m[0].length) - if (!this.buf || (!end && MARKS.some((k) => k.startsWith(this.buf)))) break - // a tag cut short at the end ( 1 && MARKS.some((k) => k.startsWith(this.buf.trimEnd()))) { - this.buf = "" - break - } - this.after = false - } - const i = this.buf.indexOf(OPEN) - const d = this.buf.search(DSML_AT) - const r = this.buf.search(REASON_AT) - if (r >= 0 && (i < 0 || r < i) && (d < 0 || r < d)) { - const o = objectEnd(this.buf, r) - if (o === -1 && !end) { - // not whole yet: held, the text before it sent - text += this.buf.slice(0, r) - this.buf = this.buf.slice(r) - break - } - const v = o > 0 ? looseJSON(this.buf.slice(r, o)) : null - if (v && typeof v.reasoning_content === "string") { - text += this.buf.slice(0, r) - reasoning += v.reasoning_content - this.buf = this.buf.slice(o) - continue - } - // not one after all: text, and what follows read on - text += this.buf.slice(0, r + 1) - this.buf = this.buf.slice(r + 1) - continue - } - if (i < 0 && d < 0) break - if (d >= 0 && (i < 0 || d < i)) { - text += this.buf.slice(0, d) - this.buf = this.buf.slice(d) - const tag = this.buf.match(DSML_TAG) - if (!tag) { - // a tag not closed yet; at the end, or with another tag after it, - // a stray one dropped - const next = this.buf.indexOf("<", 1) - if (next < 0 && !end) break - this.buf = next < 0 ? "" : this.buf.slice(next) - continue - } - const inv = tag[0].match(DSML_INVOKE) - if (!inv) { - // function_calls, a parameter's close, any other tag: dropped, - // with the blanks after it - this.buf = this.buf.slice(tag[0].length) - this.after = true - continue - } - const body = this.buf.slice(tag[0].length) - const c = body.match(DSML_CLOSE) - const n = body.search(DSML_INVOKE_AT) - let stop = c ? c.index : n >= 0 ? n : -1 - if (n >= 0 && n < stop) stop = n - if (stop < 0) { - if (!end) break - stop = body.length - } - calls.push({ name: inv[1], arguments: dsmlArgs(body.slice(0, stop)) }) - this.buf = body.slice(c && c.index === stop ? stop + c[0].length : stop) - this.after = true - continue - } - const o = objectEnd(this.buf, i + OPEN.length) - const inner = this.buf.slice(i + OPEN.length).trimStart() - if (inner.startsWith("<") || (end && !inner)) { - // no JSON in it: DeepSeek's own invoke, or only the closes of one - // (magpie#823 again); the opener is dropped and what follows read - // as it is - text += this.buf.slice(0, i) - this.buf = inner - this.after = true - continue - } - const v = o > 0 ? looseJSON(this.buf.slice(i + OPEN.length, o)) : null - if (v?.name) { - text += this.buf.slice(0, i) - calls.push({ name: String(v.name), arguments: callArgs(v) }) - this.buf = this.buf.slice(o) - this.after = true - continue - } - let j = this.buf.indexOf(CLOSE, i + OPEN.length) - if (j < 0) { - // GLM's call, cut short at the end, is still the call - if (!end || !glmCall(this.buf.slice(i + OPEN.length), this.tools)) break - j = this.buf.length - } - text += this.buf.slice(0, i) - const raw = this.buf.slice(i + OPEN.length, j).trim() - this.buf = this.buf.slice(j + CLOSE.length) - const w = looseJSON(raw) ?? glmCall(raw, this.tools) ?? {} - if (w.name) { - calls.push({ name: String(w.name), arguments: callArgs(w) }) - this.after = true - } else text += OPEN + raw + CLOSE - } - if (end) { - text += this.buf - this.buf = "" - } else { - // keep back an opened block, or what may be the start of one - const at = [this.buf.indexOf(OPEN), this.buf.search(DSML_AT), this.buf.search(REASON_AT)].filter((x) => x >= 0) - let keep = at.length ? this.buf.length - Math.min(...at) : 0 - if (!keep) for (let k = Math.min(MARK_MAX - 1, this.buf.length); k > 0; k--) if (MARKS.some((m) => m.startsWith(this.buf.slice(-k)))) { keep = k; break } - text += this.buf.slice(0, this.buf.length - keep) - this.buf = this.buf.slice(this.buf.length - keep) - } - return { text, calls, reasoning } - } -} - -// GLM's call template: the tool's name, then each argument as -// kv -const GLM_ARG = /\s*([\s\S]*?)\s*<\/arg_key>\s*([\s\S]*?)<\/arg_value>/g - -// glmCall is a call GLM wrote in its template ({name, arguments}), null -// when s isn't one. A value is its text where the tool's schema says -// string (or the text isn't JSON), else its JSON, as GLM's template writes -// a value that isn't a string. A name alone is a call only to a tool the -// request has. -function glmCall(s, tools = []) { - s = String(s ?? "").replace(/<\/tool_call>\s*$/, "") - const k = s.indexOf("") - const name = (k < 0 ? s : s.slice(0, k)).trim() - if (!/^[\w.:-]{1,128}$/.test(name)) return null - if (k < 0 && !tools.some((t) => (t.function ?? t)?.name === name)) return null - const props = (tools.find((t) => (t.function ?? t)?.name === name)?.function ?? {}).parameters?.properties ?? {} - const args = {} - for (const m of s.matchAll(GLM_ARG)) { - const raw = m[2] - if (props[m[1]]?.type === "string") { - args[m[1]] = raw - continue - } - try { - args[m[1]] = JSON.parse(raw.trim()) - } catch { - args[m[1]] = raw - } - } - if (k >= 0 && !Object.keys(args).length) return null - return { name, arguments: args } -} - -// toolNamed is the request's own name for a tool a model named otherwise -// (Read for read, list-files for list_files); name itself when the request -// has none like it. A tool it has none of goes on as named: the agent tells -// the model there's no such tool, which it can act on, where a call -// dropped here would end the turn with nothing. -function toolNamed(name, tools) { - const names = tools.map((t) => (t.function ?? t)?.name).filter(Boolean) - if (!names.length || names.includes(name)) return name - const norm = (n) => String(n).toLowerCase().replace(/[^a-z0-9]/g, "") - return names.find((n) => norm(n) === norm(name)) ?? name -} - -// DeepSeek's tags, with its full-width bar or a plain one -const DSML = String.raw`<\s*\/?\s*[||][\s||]*DSML[\s||]*` -const DSML_AT = new RegExp(DSML) -const DSML_TAG = new RegExp("^" + DSML + "[^<>]*>") -const DSML_INVOKE = new RegExp(String.raw`^<\s*[||][\s||]*DSML[\s||]*invoke\s+name\s*=\s*"([^"]+)"\s*>`) -const DSML_INVOKE_AT = new RegExp(String.raw`<\s*[||][\s||]*DSML[\s||]*invoke\s+name\s*=`) -const DSML_CLOSE = new RegExp(String.raw`<\s*\/\s*[||][\s||]*DSML[\s||]*invoke\s*>`) -const DSML_PARAM = new RegExp(String.raw`<\s*[||][\s||]*DSML[\s||]*parameter\s+name\s*=\s*"([^"]+)"((?:\s+\w+\s*=\s*"[^"]*")*)\s*>([\s\S]*?)` + DSML + String.raw`parameter\s*>`, "g") -// what is left after a call: blanks, our close, DeepSeek's tags but the -// next call's -const LEFTOVER = new RegExp(String.raw`^(?:\s+|<\/tool_calls?>||` + DSML + String.raw`(?![\s||]*invoke\b)[^<>]*>)+`) -// what text may be the start of, so held back -const MARKS = [OPEN, CLOSE, "<|DSML|", "<|DSML|", " m.length)) - -// dsmlArgs is the arguments of a DSML invoke as JSON: a parameter marked -// string="true" is its text, any other its JSON (its text when not JSON) -function dsmlArgs(body) { - const args = {} - for (const p of body.matchAll(DSML_PARAM)) { - if (/string\s*=\s*"true"/.test(p[2])) { - args[p[1]] = p[3] - continue - } - try { - args[p[1]] = JSON.parse(p[3].trim()) - } catch { - args[p[1]] = p[3] - } - } - return JSON.stringify(args) -} - -// objectEnd is where the JSON object starting at from (after blanks) ends: -// past its closing brace, -1 when it isn't whole yet, -2 when there's none -function objectEnd(s, from) { - let k = from - while (k < s.length && /\s/.test(s[k])) k++ - if (k >= s.length) return -1 - if (s[k] !== "{") return -2 - let depth = 0 - let str = false - let esc = false - for (; k < s.length; k++) { - const ch = s[k] - if (str) { - if (esc) esc = false - else if (ch === "\\") esc = true - else if (ch === '"') str = false - continue - } - if (ch === '"') str = true - else if (ch === "{") depth++ - else if (ch === "}" && --depth === 0) return k + 1 - } - return -1 -} - -// looseJSON reads a JSON object as a model writes one: a string holding a -// raw newline or tab (a file's content written out, #799) is read as if -// they were escaped. null when it isn't one even so. -function looseJSON(s) { - for (const t of [s, escapeRaw(s)]) { - try { - const v = JSON.parse(t) - if (v && typeof v === "object" && !Array.isArray(v)) return v - } catch {} - } - return null -} - -// escapeRaw escapes the control characters inside JSON strings -function escapeRaw(s) { - let out = "" - let str = false - let esc = false - for (const ch of String(s ?? "")) { - if (str && !esc && ch < " ") { - out += ch === "\n" ? "\\n" : ch === "\r" ? "\\r" : ch === "\t" ? "\\t" : "\\u" + ch.charCodeAt(0).toString(16).padStart(4, "0") - continue - } - if (str && ch === "\\" && !esc) esc = true - else { - if (ch === '"' && !esc) str = !str - esc = false - } - out += ch - } - return out -} - -// callArgs is a tagged block's arguments as JSON: under arguments (an -// object, or a string of one), input or parameters, else the block's other -// keys, as a model that writes them beside the name means them (#799: a -// write that went out as {}) -function callArgs(v) { - let a = v.arguments ?? v.input ?? v.parameters - if (a === undefined) { - const { name, type, id, ...rest } = v - a = rest - } - if (typeof a === "string") return a.trim() ? (looseJSON(a) ? JSON.stringify(looseJSON(a)) : a) : "{}" - return JSON.stringify(a ?? {}) -} - -// nativeCall is a tool call as Trae's events carry one -function nativeCall(tc) { - const f = tc?.function ?? tc?.function_call ?? tc - const name = f?.name ?? tc?.tool_name ?? "" - const index = Number.isInteger(tc?.index) ? tc.index : null - const a = f?.arguments ?? f?.args ?? tc?.params ?? tc?.input ?? tc?.parameters ?? "" - const args = typeof a === "string" ? a : JSON.stringify(a) - if (!name && index === null && !tc?.id && !args) return null - return { id: tc?.id || tc?.tool_call_id || "", index, name: String(name), arguments: args } -} - -// NativeCalls puts together the tool calls Trae streams: a call comes in -// several events under one id (or index), each with the arguments so far -// or only the new piece, so a call is sent on once the answer is whole, -// not from its first event (#799: bash's command cut to `echo "T`) -class NativeCalls { - constructor() { - this.calls = [] - } - push(tc) { - const c = nativeCall(tc) - if (!c) return - let o = this.calls.find((x) => (c.id && x.id === c.id) || (!c.id && c.index !== null && x.index === c.index)) - if (!o && !c.id && c.index === null) - o = this.calls.findLast((x) => x.name === c.name && (x.arguments === c.arguments || (!done(x.arguments) && c.arguments.startsWith(x.arguments)))) - // a piece with nothing to say whose it is (or an index its call's - // first event didn't give) belongs to the call still being written - if (!o && !c.name && !c.id) { - o = this.calls.findLast((x) => !done(x.arguments)) - if (o && c.index !== null && o.index !== null && o.index !== c.index) o = null - } - if (!o) { - if (!c.name) return - this.calls.push({ ...c }) - return - } - if (!o.name) o.name = c.name - if (c.index !== null && o.index === null) o.index = c.index - const prev = o.arguments - const next = c.arguments - if (!next || prev.startsWith(next)) return // nothing new - if (next.startsWith(prev) || done(prev)) o.arguments = next // the arguments so far - else o.arguments = prev + next // a piece - } - take(tools = []) { - return this.calls.filter((c) => c.name).map(({ id, name, arguments: a }) => { - // a name that holds the whole call, as JSON or in GLM's template: - // that call, its arguments the name's when it gave none of its own - const w = name.trimStart().startsWith("{") ? looseJSON(name) : name.includes("") ? glmCall(name, tools) : null - if (w?.name) { - name = String(w.name) - if (!a || a.trim() === "{}") a = callArgs(w) - } - const v = a && !done(a) ? looseJSON(a) : null - return { id: id || callId(), name, arguments: v ? JSON.stringify(v) : a || "{}" } - }) - } -} - -// done says arguments are a whole JSON value already -function done(a) { - if (!a) return false - try { - JSON.parse(a) - return true - } catch { - return false - } -} - -// the events that carry the answer: output and message, and the names -// Trae has put a reply's text under otherwise (delta, or none at all); -// any other is queueing, metadata or timing -const ANSWER = new Set(["", "output", "message", "delta", "content", "text", "answer", "chunk", "output_delta", "message_delta"]) - -// finishOf is OpenAI's finish_reason for the one Trae's last event gives, -// "" for none it says or one it has no word for -function finishOf(d) { - const f = String(d?.finish_reason ?? d?.stop_reason ?? d?.finishReason ?? "").toLowerCase() - if (["length", "max_tokens", "max_output_tokens", "max_length"].includes(f)) return "length" - if (f === "content_filter" || f === "sensitive") return "content_filter" - return "" -} - -// Thoughts is the reasoning sent on so far: a piece Trae sends again (the -// same one twice in a row, or the reasoning so far, again or with more -// after it) sends only what is new -class Thoughts { - constructor() { - this.all = "" - this.last = "" - } - add(r) { - const last = this.last - this.last = r - if (r === last && r.length >= 8) return "" - if (this.all.length >= 16 && r.length >= 16 && this.all.endsWith(r)) return "" - if (this.all.length >= 16 && r.startsWith(this.all)) r = r.slice(this.all.length) - this.all += r - return r - } -} - -// parts turns Trae's events into what the answer is made of: text, -// reasoning, tool calls, the token counts, the finish, or an error. tools -// are the request's, a call to one named otherwise going on under its name. -async function* parts(events, tools = []) { - const tt = new TextTools(tools) - const nc = new NativeCalls() - const th = new Thoughts() - const call = (c) => ({ call: { ...c, name: toolNamed(c.name, tools) } }) - let finish = "" - for await (const { event, data } of events) { - const name = eventName(event) - const d = data && typeof data === "object" ? data : {} - if (data === "[DONE]") break - if (name === "error" || (name !== "output" && d.code && d.message && !d.response && !d.content)) { - const e = errorOf(d) - yield { error: e.message || "Trae returned an error", code: e.code } - return - } - if (name === "token_usage") { - const u = tokensOf(d.usage ?? d) - if (u) yield { usage: u } - continue - } - if (name === "done" || name === "response_done" || name === "stream_done") { - const u = tokensOf(d.usage) - if (u) yield { usage: u } - finish = finishOf(d) || finish - break - } - if (!ANSWER.has(name)) continue - const delta = d.delta && typeof d.delta === "object" ? d.delta : {} - const reasoning = d.reasoning_content ?? d.reasoning ?? delta.reasoning_content ?? "" - if (typeof reasoning === "string" && reasoning) { - const r = th.add(reasoning) - if (r) yield { reasoning: r } - } - let text = typeof d.response === "string" ? d.response : typeof d.content === "string" ? d.content : typeof delta.content === "string" ? delta.content : typeof d.delta === "string" ? d.delta : "" - // the IDE's own progress notes, not the model's - if (/^(Building prompt:|Completed building prompt)/.test(text)) text = "" - if (text) { - const r = tt.push(text) - const t = r.reasoning && th.add(r.reasoning) - if (t) yield { reasoning: t } - if (r.text) yield { text: r.text } - for (const c of r.calls) yield call({ ...c, id: callId() }) - } - for (const tc of Array.isArray(d.tool_calls) ? d.tool_calls : []) nc.push(tc) - const u = tokensOf(d.usage) - if (u) yield { usage: u } - finish = finishOf(d) || finish - } - const r = tt.push("", true) - const t = r.reasoning && th.add(r.reasoning) - if (t) yield { reasoning: t } - if (r.text) yield { text: r.text } - for (const c of r.calls) yield call({ ...c, id: callId() }) - for (const c of nc.take(tools)) yield call(c) - if (finish) yield { finish } -} - -// first reads events up to the first that is the answer's, so an answer -// that is only an error (signed out, out of credit, a model this account -// lacks) is known before anything is sent on -async function first(it) { - const held = [] - for (;;) { - const n = await it.next() - if (n.done) return { held, done: true } - held.push(n.value) - if (!n.value.usage) return { held, done: false } - } -} - -async function* chain(held, it) { - yield* held - for (;;) { - const n = await it.next() - if (n.done) return - yield n.value - } -} - -// failure is the response for an error Trae answered with -function failure(status, code, message) { - message = message || statusLine(status) - if (status === 401 || lapsedCode(code) || (status === 403 && lapsedWords.test(message))) { - return errorResponse(401, `Trae Global's sign-in has expired (${message}); sign in again`, "expired") - } - if (status === 429 || quotaCode(code) || (status === 403 && quotaWords.test(message))) return errorResponse(429, `Trae Global: ${message}`) - return errorResponse(status >= 400 ? status : 502, `Trae Global: ${message}${code ? ` (code ${code})` : ""}`) -} - -// openai is the answer as an OpenAI chat completion: a stream, or one body -// abort, when given, lets the answer's reader close Trae's connection the -// moment the agent goes away (a tool call made, a request cancelled): a -// generator's return can't break a read that is already waiting, so the -// fetch itself is what has to be stopped -async function openai(req, it, abort) { - const id = "chatcmpl-" + randomBytes(12).toString("hex") - const created = Math.floor(Date.now() / 1000) - const model = req.model - if (!req.stream) { - let text = "" - let reasoning = "" - const calls = [] - let usage = null - let finish = "" - for await (const p of it) { - if (p.error) return failure(502, p.code, p.error) - if (p.text) text += p.text - if (p.reasoning) reasoning += p.reasoning - if (p.call) calls.push(p.call) - if (p.usage) usage = p.usage - if (p.finish) finish = p.finish - } - const message = { role: "assistant", content: text || (calls.length ? null : "") } - if (reasoning) message.reasoning_content = reasoning - if (calls.length) message.tool_calls = calls.map((c) => ({ id: c.id, type: "function", function: { name: c.name, arguments: c.arguments } })) - const body = { id, object: "chat.completion", created, model, choices: [{ index: 0, message, finish_reason: calls.length ? "tool_calls" : finish || "stop" }] } - if (usage) body.usage = usage - return new Response(JSON.stringify(body), { status: 200, headers: { "content-type": "application/json" } }) - } - const enc = new TextEncoder() - const chunk = (delta, finish = null, extra = {}) => enc.encode(`data: ${JSON.stringify({ id, object: "chat.completion.chunk", created, model, choices: [{ index: 0, delta, finish_reason: finish }], ...extra })}\n\n`) - // a reply that failed (an error event, or Trae's stream breaking off) - // ends with the error and [DONE], not a finish that says it stopped; the - // stream is closed whatever happens, and an agent that goes away stops - // the reading of Trae's - const error = (message, code = null) => enc.encode(`data: ${JSON.stringify({ error: { message: `Trae Global: ${message}`, type: "api_error", code } })}\n\n`) - let gone = false - const stream = new ReadableStream({ - async start(ctl) { - let calls = 0 - let usage = null - let finish = "" - let failed = false - const put = (b) => { - if (!gone) ctl.enqueue(b) - } - try { - put(chunk({ role: "assistant", content: "" })) - for await (const p of it) { - if (gone) break - if (p.error) { - put(error(p.error, p.code ?? null)) - failed = true - break - } - if (p.text) put(chunk({ content: p.text })) - if (p.reasoning) put(chunk({ reasoning_content: p.reasoning })) - if (p.call) put(chunk({ tool_calls: [{ index: calls++, id: p.call.id, type: "function", function: { name: p.call.name, arguments: p.call.arguments } }] })) - if (p.usage) usage = p.usage - if (p.finish) finish = p.finish - } - if (!failed) { - put(chunk({}, calls ? "tool_calls" : finish || "stop")) - if (usage) put(enc.encode(`data: ${JSON.stringify({ id, object: "chat.completion.chunk", created, model, choices: [], usage })}\n\n`)) - } - } catch (e) { - try { - put(error(e?.message ?? e)) - } catch {} - } - try { - put(enc.encode("data: [DONE]\n\n")) - if (!gone) ctl.close() - } catch {} - }, - cancel() { - gone = true - abort?.() - it.return?.() - }, - }) - return new Response(stream, { status: 200, headers: { "content-type": "text/event-stream", "cache-control": "no-cache" } }) -} - -// a model or function this account's chat_v3 doesn't take: another may -const wrongFunction = (code) => ["4001", "4023", "1005"].includes(String(code)) -// ---- the model lists ------------------------------------------------------------ - -// chatModel: an entry of a function's list that is a model to chat with. -// The lists also hold the IDE's own helpers (summary, fast_apply, title -// generation: usage other than chat_completion), configs switched off, and -// the slots of custom models, which need a provider bound in the IDE. -// The list is the account's own: a plan's locked models are greyed out in -// the IDE but still listed here, and which identities a model is for -// (display_contact_config's identity_list) isn't something the plugin can -// read the account's own identity against — it is not told one at sign-in -// or in the entitlement answer — so nothing is filtered on it: a paying -// account keeps the models it pays for, and a locked model answers Trae's -// own 1005 when asked (yetone/magpie#22). -function chatModel(m) { - const id = String(m?.config_name ?? "") - if (!id || /^custom_model/i.test(id)) return false - if (m.usage && m.usage !== "chat_completion") return false - if (m.config_switch === false) return false - if (m.is_custom_model === true || m.display_config?.is_custom_model === true) return false - // the IDE's own picker hides these: Auto-mode routing channels and - // pay-as-you-go twins of another entry (gemini-3.1-pro vs -paygo/-auto, - // the search_agent family), not entries to pick by hand - if (m.is_invisible_to_user === true) return false - return true -} - -// devModel is the model an entry serves requests with: its __dev one -const devModel = (m) => (Array.isArray(m?.model_detail_list) ? m.model_detail_list : []).find((d) => /__dev$/.test(String(d?.model_name ?? ""))) - -// maxModel is a model's Max mode, from the entries its lists give it (the -// one it is asked through first): the first __max model one names, and the -// window context_window_tokens.max gives it, when that is bigger than dev's. -// The lists needn't agree: chat_v3 can name the __max model while the SOLO -// list the model is asked through names only __dev, and the window can be -// another entry's again. A model with no __max, or no bigger window, has no -// Max. -const maxModel = (...ms) => { - const details = (m) => (Array.isArray(m?.model_detail_list) ? m.model_detail_list : []) - const at = ms.find((m) => details(m).some((d) => /__max$/.test(String(d?.model_name ?? "")))) - if (!at) return null - const d = details(at).find((d) => /__max$/.test(String(d?.model_name ?? ""))) - const first = (k) => [at, ...ms].map((m) => Number(m?.context_window_tokens?.[k]) || 0).find((n) => n > 0) || 0 - const window = first("max") - return window > first("dev") ? { name: String(d.model_name), most: Number(d.max_tokens) || 0, window, entry: at } : null -} - -// MAX is the suffix of a model's Max: deepseek-v4.1-flash-max is -// deepseek-v4.1-flash in Max mode -const MAX = "-max" -// ---- usage ------------------------------------------------------------------------ - -const round = (n) => Math.round(n * 100) / 100 -// ---- the plugin --------------------------------------------------------------------- - -export const TraeGlobalAuthPlugin = async ({ client }) => { - // renewals under way, one to a refresh token (Trae spends it once), and - // the last each account got here, so a sign-in from before it is given - // that one rather than spending the token again - const renewing = new Map() - const renewed = new Map() - // the chat function that served each account last - const fnOf = new Map() - // the chat function whose model list has each model, and the __dev - // model it names there - const listedBy = new Map() - const modelNames = new Map() - // the Max each model the list last read has (null: none) - const maxes = new Map() - - const save = async (auth) => { - try { - await client?.auth?.set?.({ path: { id: ID }, body: auth }) - } catch {} - } - - const renew = (a, keep) => { - const key = a.refresh - let r = renewing.get(key) - if (!r) { - r = (async () => { - const x = await exchange(a.refresh, a.clientId) - const got = { ...a, token: x.token, refresh: x.refresh, expires: x.expires || jwtExp(x.token) || Date.now() + DAY, clientId: x.clientId || a.clientId, renewed: true } - renewed.set(a.uid || a.name, { was: a.refresh, got }) - if (keep) await save(toAuth(got)) - return got - })().finally(() => renewing.delete(key)) - renewing.set(key, r) - } - return r - } - - // fresh is the account with a token that has a while to go, renewed - // when it hasn't - const fresh = async (getAuth) => { - const a = fromAuth(await getAuth()) - if (!a) throw new Expired("Trae Global: not signed in") - const last = renewed.get(a.uid || a.name) - if (last && last.was === a.refresh) return { ...last.got, renewed: false } - if (!a.expires || a.expires - Date.now() > EARLY_MS || !a.refresh) return a - try { - return await renew(a, true) - } catch (e) { - // a hiccup: the token in hand may still do - if (!(e instanceof Expired) && a.expires > Date.now()) return a - throw e - } - } - - // refresh is magpie's auth.refresh: the token renewed LEAD_MS before its - // end, as the fields that changed - const refresh = async (auth) => { - const a = fromAuth(auth) - if (!a || !a.refresh) return undefined - const last = renewed.get(a.uid || a.name) - if (last && last.was === a.refresh) return { access: last.got.token, refresh: last.got.refresh, expires: last.got.expires } - const s = await renew(a, false) - return { access: s.token, refresh: s.refresh, expires: s.expires } - } - - // post asks one of Trae's JSON pages with the account - const post = async (a, url, body) => { - const res = await fetch(url, { method: "POST", headers: ideHeaders(a, { Accept: "application/json" }), body: JSON.stringify(body), signal: AbortSignal.timeout(20_000) }) - const text = await res.text() - return { status: res.status, text, v: parseJSON(text) } - } - - // dollarUsageOf reads the account's entitlement pack as the dollar billing - // has it: the period's allowance in dollars (basic_usage_limit plus - // bonus_usage_limit) and what was used of each (basic_usage_amount, - // bonus_usage_amount). null when the answer carries no pack. - const dollarUsageOf = (v) => { - const pack = (v?.user_entitlement_pack_list ?? []).find((p) => p?.usage || p?.entitlement_base_info?.quota) - const quota = pack?.entitlement_base_info?.quota - if (!pack || !quota) return null - const basic = Number(quota.basic_usage_limit) || 0 - const bonus = Number(quota.bonus_usage_limit) || 0 - const used = Number(pack.usage?.basic_usage_amount) || 0 - const usedBonus = Number(pack.usage?.bonus_usage_amount) || 0 - const end = whenOf(pack.entitlement_base_info.end_time) - return { plan: String(pack.display_desc ?? ""), basic, bonus, used, usedBonus, end } - } - - const usage = async (getAuth) => { - let a - try { - a = await fresh(getAuth) - } catch (e) { - return { error: e.message, signIn: e instanceof Expired ? "expired" : "kept" } - } - const signIn = a.renewed ? "renewed" : "kept" - // the dollar billing's page (international, 2026-02+): the pack's - // allowances and what they used, asked on the pay host, not the auth - // host, whose /cloudide/api/v2/pay pages answer 403 Api Scope Forbidden - let r - try { - r = await post(a, payHost(a) + "/trae/api/v1/pay/user_current_entitlement_list", {}) - } catch (e) { - return { error: "Trae Global usage: " + (e?.message ?? e), signIn } - } - const e = errorOf(r.v) - if (r.status === 401 || lapsedCode(e.code)) return { error: `${a.name || a.uid}: Trae Global's sign-in has expired — sign in again`, signIn: "expired" } - if (r.status !== 200 || (e.code && String(e.code) !== "0")) return { error: `Trae Global usage: ${e.message || statusLine(r.status)}`, signIn, user: a.name } - const d = dollarUsageOf(r.v) - if (!d) return { error: "Trae Global usage: no entitlement pack in the answer", signIn, user: a.name } - const total = d.basic + d.bonus - const used = d.used + d.usedBonus - const out = { plan: d.plan || "Free", user: a.name || a.uid, signIn } - if (total > 0) { - // the allowance rides the window (amount of limit, in dollars), as - // WorkBuddy's does, so magpie says it in the window's row, used or - // left, in its own words and number format (yetone/magpie#694) - const w = { name: "Dollar Usage", used: Math.round(Math.max(0, Math.min(100, (used / total) * 100)) * 100) / 100, amount: round(used), limit: round(total), unit: "usd" } - if (d.end) w.resetsAt = new Date(d.end).toISOString() // whenOf already made it ms - out.windows = [w] - } - return out - } - - // batchLists is every chat function's model list in one ask, as TRAE - // SOLO's ai-agent asks (batch_get_detail_param): {function: entries}. - // null when Trae answers it with no lists. - const batchLists = async (a) => { - const r = await post(a, apiOf(a) + "/api/ide/v1/batch_get_detail_param", { - functions: FUNCTIONS, 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, - }) - if (r.status === 401 || lapsedCode(errorOf(r.v).code)) throw new Expired("Trae Global's sign-in has expired; sign in again") - if (r.status !== 200) throw new Error(`Trae Global models: ${statusLine(r.status)}`) - const groups = r.v.function_configs ?? r.v.data?.function_configs - if (!Array.isArray(groups)) return null - const out = {} - for (const g of groups) { - const fn = String(g?.function ?? "") - if (!FUNCTIONS.includes(fn) || !Array.isArray(g.config_info_list)) continue - out[fn] = [...(out[fn] ?? []), ...g.config_info_list.filter((m) => m?.config_name)] - } - return Object.keys(out).length ? out : null - } - - // listOf is one function's model list, as the IDE asks for it - const listOf = async (a, fn) => { - const r = await post(a, apiOf(a) + "/api/ide/v1/get_detail_param", { - function: fn, config_names: null, need_prompt: false, current_config_info: null, poly_prompt: true, mode_type: null, agent_type: null, - }) - if (r.status === 401 || lapsedCode(errorOf(r.v).code)) throw new Expired("Trae Global's sign-in has expired; sign in again") - if (r.status !== 200) throw new Error(`Trae Global models: ${statusLine(r.status)}`) - const list = r.v.config_info_list ?? r.v.data?.config_info_list ?? [] - return list.filter((m) => m?.config_name) - } - - // liveModels is the account's model list: every chat function's, since - // SOLO lists models the classic IDE's chat_v3 doesn't (deepseek-v4.1-flash - // came to the TRAE agent's first, yetone/magpie#681); a model listed by one function - // only is asked through that one. One function's list failing leaves the - // others'; all failing is the error. - // - // The lists come from batch_get_detail_param, as TRAE SOLO asks them; - // when that gives none, from get_detail_param, one function at a time. - // A model several functions list is asked through the first whose entry - // names a __dev model (one Trae serves) and isn't misnamed, else the - // first that names one, else the first. - const liveModels = async (a) => { - let lists = null - try { - lists = await batchLists(a) - } catch (e) { - if (e instanceof Expired) throw e - } - if (!lists) { - const got = await Promise.allSettled(FUNCTIONS.map((fn) => listOf(a, fn))) - const expired = got.find((g) => g.status === "rejected" && g.reason instanceof Expired) - if (expired) throw expired.reason - if (got.every((g) => g.status === "rejected")) throw got[0].reason - lists = {} - got.forEach((g, i) => { - if (g.status === "fulfilled") lists[FUNCTIONS[i]] = g.value - }) - } - // a function can give a model another's name: chat_v3 calls - // deepseek-v4.1-flash "DeepSeek-V4-Flash 正式版", as it does - // DeepSeek-V4-Flash-Official, where SOLO's lists call it - // DeepSeek-V4.1-Flash (yetone/magpie#681) — Trae's usage page then books - // it under that name too. Such an entry is misnamed: its name is another - // model's in the same list, and other lists name it otherwise. - const nameOf = (m) => String(m.display_config?.display_name || m.display_name || m.display_model_name || m.config_name) - const names = new Map() // id → the names its lists give it - for (const fn of FUNCTIONS) { - for (const m of lists[fn] ?? []) { - if (!chatModel(m)) continue - const id = String(m.config_name) - names.set(id, (names.get(id) ?? new Set()).add(nameOf(m))) - } - } - const misnamed = (fn, m) => { - const id = String(m.config_name), name = nameOf(m) - return names.get(id).size > 1 && (lists[fn] ?? []).some((o) => chatModel(o) && String(o.config_name) !== id && nameOf(o) === name) - } - // a function's entry is worth more when it names a __dev model, then - // when it isn't misnamed; the first of the best is taken - const worth = (fn, m) => (devModel(m) ? 2 : 0) + (misnamed(fn, m) ? 0 : 1) - const out = new Map() - for (const fn of FUNCTIONS) { - for (const m of lists[fn] ?? []) { - if (!chatModel(m)) continue - const id = String(m.config_name) - const was = out.get(id) - if (!was || worth(fn, m) > was.worth) out.set(id, { m, fn, worth: worth(fn, m) }) - } - } - for (const [id, { m, fn }] of out) { - listedBy.set(id, fn) - const dev = devModel(m) - if (dev) modelNames.set(id, { fn, name: dev.model_name, most: Number(dev.max_tokens) || 0 }) - else modelNames.delete(id) - if (out.has(id + MAX)) continue - // its Max is asked through the function whose entry names the __max - // model: the lists needn't agree — chat_v3 can name the __max model - // while the SOLO list the model is asked through names only __dev - const entries = [{ m, fn }, ...FUNCTIONS.flatMap((f) => (lists[f] ?? []).filter((o) => o !== m && chatModel(o) && String(o.config_name) === id).map((o) => ({ m: o, fn: f })))] - const max = maxModel(...entries.map((e) => e.m)) - maxes.set(id, max) - if (max) { - const by = entries.find((e) => e.m === max.entry).fn - listedBy.set(id + MAX, by) - modelNames.set(id + MAX, { fn: by, name: max.name, most: max.most, max: { base: id, window: max.window } }) - } else { - listedBy.delete(id + MAX) - modelNames.delete(id + MAX) - } - } - return [...out.values()].map((x) => x.m) - } - - const modelOf = (provider, m) => { - const id = String(m.config_name) - const was = provider.models?.[id] ?? {} - // context_window_tokens: dev is what a request gets, max only in Max mode - const ctx = Number(m.context_window_tokens?.dev ?? m.context_window_size?.max?.[0] ?? m.context_window_size?.max ?? m.context_window_tokens?.max ?? m.prompt_max_tokens) || was.limit?.context || MODEL.limit.context - const out = Number(devModel(m)?.max_tokens) || was.limit?.output || 0 - const name = m.display_config?.display_name || m.display_name || m.display_model_name || was.name || id - return { ...MODEL, ...was, id, providerID: ID, name: String(name), limit: { context: ctx, output: out }, api: was.api ?? { id, url: HOSTS.api, npm: "@ai-sdk/openai-compatible" } } - } - - return { - config: async (config) => { - config.provider ??= {} - const was = config.provider[ID] ?? {} - config.provider[ID] = { - name: "Trae Global", - npm: "@ai-sdk/openai-compatible", - api: HOSTS.api + "/v1", - ...was, - models: { ...MODELS, ...(was.models ?? {}) }, - } - }, - provider: { - id: ID, - // the account's own list, when Trae answers; else the list above - async models(provider, { auth }) { - if (auth?.type !== "oauth" || !auth.access) return provider.models - try { - const ms = await liveModels(await fresh(async () => auth)) - if (!ms.length) return provider.models - const ids = new Set(ms.map((m) => String(m.config_name))) - return Object.fromEntries(ms.flatMap((m) => { - const id = String(m.config_name) - const own = modelOf(provider, m) - const max = maxes.get(id) - if (!max || ids.has(id + MAX)) return [[id, own]] - // its Max, a model of its own: the window and output Max mode gives - const was = provider.models?.[id + MAX] ?? {} - return [[id, own], [id + MAX, { ...own, ...was, id: id + MAX, name: own.name + " (Max)", limit: { context: max.window, output: max.most || own.limit.output }, api: { ...own.api, id: id + MAX } }]] - })) - } catch (e) { - if (e instanceof Expired) throw e - return provider.models - } - }, - }, - auth: { - provider: ID, - usage, - // magpie renews the token LEAD_MS before its end, once, before its - // requests, models and usage ask; the check before each request - // stays for OpenCode, which doesn't call this - refreshLead: LEAD_MS, - refresh, - loader: async (getAuth) => { - const a0 = fromAuth(await getAuth()) - if (!a0) return {} - return { - baseURL: apiOf(a0) + "/v1", - apiKey: "trae", // the engine's placeholder; the request carries the JWT - async fetch(input, init = {}) { - const r0 = input instanceof Request ? input : null - let body = init.body ?? (r0 ? await r0.text() : undefined) - if (body instanceof ArrayBuffer) body = new TextDecoder().decode(body) - else if (ArrayBuffer.isView(body)) body = new TextDecoder().decode(new Uint8Array(body.buffer, body.byteOffset, body.byteLength)) - const url = r0 ? r0.url : input instanceof URL ? input.href : String(input) - const req = parseJSON(body) - if (!Array.isArray(req.messages)) return errorResponse(400, "Trae Global: only chat completions are served") - let a - try { - a = await fresh(getAuth) - } catch (e) { - if (e instanceof Expired) return errorResponse(401, `${a0.name || a0.uid}: ${e.message}`, "expired") - throw e - } - const signIn = a.renewed ? "renewed" : "kept" - const who = a.uid || a.name - // the function that lists the model first, then the one that - // served this account last, then the rest - const fns = [...new Set([listedBy.get(String(req.model)), fnOf.get(who), ...FUNCTIONS].filter(Boolean))] - let last - let named = modelNames.get(String(req.model)) - if (!named && String(req.model).endsWith(MAX)) { - // a Max asked before the list was read here: read it - await liveModels(a).catch(() => {}) - named = modelNames.get(String(req.model)) - if (named) fns.unshift(named.fn) - } - const max = named?.max ?? null - // the answer's own signal: the caller's abort (a cancelled - // request) and the stream's cancel both stop Trae's fetch, so - // no read is left hanging on a connection the agent walked - // away from - const ac = new AbortController() - const outer = init.signal ?? r0?.signal ?? null - if (outer) { - if (outer.aborted) ac.abort() - else outer.addEventListener("abort", () => ac.abort(), { once: true }) - } - for (const fn of [...new Set(fns)]) { - const res = await fetch(apiOf(a) + "/api/agent/v3/llm_utils_chat", { - method: "POST", - headers: ideHeaders(a, { 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)), - signal: ac.signal, - }) - if (!res.ok) { - const text = await res.text() - const e = errorOf(text) - last = failure(res.status, e.code, e.message || text.trim().slice(0, 300)) - if (res.status === 400 && wrongFunction(e.code)) continue - break - } - const ct = res.headers.get("content-type") ?? "" - if (!ct.includes("event-stream") && ct.includes("json")) { - // an answer that isn't a stream is an error in a 200 - const e = errorOf(await res.text()) - last = failure(502, e.code, e.message) - if (wrongFunction(e.code)) continue - break - } - const it = parts(sse(res.body), Array.isArray(req.tools) ? req.tools : [])[Symbol.asyncIterator]() - const { held, done } = await first(it) - const err = held.find((p) => p.error) - if (err) { - last = failure(502, err.code, err.error) - if (wrongFunction(err.code)) { - // another function may take it: this answer's read goes - // with the function it came from, not left hanging - it.return?.() - res.body.cancel?.().catch(() => {}) - continue - } - break - } - fnOf.set(who, fn) - const out = await openai(req, done ? held : chain(held, it), () => ac.abort()) - out.headers.set("X-Magpie-Sign-In", signIn) - return out - } - if (!last.headers.has("X-Magpie-Sign-In")) last.headers.set("X-Magpie-Sign-In", signIn) - return last - }, - } - }, - methods: [{ type: "oauth", label: "Trae Global account (browser)", authorize: browserSignIn }], - }, - } -} - -// for tests -export const _internal = { HOSTS, MODELS, TextTools, NativeCalls, looseJSON, glmCall, toolNamed, traeMessages, chatBody, whenOf, newDevice, apiOf, regionOf } diff --git a/packages/trae-global/nonet.mjs b/packages/trae-global/nonet.mjs deleted file mode 100644 index 79012d6..0000000 --- a/packages/trae-global/nonet.mjs +++ /dev/null @@ -1,18 +0,0 @@ -// 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) -} diff --git a/packages/trae-global/package.json b/packages/trae-global/package.json deleted file mode 100644 index d073670..0000000 --- a/packages/trae-global/package.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "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=" - } -} diff --git a/packages/trae-global/refresh.test.mjs b/packages/trae-global/refresh.test.mjs deleted file mode 100644 index 100f2db..0000000 --- a/packages/trae-global/refresh.test.mjs +++ /dev/null @@ -1,56 +0,0 @@ -// 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") -}) diff --git a/packages/trae-global/request.test.mjs b/packages/trae-global/request.test.mjs deleted file mode 100644 index 9fb28c4..0000000 --- a/packages/trae-global/request.test.mjs +++ /dev/null @@ -1,237 +0,0 @@ -// 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("") - 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('{"name":"read","arguments":{"path":"a"}}') - 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. {"name":"read","arguments":{"path":"a"}}' }], - ["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 b").text).toBe(" 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 = '{"name":"write","arguments":{"path":"a.py","content":"import sys\n\tprint(\\"hi\\")\n"}}' - f.route("POST /api/agent/v3/llm_utils_chat", () => sse([ - ["output", { response: "Writing it. " + block }], - ["output", { response: '{"name":"read","path":"a.py"}' }], - ["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) -}) diff --git a/packages/trae-global/signin.test.mjs b/packages/trae-global/signin.test.mjs deleted file mode 100644 index 5262ff1..0000000 --- a/packages/trae-global/signin.test.mjs +++ /dev/null @@ -1,106 +0,0 @@ -// 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" }) -}) diff --git a/packages/trae-global/stream.test.mjs b/packages/trae-global/stream.test.mjs deleted file mode 100644 index c57a69a..0000000 --- a/packages/trae-global/stream.test.mjs +++ /dev/null @@ -1,238 +0,0 @@ -// 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 / call is a call, split over events, a string kept as written and a number read as one", async () => { - stream([ - ["output", { response: "Reading.\nread\npath\n007.txt\nlimit\n20\n" }], - ["output", { response: 'bashcommandecho "a\nb"' }], - ["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: "bashcommandls", 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: '{"name":"Read","arguments":{"path":"a"}}' }], ["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) -}) diff --git a/packages/trae-global/usage.test.mjs b/packages/trae-global/usage.test.mjs deleted file mode 100644 index 79bace9..0000000 --- a/packages/trae-global/usage.test.mjs +++ /dev/null @@ -1,253 +0,0 @@ -// 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") -}) diff --git a/packages/trae/README.md b/packages/trae/README.md index 91d6761..abe9912 100644 --- a/packages/trae/README.md +++ b/packages/trae/README.md @@ -1,29 +1,60 @@ # @magpie-community/opencode-trae-auth -Signs in to **Trae CN** (trae.cn, ByteDance's AI IDE) with your Trae CN -account, the way the IDE does, and makes its model requests. The free tier -works as well. Provider id: `trae-cn`. +Two providers, one package: **Trae CN** (trae.cn, ByteDance's AI IDE, provider +id `trae-cn`) and **Trae Global** (trae.ai, the international deployment, +provider id `trae-global`). Each signs in with its own Trae account, the way +the IDE does, and makes its model requests. The free tier works as well. -> **Experimental.** The protocol was worked out from two open-source relays, -> [wangqi233/trae2api](https://github.com/wangqi233/trae2api) and -> [autumnsentiment/Trae2api-cn](https://github.com/autumnsentiment/Trae2api-cn). -> The plugin hasn't been run against a real Trae CN account yet. If something -> fails, open an issue and include the error magpie shows. +The two are separate services — different domains, a different client's +catalog, barely overlapping model lists — so they are two providers rather +than a setting. They share one implementation: the request, stream and +tool-call machinery is the same code, and each realm is a table (hosts, +client, versions, usage page, fallback models, error codes) in `index.mjs`. +A fix to that machinery reaches both. + +| Provider id | Signs in to | Endpoints | +|---|---|---| +| `trae-cn` | Trae CN (trae.cn) | `api.trae.cn`, `trae-api-cn.mchost.guru` | +| `trae-global` | Trae international (trae.ai) | `growsg-normal.trae.ai`, `coresg-normal.trae.ai` (SG) / `coreva-normal.trae.ai` (US) | + +> **Experimental (both).** The CN protocol was worked out from two +> open-source relays, [wangqi233/trae2api](https://github.com/wangqi233/trae2api) +> and [autumnsentiment/Trae2api-cn](https://github.com/autumnsentiment/Trae2api-cn), +> and the international one from the same relays' realm table. Neither has +> been run against a real account here: Trae CN has not been tried at all, and +> Trae Global has been tried on one Free account in the SG region only — no +> Pro and no US account. Paid-account behaviour (which models a plan lists, +> what its allowance shows) is implemented from the interface's shape, not +> confirmed on a live one. If something fails, open an issue and include the +> error magpie shows. ## Sign-in -One way, **Trae CN account (browser)**. The plugin opens trae.cn's -authorization page (`www.trae.cn/authorization`, the IDE's client -`ono9krqynydwx5`). Sign in there and allow the sign-in. trae.cn then sends the -browser back to a callback on `http://127.0.0.1:/authorize`; it accepts +One way per provider, **Trae CN account (browser)** or **Trae Global account +(browser)**. The plugin opens that realm's authorization page +(`www.trae.cn/authorization` or `www.trae.ai/authorization`, the IDE's client +`ono9krqynydwx5`). Sign in there and allow the sign-in; the page then sends the +browser back to a callback on `http://127.0.0.1:/authorize` — it accepts no other kind of callback. The callback carries the account's Cloud-IDE-JWT, refresh token and account. Nothing needs pasting back. +An account of one realm does not sign in to the other: trae.cn's accounts are +not trae.ai's. + At sign-in the plugin creates the account's device and names it to the authorization page: `device_id` (19 digits) and `machine_id` (32 hex). Every request then sends that same device. The relays saw requests dropped when the device was new each time. +### The international realm's region + +Trae Global has two deployments. The sign-in's `AIRegion` (or a US auth host +such as `api-us-east.trae.ai`) selects the US one; anything else uses the SG +one. The US account's model requests go to `coreva-normal.trae.ai` and its +usage page to `api-us-east.trae.ai`; the SG account uses +`coresg-normal.trae.ai` and `api-sg-central.trae.ai`. Nothing has to be +configured: the region rides in the saved sign-in. + ## Requests Chat completions (`@ai-sdk/openai-compatible`) are translated for the IDE @@ -94,16 +125,18 @@ thinking level, so the plugin lists no variants and a level an agent picks does nothing. When no -list can be read, the plugin uses the models Trae CN's `chat_v3` is -known to serve: GLM-5.2, GLM-5, Kimi K2.6, Qwen 3.7 Plus, DeepSeek V4 Pro -and DeepSeek V4 Flash. +list can be read, the plugin uses the realm's own fallback list. Trae CN's +`chat_v3` is known to serve GLM-5.2, GLM-5, Kimi K2.6, Qwen 3.7 Plus, +DeepSeek V4 Pro and DeepSeek V4 Flash; Trae Global's serves GPT-5.4, +Gemini 3 Flash, Kimi K2.5, MiniMax M2 and DeepSeek V3.2. The live list +replaces either. ## Renewal -The JWT is renewed with the refresh token at -`api.trae.cn/cloudide/api/v3/trae/oauth/ExchangeToken`. Trae issues a new -refresh token each time and spends the old one, so only one renewal runs at -a time. +The JWT is renewed with the refresh token at the realm's auth host, +`/cloudide/api/v3/trae/oauth/ExchangeToken` (`api.trae.cn` for Trae CN, +`growsg-normal.trae.ai` for Trae Global). Trae issues a new refresh token +each time and spends the old one, so only one renewal runs at a time. magpie renews the JWT ten minutes before it ends (`refreshLead`) through `auth.refresh`. Each request also checks it, two minutes before the end, for @@ -112,7 +145,8 @@ OpenCode. The account is marked for a new sign-in in these cases: - the refresh token is turned away; -- a request is answered 401, or with code 1001. +- a request is answered 401, or with a code that means the sign-in lapsed: + 1001 for both realms, and 20101 for Trae Global. Trae signs other clients out of an account when its token is renewed. The IDE may therefore ask you to sign in again after magpie renews. @@ -121,13 +155,16 @@ IDE may therefore ask you to sign in again after magpie renews. | Trae's answer | What the agent gets | | --- | --- | -| 401 / code 1001 | 401, and the account is marked for a new sign-in | -| code 4008 / 1005 (quota, plan) | 429 | +| 401 / code 1001 (both), 20101 (Global) | 401, and the account is marked for a new sign-in | +| code 4008 / 1005 (quota, plan; both), 4011 (Global) | 429 | | Anything else | Trae's message and code, as a 502 or Trae's own status | ## Usage -magpie's usage card shows the account's credits: +magpie's usage card shows the account's plan and allowance, from whichever +page the realm bills on: + +**Trae CN** — the credits page: - **Source:** `api.trae.cn/trae/api/v2/pay/ide_user_ent_usage`. - **What it adds up:** each entitlement pack's `credits_limit` (-1 means @@ -136,9 +173,23 @@ magpie's usage card shows the account's credits: total, with the share, which magpie shows as used or left like WorkBuddy's. +**Trae Global** — the dollar billing's entitlements: + +- **Source:** `POST api-sg-central.trae.ai/trae/api/v1/pay/user_current_entitlement_list` + (a US account asks `api-us-east.trae.ai`). +- **What it adds up:** the pack's allowance in dollars + (`basic_usage_limit` plus `bonus_usage_limit`) and what was used of each + (`basic_usage_amount`, `bonus_usage_amount`). +- **What it shows:** one Dollar Usage window, the dollars used of the + allowance, resetting when the pack ends. + +A 200 carrying an error code is shown as Trae's own message rather than as +an empty answer. + ## Daily check-in -Trae CN gives credits for a daily check-in (每日签到). magpie can press it +Trae CN gives credits for a daily check-in (每日签到); Trae Global has no +such page, so this is CN only. magpie can press it once a day for each account (Settings, or the switch on the usage card). It asks Trae CN's own pages through this plugin's fetch, which sends them as the account: its Cloud-IDE-JWT diff --git a/packages/trae/fake.mjs b/packages/trae/fake.mjs index e89ed0a..527ffbe 100644 --- a/packages/trae/fake.mjs +++ b/packages/trae/fake.mjs @@ -1,10 +1,14 @@ -// A fake of Trae CN for the tests: one local server standing in for -// trae.cn's authorization page host, api.trae.cn and the model host, which -// the plugin's HOSTS are pointed at. route(method, path) answers a -// request; seen lists what came. +// A fake of Trae for the tests: one local server standing in for the +// realm's authorization page host and its other hosts, which the plugin's +// HOSTS are pointed at. route(method, path) answers a request; seen lists +// what came. The CN realm is the default, so a test written before the two +// realms shared a package is unchanged; pass "trae-global" for the +// international one, whose hosts and usage page differ. import { _internal } from "./index.mjs" -export function fakeTrae() { +const HOST_KEYS = ["web", "auth", "api", "us", "pay", "usPay"] + +export function fakeTrae(siteId = "trae-cn") { const routes = new Map() const seen = [] const server = Bun.serve({ @@ -22,15 +26,18 @@ export function fakeTrae() { }, }) const origin = `http://127.0.0.1:${server.port}` - const was = { ..._internal.HOSTS } - Object.assign(_internal.HOSTS, { web: origin, auth: origin, api: origin }) + const hosts = _internal.SITES[siteId].hosts + const was = { ...hosts } + Object.assign(hosts, { web: origin, auth: origin, api: origin, us: origin, pay: origin, usPay: origin }) return { origin, + site: _internal.SITES[siteId], seen, route: (key, h) => routes.set(key, h), close() { server.stop(true) - Object.assign(_internal.HOSTS, was) + for (const k of HOST_KEYS) if (was[k] === undefined) delete hosts[k] + Object.assign(hosts, was) }, } } diff --git a/packages/trae/global.test.mjs b/packages/trae/global.test.mjs new file mode 100644 index 0000000..cd62884 --- /dev/null +++ b/packages/trae/global.test.mjs @@ -0,0 +1,261 @@ +// Trae Global (trae-global) against a local stand-in for its hosts: the +// international deployment's own authorization page, auth host, model hosts +// (SG and the US one) and its usage page. The shared machinery — the SSE +// events, tool calls, the model list — is covered by the files the two +// realms share; what is here is what only the international realm does: +// the dollar billing's entitlements, the US/SG routing, its own error +// codes, and its own model names. Every host a call goes to is asserted, +// so a call meant for trae.ai can't end up on a trae.cn host. +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()) + +const GLOBAL = _internal.SITES["trae-global"] + +test("the realm's table is its own: hosts, client and versions differ from CN's", () => { + const cn = _internal.SITES["trae-cn"] + expect(GLOBAL.id).toBe("trae-global") + expect(GLOBAL.hosts.web).toBe("https://www.trae.ai") + expect(GLOBAL.hosts.auth).toBe("https://growsg-normal.trae.ai") + expect(GLOBAL.hosts.api).toBe("https://coresg-normal.trae.ai") + expect(GLOBAL.hosts.us).toBe("https://coreva-normal.trae.ai") + expect(GLOBAL.hosts.pay).toBe("https://api-sg-central.trae.ai") + expect(GLOBAL.hosts.usPay).toBe("https://api-us-east.trae.ai") + // no trae.cn host is reachable from this realm's table + expect(Object.values(GLOBAL.hosts).some((h) => /trae\.cn|mchost\.guru/.test(h))).toBe(false) + expect(cn.hosts.web).toBe("https://www.trae.cn") + expect(cn.hosts.api).toBe("https://trae-api-cn.mchost.guru") +}) + +test("the model host is the account's region: SG by default, US for a US account", () => { + expect(GLOBAL.apiOf({ region: "SG" })).toBe(GLOBAL.hosts.api) + expect(GLOBAL.apiOf({ region: "" })).toBe(GLOBAL.hosts.api) + expect(GLOBAL.apiOf({ region: "US-East" })).toBe(GLOBAL.hosts.us) + expect(GLOBAL.apiOf({ region: "US" })).toBe(GLOBAL.hosts.us) + // a sign-in that named a US auth host routes there even without a region + expect(GLOBAL.apiOf({ api: "https://api-us-east.trae.ai" })).toBe(GLOBAL.hosts.us) + // and a chat host the sign-in named is taken as it is + expect(GLOBAL.apiOf({ api: "https://coresg-normal.trae.ai" })).toBe("https://coresg-normal.trae.ai") +}) + +test("the international realm's own error codes: 20101 is a lapsed sign-in, 4011 a quota", async () => { + f = fakeTrae("trae-global") + f.route("POST /api/agent/v3/llm_utils_chat", () => sse([["error", { code: 20101, message: "token not matched" }]])) + const hooks = await TraeGlobalAuthPlugin({ client: {} }) + const opts = await hooks.auth.loader(async () => signedIn()) + let 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(401) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("expired") + f.route("POST /api/agent/v3/llm_utils_chat", () => sse([["error", { code: 4011, message: "rate limited" }]])) + 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(429) +}) + +test("the errors carry the realm's name, not CN's", async () => { + f = fakeTrae("trae-global") + f.route("POST /api/agent/v3/llm_utils_chat", () => sse([["error", { code: 4008, message: "quota exceeded" }]])) + 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: "gpt-5.4", messages: [{ role: "user", content: "hi" }] }) }) + expect((await res.json()).error.message).toBe("Trae Global: quota exceeded") +}) + +test("the usage page is the dollar billing's, and the allowance rides the window", async () => { + f = fakeTrae("trae-global") + 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("a US account asks its own pay host, and bonus usage adds to the allowance", async () => { + f = fakeTrae("trae-global") + 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 200 carrying an error code says Trae's own message, not \"no entitlement pack\"", async () => { + f = fakeTrae("trae-global") + 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") +}) + +test("a 401 reading usage marks the account", async () => { + f = fakeTrae("trae-global") + 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") +}) + +test("the international model names are the realm's own fallback list", () => { + expect(Object.keys(GLOBAL.models)).toEqual(["gpt-5.4", "gemini-3-flash", "kimi-k2.5", "minimax-m2", "deepseek-v3.2"]) + expect(GLOBAL.models["gemini-3-flash"].limit.context).toBe(1_000_000) + // the CN list is untouched by it + expect(Object.keys(_internal.MODELS)).toContain("glm-5.2") + expect(Object.keys(_internal.MODELS)).not.toContain("gpt-5.4") +}) + +test("the config declares the realm's own provider, at its own host", async () => { + const hooks = await TraeGlobalAuthPlugin({ client: {} }) + const cfg = { provider: {} } + await hooks.config(cfg) + expect(Object.keys(cfg.provider)).toEqual(["trae-global"]) + expect(cfg.provider["trae-global"].api).toBe(GLOBAL.hosts.api + "/v1") + expect(cfg.provider["trae-global"].name).toBe("Trae Global") +}) + +test("a model the plan locks is still listed: the account keeps what it pays for", async () => { + f = fakeTrae("trae-global") + 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", 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: "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" }] }, + ] }, + ] })) + f.route("POST /api/agent/v3/llm_utils_chat", () => sse([["output", { response: "ok" }], ["done", {}]])) + const hooks = await TraeGlobalAuthPlugin({ client: {} }) + const p = { models: { ...GLOBAL.models } } + const live = await hooks.provider.models(p, { auth: signedIn() }) + // gpt-5.5's identities don't hold the 0 (Free), so the IDE greys it out on + // Free — but the plugin is not told the account's own identity, so it lists + // it: a paying account keeps the models it pays for. The invisible paygo + // twin stays out. + expect(Object.keys(live)).toEqual(["gpt-5.4", "gpt-5.5"]) + const opts = await hooks.auth.loader(async () => signedIn()) + 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("Trae CN's lists are served whole: only Global hides is_invisible_to_user", async () => { + f = fakeTrae("trae-cn") + 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", display_config: { display_name: "GPT-5.4" }, model_detail_list: [{ model_name: "gpt-5.4__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" }] }, + ] }, + ] })) + const { TraeCNAuthPlugin } = await import("./index.mjs") + const hooks = await TraeCNAuthPlugin({ client: {} }) + const live = await hooks.provider.models({ models: { ..._internal.SITES["trae-cn"].models } }, { auth: signedIn() }) + expect(Object.keys(live)).toContain("gemini-3.1-pro-paygo") +}) + +test("a US account's request goes to the US chat host, and its sign-in keeps the region", async () => { + f = fakeTrae("trae-global") + 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("a US callback keeps the region, and its saved auth routes to the US chat host", async () => { + f = fakeTrae("trae-global") + const hooks0 = await TraeGlobalAuthPlugin({ client: {} }) + const [method] = hooks0.auth.methods + const a = await method.authorize() + const u = new URL(a.url) + const cb = new URL(u.searchParams.get("auth_callback_url")) + 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 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 + let cancelled = false + f = fakeTrae("trae-global") + 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("an answer the agent walks away from lets Trae's connection go", async () => { + let cancelled = false + f = fakeTrae("trae-global") + 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 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: "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) +}) diff --git a/packages/trae/index.mjs b/packages/trae/index.mjs index 1215ba3..48c1f0c 100644 --- a/packages/trae/index.mjs +++ b/packages/trae/index.mjs @@ -12,45 +12,205 @@ import { randomBytes, randomUUID, randomInt } from "node:crypto" import { createServer, STATUS_CODES } from "node:http" -const ID = "trae-cn" -// where each part of Trae CN is served; tests point them at a fake -const HOSTS = { - web: "https://www.trae.cn", // the authorization page - auth: "https://api.trae.cn", // tokens, the account, credits - api: "https://trae-api-cn.mchost.guru", // the models +const SITES = { + // Trae CN (trae.cn): the authorization page sends the browser back to a + // callback on 127.0.0.1 with the account's Cloud-IDE-JWT and refresh + // token; the refresh token is exchanged for a new JWT at + // /cloudide/api/v3/trae/oauth/ExchangeToken; model requests go to the IDE + // agent's /api/agent/v3/llm_utils_chat, which answers in its own SSE + // events. Worked out from two open-source relays (wangqi233/trae2api and + // autumnsentiment/Trae2api-cn); not run against a real account here. + // 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). + "trae-cn": { + id: "trae-cn", + name: "Trae CN", + realm: "Trae CN", // the name the errors and messages carry + webHost: "trae.cn", // the bare host the sign-in copy names + // where each part of Trae CN is served; tests point them at a fake + hosts: { + web: "https://www.trae.cn", // the authorization page + auth: "https://api.trae.cn", // tokens, the account, credits + api: "https://trae-api-cn.mchost.guru", // the models + }, + clientId: "ono9krqynydwx5", // Trae CN's IDE + appId: "6eefa01c-1036-4c7e-9ca5-d891f63bfcd8", + ideVersion: "3.3.65", // named to the authorization page + ideVersionCode: "20260401", + // the client the model host is told it serves: TRAE SOLO CN 0.1.69, as + // its ai-agent names itself (same app id). Trae offers a model only to + // clients new enough for it, and an April IDE was offered no + // deepseek-v4.1-flash. + clientVersion: "0.1.69", + clientVersionCode: "20260917", + pluginVersion: "2.3.24254", + brand: "ASUS TUF Gaming A15 FA507RM_FA507RM", + // the IDE's chat functions: the classic IDE's agent, then SOLO's Work + // mode, then the TRAE agent (solo_agent, which has deepseek-v4.1-flash), + // then SOLO Lite's agent + functions: ["chat_v3", "solo_work_lite", "solo_agent", "solo_agent_lite"], + // what Trae CN's chat_v3 is known to serve; the live list replaces it + // (the MODEL defaults are spread in at the end of the module, once MODEL + // is defined, so a site's entry only names what differs) + models: { + "glm-5.2": { name: "GLM-5.2", limit: { context: 200_000, output: 32_000 } }, + "glm-5": { name: "GLM-5" }, + "kimi-k2.6": { name: "Kimi K2.6", limit: { context: 256_000, output: 0 } }, + "qwen-3.7-plus": { name: "Qwen 3.7 Plus" }, + "DeepSeek-V4-Pro": { name: "DeepSeek V4 Pro" }, + "DeepSeek-V4-Flash": { name: "DeepSeek V4 Flash" }, + }, + // the model host for an account: Trae CN's own hosts serve no models, + // so only a host that is one is taken, else the one gateway + apiOf: (a) => { + const h = String(a?.api ?? "").replace(/\/+$/, "") + return /mchost\.guru|trae-api-/i.test(h) ? h : SITES["trae-cn"].hosts.api + }, + // whether a host named by a sign-in is one of the model hosts + modelHost: (h) => /mchost\.guru|trae-api-/i.test(String(h ?? "")), + // ownPage: url is one of Trae CN's own JSON pages on api.trae.cn + // (/trae/api/…: the daily check-in, credits), which the account's fetch + // sends as the account rather than as a chat + ownPage: (url) => { + try { + const u = new URL(url) + return u.origin === new URL(SITES["trae-cn"].hosts.auth).origin && u.pathname.startsWith("/trae/api/") + } catch { + return false + } + }, + // Trae CN's account info carries no region: its one deployment is the + // one it is asked through + regionOf: () => "", + // where usage is asked, and which page it is (CN: credits) + usage: { + kind: "credits", + path: "/trae/api/v2/pay/ide_user_ent_usage", + label: "credits", + host: (site) => site.hosts.auth, + body: { require_usage: true, req_source: 0 }, + read: (v, a, signIn, { credits, round }) => { + const c = credits(v) + const out = { plan: v.is_credits_billing ? "Credits" : "Free", user: a.name || a.uid, signIn } + if (c.unlimited) out.balance = "unlimited" + else if (c.limit > 0) { + // the count rides on the window (amount of limit, in credits), as + // WorkBuddy's does, so magpie says it in the window's row, used or + // left, in its own words and number format, rather than as an + // English balance line beside it (yetone/magpie#694) + const w = { name: "Credits", used: Math.max(0, Math.min(100, (c.used / c.limit) * 100)), amount: round(c.used), limit: round(c.limit), unit: "credits" } + if (c.until) w.resetsAt = new Date(c.until).toISOString() + out.windows = [w] + } + return out + }, + }, + }, + // Trae international (trae.ai): the same IDE sign-in flow against the + // international deployment. Its own authorization page, its own auth and + // chat hosts, a second (US) deployment the account's region selects, and + // the dollar billing's entitlements rather than the CN credits page. + // Worked out from the realm table of wangqi233/trae2api (cn/sg dual-region) + // and the login URL of wefew/trae2api; run against one Free SG account. + "trae-global": { + id: "trae-global", + name: "Trae Global", + realm: "Trae Global", + // its lists mark Auto-mode channels and pay-as-you-go twins + // is_invisible_to_user, which its picker hides; Trae CN's lists are + // served whole, as they were before Global joined this package + hidesInvisible: true, + webHost: "trae.ai", + hosts: { + web: "https://www.trae.ai", // the authorization page + auth: "https://growsg-normal.trae.ai", // tokens, the account + api: "https://coresg-normal.trae.ai", // the models, SG + us: "https://coreva-normal.trae.ai", // the models, US + pay: "https://api-sg-central.trae.ai", // usage + usPay: "https://api-us-east.trae.ai", // usage, the US deployment + }, + clientId: "ono9krqynydwx5", + appId: "6eefa01c-1036-4c7e-9ca5-d891f63bfcd8", + ideVersion: "3.5.51", // named to the international IDE's current build + ideVersionCode: "20260401", + clientVersion: "0.1.69", + clientVersionCode: "20260917", + pluginVersion: "2.3.62834", + brand: "ASUS TUF Gaming A15 FA507RM_FA507RM", + functions: ["chat_v3", "solo_work_lite", "solo_agent", "solo_agent_lite"], + // what Trae Global's chat is known to serve (its catalog barely overlaps + // the CN one's); the live list replaces it + models: { + "gpt-5.4": { name: "GPT-5.4" }, + "gemini-3-flash": { name: "Gemini 3 Flash", limit: { context: 1_000_000, output: 0 } }, + "kimi-k2.5": { name: "Kimi K2.5", limit: { context: 256_000, output: 0 } }, + "minimax-m2": { name: "MiniMax M2" }, + "deepseek-v3.2": { name: "DeepSeek V3.2" }, + }, + // the model host: the account's region (or a US host the sign-in named) + // selects the US deployment, else the SG one + apiOf: (a) => { + const h = String(a?.api ?? "").replace(/\/+$/, "") + const region = String(a?.region ?? "").toUpperCase() + if (/coreva/i.test(h) || /api-us(?:[-.]|$)/i.test(h) || /^US(?:[-_ ]|$)/.test(region)) return SITES["trae-global"].hosts.us + if (/coresg/i.test(h)) return h + return SITES["trae-global"].hosts.api + }, + // a sign-in names a host of Trae's, which can be an auth host + // (api-us-east), not the chat host + modelHost: (h) => /trae\.ai/i.test(String(h ?? "")), + // Trae Global serves no own JSON pages through the account's fetch + ownPage: () => false, + // the account's region, from the sign-in's user info + regionOf: (s) => String(s?.region ?? s?.aiRegion ?? s?.Region ?? s?.AIRegion ?? "").trim(), + // the international deployment also answers these + lapsed: [1001, "1001", 20101, "20101", 401, "401"], + quota: [4008, "4008", 1005, "1005", 4011, "4011"], + // where usage is asked, and which page it is (Global: the dollar + // billing's entitlements) + usage: { + kind: "dollar", + path: "/trae/api/v1/pay/user_current_entitlement_list", + label: "usage", + // the US account pays on its own host, the rest on the central one — + // the auth host's own /cloudide/api/v2/pay pages answer 403 Api Scope + // Forbidden here + host: (site, a) => (/^US(?:[-_ ]|$)/i.test(String(a?.region ?? "")) || /api-us/i.test(String(a?.api ?? "")) ? site.hosts.usPay : site.hosts.pay), + body: {}, + read: (v, a, signIn, { round }) => { + const d = dollarUsageOf(v) + if (!d) return { error: "Trae Global usage: no entitlement pack in the answer", signIn, user: a.name } + const total = d.basic + d.bonus + const used = d.used + d.usedBonus + const out = { plan: d.plan || "Free", user: a.name || a.uid, signIn } + if (total > 0) { + // the allowance rides the window (amount of limit, in dollars), as + // WorkBuddy's does, so magpie says it in the window's row, used or + // left, in its own words and number format (yetone/magpie#694) + const w = { name: "Dollar Usage", used: Math.round(Math.max(0, Math.min(100, (used / total) * 100)) * 100) / 100, amount: round(used), limit: round(total), unit: "usd" } + if (d.end) w.resetsAt = new Date(d.end).toISOString() + out.windows = [w] + } + return out + }, + }, + }, } -const CLIENT_ID = "ono9krqynydwx5" // Trae CN's IDE -const APP_ID = "6eefa01c-1036-4c7e-9ca5-d891f63bfcd8" -const IDE_VERSION = "3.3.65" // named to the authorization page -const IDE_VERSION_CODE = "20260401" -// the client the model host is told it serves: TRAE SOLO CN 0.1.69, as its -// ai-agent names itself (same app id). Trae offers a model only to clients -// new enough for it, and an April IDE was offered no deepseek-v4.1-flash. -const CLIENT_VERSION = "0.1.69" -const CLIENT_VERSION_CODE = "20260917" -const PLUGIN_VERSION = "2.3.24254" -const BRAND = "ASUS TUF Gaming A15 FA507RM_FA507RM" + const SIGN_IN_TIMEOUT = 10 * 60 * 1000 const EARLY_MS = 2 * 60 * 1000 // a token this close to its end is renewed before a request const LEAD_MS = 10 * 60 * 1000 // and this close, magpie renews it ahead of time (auth.refresh) const DAY = 24 * 3600 * 1000 -// the IDE's chat functions: the classic IDE's agent, then SOLO's Work -// mode, then the TRAE agent (solo_agent, which has deepseek-v4.1-flash), -// then SOLO Lite's agent -const FUNCTIONS = ["chat_v3", "solo_work_lite", "solo_agent", "solo_agent_lite"] // a reply limit of 0 is one Trae doesn't say: magpie then takes models.dev's // for the model (magpie's catalog), where a made-up 32K told agents a far // smaller one than DeepSeek V4.1 Flash's (ARNO on magpie's Discord) const MODEL = { attachment: false, tool_call: true, reasoning: true, temperature: true, limit: { context: 128_000, output: 0 }, modalities: { input: ["text"], output: ["text"] } } -// what Trae CN's chat_v3 is known to serve; the live list replaces it -const MODELS = { - "glm-5.2": { name: "GLM-5.2", ...MODEL, limit: { context: 200_000, output: 32_000 } }, - "glm-5": { name: "GLM-5", ...MODEL }, - "kimi-k2.6": { name: "Kimi K2.6", ...MODEL, limit: { context: 256_000, output: 0 } }, - "qwen-3.7-plus": { name: "Qwen 3.7 Plus", ...MODEL }, - "DeepSeek-V4-Pro": { name: "DeepSeek V4 Pro", ...MODEL }, - "DeepSeek-V4-Flash": { name: "DeepSeek V4 Flash", ...MODEL }, +// a site's fallback list names only what differs from MODEL: the defaults go +// in here, where MODEL is defined (a site table above can't spread it) +for (const site of Object.values(SITES)) { + for (const [id, m] of Object.entries(site.models)) site.models[id] = { ...MODEL, ...m } } const digits = (n) => Array.from({ length: n }, (_, i) => (i === 0 ? randomInt(1, 10) : randomInt(0, 10))).join("") @@ -99,7 +259,7 @@ const parseJSON = (s) => { // The sign-in is kept as OpenCode keeps an OAuth one: access the // Cloud-IDE-JWT, refresh the refresh token, expires the JWT's end; beside // them the account, the client it was issued to and its device. -function toAuth(s) { +function toAuth(s, site) { return { type: "oauth", access: s.token, @@ -107,15 +267,16 @@ function toAuth(s) { expires: s.expires || jwtExp(s.token) || Date.now() + DAY, accountId: s.name || s.uid, uid: s.uid, - clientId: s.clientId || CLIENT_ID, + clientId: s.clientId || site.clientId, deviceId: s.deviceId, machineId: s.machineId, // the model host the sign-in named, if it named one - ...(/mchost\.guru|trae-api-/i.test(s.api ?? "") ? { api: s.api } : {}), + ...(site.modelHost(s.api) ? { api: s.api } : {}), + ...(s.region ? { region: s.region } : {}), } } -function fromAuth(auth) { +function fromAuth(auth, site) { if (auth?.type !== "oauth" || !auth.access) return null return { token: auth.access, @@ -123,31 +284,24 @@ function fromAuth(auth) { expires: Number(auth.expires) || 0, uid: String(auth.uid ?? ""), name: String(auth.accountId ?? ""), - clientId: auth.clientId || CLIENT_ID, + clientId: auth.clientId || site.clientId, deviceId: auth.deviceId || "", machineId: auth.machineId || "", api: auth.api || "", + region: site.regionOf(auth), } } -// apiOf is the model host for an account: the one its sign-in named when -// that is a model host (trae.cn's own hosts serve no models), else Trae -// CN's -function apiOf(a) { - const h = String(a?.api ?? "").replace(/\/+$/, "") - return /mchost\.guru|trae-api-/i.test(h) ? h : HOSTS.api +// apiOf is the model host for an account +function apiOf(a, site) { + return site.apiOf(a) } -// ownPage: url is one of Trae CN's own JSON pages on api.trae.cn -// (/trae/api/…: the daily check-in, credits), which the account's fetch -// sends as the account rather than as a chat -function ownPage(url) { - try { - const u = new URL(url) - return u.origin === new URL(HOSTS.auth).origin && u.pathname.startsWith("/trae/api/") - } catch { - return false - } +// ownPage: url is one of Trae's own JSON pages (the daily check-in, +// credits), which the account's fetch sends as the account rather than as +// a chat +function ownPage(url, site) { + return site.ownPage(url) } // ---- errors -------------------------------------------------------------------- @@ -173,9 +327,13 @@ function errorOf(v) { } // lapsed: Trae turned the token away. 1001 is its "not signed in". -const lapsedCode = (code) => [1001, "1001", 401, "401"].includes(code) +// The realms differ in which codes they send: the international deployment +// also answers 20101 for a token it no longer takes. +const CN_LAPSED = [1001, "1001", 401, "401"] +const lapsedCode = (code, site) => (site?.lapsed ?? CN_LAPSED).includes(code) const lapsedWords = /not ?log(ged)? ?in|unauthori[sz]ed|token (is )?(expired|invalid)|jwt|未登录|登录(已)?(过期|失效)/i -const quotaCode = (code) => [4008, "4008", 1005, "1005"].includes(code) +const CN_QUOTA = [4008, "4008", 1005, "1005"] +const quotaCode = (code, site) => (site?.quota ?? CN_QUOTA).includes(code) const quotaWords = /quota|credit|insufficient|exceed|limit|额度|积分|次数|上限|用完/i // errorResponse is an OpenAI-style error, as the agent reads one @@ -190,17 +348,17 @@ const errorResponse = (status, message, signIn) => { // exchange trades a refresh token for a new Cloud-IDE-JWT, as the IDE // does: the answer's Result holds the new token pair and the account. // Trae issues a new refresh token each time and spends the old one. -async function exchange(refresh, clientId, host = HOSTS.auth) { +async function exchange(refresh, clientId, site, host = site.hosts.auth) { let res try { res = await fetch(host.replace(/\/+$/, "") + "/cloudide/api/v3/trae/oauth/ExchangeToken", { method: "POST", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ ClientID: clientId || CLIENT_ID, RefreshToken: refresh, ClientSecret: "-", UserID: "" }), + body: JSON.stringify({ ClientID: clientId || site.clientId, RefreshToken: refresh, ClientSecret: "-", UserID: "" }), signal: AbortSignal.timeout(20_000), }) } catch (e) { - throw new Error("Trae CN: renewing the sign-in: " + (e?.message ?? e)) + throw new Error(`${site.realm}: renewing the sign-in: ` + (e?.message ?? e)) } const text = await res.text() const v = parseJSON(text) @@ -216,6 +374,7 @@ async function exchange(refresh, clientId, host = HOSTS.auth) { uid: String(info.UserID ?? info.userId ?? r.UserID ?? ""), name: String(info.ScreenName ?? info.screenName ?? ""), api: info.Host ?? "", + region: site.regionOf(info), } } const e = errorOf(text) @@ -223,9 +382,9 @@ async function exchange(refresh, clientId, host = HOSTS.auth) { // a refresh token Trae no longer takes (spent, revoked, past its end, or // of another client) is a sign-in to make again if ([400, 401, 403].includes(res.status) || /refresh|expired|invalid|not matched|revoked|unauthori/i.test(msg) || String(e.code) === "10101") { - throw new Expired(`Trae CN's sign-in has expired (${msg}); sign in again`) + throw new Expired(`${site.realm}'s sign-in has expired (${msg}); sign in again`) } - throw new Error(`Trae CN: renewing the sign-in: ${statusLine(res.status)} ${msg}`.trim()) + throw new Error(`${site.realm}: renewing the sign-in: ${statusLine(res.status)} ${msg}`.trim()) } // ---- the browser sign-in -------------------------------------------------------- @@ -239,7 +398,7 @@ const page = (ok, title, text) => ` { - // trae.cn's page may call the callback from script as well as open it + // the site's page may call the callback from script as well as open it const cors = { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, OPTIONS", "Access-Control-Allow-Headers": "Content-Type" } if (req.method === "OPTIONS") return res.writeHead(204, cors).end() const url = new URL(req.url ?? "/", "http://127.0.0.1") @@ -291,11 +451,11 @@ async function browserSignIn() { finish({ type: "failed", error: msg }) return html(page(false, "Sign-in didn't finish", msg)) } - if (!q.get("userJwt") && !q.get("refreshToken")) return html(page(false, "Nothing to sign in with", "trae.cn sent no token; start the sign-in again.")) + if (!q.get("userJwt") && !q.get("refreshToken")) return html(page(false, "Nothing to sign in with", `${site.webHost} sent no token; start the sign-in again.`)) try { - const s = await signedIn(q, device) - finish({ ...toAuth(s), type: "success" }) - html(page(true, "You're signed in", `${s.name || s.uid || "Your Trae CN account"} is signed in. You can close this tab.`)) + const s = await signedIn(q, device, site) + finish({ ...toAuth(s, site), type: "success" }) + html(page(true, "You're signed in", `${s.name || s.uid || `Your ${site.name} account`} is signed in. You can close this tab.`)) } catch (e) { finish({ type: "failed", error: e.message }) html(page(false, "Sign-in didn't finish", e.message)) @@ -315,9 +475,9 @@ async function browserSignIn() { login_version: "1", auth_from: "solo", login_channel: "native_ide", - plugin_version: PLUGIN_VERSION, + plugin_version: site.pluginVersion, auth_type: "local", - client_id: CLIENT_ID, + client_id: site.clientId, redirect: "0", login_trace_id: trace, auth_callback_url: callback, @@ -325,17 +485,17 @@ async function browserSignIn() { device_id: device.deviceId, x_device_id: device.deviceId, x_machine_id: device.machineId, - x_device_brand: BRAND, + x_device_brand: site.brand, x_device_type: "windows", x_os_version: "Windows 10 Pro", x_env: "", - x_app_version: IDE_VERSION, + x_app_version: site.ideVersion, x_app_type: "stable", hide_saas_login: "true", }) return { - url: `${HOSTS.web}/authorization?${q}`, - instructions: "Sign in to Trae CN (trae.cn) in the browser and allow the sign-in. It finishes here by itself.", + url: `${site.hosts.web}/authorization?${q}`, + instructions: `Sign in to ${site.name} (${site.webHost}) in the browser and allow the sign-in. It finishes here by itself.`, method: "auto", callback: () => done, } @@ -344,24 +504,24 @@ async function browserSignIn() { // ---- requests --------------------------------------------------------------------- // headers are the IDE's, for the account and its device -function ideHeaders(a, extra = {}) { +function ideHeaders(a, site, extra = {}) { return { "Content-Type": "application/json", Authorization: `Cloud-IDE-JWT ${a.token}`, "X-Cloudide-Token": a.token, "x-ide-token": a.token, "x-uid": a.uid, - "x-app-id": APP_ID, + "x-app-id": site.appId, "x-device-id": a.deviceId, "x-machine-id": a.machineId, "x-request-id": randomUUID(), - "x-app-version": CLIENT_VERSION, - "x-app-version-code": CLIENT_VERSION_CODE, - "x-ide-version": CLIENT_VERSION, - "x-ide-version-code": CLIENT_VERSION_CODE, + "x-app-version": site.clientVersion, + "x-app-version-code": site.clientVersionCode, + "x-ide-version": site.clientVersion, + "x-ide-version-code": site.clientVersionCode, "x-ide-version-type": "stable", "x-device-cpu": "AMD", - "x-device-brand": BRAND, + "x-device-brand": site.brand, "x-device-type": "windows", "x-os-version": "Windows 10", "x-system-type": "Windows", @@ -500,28 +660,36 @@ async function* sse(stream) { yield { event: event || (v && typeof v === "object" ? String(v.event ?? v.type ?? "") : ""), data: v } event = "" } - for (;;) { - const { value, done } = await reader.read() - if (done) break - buf += dec.decode(value, { stream: true }) - let i - while ((i = buf.indexOf("\n")) >= 0) { - const line = buf.slice(0, i).replace(/\r$/, "") - buf = buf.slice(i + 1) - if (!line) { - yield* flush() - continue + try { + for (;;) { + const { value, done } = await reader.read() + if (done) break + buf += dec.decode(value, { stream: true }) + let i + while ((i = buf.indexOf("\n")) >= 0) { + const line = buf.slice(0, i).replace(/\r$/, "") + buf = buf.slice(i + 1) + if (!line) { + yield* flush() + continue + } + if (line.startsWith(":")) continue + if (line.startsWith("event:")) { + yield* flush() + event = line.slice(6).trim() + } else if (line.startsWith("data:")) data.push(line.slice(5).trimStart()) } - if (line.startsWith(":")) continue - if (line.startsWith("event:")) { - yield* flush() - event = line.slice(6).trim() - } else if (line.startsWith("data:")) data.push(line.slice(5).trimStart()) } + buf += dec.decode() + if (buf.startsWith("data:")) data.push(buf.slice(5).trimStart()) + yield* flush() + } finally { + // the answer the agent goes away from (a tool call made, a request + // aborted) closes this generator mid-read: let Trae's connection go, + // or the read hangs on and the host the next ask reuses is one Trae + // has dropped — a stream that runs, then dies + reader.cancel().catch(() => {}) } - buf += dec.decode() - if (buf.startsWith("data:")) data.push(buf.slice(5).trimStart()) - yield* flush() } // normalised event names: "TokenUsage", "token-usage" → token_usage @@ -1023,17 +1191,21 @@ async function* chain(held, it) { } // failure is the response for an error Trae answered with -function failure(status, code, message) { +function failure(site, status, code, message) { message = message || statusLine(status) - if (status === 401 || lapsedCode(code) || (status === 403 && lapsedWords.test(message))) { - return errorResponse(401, `Trae CN's sign-in has expired (${message}); sign in again`, "expired") + if (status === 401 || lapsedCode(code, site) || (status === 403 && lapsedWords.test(message))) { + return errorResponse(401, `${site.realm}'s sign-in has expired (${message}); sign in again`, "expired") } - if (status === 429 || quotaCode(code) || (status === 403 && quotaWords.test(message))) return errorResponse(429, `Trae CN: ${message}`) - return errorResponse(status >= 400 ? status : 502, `Trae CN: ${message}${code ? ` (code ${code})` : ""}`) + if (status === 429 || quotaCode(code, site) || (status === 403 && quotaWords.test(message))) return errorResponse(429, `${site.realm}: ${message}`) + return errorResponse(status >= 400 ? status : 502, `${site.realm}: ${message}${code ? ` (code ${code})` : ""}`) } // openai is the answer as an OpenAI chat completion: a stream, or one body -async function openai(req, it) { +// abort, when given, lets the answer's reader close Trae's connection the +// moment the agent goes away (a tool call made, a request cancelled): a +// generator's return can't break a read that is already waiting, so the +// fetch itself is what has to be stopped +async function openai(req, it, abort, site) { const id = "chatcmpl-" + randomBytes(12).toString("hex") const created = Math.floor(Date.now() / 1000) const model = req.model @@ -1044,7 +1216,7 @@ async function openai(req, it) { let usage = null let finish = "" for await (const p of it) { - if (p.error) return failure(502, p.code, p.error) + if (p.error) return failure(site, 502, p.code, p.error) if (p.text) text += p.text if (p.reasoning) reasoning += p.reasoning if (p.call) calls.push(p.call) @@ -1106,6 +1278,7 @@ async function openai(req, it) { }, cancel() { gone = true + abort?.() it.return?.() }, }) @@ -1121,12 +1294,16 @@ const wrongFunction = (code) => ["4001", "4023", "1005"].includes(String(code)) // The lists also hold the IDE's own helpers (summary, fast_apply, title // generation: usage other than chat_completion), configs switched off, and // the slots of custom models, which need a provider bound in the IDE. -function chatModel(m) { +function chatModel(m, site) { const id = String(m?.config_name ?? "") if (!id || /^custom_model/i.test(id)) return false if (m.usage && m.usage !== "chat_completion") return false if (m.config_switch === false) return false if (m.is_custom_model === true || m.display_config?.is_custom_model === true) return false + // the IDE's own picker hides these: Auto-mode routing channels and + // pay-as-you-go twins of another entry (gemini-3.1-pro vs -paygo/-auto, + // the search_agent family), not entries to pick by hand + if (site?.hidesInvisible && m.is_invisible_to_user === true) return false return true } @@ -1179,9 +1356,26 @@ function credits(v) { const round = (n) => Math.round(n * 100) / 100 +// dollarUsageOf reads an account's entitlement pack as the dollar billing +// has it (the international deployment): the period's allowance in dollars +// (basic_usage_limit plus bonus_usage_limit) and what was used of each +// (basic_usage_amount, bonus_usage_amount). null when the answer carries no +// pack. +function dollarUsageOf(v) { + const pack = (v?.user_entitlement_pack_list ?? []).find((p) => p?.usage || p?.entitlement_base_info?.quota) + const quota = pack?.entitlement_base_info?.quota + if (!pack || !quota) return null + const basic = Number(quota.basic_usage_limit) || 0 + const bonus = Number(quota.bonus_usage_limit) || 0 + const used = Number(pack.usage?.basic_usage_amount) || 0 + const usedBonus = Number(pack.usage?.bonus_usage_amount) || 0 + const end = whenOf(pack.entitlement_base_info.end_time) + return { plan: String(pack.display_desc ?? ""), basic, bonus, used, usedBonus, end } +} + // ---- the plugin --------------------------------------------------------------------- -export const TraeCNAuthPlugin = async ({ client }) => { +const makePlugin = (site) => async ({ client }) => { // renewals under way, one to a refresh token (Trae spends it once), and // the last each account got here, so a sign-in from before it is given // that one rather than spending the token again @@ -1198,7 +1392,7 @@ export const TraeCNAuthPlugin = async ({ client }) => { const save = async (auth) => { try { - await client?.auth?.set?.({ path: { id: ID }, body: auth }) + await client?.auth?.set?.({ path: { id: site.id }, body: auth }) } catch {} } @@ -1207,10 +1401,10 @@ export const TraeCNAuthPlugin = async ({ client }) => { let r = renewing.get(key) if (!r) { r = (async () => { - const x = await exchange(a.refresh, a.clientId) + const x = await exchange(a.refresh, a.clientId, site) const got = { ...a, token: x.token, refresh: x.refresh, expires: x.expires || jwtExp(x.token) || Date.now() + DAY, clientId: x.clientId || a.clientId, renewed: true } renewed.set(a.uid || a.name, { was: a.refresh, got }) - if (keep) await save(toAuth(got)) + if (keep) await save(toAuth(got, site)) return got })().finally(() => renewing.delete(key)) renewing.set(key, r) @@ -1221,8 +1415,8 @@ export const TraeCNAuthPlugin = async ({ client }) => { // fresh is the account with a token that has a while to go, renewed // when it hasn't const fresh = async (getAuth) => { - const a = fromAuth(await getAuth()) - if (!a) throw new Expired("Trae CN: not signed in") + const a = fromAuth(await getAuth(), site) + if (!a) throw new Expired(`${site.realm}: not signed in`) const last = renewed.get(a.uid || a.name) if (last && last.was === a.refresh) return { ...last.got, renewed: false } if (!a.expires || a.expires - Date.now() > EARLY_MS || !a.refresh) return a @@ -1238,7 +1432,7 @@ export const TraeCNAuthPlugin = async ({ client }) => { // refresh is magpie's auth.refresh: the token renewed LEAD_MS before its // end, as the fields that changed const refresh = async (auth) => { - const a = fromAuth(auth) + const a = fromAuth(auth, site) if (!a || !a.refresh) return undefined const last = renewed.get(a.uid || a.name) if (last && last.was === a.refresh) return { access: last.got.token, refresh: last.got.refresh, expires: last.got.expires } @@ -1248,7 +1442,7 @@ export const TraeCNAuthPlugin = async ({ client }) => { // post asks one of Trae's JSON pages with the account const post = async (a, url, body) => { - const res = await fetch(url, { method: "POST", headers: ideHeaders(a, { Accept: "application/json" }), body: JSON.stringify(body), signal: AbortSignal.timeout(20_000) }) + const res = await fetch(url, { method: "POST", headers: ideHeaders(a, site, { Accept: "application/json" }), body: JSON.stringify(body), signal: AbortSignal.timeout(20_000) }) const text = await res.text() return { status: res.status, text, v: parseJSON(text) } } @@ -1273,12 +1467,12 @@ export const TraeCNAuthPlugin = async ({ client }) => { // 0.1.6 failed from then on (yetone/magpie#808) const res = await fetch(url, { method, - headers: ideHeaders(a, { Accept: "application/json" }), + headers: ideHeaders(a, site, { Accept: "application/json" }), body: method === "GET" || method === "HEAD" ? undefined : typeof body === "string" ? body : "{}", signal: signal ?? AbortSignal.timeout(20_000), }) const text = await res.text() - const lapsed = res.status === 401 || lapsedCode(errorOf(text).code) + const lapsed = res.status === 401 || lapsedCode(errorOf(text).code, site) const headers = { "content-type": res.headers.get("content-type") ?? "application/json", "X-Magpie-Sign-In": lapsed ? "expired" : a.renewed ? "renewed" : "kept" } return new Response(text, { status: res.status, headers }) } @@ -1293,44 +1487,32 @@ export const TraeCNAuthPlugin = async ({ client }) => { const signIn = a.renewed ? "renewed" : "kept" let r try { - r = await post(a, HOSTS.auth + "/trae/api/v2/pay/ide_user_ent_usage", { require_usage: true, req_source: 0 }) + r = await post(a, site.usage.host(site, a) + site.usage.path, site.usage.body) } catch (e) { - return { error: "Trae CN credits: " + (e?.message ?? e), signIn } + return { error: `${site.realm} ${site.usage.label}: ` + (e?.message ?? e), signIn } } const e = errorOf(r.v) - if (r.status === 401 || lapsedCode(e.code)) return { error: `${a.name || a.uid}: Trae CN's sign-in has expired — sign in again`, signIn: "expired" } - if (r.status !== 200 || (e.code && String(e.code) !== "0")) return { error: `Trae CN credits: ${e.message || statusLine(r.status)}`, signIn, user: a.name } - const c = credits(r.v) - const out = { plan: r.v.is_credits_billing ? "Credits" : "Free", user: a.name || a.uid, signIn } - if (c.unlimited) out.balance = "unlimited" - else if (c.limit > 0) { - // the count rides on the window (amount of limit, in credits), as - // WorkBuddy's does, so magpie says it in the window's row, used or - // left, in its own words and number format, rather than as an - // English balance line beside it (yetone/magpie#694) - const w = { name: "Credits", used: Math.max(0, Math.min(100, (c.used / c.limit) * 100)), amount: round(c.used), limit: round(c.limit), unit: "credits" } - if (c.until) w.resetsAt = new Date(c.until).toISOString() - out.windows = [w] - } - return out + if (r.status === 401 || lapsedCode(e.code, site)) return { error: `${a.name || a.uid}: ${site.realm}'s sign-in has expired — sign in again`, signIn: "expired" } + if (r.status !== 200 || (e.code && String(e.code) !== "0")) return { error: `${site.realm} ${site.usage.label}: ${e.message || statusLine(r.status)}`, signIn, user: a.name } + return site.usage.read(r.v, a, signIn, { credits, round, statusLine }) } // batchLists is every chat function's model list in one ask, as TRAE // SOLO CN's ai-agent asks (batch_get_detail_param): {function: entries}. // null when Trae answers it with no lists. const batchLists = async (a) => { - const r = await post(a, apiOf(a) + "/api/ide/v1/batch_get_detail_param", { - functions: FUNCTIONS, agent_type: "", current_config_info: { config_name: "", is_custom_model: false }, + const r = await post(a, apiOf(a, site) + "/api/ide/v1/batch_get_detail_param", { + functions: site.functions, 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, }) - if (r.status === 401 || lapsedCode(errorOf(r.v).code)) throw new Expired("Trae CN's sign-in has expired; sign in again") - if (r.status !== 200) throw new Error(`Trae CN models: ${statusLine(r.status)}`) + if (r.status === 401 || lapsedCode(errorOf(r.v).code, site)) throw new Expired(`${site.realm}'s sign-in has expired; sign in again`) + if (r.status !== 200) throw new Error(`${site.realm} models: ${statusLine(r.status)}`) const groups = r.v.function_configs ?? r.v.data?.function_configs if (!Array.isArray(groups)) return null const out = {} for (const g of groups) { const fn = String(g?.function ?? "") - if (!FUNCTIONS.includes(fn) || !Array.isArray(g.config_info_list)) continue + if (!site.functions.includes(fn) || !Array.isArray(g.config_info_list)) continue out[fn] = [...(out[fn] ?? []), ...g.config_info_list.filter((m) => m?.config_name)] } return Object.keys(out).length ? out : null @@ -1338,11 +1520,11 @@ export const TraeCNAuthPlugin = async ({ client }) => { // listOf is one function's model list, as the IDE asks for it const listOf = async (a, fn) => { - const r = await post(a, apiOf(a) + "/api/ide/v1/get_detail_param", { + const r = await post(a, apiOf(a, site) + "/api/ide/v1/get_detail_param", { function: fn, config_names: null, need_prompt: false, current_config_info: null, poly_prompt: true, mode_type: null, agent_type: null, }) - if (r.status === 401 || lapsedCode(errorOf(r.v).code)) throw new Expired("Trae CN's sign-in has expired; sign in again") - if (r.status !== 200) throw new Error(`Trae CN models: ${statusLine(r.status)}`) + if (r.status === 401 || lapsedCode(errorOf(r.v).code, site)) throw new Expired(`${site.realm}'s sign-in has expired; sign in again`) + if (r.status !== 200) throw new Error(`${site.realm} models: ${statusLine(r.status)}`) const list = r.v.config_info_list ?? r.v.data?.config_info_list ?? [] return list.filter((m) => m?.config_name) } @@ -1366,13 +1548,13 @@ export const TraeCNAuthPlugin = async ({ client }) => { if (e instanceof Expired) throw e } if (!lists) { - const got = await Promise.allSettled(FUNCTIONS.map((fn) => listOf(a, fn))) + const got = await Promise.allSettled(site.functions.map((fn) => listOf(a, fn))) const expired = got.find((g) => g.status === "rejected" && g.reason instanceof Expired) if (expired) throw expired.reason if (got.every((g) => g.status === "rejected")) throw got[0].reason lists = {} got.forEach((g, i) => { - if (g.status === "fulfilled") lists[FUNCTIONS[i]] = g.value + if (g.status === "fulfilled") lists[site.functions[i]] = g.value }) } // a function can give a model another's name: chat_v3 calls @@ -1383,24 +1565,24 @@ export const TraeCNAuthPlugin = async ({ client }) => { // model's in the same list, and other lists name it otherwise. const nameOf = (m) => String(m.display_config?.display_name || m.display_name || m.display_model_name || m.config_name) const names = new Map() // id → the names its lists give it - for (const fn of FUNCTIONS) { + for (const fn of site.functions) { for (const m of lists[fn] ?? []) { - if (!chatModel(m)) continue + if (!chatModel(m, site)) continue const id = String(m.config_name) names.set(id, (names.get(id) ?? new Set()).add(nameOf(m))) } } const misnamed = (fn, m) => { const id = String(m.config_name), name = nameOf(m) - return names.get(id).size > 1 && (lists[fn] ?? []).some((o) => chatModel(o) && String(o.config_name) !== id && nameOf(o) === name) + return names.get(id).size > 1 && (lists[fn] ?? []).some((o) => chatModel(o, site) && String(o.config_name) !== id && nameOf(o) === name) } // a function's entry is worth more when it names a __dev model, then // when it isn't misnamed; the first of the best is taken const worth = (fn, m) => (devModel(m) ? 2 : 0) + (misnamed(fn, m) ? 0 : 1) const out = new Map() - for (const fn of FUNCTIONS) { + for (const fn of site.functions) { for (const m of lists[fn] ?? []) { - if (!chatModel(m)) continue + if (!chatModel(m, site)) continue const id = String(m.config_name) const was = out.get(id) if (!was || worth(fn, m) > was.worth) out.set(id, { m, fn, worth: worth(fn, m) }) @@ -1413,7 +1595,7 @@ export const TraeCNAuthPlugin = async ({ client }) => { else modelNames.delete(id) if (out.has(id + MAX)) continue // its Max is asked through the function whose entry names the __max model - const entries = [{ m, fn }, ...FUNCTIONS.flatMap((f) => (lists[f] ?? []).filter((o) => o !== m && chatModel(o) && String(o.config_name) === id).map((o) => ({ m: o, fn: f })))] + const entries = [{ m, fn }, ...site.functions.flatMap((f) => (lists[f] ?? []).filter((o) => o !== m && chatModel(o, site) && String(o.config_name) === id).map((o) => ({ m: o, fn: f })))] const max = maxModel(...entries.map((e) => e.m)) maxes.set(id, max) if (max) { @@ -1435,23 +1617,23 @@ export const TraeCNAuthPlugin = async ({ client }) => { const ctx = Number(m.context_window_tokens?.dev ?? m.context_window_size?.max?.[0] ?? m.context_window_size?.max ?? m.context_window_tokens?.max ?? m.prompt_max_tokens) || was.limit?.context || MODEL.limit.context const out = Number(devModel(m)?.max_tokens) || was.limit?.output || 0 const name = m.display_config?.display_name || m.display_name || m.display_model_name || was.name || id - return { ...MODEL, ...was, id, providerID: ID, name: String(name), limit: { context: ctx, output: out }, api: was.api ?? { id, url: HOSTS.api, npm: "@ai-sdk/openai-compatible" } } + return { ...MODEL, ...was, id, providerID: site.id, name: String(name), limit: { context: ctx, output: out }, api: was.api ?? { id, url: site.hosts.api, npm: "@ai-sdk/openai-compatible" } } } return { config: async (config) => { config.provider ??= {} - const was = config.provider[ID] ?? {} - config.provider[ID] = { - name: "Trae CN", + const was = config.provider[site.id] ?? {} + config.provider[site.id] = { + name: site.name, npm: "@ai-sdk/openai-compatible", - api: HOSTS.api + "/v1", + api: site.hosts.api + "/v1", ...was, - models: { ...MODELS, ...(was.models ?? {}) }, + models: { ...site.models, ...(was.models ?? {}) }, } }, provider: { - id: ID, + id: site.id, // the account's own list, when Trae answers; else the list above async models(provider, { auth }) { if (auth?.type !== "oauth" || !auth.access) return provider.models @@ -1475,7 +1657,7 @@ export const TraeCNAuthPlugin = async ({ client }) => { }, }, auth: { - provider: ID, + provider: site.id, usage, // magpie renews the token LEAD_MS before its end, once, before its // requests, models and usage ask; the check before each request @@ -1483,10 +1665,10 @@ export const TraeCNAuthPlugin = async ({ client }) => { refreshLead: LEAD_MS, refresh, loader: async (getAuth) => { - const a0 = fromAuth(await getAuth()) + const a0 = fromAuth(await getAuth(), site) if (!a0) return {} return { - baseURL: apiOf(a0) + "/v1", + baseURL: apiOf(a0, site) + "/v1", apiKey: "trae", // the engine's placeholder; the request carries the JWT async fetch(input, init = {}) { const r0 = input instanceof Request ? input : null @@ -1494,9 +1676,9 @@ export const TraeCNAuthPlugin = async ({ client }) => { if (body instanceof ArrayBuffer) body = new TextDecoder().decode(body) else if (ArrayBuffer.isView(body)) body = new TextDecoder().decode(new Uint8Array(body.buffer, body.byteOffset, body.byteLength)) const url = r0 ? r0.url : input instanceof URL ? input.href : String(input) - if (ownPage(url)) return ownRequest(getAuth, a0, url, init.method ?? r0?.method ?? "POST", body, init.signal ?? r0?.signal) + if (ownPage(url, site)) return ownRequest(getAuth, a0, url, init.method ?? r0?.method ?? "POST", body, init.signal ?? r0?.signal) const req = parseJSON(body) - if (!Array.isArray(req.messages)) return errorResponse(400, "Trae CN: only chat completions are served") + if (!Array.isArray(req.messages)) return errorResponse(400, `${site.realm}: only chat completions are served`) let a try { a = await fresh(getAuth) @@ -1508,7 +1690,7 @@ export const TraeCNAuthPlugin = async ({ client }) => { const who = a.uid || a.name // the function that lists the model first, then the one that // served this account last, then the rest - const fns = [...new Set([listedBy.get(String(req.model)), fnOf.get(who), ...FUNCTIONS].filter(Boolean))] + const fns = [...new Set([listedBy.get(String(req.model)), fnOf.get(who), ...site.functions].filter(Boolean))] let last let named = modelNames.get(String(req.model)) if (!named && String(req.model).endsWith(MAX)) { @@ -1518,17 +1700,27 @@ export const TraeCNAuthPlugin = async ({ client }) => { if (named) fns.unshift(named.fn) } const max = named?.max ?? null + // the answer's own signal: the caller's abort (a cancelled + // request) and the stream's cancel both stop Trae's fetch, so + // no read is left hanging on a connection the agent walked + // away from + const ac = new AbortController() + const outer = init.signal ?? r0?.signal ?? null + if (outer) { + if (outer.aborted) ac.abort() + else outer.addEventListener("abort", () => ac.abort(), { once: true }) + } for (const fn of [...new Set(fns)]) { - const res = await fetch(apiOf(a) + "/api/agent/v3/llm_utils_chat", { + const res = await fetch(apiOf(a, site) + "/api/agent/v3/llm_utils_chat", { method: "POST", - headers: ideHeaders(a, { Accept: "text/event-stream", "X-Request-ID": randomUUID() }), + 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)), - signal: init.signal ?? r0?.signal, + signal: ac.signal, }) if (!res.ok) { const text = await res.text() const e = errorOf(text) - last = failure(res.status, e.code, e.message || text.trim().slice(0, 300)) + last = failure(site, res.status, e.code, e.message || text.trim().slice(0, 300)) if (res.status === 400 && wrongFunction(e.code)) continue break } @@ -1536,7 +1728,7 @@ export const TraeCNAuthPlugin = async ({ client }) => { if (!ct.includes("event-stream") && ct.includes("json")) { // an answer that isn't a stream is an error in a 200 const e = errorOf(await res.text()) - last = failure(502, e.code, e.message) + last = failure(site, 502, e.code, e.message) if (wrongFunction(e.code)) continue break } @@ -1544,12 +1736,18 @@ export const TraeCNAuthPlugin = async ({ client }) => { const { held, done } = await first(it) const err = held.find((p) => p.error) if (err) { - last = failure(502, err.code, err.error) - if (wrongFunction(err.code)) continue + last = failure(site, 502, err.code, err.error) + if (wrongFunction(err.code)) { + // another function may take it: this answer's read goes + // with the function it came from, not left hanging + it.return?.() + res.body.cancel?.().catch(() => {}) + continue + } break } fnOf.set(who, fn) - const out = await openai(req, done ? held : chain(held, it)) + const out = await openai(req, done ? held : chain(held, it), () => ac.abort(), site) out.headers.set("X-Magpie-Sign-In", signIn) return out } @@ -1558,10 +1756,13 @@ export const TraeCNAuthPlugin = async ({ client }) => { }, } }, - methods: [{ type: "oauth", label: "Trae CN account (browser)", authorize: browserSignIn }], + methods: [{ type: "oauth", label: `${site.name} account (browser)`, authorize: () => browserSignIn(site) }], }, } } -// for tests -export const _internal = { HOSTS, MODELS, TextTools, NativeCalls, looseJSON, glmCall, toolNamed, traeMessages, chatBody, credits, whenOf, newDevice } +// for tests: the CN realm's table as before, plus both realms' factories +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, SITES } diff --git a/packages/trae/package.json b/packages/trae/package.json index 292f101..bae84c2 100644 --- a/packages/trae/package.json +++ b/packages/trae/package.json @@ -1,12 +1,12 @@ { "name": "@magpie-community/opencode-trae-auth", - "version": "0.1.15", - "description": "OpenCode provider plugin for Trae CN (trae.cn): your Trae CN account's models, free tier included, with Trae's own browser sign-in", + "version": "0.2.0", + "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", "exports": "./index.mjs", "files": ["index.mjs", "README.md"], - "keywords": ["opencode", "opencode-plugin", "trae", "trae-cn", "bytedance"], + "keywords": ["opencode", "opencode-plugin", "magpie", "trae", "trae-cn", "trae-global", "bytedance"], "license": "MIT", "repository": { "type": "git", "url": "git+https://github.com/magpie-community/plugins.git", "directory": "packages/trae" } } diff --git a/registry.json b/registry.json index 6e59fe3..b1e4cfd 100644 --- a/registry.json +++ b/registry.json @@ -27,7 +27,7 @@ "summary": { "en": "WorkBuddy's China build (CodeBuddy plan) and its international build.", "zh": "WorkBuddy 国内版(CodeBuddy 套餐)与国际版。" } }, { "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 自己的浏览器登录。实验性。" } } + { "package": "@magpie-community/opencode-trae-auth", "name": "Trae", "icon": "trae", "providers": ["trae-cn", "trae-global"], "community": true, + "summary": { "en": "Trae CN (trae.cn) and Trae international (trae.ai) models with your own account, free tier included — Trae's own browser sign-in. Experimental.", "zh": "用 Trae CN(trae.cn)与 Trae 国际版(trae.ai)账号使用各自的模型,含免费版,使用 Trae 自己的浏览器登录。实验性。" } } ] }