@aiusage/cli 1.7.5 → 1.7.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -5,7 +5,7 @@
5
5
  - discovering and managing projects across AI tools
6
6
  - scanning local Claude Code, Codex, Cursor, Copilot CLI, Copilot for VS Code, Gemini CLI, Antigravity, Amp, Kimi Code, Qwen Code, Droid, OpenCode, Pi, and Trae usage
7
7
  - importing historical usage from Anthropic Admin API
8
- - printing local usage summaries for the last 7 days, 30 days, 90 days, or all history
8
+ - printing local usage summaries for the last 7, 30, 90, or 180 days, or all history
9
9
  - scheduling automatic sync to an AIUsage Worker
10
10
  - diagnosing configuration and connectivity issues
11
11
 
@@ -31,7 +31,8 @@ differ, rather than treating every local record as billable token usage.
31
31
  | Droid | `~/.factory/sessions/*.settings.json`; uses persisted token totals first and the transcript only as a model fallback. |
32
32
  | OpenCode | OpenCode 1.2+ `opencode.db` through read-only `sqlite3`, plus legacy `storage/message/*.json`. |
33
33
  | Pi / Oh My Pi | `~/.pi/agent/sessions/` and `~/.omp/agent/sessions/` JSONL, including provider, cache-write, and session metadata. |
34
- | Trae / Trae CN | `aiusage trae sync` reads Trae CN history through Trae's official local `ai-agent` RPC and writes a privacy-minimized cache under `~/.aiusage/trae-cache/sessions/`. The scanner also accepts international Trae caches produced by `tokscale trae sync` under `~/.config/tokscale/trae-cache/sessions/`. The encrypted SQLCipher database is never opened directly. |
34
+ | Trae CN | `aiusage trae sync --edition cn` reads local history through Trae's official `ai-agent` RPC and writes a privacy-minimized cache under `~/.aiusage/trae-cache/sessions/`. The encrypted SQLCipher database is never opened directly. |
35
+ | Trae / Trae Solo (international) | `aiusage trae sync --edition intl` reads the older plain-JSON or decrypts the newer desktop credential format, then queries Trae's official account usage API once; IDE and Solo share the same account-level data. Numeric session data is cached under `~/.aiusage/trae-cache/intl/sessions/`. Existing tokscale caches under `~/.config/tokscale/trae-cache/sessions/` remain compatible and are deduplicated by session. |
35
36
 
36
37
  Only token counters and session metadata are aggregated or uploaded. Conversation
37
38
  content and local credentials are never uploaded.
@@ -80,7 +81,11 @@ Local usage report. No cloud upload required.
80
81
  aiusage report # default: last 7 days + today, English, compact
81
82
  aiusage report --range 1m # last 30 days
82
83
  aiusage report --range 3m # last 90 days
84
+ aiusage report --range 6m # last 180 days
83
85
  aiusage report --range all # all history
86
+ aiusage report --tool trae-cn --range all # Trae CN only
87
+ aiusage report --tool trae-intl --range 6m # international only
88
+ aiusage report --tool trae --range all # both editions
84
89
  aiusage report --detail # show all columns, top models, pricing notes
85
90
  aiusage report --lang zh # Chinese output
86
91
  aiusage report --no-emoji # disable emoji in title
