diff --git a/packages/trae/README.md b/packages/trae/README.md index bf1a900..5214fb9 100644 --- a/packages/trae/README.md +++ b/packages/trae/README.md @@ -66,6 +66,15 @@ fields are kept with the sign-in; nothing sends them. enterprise sign-in sends back is not known yet; if yours doesn't work, open an issue with what the sign-in page showed. +One enterprise sign-in has since been seen to name +`console.enterprise.trae.cn` as the account's host, and its usage is read +from that console (see Usage). The tenant and login-type fields are still +kept and never sent. + +The international deployment has an enterprise console too, at +`console.enterprise.trae.ai`, and the same reading is done there — **not +verified**, see Usage. + ### The international realm's region Trae Global has two deployments. The sign-in's `AIRegion` (or a US auth host @@ -362,6 +371,36 @@ page the realm bills on: total, with the share, which magpie shows as used or left like WorkBuddy's. +**Trae CN, an enterprise (SaaS) account** — Trae's enterprise console, which +bills in yuan rather than in the credits the consumer page counts: + +- **Source:** `console.enterprise.trae.cn/trae/gtm/tob/api/v1/config/get_personal_quota` + for the allowance and `…/get_user_model_usage` for the spend, both POST + with an empty body; `…/get_personal_core_data` for the period's + `ResetTime`; and the consumer credits page above for the second row. +- **What it adds up:** the seat pool in yuan (`seat_pool_currency_quota`; + the console's pay-as-you-go sentinel is no limit), and the models' own + `total_cost_currency` summed — the console gives no total of its own. The + console answers an empty body with the current period's spend, which is + what the pool resets on; a real account's sum matches its usage page. Only + the account's own seat is counted: an administrator's answer carries every + seat in the tenant. +- **What it shows:** a Seat Usage window, `¥used / ¥total` and the share, + resetting when the console says the period does, then a Credits window of + the consumer page's allowance, marked `aside`. A spend page that fails + leaves the row saying `? / ¥total` rather than reading as nothing spent. +- **Which accounts:** the sign-in named `console.enterprise.trae.cn` as the + account's host. A personal account, and any account whose usage pages + answer nothing, is read as before. +- **Why both:** the consumer page answers an enterprise account too, with a + credits allowance that real calls have been measured not to touch — two + calls through magpie moved the console's spend by ¥0.0002 each and left + the credits at 4.4 of 4700. The seat pool is what a request spends, so + the credits row is `aside`: magpie shows it without routing on it. Whether + the credits are a fallback the seat pool exhausts first is not known — no + account has spent its pool to find out. A failure on the credits page or + on the period leaves the seat pool standing. + **Trae Global** — the dollar billing's entitlements: - **Source:** `POST api-sg-central.trae.ai/trae/api/v1/pay/user_current_entitlement_list` @@ -372,6 +411,39 @@ page the realm bills on: - **What it shows:** one Dollar Usage window, the dollars used of the allowance, resetting when the pack ends. +**Trae Global, an enterprise (SaaS) account** — the international +deployment's own enterprise console, which bills in dollars: + +- **Source:** `console.enterprise.trae.ai/trae/gtm/tob/api/v1/config/get_personal_quota` + for the allowance, `…/get_user_model_usage` for the spend and + `…/get_personal_core_data` for the period, all POST with an empty body — + the three pages Trae CN's console has. +- **What it adds up:** the seat pool (`seat_pool_currency_quota`; the + console's pay-as-you-go sentinel is no limit) and the models' own + `total_cost_currency` summed. +- **What it shows:** one Seat Usage window, `$used / $total` and the share, + resetting when the console says the period does. The international realm + has no consumer credits page, so there is no second row. +- **Which accounts:** the sign-in named `console.enterprise.trae.ai` as the + account's host. Any other account is read as before. + +**Not verified.** No international enterprise account was available to try +this against, and `console.enterprise.trae.ai` answers another realm's token +with 请先登录 — exactly as it answers no token at all, so whether it refuses +the token or wants a console session of its own is not known either. What +the paths and fields are was read off the international console's own build, +which names `seat_pool_currency_quota`, the models' `total_cost_currency` +and `ResetTime` as Trae CN's console does; whether such an account's console +answers at all is not known. The Trae CN path above is the one that has been +run against a real account. + +Because that is not known, this console is not allowed to mark the sign-in: +its 401 is reported as the read's error and the account stays signed in, +where Trae CN's console — measured to take the IDE's own token — does mark +it. A console that wants a session of its own would otherwise mark every +international enterprise account expired, and signing in again would not +clear it. + A 200 carrying an error code is shown as Trae's own message rather than as an empty answer. diff --git a/packages/trae/enterprise.test.mjs b/packages/trae/enterprise.test.mjs index bb0e3d4..82000cd 100644 --- a/packages/trae/enterprise.test.mjs +++ b/packages/trae/enterprise.test.mjs @@ -6,7 +6,35 @@ import "./nonet.mjs" import { afterEach, expect, test } from "bun:test" import { TraeCNAuthPlugin, _internal } from "./index.mjs" -import { fakeTrae, signedIn } from "./fake.mjs" +import { fakeTrae, json, signedIn } from "./fake.mjs" + +// the console's own answer, as a real enterprise account's is: the seat +// pool in yuan, and each model's cost +const ENT = "https://console.enterprise.trae.cn" +const quota = (over = {}) => json({ code: 0, message: "success", user_model_quota: { tenant_id: "392641536", user_id: "393834752", seat_pool_currency_quota: 800, system_model_quota_granularity: "all", paygo_currency_quota: 9999999999, paygo_model_quota_list: null, custom_model_quota_list: null, seat_pool_token_quota: 5000, paygo_token_quota: 9999999999, paygo_model_token_quota_list: null, has_user_quota: true, ...over } }) +const spent = (costs) => json({ code: 0, message: "success", user_usage_list: [{ tenant_id: "392641536", user_id: "393834752", entitlement_id: "443246848", model_usage_detail_list: [], in_seat_detail: { chat_usage_details: costs.map((c, i) => ({ config_name: `m-${i}`, provider: "default", config_source: 1, input_token_usage: 0, output_token_usage: 0, total_token_usage: 100, display_name: `M ${i}`, total_cost_currency: c, input_cost_currency: null, output_cost_currency: null, billing_source: null })), cue_token_usage: 0 }, seat_total_cost_currency: null, extra_total_cost_currency: null }] }) +// the consumer credits page as it answers an enterprise account: a real +// allowance that real calls do not touch (measured), shown beside the pool +const page = (over = {}) => json({ is_credits_billing: true, user_entitlement_pack_list: [ + { display_desc: "老用户福利", entitlement_base_info: { quota: { credits_limit: 4000 }, end_time: 1795012095 }, usage: { credits_amount: 4.396 } }, + { display_desc: "每月登录赠送", entitlement_base_info: { quota: { credits_limit: 500 }, end_time: 1796054399 }, usage: {} }, + ...(over.extra ?? []), +] }) +const creditsWindow = { name: "Credits", used: (4.396 / 4500) * 100, display: "4.4 / 4500", amount: 4.4, limit: 4500, unit: "credits", aside: true, resetsAt: new Date(1795012095 * 1000).toISOString() } +// the console's own period, which the usage page reads its reset date from +const RESET = 1796054400000 +const core = (over = {}) => json({ code: 0, message: "", Data: { ChatUsed: 0, ChatTotal: 500, PayAsYouGoUsed: 0, PayAsYouGoTotal: 0, ResetTime: RESET, ChatStartTime: 1793462399000, ChatEndTime: 1796054399000, PayAsYouGoStartTime: 1793462399000, PayAsYouGoEndTime: 1796054399000, TotalSeats: 163, ...over }, count: 0 }) +const seatWindow = (over = {}) => ({ name: "Seat Usage", used: 47.72, display: "¥381.73 / ¥800.00", amount: 381.73, limit: 800, unit: "CNY", resetsAt: new Date(RESET).toISOString(), ...over }) + +async function enterpriseHooks(extra = {}) { + f = fakeTrae() + f.route("POST /trae/gtm/tob/api/v1/config/get_personal_quota", () => quota()) + f.route("POST /trae/gtm/tob/api/v1/config/get_user_model_usage", () => spent([215.78511296, 112.20407728, 53.74288652])) + f.route("POST /trae/gtm/tob/api/v1/config/get_personal_core_data", () => core()) + f.route("POST /trae/api/v2/pay/ide_user_ent_usage", () => page()) + const hooks = await TraeCNAuthPlugin({ client: {} }) + return { hooks, auth: signedIn({ api: ENT, host: ENT, ...extra }) } +} const CN = _internal.SITES["trae-cn"] const GLOBAL = _internal.SITES["trae-global"] @@ -96,6 +124,180 @@ test("a host off Trae's domains is refused, and the consumer one is used", async expect(GLOBAL.modelHost("https://trae.ai.evil.com")).toBe(false) }) +// The usage card for an enterprise (SaaS) account: its console bills in +// yuan, so the card leads with the seat pool in yuan. The consumer page +// answers such an account too, with a credits allowance real calls have +// been measured not to touch — that row is shown beside the pool, aside, so +// the card holds both numbers without the credits reading as routable. +test("an enterprise account's usage is its console's seat pool, in yuan", async () => { + const { hooks, auth } = await enterpriseHooks() + const u = await hooks.auth.usage(async () => auth) + expect(f.seen.map((r) => r.path)).toEqual([ + "/trae/gtm/tob/api/v1/config/get_personal_quota", + "/trae/gtm/tob/api/v1/config/get_user_model_usage", + "/trae/gtm/tob/api/v1/config/get_personal_core_data", + "/trae/api/v2/pay/ide_user_ent_usage", + ]) + // the console takes an empty body; the consumer page its own + expect(f.seen.map((r) => r.json)).toEqual([{}, {}, {}, { require_usage: true, req_source: 0 }]) + expect(f.seen[0].headers.get("authorization")).toBe("Cloud-IDE-JWT jwt-1") + expect(u.plan).toBe("Enterprise") + expect(u.user).toBe("Ann") + expect(u.signIn).toBe("kept") + expect(u.balance).toBeUndefined() // the window carries the count + expect(u.windows).toEqual([seatWindow(), creditsWindow]) +}) + +test("an enterprise account that spent nothing shows the whole pool", async () => { + f = fakeTrae() + f.route("POST /trae/gtm/tob/api/v1/config/get_personal_quota", () => quota()) + f.route("POST /trae/gtm/tob/api/v1/config/get_user_model_usage", () => spent([])) + const hooks = await TraeCNAuthPlugin({ client: {} }) + const u = await hooks.auth.usage(async () => signedIn({ host: ENT })) + expect(u.windows[0].used).toBe(0) + expect(u.windows[0].display).toBe("¥0.00 / ¥800.00") + expect(u.windows[0].limit).toBe(800) +}) + +test("an unlimited seat pool says so rather than showing the console's sentinel", async () => { + f = fakeTrae() + f.route("POST /trae/gtm/tob/api/v1/config/get_personal_quota", () => quota({ seat_pool_currency_quota: 9999999999 })) + f.route("POST /trae/gtm/tob/api/v1/config/get_user_model_usage", () => spent([1.5])) + f.route("POST /trae/api/v2/pay/ide_user_ent_usage", () => page()) + const hooks = await TraeCNAuthPlugin({ client: {} }) + const u = await hooks.auth.usage(async () => signedIn({ host: ENT })) + expect(u.balance).toBe("unlimited") + // the pool is no limit; the credits row still stands beside it + expect(u.windows).toEqual([creditsWindow]) +}) + +// a failed read is not a spend of zero: the pool stands, but the count is +// unknown, so the row says so rather than reading as untouched +test("an enterprise account whose spend page fails shows the pool, not a zero", async () => { + f = fakeTrae() + f.route("POST /trae/gtm/tob/api/v1/config/get_personal_quota", () => quota()) + f.route("POST /trae/gtm/tob/api/v1/config/get_user_model_usage", () => json({ code: 0, message: "success" }, 500)) + const hooks = await TraeCNAuthPlugin({ client: {} }) + const u = await hooks.auth.usage(async () => signedIn({ host: ENT })) + expect(u.error).toBeUndefined() + expect(u.windows[0].used).toBeNull() + expect(u.windows[0].amount).toBeUndefined() + expect(u.windows[0].display).toBe("? / ¥800.00") + expect(u.windows[0].limit).toBe(800) +}) + +// the credits row is the card's second row, never the count: when the +// consumer page is the one that fails, the pool stands alone +test("an enterprise account whose credits page fails still shows the pool", async () => { + f = fakeTrae() + f.route("POST /trae/gtm/tob/api/v1/config/get_personal_quota", () => quota()) + f.route("POST /trae/gtm/tob/api/v1/config/get_user_model_usage", () => spent([40])) + f.route("POST /trae/api/v2/pay/ide_user_ent_usage", () => json({ code: 1001, message: "not login" }, 401)) + const hooks = await TraeCNAuthPlugin({ client: {} }) + const u = await hooks.auth.usage(async () => signedIn({ host: ENT })) + expect(u.error).toBeUndefined() + expect(u.signIn).toBe("kept") // a second row's 401 is not the sign-in's + expect(u.windows.map((w) => w.name)).toEqual(["Seat Usage"]) +}) + +test("an unlimited credits page adds no row of its own", async () => { + f = fakeTrae() + f.route("POST /trae/gtm/tob/api/v1/config/get_personal_quota", () => quota()) + f.route("POST /trae/gtm/tob/api/v1/config/get_user_model_usage", () => spent([40])) + f.route("POST /trae/api/v2/pay/ide_user_ent_usage", () => json({ is_credits_billing: true, user_entitlement_pack_list: [ + { entitlement_base_info: { quota: { credits_limit: -1 } }, usage: { credits_amount: 3 } }, + ] })) + const hooks = await TraeCNAuthPlugin({ client: {} }) + const u = await hooks.auth.usage(async () => signedIn({ host: ENT })) + expect(u.windows.map((w) => w.name)).toEqual(["Seat Usage"]) +}) + +// the console's period is what the usage page's own "席位额度将于 +// 重置" line reads; without it the pool stands with no date +test("a seat pool whose console names no period has no reset date", async () => { + f = fakeTrae() + f.route("POST /trae/gtm/tob/api/v1/config/get_personal_quota", () => quota()) + f.route("POST /trae/gtm/tob/api/v1/config/get_user_model_usage", () => spent([40])) + f.route("POST /trae/gtm/tob/api/v1/config/get_personal_core_data", () => core({ ResetTime: 0 })) + const hooks = await TraeCNAuthPlugin({ client: {} }) + const u = await hooks.auth.usage(async () => signedIn({ host: ENT })) + expect(u.error).toBeUndefined() + expect(u.windows[0].name).toBe("Seat Usage") + expect(u.windows[0].resetsAt).toBeUndefined() +}) + +// a console that cannot answer the period costs the card its date alone +test("an enterprise account whose period page fails still shows the pool", async () => { + f = fakeTrae() + f.route("POST /trae/gtm/tob/api/v1/config/get_personal_quota", () => quota()) + f.route("POST /trae/gtm/tob/api/v1/config/get_user_model_usage", () => spent([40])) + f.route("POST /trae/gtm/tob/api/v1/config/get_personal_core_data", () => json({ code: 0, message: "" }, 500)) + const hooks = await TraeCNAuthPlugin({ client: {} }) + const u = await hooks.auth.usage(async () => signedIn({ host: ENT })) + expect(u.error).toBeUndefined() + expect(u.signIn).toBe("kept") + expect(u.windows[0].resetsAt).toBeUndefined() +}) + +// a console that names no pool at all has said nothing to show, and the card +// says that rather than standing empty +test("a console that names no seat pool is an error, not a blank card", async () => { + f = fakeTrae() + f.route("POST /trae/gtm/tob/api/v1/config/get_personal_quota", () => quota({ seat_pool_currency_quota: null })) + const hooks = await TraeCNAuthPlugin({ client: {} }) + const u = await hooks.auth.usage(async () => signedIn({ host: ENT })) + expect(u.error).toBe("Trae CN usage: the console named no seat pool") + expect(u.windows).toBeUndefined() +}) + +// an administrator's console answers with every seat in the tenant: the card +// counts the account's own, not the tenant's +test("an administrator's card counts its own seat, not the tenant's", async () => { + f = fakeTrae() + f.route("POST /trae/gtm/tob/api/v1/config/get_personal_quota", () => quota()) + f.route("POST /trae/gtm/tob/api/v1/config/get_user_model_usage", () => json({ code: 0, message: "success", user_usage_list: [ + { user_id: "393834752", in_seat_detail: { chat_usage_details: [{ total_cost_currency: 100 }] } }, + { user_id: "999999999", in_seat_detail: { chat_usage_details: [{ total_cost_currency: 500 }] } }, + ] })) + const hooks = await TraeCNAuthPlugin({ client: {} }) + const u = await hooks.auth.usage(async () => signedIn({ host: ENT })) + expect(u.windows[0].amount).toBe(100) + expect(u.windows[0].display).toBe("¥100.00 / ¥800.00") +}) + +// the console's reset time is milliseconds, but a seconds value must not +// land the window in 1970 +test("a reset time in seconds is read as seconds", async () => { + f = fakeTrae() + f.route("POST /trae/gtm/tob/api/v1/config/get_personal_quota", () => quota()) + f.route("POST /trae/gtm/tob/api/v1/config/get_user_model_usage", () => spent([40])) + f.route("POST /trae/gtm/tob/api/v1/config/get_personal_core_data", () => core({ ResetTime: RESET / 1000 })) + const hooks = await TraeCNAuthPlugin({ client: {} }) + const u = await hooks.auth.usage(async () => signedIn({ host: ENT })) + expect(u.windows[0].resetsAt).toBe(new Date(RESET).toISOString()) +}) + +test("a personal account still reads the consumer credits page", async () => { + f = fakeTrae() + f.route("POST /trae/api/v2/pay/ide_user_ent_usage", () => json({ is_credits_billing: false, user_entitlement_pack_list: [ + { entitlement_base_info: { quota: { credits_limit: 300 } }, usage: { credits_amount: 75 } }, + ] })) + const hooks = await TraeCNAuthPlugin({ client: {} }) + const u = await hooks.auth.usage(async () => signedIn()) + expect(f.seen.map((r) => r.path)).toEqual(["/trae/api/v2/pay/ide_user_ent_usage"]) + expect(u.plan).toBe("Free") + expect(u.windows[0].unit).toBe("credits") +}) + +test("the console's own errors are Trae CN's, as the consumer page's are", async () => { + f = fakeTrae() + f.route("POST /trae/gtm/tob/api/v1/config/get_personal_quota", () => json({ code: 1001, message: "not login" }, 401)) + const hooks = await TraeCNAuthPlugin({ client: {} }) + const u = await hooks.auth.usage(async () => signedIn({ host: ENT })) + expect(u.signIn).toBe("expired") + expect(u.error).toContain("sign in again") +}) + test("a token host the sign-in named is where the token is renewed", async () => { f = fakeTrae() const got = await signIn({ UserID: "u-e", ScreenName: "Acme", Host: "https://ent-acme.trae.cn" }, { authHost: "https://auth-acme.trae.cn" }) diff --git a/packages/trae/fake.mjs b/packages/trae/fake.mjs index 30b2cce..b434b41 100644 --- a/packages/trae/fake.mjs +++ b/packages/trae/fake.mjs @@ -6,7 +6,7 @@ // international one, whose hosts and usage page differ. import { _internal } from "./index.mjs" -const HOST_KEYS = ["web", "auth", "api", "us", "pay", "usPay"] +const HOST_KEYS = ["web", "auth", "api", "console", "us", "pay", "usPay"] // no test reads this machine's own Trae CN client: one that wants a // client points ownClient.paths at a file of its own @@ -32,7 +32,7 @@ export function fakeTrae(siteId = "trae-cn") { const origin = `http://127.0.0.1:${server.port}` const hosts = _internal.SITES[siteId].hosts const was = { ...hosts } - Object.assign(hosts, { web: origin, auth: origin, api: origin, us: origin, pay: origin, usPay: origin }) + Object.assign(hosts, { web: origin, auth: origin, api: origin, console: origin, us: origin, pay: origin, usPay: origin }) return { origin, site: _internal.SITES[siteId], diff --git a/packages/trae/global.test.mjs b/packages/trae/global.test.mjs index cd62884..a071128 100644 --- a/packages/trae/global.test.mjs +++ b/packages/trae/global.test.mjs @@ -25,6 +25,8 @@ test("the realm's table is its own: hosts, client and versions differ from CN's" 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") + expect(GLOBAL.hosts.console).toBe("https://console.enterprise.trae.ai") + expect(GLOBAL.consoleHost).toBe("console.enterprise.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") @@ -120,6 +122,59 @@ test("a 401 reading usage marks the account", async () => { expect(u.error).toContain("sign in again") }) +// The international realm's enterprise (SaaS) path: the same console Trae +// CN reads, in dollars. NOT VERIFIED against a real account — no +// international enterprise account was available, and +// console.enterprise.trae.ai answers another realm's token with 请先登录 +// (as it answers no token at all). The paths and fields are the CN +// console's shape read off the international console's own build. +test("an international enterprise account reads the console's seat pool, in dollars", async () => { + const ENT = "https://console.enterprise.trae.ai" + f = fakeTrae("trae-global") + f.route("POST /trae/gtm/tob/api/v1/config/get_personal_quota", () => json({ code: 0, message: "success", user_model_quota: { user_id: "u-1", seat_pool_currency_quota: 100, paygo_currency_quota: 9999999999, has_user_quota: true } })) + f.route("POST /trae/gtm/tob/api/v1/config/get_user_model_usage", () => json({ code: 0, message: "success", user_usage_list: [{ user_id: "u-1", in_seat_detail: { chat_usage_details: [{ total_cost_currency: 12.5 }, { total_cost_currency: 7.5 }] }, seat_total_cost_currency: null }] })) + f.route("POST /trae/gtm/tob/api/v1/config/get_personal_core_data", () => json({ code: 0, message: "", Data: { ResetTime: 1796054400000 }, count: 0 })) + const hooks = await TraeGlobalAuthPlugin({ client: {} }) + const u = await hooks.auth.usage(async () => signedIn({ host: ENT })) + expect(f.seen.map((r) => r.path)).toEqual([ + "/trae/gtm/tob/api/v1/config/get_personal_quota", + "/trae/gtm/tob/api/v1/config/get_user_model_usage", + "/trae/gtm/tob/api/v1/config/get_personal_core_data", + ]) + expect(u.plan).toBe("Enterprise") + expect(u.user).toBe("Ann") + expect(u.signIn).toBe("kept") + // the realm has no consumer credits page, so the card is the pool alone + expect(u.windows).toEqual([{ name: "Seat Usage", used: 20, display: "$20.00 / $100.00", amount: 20, limit: 100, unit: "usd", resetsAt: new Date(1796054400000).toISOString() }]) +}) + +// The international console is not known to take the IDE's own token — it +// answers 请先登录 to another realm's token exactly as it answers no token, +// so a refusal cannot be told from a lapsed sign-in. Marking the account +// expired on one would send every international enterprise user into a +// re-sign-in loop that re-signing in does not break; a failed read is the +// most this realm may say. +test("an international console that refuses the token is a failed read, not an expired sign-in", async () => { + f = fakeTrae("trae-global") + f.route("POST /trae/gtm/tob/api/v1/config/get_personal_quota", () => json({ code: 1001, message: "not login" }, 401)) + const hooks = await TraeGlobalAuthPlugin({ client: {} }) + const u = await hooks.auth.usage(async () => signedIn({ host: "https://console.enterprise.trae.ai" })) + expect(u.signIn).toBe("kept") + expect(u.error).toBe("Trae Global usage: not login") +}) + +test("an international account that names no console is read as before", 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({ host: "https://api-us-east.trae.ai", region: "US-East" })) + expect(f.seen.map((r) => r.path)).toEqual(["/trae/api/v1/pay/user_current_entitlement_list"]) + expect(u.plan).toBe("Pro plan") + expect(u.windows[0].name).toBe("Dollar Usage") +}) + 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) diff --git a/packages/trae/index.mjs b/packages/trae/index.mjs index 314293b..e04ee88 100644 --- a/packages/trae/index.mjs +++ b/packages/trae/index.mjs @@ -41,7 +41,19 @@ const SITES = { 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 + console: "https://console.enterprise.trae.cn", // an enterprise (SaaS) account's usage, in yuan }, + // the console an enterprise (SaaS) sign-in names as its account's host, + // which is what tells an enterprise account apart: it bills there, not + // on the consumer credits page. Kept apart from hosts.console so a test + // can point the requests at a fake and still sign in as an enterprise + // account. + consoleHost: "console.enterprise.trae.cn", + // Trae CN's console was measured to take the IDE's own token: the plugin's + // own headers against get_personal_quota answer 200, and a 401 from it + // really is a lapsed sign-in. The international console could not be + // measured (see its realm below), so it is not allowed to say so. + consoleTakesIdeToken: true, clientId: "ono9krqynydwx5", // Trae CN's IDE // the clients' own renewal, which binds the JWT to a device: ExchangeToken // under /trae/api/v3/oauth, signed with the device's P-256 key @@ -127,6 +139,51 @@ const SITES = { label: "credits", host: (site) => site.hosts.auth, body: { require_usage: true, req_source: 0 }, + // an enterprise (SaaS) account bills in yuan on Trae's console, not on + // the consumer credits page: its allowance is the seat pool the + // console names, and what it spent is the models' own cost — two of + // the console's pages, not one. A personal account is read as before. + // + // The consumer page answers such an account too, with a credits + // allowance that real calls have been measured not to touch (two calls + // through magpie moved the console's spend by ¥0.0002 each and left + // the credits at 4.4 of 4700). It is shown beside the seat pool so the + // card holds both numbers, but marked aside: the seat pool is what a + // request spends, so the credits must not read as allowance magpie can + // route on. Whether they are a fallback the seat pool exhausts first + // is not known — no account has spent its pool to find out. + ent: { + quota: { path: "/trae/gtm/tob/api/v1/config/get_personal_quota" }, + spent: { path: "/trae/gtm/tob/api/v1/config/get_user_model_usage" }, + // the console's own period, which is the seat pool's: the usage page + // says "席位额度将于 重置" from exactly this call, while + // get_personal_quota names the allowance and no date at all + core: { path: "/trae/gtm/tob/api/v1/config/get_personal_core_data" }, + read: ({ quota, spent, core, credits: page }, a, signIn, { credits, round }) => { + const q = seatPoolOf(quota) + if (!q) return { error: "Trae CN usage: the console named no seat pool", signIn, user: a.name } + const out = { plan: "Enterprise", user: a.name || a.uid, signIn } + const windows = [] + if (q.unlimited) out.balance = "unlimited" + else if (q.limit > 0) windows.push(seatUsageWindow(q, seatSpentOf(spent, quota?.user_model_quota?.user_id), entResetOf(core), yuan, "CNY")) + const c = page ? credits(page) : null + if (c && !c.unlimited && c.limit > 0) { + const w = { + name: "Credits", + used: Math.max(0, Math.min(100, (c.used / c.limit) * 100)), + display: `${round(c.used)} / ${round(c.limit)}`, + amount: round(c.used), + limit: round(c.limit), + unit: "credits", + aside: true, + } + if (c.until) w.resetsAt = new Date(c.until).toISOString() + windows.push(w) + } + if (windows.length) out.windows = windows + return out + }, + }, 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 } @@ -166,7 +223,18 @@ const SITES = { 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 + console: "https://console.enterprise.trae.ai", // an enterprise (SaaS) account's usage, in dollars }, + // the console an enterprise (SaaS) sign-in names as its account's host, + // as on Trae CN: it bills there, not on the dollar billing's page. Kept + // apart from hosts.console for the same reason as Trae CN's. + consoleHost: "console.enterprise.trae.ai", + // Not measured: no international enterprise account could be found, and + // console.enterprise.trae.ai answers a foreign realm's token with 请先登录 + // exactly as it answers no token at all, so whether it refuses the token + // or wants a console session is unknown. Until an account says otherwise, + // its 401 is a failed read, never a lapsed sign-in. + consoleTakesIdeToken: false, clientId: "ono9krqynydwx5", appId: "6eefa01c-1036-4c7e-9ca5-d891f63bfcd8", ideVersion: "3.5.51", // named to the international IDE's current build @@ -222,6 +290,34 @@ const SITES = { // 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: {}, + // An enterprise (SaaS) account bills on Trae's enterprise console + // here too, on the same three pages Trae CN's console has and in + // dollars. The international deployment has no consumer credits page + // (its own page is the dollar billing's), so the card is the seat + // pool alone. + // + // NOT VERIFIED against a real account: no international enterprise + // account was available, and console.enterprise.trae.ai answers + // another realm's token with 请先登录 — as it answers no token at all, + // so whether it refuses the token or wants a console session is not + // known either. The paths and fields below are the CN console's shape + // read off the international console's own build, which names + // seat_pool_currency_quota, the models' total_cost_currency and + // ResetTime exactly as Trae CN's does. Whether such an account's + // console answers at all is not known. + ent: { + quota: { path: "/trae/gtm/tob/api/v1/config/get_personal_quota" }, + spent: { path: "/trae/gtm/tob/api/v1/config/get_user_model_usage" }, + core: { path: "/trae/gtm/tob/api/v1/config/get_personal_core_data" }, + read: ({ quota, spent, core }, a, signIn) => { + const q = seatPoolOf(quota) + if (!q) return { error: "Trae Global usage: the console named no seat pool", signIn, user: a.name } + const out = { plan: "Enterprise", user: a.name || a.uid, signIn } + if (q.unlimited) out.balance = "unlimited" + else if (q.limit > 0) out.windows = [seatUsageWindow(q, seatSpentOf(spent, quota?.user_model_quota?.user_id), entResetOf(core), DOLLARS, "usd")] + return out + }, + }, 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 } @@ -3079,6 +3175,129 @@ function credits(v) { const round = (n) => Math.round(n * 100) / 100 +// yuan is money as Trae CN's console counts it, in yuan. The consumer +// window's unit is a bare word ("credits"); a currency the card can't name +// in a unit goes in display, as Cursor's and JoyCode's do. +const yuan = (n) => "¥" + Number(n).toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + +// dollars is the same money as the international console counts it. The +// console's own build picks the symbol by deployment (volcengine ¥, +// byteplus $), so each realm's console is asked with its own. +const DOLLARS = (n) => "$" + Number(n).toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 }) + +// seatUsageWindow is the seat pool's window, which both realms' consoles +// name the same way: the pool as the limit and the models' own cost as what +// was spent, in the realm's money, resetting when the console's period does. +// The count rides on the window (amount of limit), as the consumer window's +// does, so magpie says it in the window's row; display carries the currency +// the card's own row can't name (yetone/magpie#694). +// +// A spend the console did not answer (used === null) is not a spend of +// nothing: the window says no percent and no amount, and its display names +// the pool with a question mark, so magpie reads the account as unknown +// rather than as one that has spent none of its allowance. +function seatUsageWindow(pool, used, until, money, unit) { + const w = { + name: "Seat Usage", + display: used === null ? `? / ${money(pool.limit)}` : `${money(used)} / ${money(pool.limit)}`, + limit: round(pool.limit), + unit, + } + if (used === null) w.used = null + else { + w.used = Math.round(Math.max(0, Math.min(100, (used / pool.limit) * 100)) * 100) / 100 + w.amount = round(used) + } + if (until) w.resetsAt = until + return w +} + +// PAYGO_UNLIMITED is the console's "no limit": a pay-as-you-go pool is +// handed this instead of a real one (9999999999), which is not a limit a +// card should show. The seat pool is the limit that matters. +const PAYGO_UNLIMITED = 1e9 + +// seatPoolOf reads an enterprise account's allowance as its console has it: +// the seat pool, in the realm's money (seat_pool_currency_quota). A pool the +// console hands PAYGO_UNLIMITED is no limit at all, as the consumer page's +// -1 is. A pool the console names as null or "" is no pool either: Number() +// would read both as 0, which would draw an allowance of nothing rather than +// say the console named none. +function seatPoolOf(v) { + const q = v?.user_model_quota + if (!q) return null + const raw = q.seat_pool_currency_quota + if (raw === null || raw === undefined || raw === "") return null + const limit = Number(raw) + if (!Number.isFinite(limit)) return null + if (limit < 0 || limit >= PAYGO_UNLIMITED) return { limit: 0, unlimited: true } + return { limit, unlimited: false } +} + +// seatSpentOf adds up what an enterprise account's models cost, in the +// realm's money: each model's total_cost_currency in the seat's usage +// detail. The console gives no total of its own +// (seat_total_cost_currency is null), so this is the sum, and a model the +// answer leaves out costs nothing. +// +// Only the account's own seat is counted. The console answers an +// administrator with every seat in the tenant, and adding those up would +// show one person's card the whole tenant's spend; the account's own seat is +// the one the quota names (user_model_quota.user_id), which a real console +// sends. A seat the account's cannot be told apart — several seats and no id +// to pick by — is not guessed at. +// +// null when there is nothing to add up honestly: no usage list at all (the +// read failed, and a failed read is not a spend of zero), or several seats +// with no way to say which is the account's. +function seatSpentOf(v, uid) { + const list = v?.user_usage_list + if (!Array.isArray(list)) return null + const me = uid === undefined || uid === null || uid === "" ? null : String(uid) + const ids = new Set(list.map((u) => (u?.user_id === undefined || u?.user_id === null ? "" : String(u.user_id))).filter((s) => s !== "")) + let seats = list + if (ids.size > 0) { + // the seats carry ids: take the account's own. With no id from the quota, + // a single seat's answer is that seat; several seats' is not knowable. + const want = me ?? (ids.size === 1 ? [...ids][0] : null) + if (want === null) return null + seats = list.filter((u) => String(u?.user_id ?? "") === want) + if (seats.length === 0) return null + } + let used = 0 + for (const u of seats) { + for (const m of u?.in_seat_detail?.chat_usage_details ?? []) { + const c = Number(m?.total_cost_currency) + if (Number.isFinite(c) && c > 0) used += c + } + } + return used +} + +// entResetOf is when an enterprise account's seat pool refills, as an ISO +// string: the console's ResetTime. The usage page reads the same field for +// its "席位额度将于 重置" line, so the card and the page name one +// date. whenOf reads it, which takes the milliseconds the console sends and +// the seconds a stand-in may. Absent when the console gives none. +function entResetOf(v) { + const t = whenOf(v?.Data?.ResetTime) + return t > 0 ? new Date(t).toISOString() : null +} + +// isEnterprise: the sign-in named the realm's enterprise console as the +// account's host, which is what an enterprise (SaaS) sign-in does — the +// console serves that account's models and holds its usage. A personal +// account names the consumer hosts, or none. +function isEnterprise(a, site) { + const named = String(site?.consoleHost ?? "").toLowerCase() + if (!named || !a?.host) return false + try { + return new URL(String(a.host)).hostname.toLowerCase() === named + } catch { + return false + } +} + // 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 @@ -3427,6 +3646,70 @@ const makePlugin = (site) => async ({ client }) => { return { outcome: "claimed", ...(credit > 0 ? { credit } : {}) } } + // enterpriseUsage reads an enterprise (SaaS) account's usage: the seat + // pool and what the account's models cost (get_personal_quota and + // get_user_model_usage on the realm's console, in the realm's money). On + // Trae CN the consumer credits page is read beside them for the card's + // second row — that realm's console is what such an account bills on, and + // the credits page answers it too with an allowance real calls have been + // measured not to touch. The international realm has no such page. + const enterpriseUsage = async (a, signIn) => { + const ent = site.usage.ent + const ask = async (path) => { + const r = await post(a, site.hosts.console + path, {}) + const e = errorOf(r.v) + // A console known to take the IDE's own token answers a lapsed sign-in + // with 401 or the realm's lapsed code, and that is the sign-in's + // trouble. A console that is not known to (the international one, which + // no such account could be found to ask) is not allowed to say so: its + // refusal is reported as the read's error and the sign-in stands, + // because a console that wants its own session would otherwise mark + // every one of that realm's enterprise accounts expired, and signing in + // again would not clear it. + if (r.status === 401 || lapsedCode(e.code, site)) { + return site.consoleTakesIdeToken ? { gone: true } : { error: e.message || statusLine(r.status) } + } + if (r.status !== 200 || (e.code && String(e.code) !== "0")) return { error: e.message || statusLine(r.status) } + return { v: r.v } + } + let quota + try { + quota = await ask(ent.quota.path) + } catch (e) { + return { error: `${site.realm} usage: ` + (e?.message ?? e), signIn } + } + if (quota.gone) return { error: `${a.name || a.uid}: ${site.realm}'s sign-in has expired — sign in again`, signIn: "expired" } + if (quota.error) return { error: `${site.realm} usage: ${quota.error}`, signIn, user: a.name } + // the spend page is the second half of the count: when it fails, the + // allowance is still worth showing but the spend is unknown, and the + // window says so (used: null) rather than reading as nothing spent — a + // failed read is not a spend of zero + let spent = { v: {} } + try { + const got = await ask(ent.spent.path) + if (!got.gone && !got.error) spent = got + } catch {} + // the console's own period, for the date the pool refills: a failure + // there costs the card its reset date and nothing else + let core = { v: {} } + try { + const got = await ask(ent.core.path) + if (!got.gone && !got.error) core = got + } catch {} + // the credits page is the card's second row, never the count: a failure + // there leaves the seat pool standing. Trae Global has no such page — + // its own usage page is the dollar billing's, read above as the pool. + let page = null + if (site.usage.kind === "credits") { + try { + const r = await post(a, site.usage.host(site, a) + site.usage.path, site.usage.body) + const e = errorOf(r.v) + if (r.status === 200 && (!e.code || String(e.code) === "0")) page = r.v + } catch {} + } + return ent.read({ quota: quota.v, spent: spent.v, core: core.v, credits: page }, a, signIn, { credits, round }) + } + const usage = async (getAuth) => { let a try { @@ -3435,6 +3718,9 @@ const makePlugin = (site) => async ({ client }) => { return { error: e.message, signIn: e instanceof Expired ? "expired" : "kept" } } const signIn = a.renewed ? "renewed" : "kept" + // an enterprise (SaaS) account bills on the realm's own console, not on + // the page its realm otherwise bills on + if (site.usage.ent && isEnterprise(a, site)) return enterpriseUsage(a, signIn) let r try { r = await post(a, site.usage.host(site, a) + site.usage.path, site.usage.body) @@ -3840,4 +4126,4 @@ const makePlugin = (site) => async ({ client }) => { export const TraeCNAuthPlugin = makePlugin(SITES["trae-cn"]) export const TraeGlobalAuthPlugin = makePlugin(SITES["trae-global"]) -export const _internal = { ownClient, clientStoragePaths, clientDevice, clientProfiles, deviceNote, clientDecode, thisMachine, traeHost, accountOf, HOSTS: SITES["trae-cn"].hosts, MODELS: SITES["trae-cn"].models, TextTools, NativeCalls, looseJSON, glmCall, nameCall, toolNamed, unwrapped, traeMessages, chatBody, nativeTools, moonshotSchema, credits, dollarUsageOf, whenOf, newDevice, ugDevice, proofOf, SITES, SESSION, conversationID, LEVELS, levelsOf, variantsOf, effortOf, offered, traeRateOf } +export const _internal = { ownClient, clientStoragePaths, clientDevice, clientProfiles, deviceNote, clientDecode, thisMachine, traeHost, accountOf, HOSTS: SITES["trae-cn"].hosts, MODELS: SITES["trae-cn"].models, TextTools, NativeCalls, looseJSON, glmCall, nameCall, toolNamed, unwrapped, traeMessages, chatBody, nativeTools, moonshotSchema, credits, dollarUsageOf, seatPoolOf, seatSpentOf, entResetOf, isEnterprise, yuan, whenOf, newDevice, ugDevice, proofOf, SITES, SESSION, conversationID, LEVELS, levelsOf, variantsOf, effortOf, offered, traeRateOf } diff --git a/packages/trae/package.json b/packages/trae/package.json index 1897bea..dfcd7d6 100644 --- a/packages/trae/package.json +++ b/packages/trae/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-trae-auth", - "version": "0.2.33", + "version": "0.2.34", "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": "./opencode.mjs",