Documentation
¶
Overview ¶
adopt.go migrates legacy trae-cn / trae-solo-cn / trae-intl auth files to the merged trae provider (v0.12.0).
The three legacy plugins ran against DIFFERENT upstreams (api.trae.cn inline_chat, api.trae.cn solo_work_lite, api.marscode.com chat_sessions), so there is NO dedupe across them. Filenames are KEPT — trae-cn-<uid>.json, trae-solo-cn-<uid>.json and trae-intl-<uid>.json all carry the canonical "trae-" prefix — and only the JSON type/provider is rewritten in place:
type/provider: trae-cn | trae-solo-cn | trae-intl → trae auth.variant: cn | solo | intl (derived from the filename)
The host routes auth files to plugins by the file's type field, so without this rewrite legacy files would be orphaned. Idempotent, 1-minute guard, runs in the background.
configparse.go decodes the plugin lifecycle config payload (config_yaml) as real YAML — block style, flow-style one-liners ({k: v}) and JSON (a YAML subset) all land in the same flat map. The per-plugin line-scan in usage_config.go stays as a fallback for payloads yaml.v3 refuses; both views agree on block style, so the map only ever ADDS visibility.
History (issue #24): three plugins read login_variant/login_region by scanning YAML lines, which silently misses flow-style mappings — and the exact serialization style depends on how config.yaml was written. Parsing the document removes that ambiguity.
device_identity.go — v0.12.79: ONE sign-in device identity per login, from the authorization URL all the way to the bound refresh (magpie semantics; issue #47 hotfix).
History:
- v0.12.75 and earlier minted a RANDOM device per login attempt — the pile-up that locked accounts out with 403 code=20401 "Device limit reached" (issue #38 aftermath).
- v0.12.76 shipped a stable PER-INSTALL identity (one device shared by every account of a variant on this machine). User review rejected the SHAPE (many accounts hopping on one server-side device), not the stability.
- v0.12.77/v0.12.78 tried to square that circle by deriving the device PER ACCOUNT — deriveAccountDeviceIdentity(variant, uid), applied the moment the OAuth callback echoed the account's uid. That was WRONG: the authorization-page URL is built BEFORE anyone knows which account is logging in, so it carried the install's BOOTSTRAP device while the ExchangeToken carried the DERIVED one. Upstream ties every auth code to the device of the URL that requested it and now enforces the match (live 2026-10-20/21, issue #47: EVERY fresh CN/intl login died with HTTP 401 code=20403 "Token device not match"). The earlier "live-proven 2026-10: the server happily registered a different identity" observation no longer holds — the gate was tightened.
- v0.12.79 (this file): the sign-in identity — the bootstrap identity resolved at start-login — is THE identity for the whole login: URL params, ExchangeToken DeviceInfo, saved credential and every later bound refresh all read the same loginCtx fields, and nothing swaps them mid-flight. That is exactly what the official IDE and the magpie reference do (newDevice() once at sign-in, shared by the URL and signedIn()).
What remains of the per-account derivation: deriveAccountDeviceIdentity is kept as a PURE, side-effect-free function and the callback handlers call noteAccountDeviceIdentityCN/Intl to log what the account's canonical device WOULD be — useful diagnostics for 20401/20403 reports, and the building block for a future two-phase login (panel-side account selection or a re-issued authorization with the derived device) IF per-account devices are ever wanted. It is never applied to a live login ctx anymore.
Consequences of the one-device-per-login model:
- Re-logins never mint a new device, so the 20401 device-cap burn of v0.12.75-and-earlier stays fixed (the bootstrap identity is stable on disk per variant).
- Several accounts of one variant on one installation share that variant's bootstrap device — the trade the 20403 gate forces on us; the alternative (per-account devices) requires knowing the account before the URL exists.
- Credentials saved by v0.12.77/v0.12.78 (derived device + derived keys, tokens actually bound elsewhere) cannot refresh — they must re-login once on v0.12.79+ to land on a consistent identity.
devicekey.go: EC P-256 device key pair for the ExchangeToken DeviceInfo, mirroring cockpit-tools generate_device_key_pair (trae_oauth.rs:229-247).
Why (v0.12.24): the official Trae client generates a FRESH P-256 key pair per login and uploads the SPKI public-key PEM inside DeviceInfo.DevicePublicKey ("每登录一套设备指纹:EC P-256 keypair + DeviceID + MachineID, 首登上传公钥、服务端绑定" — codex-app-transfer trae/flow.rs reverse engineering, 2026-06-22). cockpit-tools does the same since v0.26.1 (2026-06-18, "适配当前官方客户端行为"). Sending an empty DevicePublicKey (the old traework2api-compatible behavior) now surfaces as ExchangeToken => HTTP 401 business code 20405 (the 2xxxx family = credential/device-binding rejection; 10101 is the request-validation family, live-probed 2026-09-04).
The private key is returned alongside so the login result can persist it (auth.devicePrivateKey) for the refresh DeviceProof signing the official client performs (cockpit-tools v1.3.28 keeps the same key material).
helpers.go: net aliases, random device identifiers, PKCE pair, URL encoding, and login trace ID generation — all aligned with cockpit-tools trae_oauth.rs.
Package main implements the trae-intl CLIProxyAPI dynamic plugin.
trae-intl wraps Trae Intl (api.marscode.com + core-normal.trae.ai) as a cliproxy provider: Trae OAuth (GetLoginGuidance + AuthCode ExchangeToken), Cloud-IDE-JWT auth, Web SOLO remote chat_sessions + events SSE protocol, v1 credit API. Intl has no daily check-in.
Protocol layer based on OmniRoute/open-sse/executors/trae.ts (MIT, by diegosouzapw). Translated from TypeScript to Go.
management.go implements the Trae Intl management API and web panel.
Trae Intl uses the Web SOLO remote protocol (chat_sessions + events SSE on core-normal.trae.ai); it has NO daily check-in and NO multi-account pool / scheduler (each request goes to whichever account the host routed it to). The management API therefore exposes only the account listing + a simple status check + the embedded panel.html. This is enough to:
- see which Trae Intl accounts are configured in the CPA UI,
- inspect their on-disk metadata (uid, nickname, expiry),
- test the upstream reachability with a /status ping.
Routes (intlproviderName = "trae-intl"):
- GET /v0/management/plugins/trae-intl/accounts — list accounts from host.auth.list
- GET /v0/management/plugins/trae-intl/status — pool/health summary
- GET /v0/resource/plugins/trae-intl/panel — embedded panel.html (browser UI)
Envelope contract (same as workbuddy / trae-solo-cn / trae-cn): intlhandleManagement returns an envelope-wrapped pluginapi.ManagementResponse; CPA's rpcPluginAdapter.callPlugin[pluginapi.ManagementResponse] unwraps the envelope, and CPA's ServeManagementHTTP / ServeResourceHTTP write only resp.Body to the browser.
oauth_fallback.go: multi-endpoint OAuth fallback helpers, ported from cockpit-tools trae_oauth.rs to fix "404 page not found" during OAuth login.
Fixes applied (all mirror cockpit-tools behavior):
- intlensureHTTPSScheme: cockpit-tools ensure_https_url (trae_oauth.rs:1117-1126). GetLoginGuidance returns LoginHost as a BARE domain ("www.trae.ai"); the login URL must get an https:// prefix or the panel/browser resolves it as a RELATIVE URL against the CPA server itself → gin default 404 body "404 page not found".
- intlrequestLoginGuidance: cockpit-tools request_login_guidance (trae_oauth.rs:1762-1848) — tries every GetLoginGuidance endpoint in the platform list before failing. Intl candidates: api.marscode.com → api.trae.ai → www.trae.ai, so a single-host outage/404 no longer blocks the whole login flow.
- intlcandidateAPIOorigins + intlbuildAPIURLs: cockpit-tools candidate_api_origins / candidate_account_api_origins (trae_oauth.rs:1994-2049, 673-689) — derives candidate API origins from the callback loginHost (rewriting www. → api.), then appends the Intl account-API defaults (grow-normal.trae.ai / growsg-normal.trae.ai). ExchangeToken/GetUserInfo try each URL in turn until one returns an access token.
intl_pay.go — Trae Intl 计费面(issue #29 评论实测证据,Xyloz3n 2026-10-03)。
intl 账号的额度/支付端点不在 CN 的 api.trae.cn + v2 上(打过去 401 code 4014,面板表现为 "ent_usage: upstream session_dead"),而是:
https://grow-normal.trae.ai + /trae/api/v1/pay/*
此前 refreshAccountCredits 对 intl 账号也走 CN 客户端(v0.12.2 起 intl 由统一插件接管,但 credits 查询从未分流)。实测可用的请求形状:
POST,body {}
Authorization: Cloud-IDE-JWT <accessToken>
X-User-Region: <auth.region> # 实测任意值都过(CN 值也过)
X-Device-Id: <auth.boundDeviceId>
User-Agent: Trae/3.5.66
Content-Type: application/json
注意 intl v1 回包的 usage 数值是浮点(basic_usage_amount: 0.2147 — is_flash_consuming 按次数分数扣减),与 CN v2 的 int64 不同;先解码为 float,换算进 CN 口径(upstream.EntUsageResult)时四舍五入,后续 SummarizeUsage / 面板投影全部复用 CN 管线。
login_identity.go — v0.12.25: stable per-account credential-file identity.
Bug report this fixes: the same account logged in twice showed as multiple panel accounts ("凭证 init 的账户同一个显示多个,因为我交了两次"). Root cause chain (code-traced, cockpit-tools cross-checked):
- The upstream callback URL carries a userInfo parameter with the account's real identity (TraeCallbackPayload.userInfo — cockpit-tools falls back to it whenever GetUserInfo fails: trae_oauth.rs:2707-2734). This plugin ignored it.
- GetUserInfo (cloudide/api/v3/trae/GetUserInfo) can fail (network/401) or answer 200 with an unexpected envelope → empty uid, and the poll path (handlePollLogin) proceeded "with empty UID" → the nameless trae-.json; the self-complete path (v0.12.17-0.12.24) fell back to the PER-LOGIN loginTraceID → trae-<uuid>.json, a fresh file name for every submission of the SAME account — the reported duplicates.
Fix: parse the callback's userInfo echo and resolve the file identity as GetUserInfo → callback userInfo → a STABLE per-realm "unknown" name. The unknown fallback deliberately collides (one file per realm, overwritten on re-login) instead of minting unique garbage per submission; a re-login always repairs it, and both real sources make the case vanishingly rare.
Package main implements the trae-solo-cn CLIProxyAPI dynamic plugin.
trae-solo-cn wraps TRAE Work CN / SOLO CN (trae-api-cn.mchost.guru + api.trae.cn) as a cliproxy provider: Trae OAuth (GetLoginGuidance + AuthCode ExchangeToken), Cloud-IDE-JWT auth, llm_utils_chat + function=solo_work_lite chat executor, daily check-in via checkin_credits, v2 credit API query, multi-account pool with credit-aware scheduler.
Protocol layer based on Sliverkiss/traework2api (MIT). Adapted to CPA dynamic plugin C ABI with OAuth login flow, executor, scheduler, checkin, token keepalive, and credit lifecycle.
management.go implements the Trae SOLO CN management API and web panel: the account dashboard (uid, nickname, credits, plan, check-in status), manual check-in (single or all accounts), credit query, token refresh, and the account-pool status (cooling / disabled state).
Routes are exposed under two prefixes:
- /v0/management/plugins/trae-solo-cn/* — JSON endpoints (CPA-management- authenticated by host middleware; plugin-layer auth only kicks in when management_key is configured).
- /v0/resource/plugins/trae-solo-cn/* — unauthenticated browser UI (panel.html) and menu entries surfaced in the CPA management UI.
The contract follows workbuddy/management.go: handleManagement returns an envelope-wrapped pluginapi.ManagementResponse (envelope is consumed by CPA's rpcPluginAdapter.callPlugin[pluginapi.ManagementResponse]; CPA's HTTP layer writes only resp.Body to the browser, so JSON.parse / HTML rendering work transparently).
models_exclusion.go — v0.12.62: oauth-excluded-models consumption for the trae plugin, at BOTH granularities the management panel's global page can express: the bare provider key ("trae" — excludes across every variant namespace) and the variant sub-keys ("trae-cn" / "trae-solo" / "trae-intl" — one namespace each). Any key present in the host config shows up in the panel's provider dropdown, so per-channel entries become first-class citizens of the global exclude page. trae's namespaces are model-ID-suffixed (cn = bare ids, solo = "-solo", intl = "-intl" plus the bare virtual auto/work), so exclusion patterns always match the ADVERTISED id.
models_groups.go — v0.12.63: per-variant model catalog endpoint for the panel's model-exclusion picker (GET /plugins/trae/models/groups). Port of the workbuddy v0.9.40 design onto trae's cn/solo/intl variant namespaces.
Why: the HOST's global oauth-excluded-models page cannot offer candidate lists for plugin channels (model-definitions/:channel is an upstream-static 8-channel catalog; unknown channels 400 "unknown channel"), so excluding a trae model there meant hand-typing suffixed ids. This endpoint serves the catalog from the plugin's OWN knowledge — the per-credential model_cache snapshots (v0.12.63) — grouped by variant namespace, and the panel renders per-variant checkboxes that write the host's trae-<variant> sub-keys via PATCH /v0/management/oauth-excluded-models. Consumption stays host-config-shaped (models_exclusion.go), so the global page and this picker drive the SAME exclusion map — no parallel truth, nothing plugin-proprietary to persist.
Read-only by default: groups are served from the newest model_cache snapshot per variant (zero upstream calls). ?refresh=1 additionally runs one live discovery per variant through the credential's own for_auth chain (refresh → discover → snapshot → static), which also re-stamps the snapshot — so what the picker shows and what the runtime advertises cannot diverge. Excluded models stay listed (the snapshot is pre-exclusion), so un-excluding never requires a lucky upstream round-trip.
models_persist.go — v0.12.63: persist each variant's last successful model discovery INTO the credential files themselves (top-level "model_cache" key), so the last-known-good catalog survives host restarts and upstream outages. Port of the workbuddy v0.9.38 design onto trae's cn/solo/intl variant namespaces.
Why: modelsForVariant / intlhandleModelForAuth have exactly one fallback — the compiled-in static catalogs. Those are guesses frozen at release time; a discovery outage (or a restart before the first successful discovery) advertised them as if they were upstream truth. Persisting the snapshot means the failure ladder serves REAL upstream data (change-guarded) before touching the static guess.
Snapshot semantics: the persisted list is the ADVERTISED catalog — ids already carry the variant suffix ("-solo"/"-intl") and the Intl virtuals (auto/work) — because exclusions and host routing both key on the advertised id. The list is PRE-exclusion, so excluded models stay visible in the picker and un-excluding never needs an upstream round-trip.
Scope guard: snapshots are per-VARIANT and only ever served back to credentials of the SAME variant — a cn catalog must never satisfy a solo or intl credential (different namespaces, suffixed ids).
Write hygiene: every host.auth.save re-fires the watcher → model.for_auth. persistModelSnapshot therefore writes ONLY when the discovered list actually changed (full ModelInfo compare), so the loop converges after one save per catalog change. Known gap (accepted): the scheduler's auth.Auth.SaveAtomic rebuilds the file in its minimal legacy shape and drops the snapshot; it re-stamps on the next successful discovery, and same-variant peers still serve theirs.
oauth_callback.go: CPA-host-aware OAuth callback plumbing for the merged trae plugin (v0.12.4).
v0.12.1 shipped a 127.0.0.1:0 listener bound INSIDE the CPA process with that ephemeral URL as auth_callback_url; the browser redirect then failed with "无法连接到 127.0.0.1:46837" whenever the listener was gone or the browser was not on the CPA host machine (remote / docker deployments). v0.12.2/3 hardened the listener (loop-Accept, callback_bind/public_host knobs) but still required manual configuration for remote deployments.
v0.12.4 (this file): when CPA supplies BaseURL via auth.login.start (pluginapi.AuthLoginStartRequest — its own oauth-callback endpoint), the callback targets this plugin's UNAUTHENTICATED resource route /v0/resource/plugins/trae/oauth_callback on the SAME origin the user is already browsing — zero-config, browser-reachable for local/LAN/docker. The full upstream query (authCode / refreshToken / loginHost) reaches the plugin unchanged. The configured local listener stays as the stand-alone fallback, and PollLogin additionally consumes the host-written .oauth-<provider>-<state>.oauth file as a last resort.
oauth_fallback.go: multi-endpoint OAuth fallback helpers, ported from cockpit-tools trae_oauth.rs to fix "404 page not found" during OAuth login.
Fixes applied (all mirror cockpit-tools behavior):
- ensureHTTPSScheme: cockpit-tools ensure_https_url (trae_oauth.rs:1117-1126). GetLoginGuidance returns LoginHost as a BARE domain ("www.trae.cn"); the login URL must get an https:// prefix or the panel/browser resolves it as a RELATIVE URL against the CPA server itself → gin default 404 body "404 page not found".
- requestLoginGuidance: cockpit-tools request_login_guidance (trae_oauth.rs:1762-1848) — tries every GetLoginGuidance endpoint in the platform list before failing; CN falls back to the default login host.
- candidateAPIOorigins + buildAPIURLs: cockpit-tools candidate_api_origins / build_api_urls (trae_oauth.rs:1994-2037) — derives candidate API origins from the callback loginHost (rewriting www. → api.), then appends the platform defaults. ExchangeToken/GetUserInfo try each URL in turn until one returns an access token, instead of hard-coding a single host.
scheduler_pick.go implements the pluginabi.MethodSchedulerPick capability for the trae plugin.
issue #2: the host unconditionally probes scheduler.pick on every plugin. A missing method made the host log
scheduler rejected auth pick plugin_id=trae error=unknown method: scheduler.pick
and fail the whole /v1/chat/completions request with HTTP 500 — enabling the trae plugin alone was enough to break every request, even ones routed to other plugins.
Trae deliberately does NOT take over auth routing: each request goes to whichever account the host routed it to (see intl_management.go). So the handler validates the request envelope and defers every pick back to the built-in scheduler (Handled: false). The method now exists — the host stops treating the plugin as broken — and routing behavior is unchanged.
split_build.go — split-channel flavor support (issue #29).
The repo ships TWO release packages per platform from the SAME source:
- cpa-multi-plugins-<os>-<arch>.zip — the unified flavor (default): one plugin per provider merging cn/intl/solo realms behind a single identifier with per-account variant config.
- cpa-multi-plugins-split-<os>-<arch>.zip — the split-channel flavor: the legacy per-variant plugins (trae-cn / trae-solo-cn / trae-intl, plus the qoder/workbuddy equivalents), each registering as its own panel entry with its own OAuth login pinned to its realm.
A trae split build is produced purely at BUILD TIME — no source fork:
go build -ldflags "-X main.providerName=trae-intl -X main.pluginVariantPin=intl" - providerName (var since the split flavor) → the registered plugin id, credential namespace and panel entry. - pluginVariantPin → the DEFAULT for the sticky login_variant config; an explicit login_variant in config.yaml still wins (issue #24 sticky semantics are untouched). Per-account variants keep their own realm routing — the pin only defaults NEW logins.
Empty values (the unified flavor default) keep behavior byte-for-byte.
sse_convert.go: SOLO SSE → OpenAI SSE real-time converter. Reads upstream SOLO SSE events and emits OpenAI-compatible SSE chunks.
usage_note.go — v0.12.64: per-credential usage & quota summary rendered into the auth file's `note` — the note is the credential display field the HOST's local credential management (本地凭据管理) already renders, so this puts 用量/额度 where the user actually looks, NOT inside the plugin panel (the panel keeps its richer views; this is the credential-card summary). Trae-specific: this plugin never had a note writer, so the 【用量】 segment is the whole usage story; any pre-existing hand-written note text is preserved as the base ahead of it. The UsagePlugin capability was declared but never dispatched before v0.12.64 — the handleUsage case lands here.
Design (mirrors the cockpit-tools credential usage card, adapted to what a static note can carry):
- attribution: every request is matched to its credential by the host's UsagePlugin record (AuthID / AuthIndex — 当前登录凭证和凭证序号);
- 凭证总体用量: request count, token count, success rate over 今日 / 累计 (ledger lifetime);
- 额度窗口: when the plugin's billing snapshots expose window boundaries (qoder package cycles), interval stats are computed for [start, end) from the hourly buckets; otherwise the note says 该账号暂未解析出额度窗口;
- 标准额度: trae's account-level pool is the credits pool (Σ max(credits_limit - usage, 0), official cashier formula) — folded in from the /credits query snapshots whenever those run.
- 预估花费: omitted — qoder exposes no authoritative per-token price (price_factor is a relative multiplier); inventing a price would be a wrong answer, not an estimate.
Data: the host delivers one UsagePlugin record per completed request (v0.12.64 wires MethodUsageHandle — the capability was declared but the dispatch case never existed, so trae records went to unknown_method). The ledger keeps all-time totals, 35 daily buckets and 72 hourly buckets per credential, persisted to `<authDirParent>/.trae-usage.json` — the PARENT of the auth dir (v0.12.69: the host's 本地凭据管理 lists every auth-dir file no plugin claims as a credential, so even this dot-prefixed sidecar showed up there as 平台 unknown 未识别凭证 noise — user report 2026-09-30; the parent dir is not scanned by the host). The dot prefix stays as belt-and-braces; a pre-relocation ledger inside the auth dir migrates once on first load. Flushes are throttled and change-guarded. Note writes are per-credential throttled (60s) and change-guarded — every host.auth.save re-fires the watcher, so the loop must converge.
Ownership: trae has no other note writer, so this writer owns the whole note — but a hand-written note (CPA credential editor) is preserved as the base and the 【用量】 segment appended; saves flow through the preservePluginDocKeys funnel so the model_cache snapshot survives.
variant.go — per-account variant plumbing for the merged trae plugin (v0.12.0). trae-cn, trae-solo-cn and trae-intl were separate plugins; they are merged here. Each auth file carries its variant explicitly (auth.variant), derived from the filename for legacy files by adopt.go. NEW logins target the variant configured via login_variant.
Source Files
¶
- adopt.go
- configparse.go
- device_identity.go
- devicekey.go
- heal.go
- helpers.go
- host_owned_fields.go
- intl_main.go
- intl_management.go
- intl_oauth_fallback.go
- intl_pay.go
- login_identity.go
- main.go
- management.go
- models_exclusion.go
- models_groups.go
- models_persist.go
- oauth_callback.go
- oauth_fallback.go
- pending_persist.go
- scheduler_pick.go
- split_build.go
- sse_convert.go
- usage_note.go
- variant.go
- variant_file.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Package auth 解析 TRAE SOLO auth 文件(嵌套形:auth + account), 提供原子写回与目录扫描。
|
Package auth 解析 TRAE SOLO auth 文件(嵌套形:auth + account), 提供原子写回与目录扫描。 |
|
Package upstream implements Trae Intl Web SOLO remote protocol.
|
Package upstream implements Trae Intl Web SOLO remote protocol. |
|
Package pool 账号池:内存索引 + 冷却/禁用状态机 + state.json 持久化。
|
Package pool 账号池:内存索引 + 冷却/禁用状态机 + state.json 持久化。 |
|
Package scheduler 定时任务:每日签到 + token 预刷新。
|
Package scheduler 定时任务:每日签到 + token 预刷新。 |
|
bound_exchange.go — device-bound token renewal (v0.12.73 引入,v0.12.74 与 magpie-community 权威实现逐字节对齐).
|
bound_exchange.go — device-bound token renewal (v0.12.73 引入,v0.12.74 与 magpie-community 权威实现逐字节对齐). |