@@ -93,16 +98,23 @@ Reads data from local tool data directories including `~/.claude/projects` (Clau
93
98
 
94
99
  ### trae sync
95
100
 
96
- Sync Trae CN's local historical token counters before running a regular report or dashboard upload:
101
+ Sync either Trae edition before running a regular report or dashboard upload:
97
102
 
98
103
  ```bash
99
- aiusage trae sync
100
- aiusage report --range all
104
+ aiusage trae sync --edition cn
105
+ aiusage trae sync --edition intl --since 180
106
+ aiusage trae sync --edition all --since 180
107
+
108
+ aiusage report --tool trae-cn --range all
109
+ aiusage report --tool trae-intl --range 6m
110
+ aiusage report --tool trae --range all
101
111
  ```
102
112
 
103
113
  If Trae CN is closed, AIUsage temporarily launches it with a local-only debugging port, reads the official `ai-agent` session API, then closes the temporary instance. If Trae is already running without that port, quit Trae and rerun the command. Use `--port 9230 --no-launch` to connect to an instance you started yourself.
104
114
 
105
- Only session identifiers, workspace paths, timestamps, model labels, and numeric token counters are cached. Conversation content and login credentials are neither cached nor uploaded. International Trae users can run `tokscale trae sync`; AIUsage reads that compatible cache automatically.
115
+ Trae IDE and Trae Solo share account-level international usage, so AIUsage stops after the first working credential and does not double-count the account. It reads or decrypts `storage.json` locally and stores credentials with `0600` permissions under `~/.aiusage/trae-cache/intl/credentials-{ide,solo}.json`; credentials and conversation content are never uploaded. The numeric API cache is written to `~/.aiusage/trae-cache/intl/sessions/usage.json`. Existing tokscale session caches are still read, with the newest snapshot retained per session.
116
+
117
+ Use `--tool trae-cn` or `--tool trae-intl` to isolate one edition. `--tool trae` is the stable combined alias and includes compatible legacy rows. Regular `sync` deliberately rejects `--tool` because it uploads authoritative full-day snapshots.
106
118
 
107
119
  ### Shared date options
108
120
 
@@ -112,11 +124,12 @@ Only session identifiers, workspace paths, timestamps, model labels, and numeric
112
124
  aiusage scan --today # today only
113
125
  aiusage report --date 2026-03-31 # specific date
114
126
  aiusage sync --range 1m # last 30 days
127
+ aiusage report --range 6m # last 180 days
115
128
  aiusage sync --lookback 14 # last 14 days + today
116
129
  aiusage scan --from 2025-01-01 --to 2026-04-05
117
130
  ```
118
131
 
119
- Use `--range 1m`, not `range -1m`. `report` also supports `--range all`; `scan` and `sync` require explicit `--from/--to` for large historical ranges.
132
+ Use `--range 1m`, not `range -1m`. `scan`, `report`, and `sync` support `--range 6m`; `report` also supports `--range all`. Use explicit `--from/--to` for larger scan or sync ranges.
120
133
 
121
134
  ### scan
122
135
 
@@ -126,6 +139,7 @@ Scan local usage and print detailed breakdowns.
126
139
  aiusage scan # yesterday
127
140
  aiusage scan --date 2026-03-31 # specific date
128
141
  aiusage scan --range 1m # last 30 days
142
+ aiusage scan --tool trae-cn --range 6m # Trae CN only, last 180 days
129
143
  aiusage scan --date 2026-03-31 --json # JSON output
130
144
  ```
131
145
 
package/README.zh-CN.md CHANGED
@@ -5,7 +5,7 @@
5
5
  - 发现和管理本机 AI 工具项目
6
6
  - 扫描本地 AI 编程工具的 Token 用量(Claude Code、Codex、Cursor、Copilot CLI、Copilot VS Code、Gemini CLI、Antigravity、Amp、Kimi Code、Qwen Code、Droid、OpenCode、Pi、Trae)
7
7
  - 通过 Anthropic Admin API 导入历史用量
8
- - 生成本地用量报告(最近 7 天、30 天、90 天或全部历史)
8
+ - 生成本地用量报告(最近 7 天、30 天、90 天、180 天或全部历史)
9
9
  - 定时自动同步数据到 AIUsage Worker
10
10
  - 诊断配置与连接问题
11
11
 
@@ -14,9 +14,11 @@ Kimi 同时支持旧版 Kimi CLI 的 `~/.kimi/sessions/` 与新版 Kimi Code 的
14
14
  `wire.jsonl` 中的 Token 计数与会话元数据,不上传对话正文;新版格式参考了
15
15
  [tokscale](https://github.com/junhoyeo/tokscale) 的 MIT 开源实现。
16
16
 
17
- Trae CN 通过 `aiusage trae sync` 调用 Trae 自己的本地 `ai-agent` 接口读取历史
18
- Token 计数,缓存到 `~/.aiusage/trae-cache/sessions/`;不会直接破解加密数据库。
19
- 国际版 Trae 也兼容 `tokscale trae sync` 生成的缓存。
17
+ Trae CN 通过 `aiusage trae sync --edition cn` 调用 Trae 自己的本地 `ai-agent`
18
+ 接口读取历史 Token 计数,缓存到 `~/.aiusage/trae-cache/sessions/`;不会直接破解
19
+ 加密数据库。国际版通过 `--edition intl` 在本机读取 Trae IDE 或 Trae Solo 的登录
20
+ 信息(旧版直接读取、新版在本机解密),并调用官方账号用量 API;实现和缓存解析均与
21
+ [tokscale](https://github.com/junhoyeo/tokscale) 的 MIT 开源实现交叉校验。
20
22
 
21
23
  ## 安装
22
24
 
@@ -62,7 +64,11 @@ aiusage project alias --remove myapp # 移除别名
62
64
  aiusage report # 默认: 最近 7 天 + 今天,英文,紧凑模式
63
65
  aiusage report --range 1m # 最近 30 天
64
66
  aiusage report --range 3m # 最近 90 天
67
+ aiusage report --range 6m # 最近 180 天
65
68
  aiusage report --range all # 全部历史
69
+ aiusage report --tool trae-cn --range all # 仅 Trae CN
70
+ aiusage report --tool trae-intl --range 6m # 仅 Trae 国际版
71
+ aiusage report --tool trae --range all # 两个版本合计
66
72
  aiusage report --detail # 展示全部列、热门模型、定价说明
67
73
  aiusage report --lang zh # 中文输出
68
74
  aiusage report --no-emoji # 禁用标题 emoji
@@ -73,19 +79,31 @@ aiusage report --json # JSON 输出
73
79
 
74
80
  ### trae sync
75
81
 
76
- 先同步 Trae CN 的本地历史用量,再运行常规报告或看板上传:
82
+ 按版本同步 Trae 历史用量,再运行常规报告或看板上传:
77
83
 
78
84
  ```bash
79
- aiusage trae sync
80
- aiusage report --range all
85
+ aiusage trae sync --edition cn # 默认值;Trae CN 本地历史
86
+ aiusage trae sync --edition intl --since 180 # 国际版账号最近 180 天
87
+ aiusage trae sync --edition all --since 180 # 两边都尝试,任一成功即可
88
+
89
+ aiusage report --tool trae-cn --range all
90
+ aiusage report --tool trae-intl --range 6m
91
+ aiusage report --tool trae --range all # CN + 国际版 + 兼容旧数据
81
92
  ```
82
93
 
83
94
  如果 Trae CN 未运行,AIUsage 会用仅限本机的调试端口临时启动它,读取官方
84
95
  `ai-agent` 会话接口,完成后自动退出。如果 Trae 已经在运行但没有开启该端口,
85
96
  请先退出 Trae 再重试。也可以通过 `--port 9230 --no-launch` 连接自行启动的实例。
86
97
 
87
- 缓存只包含会话标识、项目路径、时间、模型名和 Token 数字,不包含对话正文或登录凭据。
88
- 国际版用户可先执行 `tokscale trae sync`,AIUsage 会自动读取兼容缓存。
98
+ Trae 国际版 IDE 与 Trae Solo 共用账号级用量,只会通过第一个可用凭据请求一次,不会
99
+ 重复统计。AIUsage 会在本机读取或解密 `storage.json` 中的登录信息,并以 `0600` 权限保存到
100
+ `~/.aiusage/trae-cache/intl/credentials-{ide,solo}.json`;凭据和对话正文都不会上传。
101
+ 官方 API 返回的会话级 Token/费用缓存位于
102
+ `~/.aiusage/trae-cache/intl/sessions/usage.json`。现有
103
+ `~/.config/tokscale/trae-cache/sessions/*.json` 仍会读取,并按会话保留最新快照,避免双算。
104
+
105
+ 报告筛选值为 `trae-cn`、`trae-intl`;`trae` 是两者合计的稳定别名。常规 `sync`
106
+ 始终按完整日期汇总上传,因此不接受 `--tool`,避免把局部结果当成整日统计。
89
107
 
90
108
  ### 统一日期参数
91
109
 
@@ -95,11 +113,12 @@ aiusage report --range all
95
113
  aiusage scan --today # 仅今天
96
114
  aiusage report --date 2026-03-31 # 指定日期
97
115
  aiusage sync --range 1m # 最近 30 天
116
+ aiusage report --range 6m # 最近 180 天
98
117
  aiusage sync --lookback 14 # 最近 14 天 + 今天
99
118
  aiusage scan --from 2025-01-01 --to 2026-04-05
100
119
  ```
101
120
 
102
- 使用 `--range 1m`,不要写成 `range -1m`。`report` 额外支持 `--range all`;`scan` 和 `sync` 如需很长历史范围,请明确使用 `--from/--to`。
121
+ 使用 `--range 1m`,不要写成 `range -1m`。`scan`、`report`、`sync` 支持 `--range 6m`;`report` 额外支持 `--range all`。`scan` 和 `sync` 如需更长历史范围,请明确使用 `--from/--to`。
103
122
 
104
123
  ### scan
105
124
 
@@ -109,6 +128,7 @@ aiusage scan --from 2025-01-01 --to 2026-04-05
109
128
  aiusage scan # 昨天
110
129
  aiusage scan --date 2026-03-31 # 指定日期
111
130
  aiusage scan --range 1m # 最近 30 天
131
+ aiusage scan --tool trae-cn --range 6m # 仅 Trae CN 最近 180 天
112
132
  aiusage scan --date 2026-03-31 --json # JSON 输出
113
133
  ```
114
134
 
@@ -0,0 +1,29 @@
1
+ # Third-Party Notices
2
+
3
+ ## tokscale
4
+
5
+ Portions of the Kimi and Trae local usage parsers, Trae credential decryption,
6
+ and Trae account usage synchronization are adapted from
7
+ [junhoyeo/tokscale](https://github.com/junhoyeo/tokscale).
8
+
9
+ MIT License
10
+
11
+ Copyright (c) 2025 Junho Yeo
12
+
13
+ Permission is hereby granted, free of charge, to any person obtaining a copy
14
+ of this software and associated documentation files (the "Software"), to deal
15
+ in the Software without restriction, including without limitation the rights
16
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17
+ copies of the Software, and to permit persons to whom the Software is
18
+ furnished to do so, subject to the following conditions:
19
+
20
+ The above copyright notice and this permission notice shall be included in all
21
+ copies or substantial portions of the Software.
22
+
23
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29
+ SOFTWARE.
package/dist/cli.js CHANGED
@@ -3265,61 +3265,68 @@ function resolveTokscaleTraeCacheDir(home = homedir14()) {
3265
3265
  let configDir = process.env.TOKSCALE_CONFIG_DIR?.trim();
3266
3266
  return configDir ? join15(resolve2(configDir), "trae-cache", "sessions") : join15(home, ".config", "tokscale", "trae-cache", "sessions");
3267
3267
  }
3268
+ function resolveTraeIntlCacheDir(home = homedir14()) {
3269
+ let explicit = process.env.AIUSAGE_TRAE_INTL_CACHE_DIR?.trim();
3270
+ return explicit ? resolve2(explicit) : join15(home, ".aiusage", "trae-cache", "intl", "sessions");
3271
+ }
3268
3272
  async function scanTraeDates(targetDates, options = {}) {
3269
3273
  let dates = new Set(targetDates);
3270
3274
  if (dates.size === 0) return /* @__PURE__ */ new Map();
3271
- let nativeDir = options.nativeCacheDir ?? resolveTraeNativeCacheDir(), tokscaleDir = options.tokscaleCacheDir ?? resolveTokscaleTraeCacheDir(), cacheSources = [.../* @__PURE__ */ new Set([
3275
+ let nativeDir = options.nativeCacheDir ?? resolveTraeNativeCacheDir(), intlDir = options.intlCacheDir ?? resolveTraeIntlCacheDir(), tokscaleDir = options.tokscaleCacheDir ?? resolveTokscaleTraeCacheDir(), cacheSources = [.../* @__PURE__ */ new Set([
3272
3276
  `${nativeDir}\0native`,
3277
+ `${intlDir}\0intl`,
3273
3278
  `${tokscaleDir}\0tokscale`
3274
3279
  ])], files = (await Promise.all(cacheSources.map(async (source) => {
3275
3280
  let [dir, kind] = source.split("\0");
3276
3281
  return (await walkFiles(dir, ".json")).map((filePath) => ({ filePath, kind }));
3277
3282
  }))).flat();
3278
3283
  if (files.length === 0) return emptyResult(dates);
3279
- let grouped = initDateMap(dates), seenEvents = /* @__PURE__ */ new Set(), sessionSets = /* @__PURE__ */ new Map();
3284
+ let grouped = initDateMap(dates), selectedEvents = /* @__PURE__ */ new Map(), sessionSets = /* @__PURE__ */ new Map();
3280
3285
  for (let { filePath, kind } of files) {
3281
3286
  let value = await readJson2(filePath);
3282
3287
  if (value == null) continue;
3283
- let events = kind === "native" ? parseNativeCache(value) : parseTokscaleCache(value);
3288
+ let events = kind === "native" ? parseNativeCache(value) : parseIntlCache(value);
3284
3289
  for (let event of events) {
3285
- if (seenEvents.has(event.dedupKey)) continue;
3286
- seenEvents.add(event.dedupKey);
3287
- let usageDate = dateKey(event.timestamp);
3288
- if (!dates.has(usageDate)) continue;
3289
- let day = grouped.get(usageDate);
3290
- if (!day) continue;
3291
- let projectFields = resolveProjectFields(event.project, options.projectAliases), breakdownKey = `${event.provider}|${event.model}|${projectFields.project}`;
3292
- if (accumulate(
3293
- day,
3294
- breakdownKey,
3295
- {
3296
- provider: event.provider,
3297
- product: "trae",
3298
- channel: "ide",
3299
- model: event.model,
3300
- project: projectFields.project,
3301
- projectDisplay: projectFields.projectDisplay,
3302
- projectAlias: projectFields.projectAlias,
3303
- sessionCount: 0,
3304
- inputTokens: 0,
3305
- cachedInputTokens: 0,
3306
- cacheWriteTokens: 0,
3307
- outputTokens: 0,
3308
- reasoningOutputTokens: 0
3309
- },
3310
- event
3311
- ), event.costUSD && event.costUSD > 0) {
3312
- let breakdown = day.get(breakdownKey);
3313
- breakdown && (breakdown.costUSD = (breakdown.costUSD ?? 0) + event.costUSD);
3314
- }
3315
- let sessionKey = `${usageDate}|${breakdownKey}`, sessions = sessionSets.get(sessionKey);
3316
- sessions || (sessions = /* @__PURE__ */ new Set(), sessionSets.set(sessionKey, sessions)), sessions.add(event.sessionId);
3290
+ let existing = selectedEvents.get(event.dedupKey);
3291
+ (!existing || shouldReplaceEvent(existing, event)) && selectedEvents.set(event.dedupKey, event);
3292
+ }
3293
+ }
3294
+ for (let event of selectedEvents.values()) {
3295
+ let usageDate = dateKey(event.timestamp);
3296
+ if (!dates.has(usageDate)) continue;
3297
+ let day = grouped.get(usageDate);
3298
+ if (!day) continue;
3299
+ let projectFields = resolveProjectFields(event.project, options.projectAliases), breakdownKey = `${event.product}|${event.provider}|${event.model}|${projectFields.project}`;
3300
+ if (accumulate(
3301
+ day,
3302
+ breakdownKey,
3303
+ {
3304
+ provider: event.provider,
3305
+ product: event.product,
3306
+ channel: "ide",
3307
+ model: event.model,
3308
+ project: projectFields.project,
3309
+ projectDisplay: projectFields.projectDisplay,
3310
+ projectAlias: projectFields.projectAlias,
3311
+ sessionCount: 0,
3312
+ inputTokens: 0,
3313
+ cachedInputTokens: 0,
3314
+ cacheWriteTokens: 0,
3315
+ outputTokens: 0,
3316
+ reasoningOutputTokens: 0
3317
+ },
3318
+ event
3319
+ ), event.costUSD && event.costUSD > 0) {
3320
+ let breakdown = day.get(breakdownKey);
3321
+ breakdown && (breakdown.costUSD = (breakdown.costUSD ?? 0) + event.costUSD, breakdown.pricingVersion = PRICING_VERSION);
3317
3322
  }
3323
+ let sessionKey = `${usageDate}|${breakdownKey}`, sessions = sessionSets.get(sessionKey);
3324
+ sessions || (sessions = /* @__PURE__ */ new Set(), sessionSets.set(sessionKey, sessions)), sessions.add(event.sessionId);
3318
3325
  }
3319
3326
  let result = finalize(grouped);
3320
3327
  for (let [usageDate, breakdowns] of result)
3321
3328
  for (let breakdown of breakdowns) {
3322
- let key = `${usageDate}|${breakdown.provider}|${breakdown.model}|${breakdown.project}`;
3329
+ let key = `${usageDate}|${breakdown.product}|${breakdown.provider}|${breakdown.model}|${breakdown.project}`;
3323
3330
  breakdown.sessionCount = sessionSets.get(key)?.size ?? 0;
3324
3331
  }
3325
3332
  return result;
@@ -3344,6 +3351,7 @@ function parseNativeCache(value) {
3344
3351
  dedupKey: `trae-cn:${messageId}`,
3345
3352
  sessionId,
3346
3353
  timestamp,
3354
+ product: "trae-cn",
3347
3355
  provider: inferProviderFromModel(model, "trae"),
3348
3356
  model,
3349
3357
  project,
@@ -3352,7 +3360,7 @@ function parseNativeCache(value) {
3352
3360
  }
3353
3361
  return events;
3354
3362
  }
3355
- function parseTokscaleCache(value) {
3363
+ function parseIntlCache(value) {
3356
3364
  if (!Array.isArray(value)) return [];
3357
3365
  let events = [];
3358
3366
  for (let raw of value) {
@@ -3367,9 +3375,12 @@ function parseTokscaleCache(value) {
3367
3375
  reasoning: 0
3368
3376
  };
3369
3377
  tokenTotal2(tokens) !== 0 && events.push({
3370
- dedupKey: `trae-intl:${sessionId}:${session.usage_time}`,
3378
+ // The international API returns aggregate rows by session. Multiple
3379
+ // cache artifacts can contain newer snapshots of the same session.
3380
+ dedupKey: `trae-intl:${sessionId}`,
3371
3381
  sessionId,
3372
3382
  timestamp,
3383
+ product: "trae-intl",
3373
3384
  provider: inferProviderFromModel(model, "trae"),
3374
3385
  model,
3375
3386
  project: "unknown",
@@ -3379,6 +3390,12 @@ function parseTokscaleCache(value) {
3379
3390
  }
3380
3391
  return events;
3381
3392
  }
3393
+ function shouldReplaceEvent(existing, incoming) {
3394
+ if (incoming.timestamp.getTime() !== existing.timestamp.getTime())
3395
+ return incoming.timestamp > existing.timestamp;
3396
+ let incomingTotal = tokenTotal2(incoming), existingTotal = tokenTotal2(existing);
3397
+ return incomingTotal !== existingTotal ? incomingTotal > existingTotal : (incoming.costUSD ?? 0) > (existing.costUSD ?? 0);
3398
+ }
3382
3399
  function normalizeTraeModel(name) {
3383
3400
  let value = name?.trim() ?? "";
3384
3401
  return {
@@ -3428,6 +3445,37 @@ function isRecord2(value) {
3428
3445
  }
3429
3446
 
3430
3447
  // src/scan.ts
3448
+ var TOOL_IDS = [
3449
+ "amp",
3450
+ "antigravity",
3451
+ "claude-code",
3452
+ "codex",
3453
+ "copilot-cli",
3454
+ "copilot-vscode",
3455
+ "cursor",
3456
+ "droid",
3457
+ "gemini-cli",
3458
+ "kimi-code",
3459
+ "opencode",
3460
+ "pi",
3461
+ "qwen-code",
3462
+ "trae",
3463
+ "trae-cn",
3464
+ "trae-intl"
3465
+ ], TOOL_ID_SET = new Set(TOOL_IDS);
3466
+ function parseToolSelection(value, zh2 = !1) {
3467
+ if (value == null) return;
3468
+ if (typeof value != "string" || value.trim() === "")
3469
+ throw new Error(zh2 ? "--tool \u9700\u8981\u6307\u5B9A\u5DE5\u5177\u540D\u79F0" : "--tool requires a tool name");
3470
+ let selected = /* @__PURE__ */ new Set();
3471
+ for (let raw of value.split(",")) {
3472
+ let tool = raw.trim().toLowerCase();
3473
+ if (!TOOL_ID_SET.has(tool))
3474
+ throw new Error(zh2 ? `\u672A\u77E5\u5DE5\u5177: ${raw.trim()}\u3002\u53EF\u7528\u503C: ${TOOL_IDS.join(", ")}` : `Unknown tool: ${raw.trim()}. Available values: ${TOOL_IDS.join(", ")}`);
3475
+ tool === "trae" ? (selected.add("trae-cn"), selected.add("trae-intl"), selected.add("trae")) : selected.add(tool);
3476
+ }
3477
+ return [...selected];
3478
+ }
3431
3479
  async function scanDate(targetDate, options = {}) {
3432
3480
  let [result] = await scanDates([targetDate], options);
3433
3481
  return result ?? {
@@ -3439,24 +3487,27 @@ async function scanDate(targetDate, options = {}) {
3439
3487
  async function scanDates(targetDates, options = {}) {
3440
3488
  let uniqueDates = [...new Set(targetDates)];
3441
3489
  if (uniqueDates.length === 0) return [];
3442
- let scanners = [
3443
- scanAntigravityDates(uniqueDates),
3444
- scanClaudeDates(uniqueDates, void 0, options.projectAliases),
3445
- scanCodexDates(uniqueDates, void 0, options.projectAliases),
3446
- scanCopilotDates(uniqueDates, void 0, options.projectAliases),
3447
- scanCopilotVscodeDates(uniqueDates, void 0, options.projectAliases),
3448
- scanCursorDates(uniqueDates),
3449
- scanGeminiDates(uniqueDates, void 0, options.projectAliases),
3450
- scanQwenDates(uniqueDates, void 0, options.projectAliases),
3451
- scanKimiDates(uniqueDates, void 0, options.projectAliases),
3452
- scanAmpDates(uniqueDates, void 0, options.projectAliases),
3453
- scanDroidDates(uniqueDates, void 0, options.projectAliases),
3454
- scanOpencodeDates(uniqueDates, void 0, options.projectAliases),
3455
- scanPiDates(uniqueDates, void 0, options.projectAliases),
3456
- scanTraeDates(uniqueDates, { projectAliases: options.projectAliases })
3457
- ], results = await Promise.all(scanners);
3490
+ let selected = options.tools ? new Set(options.tools) : void 0, scanners = [
3491
+ { products: ["antigravity"], scan: () => scanAntigravityDates(uniqueDates) },
3492
+ { products: ["claude-code"], scan: () => scanClaudeDates(uniqueDates, void 0, options.projectAliases) },
3493
+ { products: ["codex"], scan: () => scanCodexDates(uniqueDates, void 0, options.projectAliases) },
3494
+ { products: ["copilot-cli"], scan: () => scanCopilotDates(uniqueDates, void 0, options.projectAliases) },
3495
+ { products: ["copilot-vscode"], scan: () => scanCopilotVscodeDates(uniqueDates, void 0, options.projectAliases) },
3496
+ { products: ["cursor"], scan: () => scanCursorDates(uniqueDates) },
3497
+ { products: ["gemini-cli"], scan: () => scanGeminiDates(uniqueDates, void 0, options.projectAliases) },
3498
+ { products: ["qwen-code"], scan: () => scanQwenDates(uniqueDates, void 0, options.projectAliases) },
3499
+ { products: ["kimi-code"], scan: () => scanKimiDates(uniqueDates, void 0, options.projectAliases) },
3500
+ { products: ["amp"], scan: () => scanAmpDates(uniqueDates, void 0, options.projectAliases) },
3501
+ { products: ["droid"], scan: () => scanDroidDates(uniqueDates, void 0, options.projectAliases) },
3502
+ { products: ["opencode"], scan: () => scanOpencodeDates(uniqueDates, void 0, options.projectAliases) },
3503
+ { products: ["pi"], scan: () => scanPiDates(uniqueDates, void 0, options.projectAliases) },
3504
+ {
3505
+ products: ["trae-cn", "trae-intl", "trae"],
3506
+ scan: () => scanTraeDates(uniqueDates, { projectAliases: options.projectAliases })
3507
+ }
3508
+ ].filter((definition) => !selected || definition.products.some((product) => selected.has(product))).map((definition) => definition.scan()), results = await Promise.all(scanners);
3458
3509
  return uniqueDates.map((usageDate) => {
3459
- let breakdowns = results.flatMap((m) => m.get(usageDate) ?? []), totals = breakdowns.reduce(
3510
+ let breakdowns = results.flatMap((m) => m.get(usageDate) ?? []).filter((breakdown) => !selected || selected.has(breakdown.product)), totals = breakdowns.reduce(
3460
3511
  (acc, b) => ({
3461
3512
  eventCount: acc.eventCount + b.eventCount,
3462
3513
  inputTokens: acc.inputTokens + b.inputTokens,
@@ -3633,7 +3684,10 @@ import { readdir as readdir5, readFile as readFile14 } from "node:fs/promises";
3633
3684
  import { homedir as homedir15 } from "node:os";
3634
3685
  import { basename as basename11, dirname as dirname6, join as join16 } from "node:path";
3635
3686
  async function buildLocalReport(range, options = {}) {
3636
- let requestedDates = options.dates ? options.dates : range === "all" ? await discoverAllDates() : range === "today" ? [dateKey(getTodayLocalDate())] : buildPresetDates(range), daily = [], totals = createEmptyTotals2(), bySource = /* @__PURE__ */ new Map(), byModel = /* @__PURE__ */ new Map(), pricingWarnings = /* @__PURE__ */ new Set(), daysWithData = 0, results = await scanDates(requestedDates, { projectAliases: options.projectAliases });
3687
+ let requestedDates = options.dates ? options.dates : range === "all" ? await discoverAllDates(options.tools) : range === "today" ? [dateKey(getTodayLocalDate())] : buildPresetDates(range), daily = [], totals = createEmptyTotals2(), bySource = /* @__PURE__ */ new Map(), byModel = /* @__PURE__ */ new Map(), pricingWarnings = /* @__PURE__ */ new Set(), daysWithData = 0, results = await scanDates(requestedDates, {
3688
+ projectAliases: options.projectAliases,
3689
+ tools: options.tools
3690
+ });
3637
3691
  for (let result of results) {
3638
3692
  let usageDate = result.usageDate, dayTotals = withTotalTokens(result.totals), hasData = result.breakdowns.length > 0 || dayTotals.eventCount > 0 || dayTotals.totalTokens > 0;
3639
3693
  if (hasData) {
@@ -3667,14 +3721,15 @@ async function buildLocalReport(range, options = {}) {
3667
3721
  source: "bundled",
3668
3722
  version: options.pricingCatalog?.version ?? "bundled"
3669
3723
  },
3670
- pricingWarnings: [...pricingWarnings].sort()
3724
+ pricingWarnings: [...pricingWarnings].sort(),
3725
+ ...options.tools ? { tools: [...options.tools] } : {}
3671
3726
  };
3672
3727
  }
3673
3728
  function parseReportRange(value, today) {
3674
3729
  if (today) return "today";
3675
3730
  if (value === void 0 || value === !0) return "7d";
3676
- if (value === "7d" || value === "1m" || value === "3m" || value === "all" || value === "today") return value;
3677
- throw new Error("--range \u4EC5\u652F\u6301 7d\u30011m\u30013m\u3001all\u3001today");
3731
+ if (value === "7d" || value === "1m" || value === "3m" || value === "6m" || value === "all" || value === "today") return value;
3732
+ throw new Error("--range \u4EC5\u652F\u6301 7d\u30011m\u30013m\u30016m\u3001all\u3001today");
3678
3733
  }
3679
3734
  function getRangeLabel(range) {
3680
3735
  switch (range) {
@@ -3684,6 +3739,8 @@ function getRangeLabel(range) {
3684
3739
  return "\u6700\u8FD1 30 \u5929";
3685
3740
  case "3m":
3686
3741
  return "\u6700\u8FD1 90 \u5929";
3742
+ case "6m":
3743
+ return "\u6700\u8FD1 180 \u5929";
3687
3744
  case "all":
3688
3745
  return "\u5168\u90E8\u5386\u53F2";
3689
3746
  case "today":
@@ -3691,35 +3748,20 @@ function getRangeLabel(range) {
3691
3748
  }
3692
3749
  }
3693
3750
  function buildPresetDates(range) {
3694
- let days = range === "7d" ? 7 : range === "1m" ? 30 : 90, today = getTodayLocalDate(), result = [];
3751
+ let days = range === "7d" ? 7 : range === "1m" ? 30 : range === "3m" ? 90 : 180, today = getTodayLocalDate(), result = [];
3695
3752
  for (let offset = days - 1; offset >= 0; offset -= 1) {
3696
3753
  let day = new Date(today);
3697
3754
  day.setDate(today.getDate() - offset), result.push(dateKey(day));
3698
3755
  }
3699
3756
  return result;
3700
3757
  }
3701
- async function discoverAllDates() {
3702
- let dates = /* @__PURE__ */ new Set(), home = homedir15();
3703
- await Promise.all([
3704
- discoverClaudeDates(dates),
3705
- discoverCodexDates(dates),
3706
- discoverGeminiDates(dates),
3707
- discoverCopilotVscodeDates(dates),
3708
- discoverAntigravityDates(dates),
3709
- discoverGenericJsonlDates(join16(home, ".copilot", "session-state"), dates),
3710
- discoverGenericJsonlDates(join16(home, ".copilot", "otel"), dates),
3711
- discoverGenericJsonlDates(join16(home, ".qwen", "tmp"), dates),
3712
- discoverGenericJsonlDates(join16(home, ".qwen", "projects"), dates),
3713
- discoverGenericJsonlDates(join16(home, ".kimi", "sessions"), dates),
3714
- discoverGenericJsonlDates(join16(resolveKimiCodeHome(home), "sessions"), dates),
3715
- discoverGenericJsonDates(join16(home, ".local", "share", "amp", "threads"), dates),
3716
- discoverGenericJsonDates(join16(home, ".factory", "sessions"), dates),
3717
- discoverOpenCodeUsageDates().then((found) => found.forEach((date) => dates.add(date))),
3718
- discoverGenericJsonlDates(join16(home, ".pi", "agent", "sessions"), dates),
3719
- discoverGenericJsonlDates(join16(home, ".omp", "agent", "sessions"), dates)
3720
- ]);
3758
+ async function discoverAllDates(tools) {
3759
+ let dates = /* @__PURE__ */ new Set(), home = homedir15(), selected = tools ? new Set(tools) : null, includes = (...products) => !selected || products.some((product) => selected.has(product)), discoveries = [];
3760
+ includes("claude-code") && discoveries.push(discoverClaudeDates(dates)), includes("codex") && discoveries.push(discoverCodexDates(dates)), includes("gemini-cli") && discoveries.push(discoverGeminiDates(dates)), includes("copilot-vscode") && discoveries.push(discoverCopilotVscodeDates(dates)), includes("antigravity") && discoveries.push(discoverAntigravityDates(dates)), includes("copilot-cli") && (discoveries.push(discoverGenericJsonlDates(join16(home, ".copilot", "session-state"), dates)), discoveries.push(discoverGenericJsonlDates(join16(home, ".copilot", "otel"), dates))), includes("qwen-code") && (discoveries.push(discoverGenericJsonlDates(join16(home, ".qwen", "tmp"), dates)), discoveries.push(discoverGenericJsonlDates(join16(home, ".qwen", "projects"), dates))), includes("kimi-code") && (discoveries.push(discoverGenericJsonlDates(join16(home, ".kimi", "sessions"), dates)), discoveries.push(discoverGenericJsonlDates(join16(resolveKimiCodeHome(home), "sessions"), dates))), includes("amp") && discoveries.push(discoverGenericJsonDates(join16(home, ".local", "share", "amp", "threads"), dates)), includes("droid") && discoveries.push(discoverGenericJsonDates(join16(home, ".factory", "sessions"), dates)), includes("opencode") && discoveries.push(discoverOpenCodeUsageDates().then((found) => {
3761
+ found.forEach((date) => dates.add(date));
3762
+ })), includes("pi") && (discoveries.push(discoverGenericJsonlDates(join16(home, ".pi", "agent", "sessions"), dates)), discoveries.push(discoverGenericJsonlDates(join16(home, ".omp", "agent", "sessions"), dates))), includes("trae-cn", "trae") && discoveries.push(discoverGenericJsonDates(resolveTraeNativeCacheDir(home), dates)), includes("trae-intl", "trae") && (discoveries.push(discoverGenericJsonDates(resolveTraeIntlCacheDir(home), dates)), discoveries.push(discoverGenericJsonDates(resolveTokscaleTraeCacheDir(home), dates))), await Promise.all(discoveries);
3721
3763
  let explicitCopilotOtel = process.env.COPILOT_OTEL_FILE_EXPORTER_PATH?.trim();
3722
- return explicitCopilotOtel && await discoverJsonlFileDates(explicitCopilotOtel, dates), [...dates].sort();
3764
+ return explicitCopilotOtel && includes("copilot-cli") && await discoverJsonlFileDates(explicitCopilotOtel, dates), [...dates].sort();
3723
3765
  }
3724
3766
  async function discoverGenericJsonlDates(baseDir, dates) {
3725
3767
  let files = [];
@@ -3767,6 +3809,7 @@ async function discoverGenericJsonDates(baseDir, dates) {
3767
3809
  } catch {
3768
3810
  continue;
3769
3811
  }
3812
+ if (Array.isArray(data) && data.length === 0) continue;
3770
3813
  (Array.isArray(data) ? data.reduce((found, row) => collectRecordDates(row, dates) || found, !1) : collectRecordDates(data, dates)) || await addFileModifiedDate(filePath, dates);
3771
3814
  }
3772
3815
  }
@@ -3786,6 +3829,7 @@ function collectRecordDates(record, dates) {
3786
3829
  record._hrTime,
3787
3830
  record.observedTimestamp,
3788
3831
  record.timeUnixNano,
3832
+ record.usage_time,
3789
3833
  record.time?.created
3790
3834
  ];
3791
3835
  for (let value of candidates) {
@@ -3798,7 +3842,8 @@ function collectRecordDates(record, dates) {
3798
3842
  ...Array.isArray(record.data?.messages) ? record.data.messages : [],
3799
3843
  ...Array.isArray(record.data?.history) ? record.data.history : [],
3800
3844
  ...Array.isArray(record.$set?.messages) ? record.$set.messages : [],
3801
- ...Array.isArray(record.usageLedger?.events) ? record.usageLedger.events : []
3845
+ ...Array.isArray(record.usageLedger?.events) ? record.usageLedger.events : [],
3846
+ ...Array.isArray(record.events) ? record.events : []
3802
3847
  ];
3803
3848
  for (let row of nestedRows) found = collectRecordDates(row, dates) || found;
3804
3849
  return found;
@@ -4075,7 +4120,7 @@ function toBreakdownTotals(breakdown, warnings, pricingCatalog) {
4075
4120
  };
4076
4121
  }
4077
4122
  function calculateBreakdownCost(breakdown, warnings, pricingCatalog) {
4078
- let effectivePricingVersion = pricingCatalog?.version ?? PRICING_VERSION, sourceCostMatchesCatalog = breakdown.pricingVersion == null || breakdown.pricingVersion === effectivePricingVersion;
4123
+ let effectivePricingVersion = pricingCatalog?.version ?? PRICING_VERSION, sourceCostMatchesCatalog = breakdown.product === "trae-intl" || breakdown.pricingVersion == null || breakdown.pricingVersion === effectivePricingVersion;
4079
4124
  if (breakdown.costUSD != null && breakdown.costUSD > 0 && sourceCostMatchesCatalog)
4080
4125
  return breakdown.costUSD;
4081
4126
  let result = calculateCost(
@@ -4865,6 +4910,8 @@ function getRangeLabel3(range) {
4865
4910
  return "\u6700\u8FD1 30 \u5929";
4866
4911
  case "3m":
4867
4912
  return "\u6700\u8FD1 90 \u5929";
4913
+ case "6m":
4914
+ return "\u6700\u8FD1 180 \u5929";
4868
4915
  case "all":
4869
4916
  return "\u5168\u90E8\u5386\u53F2";
4870
4917
  case "today":
@@ -6339,6 +6386,392 @@ function delay(ms) {
6339
6386
  return new Promise((resolve5) => setTimeout(resolve5, ms));
6340
6387
  }
6341
6388
 
6389
+ // src/trae-intl-sync.ts
6390
+ import { createDecipheriv, createHash as createHash3, timingSafeEqual } from "node:crypto";
6391
+ import { existsSync as existsSync3 } from "node:fs";
6392
+ import { chmod, mkdir as mkdir5, open as open4, readFile as readFile20, rename as rename2, unlink as unlink2 } from "node:fs/promises";
6393
+ import { homedir as homedir23 } from "node:os";
6394
+ import { dirname as dirname8, join as join24 } from "node:path";
6395
+ var DEFAULT_HOST = "https://api-sg-central.trae.ai", CLIENT_IDS = {
6396
+ ide: "ono9krqynydwx5",
6397
+ solo: "en1oxy7wnw8j9n"
6398
+ }, EXCHANGE_TOKEN_PATH = "/cloudide/api/v3/trae/oauth/ExchangeToken", USAGE_PATH = "/trae/api/v1/pay/query_user_usage_group_by_session", PAGE_SIZE = 20, PAGE_DELAY_MS = 300, DEFAULT_SINCE_DAYS = 180;
6399
+ async function syncTraeIntlUsage(options = {}) {
6400
+ let sinceDays = normalizeSinceDays(options.sinceDays), cacheDir = options.cacheDir ?? resolveTraeIntlCacheDir(), fetchImpl = options.fetchImpl ?? fetch, now = options.now ?? /* @__PURE__ */ new Date(), releaseLock = await acquireTraeIntlSyncLock(dirname8(cacheDir));
6401
+ try {
6402
+ return await performTraeIntlSync(options, sinceDays, cacheDir, fetchImpl, now);
6403
+ } finally {
6404
+ await releaseLock();
6405
+ }
6406
+ }
6407
+ async function performTraeIntlSync(options, sinceDays, cacheDir, fetchImpl, now) {
6408
+ let resolved = await resolveCredentials(options.credentialVariant ?? "auto", fetchImpl, cacheDir), startTime = Math.floor(now.getTime() / 1e3) - sinceDays * 86400, endTime = Math.floor(now.getTime() / 1e3), credentials = resolved.credentials, sessions;
6409
+ try {
6410
+ sessions = await fetchUsagePages(credentials.host, credentials.token, startTime, endTime, fetchImpl);
6411
+ } catch (error) {
6412
+ if (!(error instanceof TraeIntlHttpError) || error.status !== 401 || !credentials.refreshToken) throw error;
6413
+ credentials = await exchangeCredentials(credentials, fetchImpl), await saveCredentials(credentials, cacheDir), sessions = await fetchUsagePages(credentials.host, credentials.token, startTime, endTime, fetchImpl);
6414
+ }
6415
+ let canonicalPath = join24(cacheDir, "usage.json"), existing = await readSessionArray(canonicalPath), merged = mergeTraeIntlSessions(existing, sessions);
6416
+ await writePrivateJson(canonicalPath, merged);
6417
+ let totals = merged.reduce((sum, session) => {
6418
+ let extra = session.extra_info ?? {};
6419
+ return sum.inputTokens += tokenValue3(extra.input_token), sum.cachedInputTokens += tokenValue3(extra.cache_read_token), sum.cacheWriteTokens += tokenValue3(extra.cache_write_token), sum.outputTokens += tokenValue3(extra.output_token), sum.costUSD += positiveNumber2(session.dollar_float), sum;
6420
+ }, {
6421
+ inputTokens: 0,
6422
+ cachedInputTokens: 0,
6423
+ cacheWriteTokens: 0,
6424
+ outputTokens: 0,
6425
+ totalTokens: 0,
6426
+ costUSD: 0
6427
+ });
6428
+ return totals.totalTokens = totals.inputTokens + totals.cachedInputTokens + totals.cacheWriteTokens + totals.outputTokens, totals.costUSD = Math.round(totals.costUSD * 1e6) / 1e6, {
6429
+ edition: "intl",
6430
+ scope: "account",
6431
+ credentialVariant: resolved.source,
6432
+ cacheDir,
6433
+ sinceDays,
6434
+ fetchedSessions: sessions.length,
6435
+ storedSessions: merged.length,
6436
+ totals
6437
+ };
6438
+ }
6439
+ async function acquireTraeIntlSyncLock(cacheRoot) {
6440
+ await mkdir5(cacheRoot, { recursive: !0, mode: 448 }), await chmod(cacheRoot, 448).catch(() => {
6441
+ });
6442
+ let lockPath = join24(cacheRoot, "sync.lock");
6443
+ for (let attempt = 0; attempt < 3; attempt += 1)
6444
+ try {
6445
+ let handle = await open4(lockPath, "wx", 384);
6446
+ try {
6447
+ await handle.writeFile(`${process.pid} ${Math.floor(Date.now() / 1e3)}
6448
+ `, "utf8");
6449
+ } finally {
6450
+ await handle.close();
6451
+ }
6452
+ return async () => {
6453
+ await unlink2(lockPath).catch(() => {
6454
+ });
6455
+ };
6456
+ } catch (error) {
6457
+ if (!isFileExistsError(error)) throw error;
6458
+ if (!await isStaleSyncLock(lockPath))
6459
+ throw new Error(`\u53E6\u4E00\u4E2A Trae \u56FD\u9645\u7248\u540C\u6B65\u6B63\u5728\u8FD0\u884C\uFF08\u9501\u6587\u4EF6: ${lockPath}\uFF09`);
6460
+ await unlink2(lockPath).catch(() => {
6461
+ });
6462
+ }
6463
+ throw new Error(`\u65E0\u6CD5\u83B7\u53D6 Trae \u56FD\u9645\u7248\u540C\u6B65\u9501\uFF08${lockPath}\uFF09`);
6464
+ }
6465
+ async function isStaleSyncLock(lockPath) {
6466
+ try {
6467
+ let pid = Number((await readFile20(lockPath, "utf8")).trim().split(/\s+/)[0]);
6468
+ if (!Number.isInteger(pid) || pid <= 0) return !0;
6469
+ try {
6470
+ return process.kill(pid, 0), !1;
6471
+ } catch (error) {
6472
+ return (isRecord3(error) ? stringValue5(error.code) : "") === "ESRCH";
6473
+ }
6474
+ } catch {
6475
+ return !0;
6476
+ }
6477
+ }
6478
+ function isFileExistsError(error) {
6479
+ return isRecord3(error) && stringValue5(error.code) === "EEXIST";
6480
+ }
6481
+ function mergeTraeIntlSessions(existing, incoming) {
6482
+ let sessions = /* @__PURE__ */ new Map();
6483
+ for (let session of [...existing, ...incoming]) {
6484
+ let id = stringValue5(session.session_id), usageTime = tokenValue3(session.usage_time);
6485
+ if (!id || usageTime === 0) continue;
6486
+ let previous = sessions.get(id), previousTime = tokenValue3(previous?.usage_time);
6487
+ (!previous || usageTime > previousTime || usageTime === previousTime && sessionWeight(session) >= sessionWeight(previous)) && sessions.set(id, session);
6488
+ }
6489
+ return [...sessions.values()].sort((a, b) => tokenValue3(a.usage_time) - tokenValue3(b.usage_time) || stringValue5(a.session_id).localeCompare(stringValue5(b.session_id)));
6490
+ }
6491
+ async function resolveCredentials(requested, fetchImpl, cacheDir) {
6492
+ let environmentToken = process.env.AIUSAGE_TRAE_INTL_TOKEN?.trim();
6493
+ if (environmentToken)
6494
+ return {
6495
+ source: "environment",
6496
+ credentials: {
6497
+ variant: requested === "solo" ? "solo" : "ide",
6498
+ token: stripAuthorizationPrefix(environmentToken),
6499
+ refreshToken: "",
6500
+ expiredAt: "",
6501
+ refreshExpiredAt: "",
6502
+ host: normalizeHost(process.env.AIUSAGE_TRAE_INTL_HOST || DEFAULT_HOST),
6503
+ clientId: process.env.AIUSAGE_TRAE_INTL_CLIENT_ID?.trim() || CLIENT_IDS[requested === "solo" ? "solo" : "ide"]
6504
+ }
6505
+ };
6506
+ let variants = requested === "auto" ? ["ide", "solo"] : [requested], errors = [];
6507
+ for (let variant of variants) {
6508
+ let cachedCandidates = [
6509
+ ["AIUsage cache", await loadCredentials(variant, cacheDir)],
6510
+ ["tokscale cache", await loadTokscaleCredentials(variant)]
6511
+ ];
6512
+ for (let [source, cached2] of cachedCandidates)
6513
+ if (cached2)
6514
+ try {
6515
+ let credentials = await ensureUsableCredentials(cached2, fetchImpl);
6516
+ return await saveCredentials(credentials, cacheDir), { credentials, source: variant };
6517
+ } catch (error) {
6518
+ errors.push(`${variant} ${source}: ${sanitizeError(error)}`);
6519
+ }
6520
+ try {
6521
+ let credentials = await ensureUsableCredentials(await decryptDesktopCredentials(variant), fetchImpl);
6522
+ return await saveCredentials(credentials, cacheDir), { credentials, source: variant };
6523
+ } catch (error) {
6524
+ errors.push(`${variant}: ${sanitizeError(error)}`);
6525
+ }
6526
+ }
6527
+ throw new Error(`\u672A\u80FD\u8BFB\u53D6 Trae \u56FD\u9645\u7248\u767B\u5F55\u4FE1\u606F\u3002\u8BF7\u5148\u767B\u5F55 Trae IDE/Trae Solo \u540E\u91CD\u8BD5\u3002${errors.length ? ` (${errors.join("; ")})` : ""}`);
6528
+ }
6529
+ async function ensureUsableCredentials(credentials, fetchImpl) {
6530
+ if (!isExpired(credentials.expiredAt, 3e5)) return credentials;
6531
+ if (!credentials.refreshToken) throw new Error("access token \u5DF2\u8FC7\u671F\u4E14\u6CA1\u6709 refresh token");
6532
+ if (isExpired(credentials.refreshExpiredAt, 864e5)) throw new Error("refresh token \u5DF2\u8FC7\u671F");
6533
+ return exchangeCredentials(credentials, fetchImpl);
6534
+ }
6535
+ async function decryptDesktopCredentials(variant) {
6536
+ if (process.platform !== "darwin")
6537
+ throw new Error("\u81EA\u52A8\u8BFB\u53D6 Trae \u56FD\u9645\u7248\u767B\u5F55\u4FE1\u606F\u76EE\u524D\u4EC5\u652F\u6301 macOS\uFF1B\u53EF\u901A\u8FC7 AIUSAGE_TRAE_INTL_TOKEN \u63D0\u4F9B\u8BBF\u95EE\u4EE4\u724C");
6538
+ let appDir = variant === "ide" ? "Trae" : "TRAE SOLO", storagePath = join24(homedir23(), "Library", "Application Support", appDir, "User", "globalStorage", "storage.json");
6539
+ if (!existsSync3(storagePath)) throw new Error(`\u672A\u627E\u5230 ${appDir} storage.json`);
6540
+ let storage = JSON.parse(await readFile20(storagePath, "utf8")), exact = storage["iCubeAuthInfo://icube.cloudide"], candidates = Object.entries(storage).filter(([key, value]) => key.startsWith("iCubeAuthInfo") && typeof value == "string").map(([, value]) => value).sort((a, b) => b.length - a.length), encoded = typeof exact == "string" ? exact : candidates[0];
6541
+ if (!encoded) throw new Error("storage.json \u4E2D\u6CA1\u6709 iCubeAuthInfo");
6542
+ let raw = JSON.parse(decodeTraeIntlAuthInfo(encoded)), token = stringValue5(raw.token);
6543
+ if (!token) throw new Error("\u89E3\u5BC6\u7ED3\u679C\u7F3A\u5C11 token");
6544
+ return {
6545
+ variant,
6546
+ token,
6547
+ refreshToken: stringValue5(raw.refreshToken),
6548
+ expiredAt: stringValue5(raw.expiredAt),
6549
+ refreshExpiredAt: stringValue5(raw.refreshExpiredAt),
6550
+ host: normalizeHost(stringValue5(raw.host) || DEFAULT_HOST),
6551
+ clientId: process.env.AIUSAGE_TRAE_INTL_CLIENT_ID?.trim() || CLIENT_IDS[variant],
6552
+ userId: stringValue5(raw.userId) || void 0
6553
+ };
6554
+ }
6555
+ function decodeTraeIntlAuthInfo(encoded) {
6556
+ let value = encoded.trim();
6557
+ if (value.startsWith("{"))
6558
+ try {
6559
+ let parsed = JSON.parse(value);
6560
+ if (isRecord3(parsed)) return value;
6561
+ } catch {
6562
+ throw new Error("Trae \u56FD\u9645\u7248\u660E\u6587\u51ED\u8BC1 JSON \u65E0\u6548");
6563
+ }
6564
+ return decryptTraeIntlAuthBlob(value);
6565
+ }
6566
+ function decryptTraeIntlAuthBlob(encoded) {
6567
+ let blob = Buffer.from(encoded.trim(), "base64"), magic = Buffer.from([116, 99, 5, 16, 0, 0]);
6568
+ if (blob.length < magic.length + 32 + 16 || !blob.subarray(0, magic.length).equals(magic))
6569
+ throw new Error("Trae \u56FD\u9645\u7248\u51ED\u8BC1\u683C\u5F0F\u65E0\u6548");
6570
+ let salt = blob.subarray(magic.length, magic.length + 32), ciphertext = blob.subarray(magic.length + 32);
6571
+ if (ciphertext.length % 16 !== 0) throw new Error("Trae \u56FD\u9645\u7248\u51ED\u8BC1\u5BC6\u6587\u957F\u5EA6\u65E0\u6548");
6572
+ let jg = [82, 9, 106, 213, 48, 54, 165, 56, 191, 64, 163, 158, 129, 243, 215, 251, 124, 227, 57, 130, 155, 47, 255, 135, 52, 142, 67, 68, 196, 222, 233, 203, 84, 123, 148, 50, 166, 194, 35, 61, 238, 76, 149, 11, 66, 250, 195, 78, 8, 46, 161, 102, 40, 217, 36, 178, 118, 91, 162, 73, 109, 139, 209, 37], kg = [31, 221, 168, 51, 136, 7, 199, 49, 177, 18, 16, 89, 39, 128, 236, 95, 96, 81, 127, 169, 25, 181, 74, 13, 45, 229, 122, 159, 147, 201, 156, 239, 160, 224, 59, 77, 174, 42, 245, 176, 200, 235, 187, 60, 131, 83, 153, 97, 23, 43, 4, 126, 186, 119, 214, 38, 225, 105, 20, 99, 85, 33, 12, 125], password = Buffer.from(jg.map((value, index) => value ^ kg[index])), saltHash = createHash3("sha512").update(salt).digest(), derived = createHash3("sha512").update(Buffer.concat([saltHash, password])).digest(), decipher = createDecipheriv("aes-128-cbc", derived.subarray(0, 16), derived.subarray(16, 32)), plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
6573
+ if (plaintext.length < 64) throw new Error("Trae \u56FD\u9645\u7248\u51ED\u8BC1\u660E\u6587\u957F\u5EA6\u65E0\u6548");
6574
+ let expectedHash = plaintext.subarray(0, 64), data = plaintext.subarray(64), actualHash = createHash3("sha512").update(data).digest();
6575
+ if (!timingSafeEqual(expectedHash, actualHash)) throw new Error("Trae \u56FD\u9645\u7248\u51ED\u8BC1\u5B8C\u6574\u6027\u6821\u9A8C\u5931\u8D25");
6576
+ return data.toString("utf8");
6577
+ }
6578
+ async function exchangeCredentials(credentials, fetchImpl) {
6579
+ if (!credentials.refreshToken) throw new Error("Trae \u56FD\u9645\u7248 refresh token \u4E0D\u53EF\u7528");
6580
+ if (credentials.refreshExpiredAt && isExpired(credentials.refreshExpiredAt, 864e5))
6581
+ throw new Error("Trae \u56FD\u9645\u7248 refresh token \u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55\u5BA2\u6237\u7AEF");
6582
+ let response = await requestJson2(
6583
+ `${normalizeHost(credentials.host)}${EXCHANGE_TOKEN_PATH}`,
6584
+ {
6585
+ method: "POST",
6586
+ headers: {
6587
+ "Content-Type": "application/json",
6588
+ "x-cloudide-token": credentials.token
6589
+ },
6590
+ body: JSON.stringify({
6591
+ ClientID: credentials.clientId,
6592
+ RefreshToken: credentials.refreshToken,
6593
+ ClientSecret: "-",
6594
+ UserID: ""
6595
+ })
6596
+ },
6597
+ fetchImpl,
6598
+ 15e3
6599
+ ), result = isRecord3(response.Result) ? response.Result : {}, token = stringValue5(result.Token);
6600
+ if (!token) throw new Error("Trae \u56FD\u9645\u7248\u5237\u65B0\u63A5\u53E3\u6CA1\u6709\u8FD4\u56DE Token");
6601
+ return {
6602
+ ...credentials,
6603
+ token,
6604
+ refreshToken: stringValue5(result.RefreshToken) || credentials.refreshToken,
6605
+ expiredAt: epochMsToIso(result.TokenExpireAt),
6606
+ refreshExpiredAt: epochMsToIso(result.RefreshExpireAt)
6607
+ };
6608
+ }
6609
+ async function fetchUsagePages(host, token, startTime, endTime, fetchImpl) {
6610
+ let all = [];
6611
+ for (let page = 1; page <= 500; page += 1) {
6612
+ let response = await requestJson2(
6613
+ `${normalizeHost(host)}${USAGE_PATH}`,
6614
+ {
6615
+ method: "POST",
6616
+ headers: {
6617
+ "Content-Type": "application/json",
6618
+ authorization: `Cloud-IDE-JWT ${token}`
6619
+ },
6620
+ body: JSON.stringify({
6621
+ start_time: startTime,
6622
+ end_time: endTime,
6623
+ page_size: PAGE_SIZE,
6624
+ page_num: page,
6625
+ usage_type: [5, 6]
6626
+ })
6627
+ },
6628
+ fetchImpl,
6629
+ 3e4
6630
+ ), batch = Array.isArray(response.user_usage_group_by_sessions) ? response.user_usage_group_by_sessions.filter(isRecord3) : [];
6631
+ all.push(...batch);
6632
+ let total = positiveInteger(response.total);
6633
+ if (batch.length === 0 || total != null && all.length >= total) break;
6634
+ await delay2(PAGE_DELAY_MS);
6635
+ }
6636
+ return all;
6637
+ }
6638
+ var TraeIntlHttpError = class extends Error {
6639
+ constructor(status, message) {
6640
+ super(message);
6641
+ this.status = status;
6642
+ }
6643
+ };
6644
+ async function requestJson2(url, init, fetchImpl, timeoutMs) {
6645
+ let controller = new AbortController(), timer = setTimeout(() => controller.abort(), timeoutMs);
6646
+ try {
6647
+ let response = await fetchImpl(url, { ...init, signal: controller.signal }), text = await response.text();
6648
+ if (!response.ok)
6649
+ throw new TraeIntlHttpError(response.status, `Trae \u56FD\u9645\u7248\u63A5\u53E3\u8FD4\u56DE ${response.status}: ${sanitizeResponse(text)}`);
6650
+ try {
6651
+ return JSON.parse(text);
6652
+ } catch {
6653
+ throw new Error("Trae \u56FD\u9645\u7248\u63A5\u53E3\u8FD4\u56DE\u4E86\u65E0\u6548 JSON");
6654
+ }
6655
+ } finally {
6656
+ clearTimeout(timer);
6657
+ }
6658
+ }
6659
+ async function loadCredentials(variant, cacheDir) {
6660
+ return readCredentialFile(join24(dirname8(cacheDir), `credentials-${variant}.json`), variant);
6661
+ }
6662
+ async function loadTokscaleCredentials(variant) {
6663
+ let root = dirname8(resolveTokscaleTraeCacheDir());
6664
+ return readCredentialFile(join24(root, `credentials-${variant}.json`), variant);
6665
+ }
6666
+ async function readCredentialFile(path, fallbackVariant) {
6667
+ try {
6668
+ let raw = JSON.parse(await readFile20(path, "utf8")), token = stringValue5(raw.token);
6669
+ if (!token) return null;
6670
+ let serializedVariant = stringValue5(raw.variant).toLowerCase();
6671
+ return {
6672
+ variant: serializedVariant === "solo" ? "solo" : serializedVariant === "ide" ? "ide" : fallbackVariant,
6673
+ token,
6674
+ refreshToken: stringValue5(raw.refreshToken) || stringValue5(raw.refresh_token),
6675
+ expiredAt: stringValue5(raw.expiredAt) || stringValue5(raw.expired_at),
6676
+ refreshExpiredAt: stringValue5(raw.refreshExpiredAt) || stringValue5(raw.refresh_expired_at),
6677
+ host: normalizeHost(stringValue5(raw.host) || DEFAULT_HOST),
6678
+ clientId: stringValue5(raw.clientId) || stringValue5(raw.client_id) || CLIENT_IDS[fallbackVariant],
6679
+ userId: stringValue5(raw.userId) || stringValue5(raw.user_id) || void 0
6680
+ };
6681
+ } catch {
6682
+ return null;
6683
+ }
6684
+ }
6685
+ async function saveCredentials(credentials, cacheDir) {
6686
+ let path = join24(dirname8(cacheDir), `credentials-${credentials.variant}.json`);
6687
+ await writePrivateJson(path, credentials);
6688
+ }
6689
+ async function readSessionArray(path) {
6690
+ try {
6691
+ let value = JSON.parse(await readFile20(path, "utf8"));
6692
+ return Array.isArray(value) ? value.filter(isRecord3) : [];
6693
+ } catch {
6694
+ return [];
6695
+ }
6696
+ }
6697
+ async function writePrivateJson(path, value) {
6698
+ let dir = dirname8(path);
6699
+ await mkdir5(dir, { recursive: !0, mode: 448 }), await chmod(dir, 448).catch(() => {
6700
+ });
6701
+ let tempPath = join24(dir, `.${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}.tmp`), handle = await open4(tempPath, "w", 384);
6702
+ try {
6703
+ await handle.writeFile(`${JSON.stringify(value, null, 2)}
6704
+ `, "utf8");
6705
+ } finally {
6706
+ await handle.close();
6707
+ }
6708
+ await rename2(tempPath, path), await chmod(path, 384).catch(() => {
6709
+ });
6710
+ }
6711
+ function normalizeSinceDays(value) {
6712
+ if (value == null) return DEFAULT_SINCE_DAYS;
6713
+ if (!Number.isInteger(value) || value <= 0 || value > 3650)
6714
+ throw new Error("--since \u5FC5\u987B\u662F 1 \u5230 3650 \u4E4B\u95F4\u7684\u6574\u6570\u5929\u6570");
6715
+ return value;
6716
+ }
6717
+ function normalizeHost(value) {
6718
+ let normalized = value.trim().replace(/\/+$/, ""), url;
6719
+ try {
6720
+ url = new URL(normalized);
6721
+ } catch {
6722
+ throw new Error("Trae \u56FD\u9645\u7248 API host \u65E0\u6548");
6723
+ }
6724
+ if (url.protocol !== "https:") throw new Error("Trae \u56FD\u9645\u7248 API host \u5FC5\u987B\u4F7F\u7528 HTTPS");
6725
+ return url.origin;
6726
+ }
6727
+ function stripAuthorizationPrefix(value) {
6728
+ return value.replace(/^(?:Cloud-IDE-JWT|Bearer)\s+/i, "").trim();
6729
+ }
6730
+ function isExpired(value, marginMs) {
6731
+ let timestamp = Date.parse(value);
6732
+ return !Number.isFinite(timestamp) || Date.now() >= timestamp - marginMs;
6733
+ }
6734
+ function epochMsToIso(value) {
6735
+ let timestamp = Number(value);
6736
+ return Number.isFinite(timestamp) && timestamp > 0 ? new Date(timestamp).toISOString() : "";
6737
+ }
6738
+ function tokenValue3(value) {
6739
+ let number = Number(value);
6740
+ return Number.isFinite(number) && number > 0 ? Math.floor(number) : 0;
6741
+ }
6742
+ function positiveNumber2(value) {
6743
+ let number = Number(value);
6744
+ return Number.isFinite(number) && number > 0 ? number : 0;
6745
+ }
6746
+ function positiveInteger(value) {
6747
+ let number = Number(value);
6748
+ return Number.isInteger(number) && number >= 0 ? number : void 0;
6749
+ }
6750
+ function sessionWeight(session) {
6751
+ let extra = session.extra_info ?? {};
6752
+ return tokenValue3(extra.input_token) + tokenValue3(extra.output_token) + tokenValue3(extra.cache_read_token) + tokenValue3(extra.cache_write_token);
6753
+ }
6754
+ function stringValue5(value) {
6755
+ return typeof value == "string" ? value.trim() : "";
6756
+ }
6757
+ function isRecord3(value) {
6758
+ return value != null && typeof value == "object" && !Array.isArray(value);
6759
+ }
6760
+ function sanitizeResponse(value) {
6761
+ return value.replace(/[\r\n\t]+/g, " ").replace(/("(?:token|refreshToken|RefreshToken|Token)"\s*:\s*")[^"]+("?)/gi, "$1[redacted]$2").replace(/eyJ[A-Za-z0-9_.-]+/g, "[token]").replace(/[A-Za-z0-9_-]{80,}/g, "[redacted]").slice(0, 300);
6762
+ }
6763
+ function sanitizeError(error) {
6764
+ let parts = [], current = error;
6765
+ for (let depth = 0; depth < 3 && current != null; depth += 1) {
6766
+ let message = current instanceof Error ? current.message : String(current);
6767
+ message && !parts.includes(message) && parts.push(message), isRecord3(current) && stringValue5(current.code) && parts.push(stringValue5(current.code)), current = isRecord3(current) ? current.cause : void 0;
6768
+ }
6769
+ return sanitizeResponse(parts.join(": "));
6770
+ }
6771
+ function delay2(ms) {
6772
+ return new Promise((resolve5) => setTimeout(resolve5, ms));
6773
+ }
6774
+
6342
6775
  // src/cli.ts
6343
6776
  var argv = process.argv.slice(2), command = argv[0];
6344
6777
  await (async () => {
@@ -6376,7 +6809,7 @@ await (async () => {
6376
6809
  await runTraeSync(parsed.flags, parsed.positionals);
6377
6810
  else {
6378
6811
  let zh2 = (await readConfig()).lang === "zh";
6379
- throw new Error(zh2 ? "\u7528\u6CD5: aiusage trae sync [--port 9230] [--no-launch] [--json]" : "Usage: aiusage trae sync [--port 9230] [--no-launch] [--json]");
6812
+ throw new Error(zh2 ? "\u7528\u6CD5: aiusage trae sync [--edition cn|intl|all] [--since 180] [--port 9230] [--no-launch] [--json]" : "Usage: aiusage trae sync [--edition cn|intl|all] [--since 180] [--port 9230] [--no-launch] [--json]");
6380
6813
  }
6381
6814
  } else if (command === "init") {
6382
6815
  let parsed = parseArgs(argv.slice(1));
@@ -6451,7 +6884,7 @@ await (async () => {
6451
6884
  async function runScan(flags, positionals = []) {
6452
6885
  let config = await readConfig(), zh2 = config.lang === "zh";
6453
6886
  assertNoPositionals("scan", positionals, zh2);
6454
- let isJson = !!flags.json, dates = resolveScanDates(flags, config), results = dates.length === 1 ? [await scanDate(dates[0], { projectAliases: config.projectAliases })] : await scanDates(dates, { projectAliases: config.projectAliases });
6887
+ let isJson = !!flags.json, dates = resolveScanDates(flags, config), tools = parseToolSelection(flags.tool, zh2), results = dates.length === 1 ? [await scanDate(dates[0], { projectAliases: config.projectAliases, tools })] : await scanDates(dates, { projectAliases: config.projectAliases, tools });
6455
6888
  if (isJson) {
6456
6889
  console.log(JSON.stringify(results.length === 1 ? results[0] : results, null, 2));
6457
6890
  return;
@@ -6490,14 +6923,15 @@ function printScanResult(result, zh2) {
6490
6923
  console.log("\u2500\u2500 \u5408\u8BA1 \u2500\u2500"), console.log(` \u4E8B\u4EF6: ${result.totals.eventCount} \u8F93\u5165: ${fmt2(result.totals.inputTokens)} \u7F13\u5B58\u8BFB: ${fmt2(result.totals.cachedInputTokens)} \u7F13\u5B58\u5199: ${fmt2(result.totals.cacheWriteTokens)} \u8F93\u51FA: ${fmt2(result.totals.outputTokens)} \u63A8\u7406: ${fmt2(result.totals.reasoningOutputTokens)}`), console.log();
6491
6924
  }
6492
6925
  async function runReport(flags, positionals = []) {
6493
- let config = await readConfig();
6494
- assertNoPositionals("report", positionals, config.lang === "zh");
6495
- let { dates, range } = resolveDateParams(flags, config), targetName = resolveOptionalString(flags.target, void 0), pricingTarget = targetName ? findTargetOrThrow(config, targetName) : config.targets?.[0], pricing = await resolvePricingCatalog(config, {
6926
+ let config = await readConfig(), zh2 = config.lang === "zh";
6927
+ assertNoPositionals("report", positionals, zh2);
6928
+ let { dates, range } = resolveDateParams(flags, config), tools = parseToolSelection(flags.tool, zh2), targetName = resolveOptionalString(flags.target, void 0), pricingTarget = targetName ? findTargetOrThrow(config, targetName) : config.targets?.[0], pricing = await resolvePricingCatalog(config, {
6496
6929
  explicitUrl: resolveOptionalString(flags["pricing-url"], void 0),
6497
6930
  target: pricingTarget
6498
6931
  }), report = await buildLocalReport(range, {
6499
6932
  projectAliases: config.projectAliases,
6500
6933
  dates,
6934
+ tools,
6501
6935
  pricingCatalog: pricing.catalog,
6502
6936
  pricingInfo: pricing.info
6503
6937
  });
@@ -6567,7 +7001,8 @@ function prompt(question) {
6567
7001
  }
6568
7002
  async function runSync(flags, positionals = []) {
6569
7003
  let config = await readConfig();
6570
- assertNoPositionals("sync", positionals, config.lang === "zh");
7004
+ if (assertNoPositionals("sync", positionals, config.lang === "zh"), flags.tool != null)
7005
+ throw new Error(config.lang === "zh" ? "--tool \u4EC5\u7528\u4E8E scan/report\uFF1Bsync \u59CB\u7EC8\u4E0A\u4F20\u6240\u9009\u65E5\u671F\u7684\u5B8C\u6574\u5FEB\u7167" : "--tool is only available for scan/report; sync always uploads complete daily snapshots");
6571
7006
  let allTargets = config.targets ?? [];
6572
7007
  if (allTargets.length === 0)
6573
7008
  throw new Error("\u672A\u914D\u7F6E\u4EFB\u4F55\u4E0A\u62A5\u76EE\u6807\uFF0C\u8BF7\u5148\u6267\u884C aiusage enroll");
@@ -6621,18 +7056,49 @@ async function runTraeSync(flags, positionals = []) {
6621
7056
  assertNoPositionals("trae sync", positionals, zh2);
6622
7057
  let portFlag = resolveOptionalString(flags.port, void 0), port = portFlag ? parsePositiveInt2(portFlag, "--port") : void 0;
6623
7058
  if (port != null && port > 65535) throw new Error("--port \u5FC5\u987B\u5728 1 \u5230 65535 \u4E4B\u95F4");
6624
- flags.json || console.log(zh2 ? "\u6B63\u5728\u901A\u8FC7 Trae CN \u5B98\u65B9\u672C\u5730\u63A5\u53E3\u540C\u6B65\u5386\u53F2\u7528\u91CF\u2026" : "Syncing Trae CN history through its official local interface\u2026");
6625
- let result = await syncTraeCnUsage({
6626
- port,
6627
- appPath: resolveOptionalString(flags.app, void 0),
6628
- launch: flags["no-launch"] !== !0
6629
- });
7059
+ let edition = parseTraeEdition(flags.edition, zh2), sinceFlag = resolveOptionalString(flags.since, void 0), sinceDays = sinceFlag ? parsePositiveInt2(sinceFlag, "--since") : void 0;
7060
+ flags.json || ((edition === "cn" || edition === "all") && console.log(zh2 ? "\u6B63\u5728\u901A\u8FC7 Trae CN \u5B98\u65B9\u672C\u5730\u63A5\u53E3\u540C\u6B65\u5386\u53F2\u7528\u91CF\u2026" : "Syncing Trae CN history through its official local interface\u2026"), (edition === "intl" || edition === "all") && console.log(zh2 ? "\u6B63\u5728\u901A\u8FC7 Trae \u56FD\u9645\u7248\u5B98\u65B9\u8D26\u53F7 API \u540C\u6B65\u7528\u91CF\u2026" : "Syncing Trae International account usage through its official API\u2026"));
7061
+ let cnResult, intlResult, warnings = [];
7062
+ if (edition === "cn" || edition === "all")
7063
+ try {
7064
+ cnResult = await syncTraeCnUsage({
7065
+ port,
7066
+ appPath: resolveOptionalString(flags.app, void 0),
7067
+ launch: flags["no-launch"] !== !0
7068
+ });
7069
+ } catch (error) {
7070
+ if (edition === "cn") throw error;
7071
+ warnings.push(`Trae CN: ${error instanceof Error ? error.message : String(error)}`);
7072
+ }
7073
+ if (edition === "intl" || edition === "all")
7074
+ try {
7075
+ intlResult = await syncTraeIntlUsage({ sinceDays });
7076
+ } catch (error) {
7077
+ if (edition === "intl") throw error;
7078
+ warnings.push(`Trae International: ${error instanceof Error ? error.message : String(error)}`);
7079
+ }
7080
+ if (!cnResult && !intlResult) throw new Error(warnings.join(`
7081
+ `) || "\u6CA1\u6709\u53EF\u540C\u6B65\u7684 Trae \u6570\u636E\u6E90");
6630
7082
  if (flags.json) {
6631
- console.log(JSON.stringify(result, null, 2));
7083
+ console.log(JSON.stringify(edition === "cn" ? cnResult : edition === "intl" ? intlResult : {
7084
+ edition: "all",
7085
+ cn: cnResult,
7086
+ intl: intlResult,
7087
+ warnings
7088
+ }, null, 2));
6632
7089
  return;
6633
7090
  }
6634
- console.log(zh2 ? `\u5DF2\u540C\u6B65 ${result.sessions} \u4E2A\u4F1A\u8BDD\u3001${result.events} \u6761\u7528\u91CF\u8BB0\u5F55\uFF0C\u5171 ${fmt2(result.totals.totalTokens)} tokens\u3002` : `Synced ${result.sessions} sessions and ${result.events} usage records (${fmt2(result.totals.totalTokens)} tokens).`), console.log(`${zh2 ? "\u7F13\u5B58" : "Cache"}: ${result.cacheDir}`);
6635
- for (let warning of result.warnings) console.warn(`${zh2 ? "\u8B66\u544A" : "Warning"}: ${warning}`);
7091
+ if (cnResult) {
7092
+ console.log(zh2 ? `Trae CN\uFF1A\u5DF2\u540C\u6B65 ${cnResult.sessions} \u4E2A\u4F1A\u8BDD\u3001${cnResult.events} \u6761\u7528\u91CF\u8BB0\u5F55\uFF0C\u5171 ${fmt2(cnResult.totals.totalTokens)} tokens\u3002` : `Trae CN: synced ${cnResult.sessions} sessions and ${cnResult.events} usage records (${fmt2(cnResult.totals.totalTokens)} tokens).`), console.log(`${zh2 ? "\u7F13\u5B58" : "Cache"}: ${cnResult.cacheDir}`);
7093
+ for (let warning of cnResult.warnings) warnings.push(`Trae CN: ${warning}`);
7094
+ }
7095
+ intlResult && (console.log(zh2 ? `Trae \u56FD\u9645\u7248\uFF1A\u672C\u6B21\u83B7\u53D6 ${intlResult.fetchedSessions} \u4E2A\u4F1A\u8BDD\uFF0C\u7F13\u5B58\u5171 ${intlResult.storedSessions} \u4E2A\u4F1A\u8BDD\u3001${fmt2(intlResult.totals.totalTokens)} tokens\u3002` : `Trae International: fetched ${intlResult.fetchedSessions} sessions; cache now contains ${intlResult.storedSessions} sessions (${fmt2(intlResult.totals.totalTokens)} tokens).`), console.log(`${zh2 ? "\u7F13\u5B58" : "Cache"}: ${intlResult.cacheDir}`));
7096
+ for (let warning of warnings) console.warn(`${zh2 ? "\u8B66\u544A" : "Warning"}: ${warning}`);
7097
+ }
7098
+ function parseTraeEdition(value, zh2) {
7099
+ if (value == null) return "cn";
7100
+ if (value === "cn" || value === "intl" || value === "all") return value;
7101
+ throw new Error(zh2 ? "--edition \u4EC5\u652F\u6301 cn\u3001intl\u3001all" : "--edition only supports cn, intl, or all");
6636
7102
  }
6637
7103
  function buildActivityPayloadByDate(items, visibility) {
6638
7104
  let map = /* @__PURE__ */ new Map(), sanitized = applyProjectPrivacy(items, visibility);
@@ -6832,11 +7298,11 @@ function printHelp(zh2 = !1) {
6832
7298
  console.log(`aiusage v${getVersion()}
6833
7299
  `);
6834
7300
  let cmds = zh2 ? [
6835
- ["scan [--date YYYY-MM-DD|--today|--range 7d|1m|3m] [--json]", "\u626B\u63CF\u7528\u91CF\u660E\u7EC6"],
6836
- ["report [--today] [--range 7d|1m|3m|all] [--detail] [--json]", "\u672C\u5730\u7528\u91CF\u62A5\u544A"],
6837
- ["activity [--today] [--range 7d|1m|3m|all] [--detail] [--json]", "\u672C\u5730\u4EA4\u4E92\u6307\u6807"],
6838
- ["sync [--today] [--range 7d|1m|3m]", "\u4E0A\u4F20\u7528\u91CF\u5230\u670D\u52A1\u7AEF"],
6839
- ["trae sync [--port 9230] [--no-launch]", "\u540C\u6B65 Trae CN \u672C\u5730\u5386\u53F2\u7528\u91CF"],
7301
+ ["scan [--tool \u5DE5\u5177] [--date YYYY-MM-DD|--today|--range 7d|1m|3m|6m] [--json]", "\u626B\u63CF\u7528\u91CF\u660E\u7EC6"],
7302
+ ["report [--tool \u5DE5\u5177] [--range 7d|1m|3m|6m|all] [--detail] [--json]", "\u672C\u5730\u7528\u91CF\u62A5\u544A"],
7303
+ ["activity [--today] [--range 7d|1m|3m|6m|all] [--detail] [--json]", "\u672C\u5730\u4EA4\u4E92\u6307\u6807"],
7304
+ ["sync [--today] [--range 7d|1m|3m|6m]", "\u4E0A\u4F20\u7528\u91CF\u5230\u670D\u52A1\u7AEF"],
7305
+ ["trae sync [--edition cn|intl|all] [--since 180]", "\u540C\u6B65 Trae CN/\u56FD\u9645\u7248\u7528\u91CF"],
6840
7306
  ["scan/report/sync --from YYYY-MM-DD [--to YYYY-MM-DD]", "\u6307\u5B9A\u65E5\u671F\u8303\u56F4\uFF08--start/--end \u540C\u4E49\uFF09"],
6841
7307
  ["project [list|alias]", "\u9879\u76EE\u7BA1\u7406\u4E0E\u522B\u540D\u8BBE\u7F6E"],
6842
7308
  ["pricing [status|update] [--url URL]", "\u67E5\u770B/\u66F4\u65B0\u5B9A\u4EF7\u76EE\u5F55"],
@@ -6847,11 +7313,11 @@ function printHelp(zh2 = !1) {
6847
7313
  ["enroll --server URL --site-id ID --enroll-token TOKEN", "\u6CE8\u518C\u8BBE\u5907\u5230\u670D\u52A1\u7AEF"],
6848
7314
  ["health [--server URL]", "\u6D4B\u8BD5\u670D\u52A1\u7AEF\u8FDE\u901A\u6027"]
6849
7315
  ] : [
6850
- ["scan [--date YYYY-MM-DD|--today|--range 7d|1m|3m] [--json]", "Scan usage breakdown"],
6851
- ["report [--today] [--range 7d|1m|3m|all] [--detail] [--json]", "Local usage report"],
6852
- ["activity [--today] [--range 7d|1m|3m|all] [--detail] [--json]", "Local interaction metrics"],
6853
- ["sync [--today] [--range 7d|1m|3m]", "Upload usage to server"],
6854
- ["trae sync [--port 9230] [--no-launch]", "Sync local Trae CN history"],
7316
+ ["scan [--tool TOOL] [--date YYYY-MM-DD|--today|--range 7d|1m|3m|6m] [--json]", "Scan usage breakdown"],
7317
+ ["report [--tool TOOL] [--range 7d|1m|3m|6m|all] [--detail] [--json]", "Local usage report"],
7318
+ ["activity [--today] [--range 7d|1m|3m|6m|all] [--detail] [--json]", "Local interaction metrics"],
7319
+ ["sync [--today] [--range 7d|1m|3m|6m]", "Upload usage to server"],
7320
+ ["trae sync [--edition cn|intl|all] [--since 180]", "Sync Trae CN/International usage"],
6855
7321
  ["scan/report/sync --from YYYY-MM-DD [--to YYYY-MM-DD]", "Date range (--start/--end aliases)"],
6856
7322
  ["project [list|alias]", "Project management & aliases"],
6857
7323
  ["pricing [status|update] [--url URL]", "Pricing catalog management"],
@@ -6871,22 +7337,22 @@ function printUsageHint(zh2 = !1) {
6871
7337
  console.log(`aiusage v${getVersion()}
6872
7338
  `);
6873
7339
  let cmds = zh2 ? [
6874
- ["scan [--date YYYY-MM-DD|--range 1m]", "\u626B\u63CF\u7528\u91CF\u660E\u7EC6"],
6875
- ["report [--today] [--range 7d|1m|3m|all]", "\u672C\u5730\u7528\u91CF\u62A5\u544A"],
6876
- ["activity [--range 7d|1m|3m|all]", "\u672C\u5730\u4EA4\u4E92\u6307\u6807"],
6877
- ["sync [--today] [--range 7d|1m|3m]", "\u4E0A\u4F20\u7528\u91CF\u5230\u670D\u52A1\u7AEF"],
6878
- ["trae sync", "\u540C\u6B65 Trae CN \u672C\u5730\u5386\u53F2\u7528\u91CF"],
7340
+ ["scan [--tool \u5DE5\u5177] [--date YYYY-MM-DD|--range 1m|6m]", "\u626B\u63CF\u7528\u91CF\u660E\u7EC6"],
7341
+ ["report [--tool \u5DE5\u5177] [--range 7d|1m|3m|6m|all]", "\u672C\u5730\u7528\u91CF\u62A5\u544A"],
7342
+ ["activity [--range 7d|1m|3m|6m|all]", "\u672C\u5730\u4EA4\u4E92\u6307\u6807"],
7343
+ ["sync [--today] [--range 7d|1m|3m|6m]", "\u4E0A\u4F20\u7528\u91CF\u5230\u670D\u52A1\u7AEF"],
7344
+ ["trae sync [--edition cn|intl|all]", "\u540C\u6B65 Trae CN/\u56FD\u9645\u7248\u7528\u91CF"],
6879
7345
  ["project [list|alias]", "\u9879\u76EE\u7BA1\u7406\u4E0E\u522B\u540D\u8BBE\u7F6E"],
6880
7346
  ["pricing [status|update]", "\u67E5\u770B/\u66F4\u65B0\u5B9A\u4EF7\u76EE\u5F55"],
6881
7347
  ["schedule [on|off|status]", "\u5B9A\u65F6\u540C\u6B65\u7BA1\u7406"],
6882
7348
  ["doctor", "\u8BCA\u65AD\u68C0\u67E5"],
6883
7349
  ["config set <key> <value>", "\u4FEE\u6539\u914D\u7F6E"]
6884
7350
  ] : [
6885
- ["scan [--date YYYY-MM-DD|--range 1m]", "Scan usage breakdown"],
6886
- ["report [--today] [--range 7d|1m|3m|all]", "Local usage report"],
6887
- ["activity [--range 7d|1m|3m|all]", "Local interaction metrics"],
6888
- ["sync [--today] [--range 7d|1m|3m]", "Upload usage to server"],
6889
- ["trae sync", "Sync local Trae CN history"],
7351
+ ["scan [--tool TOOL] [--date YYYY-MM-DD|--range 1m|6m]", "Scan usage breakdown"],
7352
+ ["report [--tool TOOL] [--range 7d|1m|3m|6m|all]", "Local usage report"],
7353
+ ["activity [--range 7d|1m|3m|6m|all]", "Local interaction metrics"],
7354
+ ["sync [--today] [--range 7d|1m|3m|6m]", "Upload usage to server"],
7355
+ ["trae sync [--edition cn|intl|all]", "Sync Trae CN/International usage"],
6890
7356
  ["project [list|alias]", "Project management & aliases"],
6891
7357
  ["pricing [status|update]", "Pricing catalog management"],
6892
7358
  ["schedule [on|off|status]", "Scheduled sync management"],
@@ -6947,7 +7413,7 @@ function resolveDateParams(flags, config) {
6947
7413
  let rangeFlag = flags.range;
6948
7414
  if (typeof rangeFlag == "string") {
6949
7415
  let range = parseReportRange(rangeFlag);
6950
- return range === "today" ? { dates: [getTodayDate()], range } : range === "7d" ? { dates: [...getClosedDates(6), getTodayDate()], range } : range === "1m" ? { dates: [...getClosedDates(29), getTodayDate()], range } : range === "3m" ? { dates: [...getClosedDates(89), getTodayDate()], range } : { range };
7416
+ return range === "today" ? { dates: [getTodayDate()], range } : range === "7d" ? { dates: [...getClosedDates(6), getTodayDate()], range } : range === "1m" ? { dates: [...getClosedDates(29), getTodayDate()], range } : range === "3m" ? { dates: [...getClosedDates(89), getTodayDate()], range } : range === "6m" ? { dates: [...getClosedDates(179), getTodayDate()], range } : { range };
6951
7417
  }
6952
7418
  if (typeof flags.lookback == "string") {
6953
7419
  let lookbackDays2 = parsePositiveInt2(flags.lookback, "--lookback"), dates2 = getClosedDates(lookbackDays2);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aiusage/cli",
3
- "version": "1.7.5",
3
+ "version": "1.7.6",
4
4
  "description": "Track and sync AI tool token usage across devices.",
5
5
  "license": "MIT",
6
6
  "private": false,
@@ -21,6 +21,7 @@
21
21
  "dist",
22
22
  "pricing-catalog.json",
23
23
  "README.md",
24
+ "THIRD_PARTY_NOTICES.md",
24
25
  "LICENSE"
25
26
  ],
26
27
  "bin": {