@aiusage/cli 1.7.4 → 1.7.5

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/dist/cli.js CHANGED
@@ -3101,12 +3101,12 @@ async function queryOpenCodeSqlite(dbPath) {
3101
3101
  return [];
3102
3102
  }
3103
3103
  function runSqlite(args) {
3104
- return new Promise((resolve4, reject) => {
3104
+ return new Promise((resolve5, reject) => {
3105
3105
  execFile(
3106
3106
  "sqlite3",
3107
3107
  args,
3108
3108
  { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 },
3109
- (error, stdout) => error ? reject(error) : resolve4(stdout)
3109
+ (error, stdout) => error ? reject(error) : resolve5(stdout)
3110
3110
  );
3111
3111
  });
3112
3112
  }
@@ -3253,6 +3253,180 @@ function extractProjectFromEncoded(encoded) {
3253
3253
  return parts.length > 0 ? parts[parts.length - 1] : "unknown";
3254
3254
  }
3255
3255
 
3256
+ // src/scanners/trae.ts
3257
+ import { readFile as readFile12 } from "node:fs/promises";
3258
+ import { homedir as homedir14 } from "node:os";
3259
+ import { join as join15, resolve as resolve2 } from "node:path";
3260
+ function resolveTraeNativeCacheDir(home = homedir14()) {
3261
+ let explicit = process.env.AIUSAGE_TRAE_CACHE_DIR?.trim();
3262
+ return explicit ? resolve2(explicit) : join15(home, ".aiusage", "trae-cache", "sessions");
3263
+ }
3264
+ function resolveTokscaleTraeCacheDir(home = homedir14()) {
3265
+ let configDir = process.env.TOKSCALE_CONFIG_DIR?.trim();
3266
+ return configDir ? join15(resolve2(configDir), "trae-cache", "sessions") : join15(home, ".config", "tokscale", "trae-cache", "sessions");
3267
+ }
3268
+ async function scanTraeDates(targetDates, options = {}) {
3269
+ let dates = new Set(targetDates);
3270
+ if (dates.size === 0) return /* @__PURE__ */ new Map();
3271
+ let nativeDir = options.nativeCacheDir ?? resolveTraeNativeCacheDir(), tokscaleDir = options.tokscaleCacheDir ?? resolveTokscaleTraeCacheDir(), cacheSources = [.../* @__PURE__ */ new Set([
3272
+ `${nativeDir}\0native`,
3273
+ `${tokscaleDir}\0tokscale`
3274
+ ])], files = (await Promise.all(cacheSources.map(async (source) => {
3275
+ let [dir, kind] = source.split("\0");
3276
+ return (await walkFiles(dir, ".json")).map((filePath) => ({ filePath, kind }));
3277
+ }))).flat();
3278
+ if (files.length === 0) return emptyResult(dates);
3279
+ let grouped = initDateMap(dates), seenEvents = /* @__PURE__ */ new Set(), sessionSets = /* @__PURE__ */ new Map();
3280
+ for (let { filePath, kind } of files) {
3281
+ let value = await readJson2(filePath);
3282
+ if (value == null) continue;
3283
+ let events = kind === "native" ? parseNativeCache(value) : parseTokscaleCache(value);
3284
+ 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);
3317
+ }
3318
+ }
3319
+ let result = finalize(grouped);
3320
+ for (let [usageDate, breakdowns] of result)
3321
+ for (let breakdown of breakdowns) {
3322
+ let key = `${usageDate}|${breakdown.provider}|${breakdown.model}|${breakdown.project}`;
3323
+ breakdown.sessionCount = sessionSets.get(key)?.size ?? 0;
3324
+ }
3325
+ return result;
3326
+ }
3327
+ function parseNativeCache(value) {
3328
+ if (!isRecord2(value) || value.schemaVersion !== 1 || value.source !== "trae-cn-local-rpc") return [];
3329
+ let sessionId = stringValue2(value.sessionId), project = stringValue2(value.project) || "unknown";
3330
+ if (!sessionId || !Array.isArray(value.events)) return [];
3331
+ let events = [];
3332
+ for (let raw of value.events) {
3333
+ if (!isRecord2(raw)) continue;
3334
+ let messageId = stringValue2(raw.messageId), timestamp = parseTs(raw.timestamp);
3335
+ if (!messageId || !timestamp) continue;
3336
+ let model = normalizeTraeModel(stringValue2(raw.model)), tokens = {
3337
+ input: tokenValue(raw.inputTokens),
3338
+ cached: tokenValue(raw.cachedInputTokens),
3339
+ cacheWrite: tokenValue(raw.cacheWriteTokens),
3340
+ output: tokenValue(raw.outputTokens),
3341
+ reasoning: tokenValue(raw.reasoningOutputTokens)
3342
+ };
3343
+ tokenTotal2(tokens) !== 0 && events.push({
3344
+ dedupKey: `trae-cn:${messageId}`,
3345
+ sessionId,
3346
+ timestamp,
3347
+ provider: inferProviderFromModel(model, "trae"),
3348
+ model,
3349
+ project,
3350
+ ...tokens
3351
+ });
3352
+ }
3353
+ return events;
3354
+ }
3355
+ function parseTokscaleCache(value) {
3356
+ if (!Array.isArray(value)) return [];
3357
+ let events = [];
3358
+ for (let raw of value) {
3359
+ if (!isRecord2(raw)) continue;
3360
+ let session = raw, sessionId = stringValue2(session.session_id), timestamp = parseTs(session.usage_time);
3361
+ if (!sessionId || !timestamp || !session.usage_time || session.usage_time <= 0) continue;
3362
+ let rawModel = stringValue2(session.model_name), mode = stringValue2(session.mode), model = rawModel ? normalizeTraeModel(rawModel) : mode ? `trae-${mode.toLowerCase()}` : "trae-unknown", extra = session.extra_info ?? {}, tokens = {
3363
+ input: tokenValue(extra.input_token),
3364
+ cached: tokenValue(extra.cache_read_token),
3365
+ cacheWrite: tokenValue(extra.cache_write_token),
3366
+ output: tokenValue(extra.output_token),
3367
+ reasoning: 0
3368
+ };
3369
+ tokenTotal2(tokens) !== 0 && events.push({
3370
+ dedupKey: `trae-intl:${sessionId}:${session.usage_time}`,
3371
+ sessionId,
3372
+ timestamp,
3373
+ provider: inferProviderFromModel(model, "trae"),
3374
+ model,
3375
+ project: "unknown",
3376
+ ...tokens,
3377
+ costUSD: positiveNumber(session.dollar_float)
3378
+ });
3379
+ }
3380
+ return events;
3381
+ }
3382
+ function normalizeTraeModel(name) {
3383
+ let value = name?.trim() ?? "";
3384
+ return {
3385
+ "GPT-5.4": "gpt-5.4",
3386
+ "GPT-5.3-Codex": "gpt-5.3-codex",
3387
+ "GPT-5.3 Codex": "gpt-5.3-codex",
3388
+ "GPT-5.3": "gpt-5.3",
3389
+ "GPT-5.2-Codex": "gpt-5.2-codex",
3390
+ "GPT-5.2 Codex": "gpt-5.2-codex",
3391
+ "GPT-5.2": "gpt-5.2",
3392
+ "GPT-5.1-Codex": "gpt-5.1-codex",
3393
+ "GPT-5.1 Codex": "gpt-5.1-codex",
3394
+ "GPT-5.1": "gpt-5.1",
3395
+ "Gemini 3.1 Pro": "gemini-3.1-pro",
3396
+ "Gemini 3.1": "gemini-3.1",
3397
+ "GLM 5.1": "glm-5.1",
3398
+ "GLM-5.1": "glm-5.1",
3399
+ "Claude Sonnet 4.6": "claude-sonnet-4.6",
3400
+ "Claude-Sonnet-4.6": "claude-sonnet-4.6",
3401
+ "Claude Sonnet 4.5": "claude-sonnet-4.5",
3402
+ "Claude-Sonnet-4.5": "claude-sonnet-4.5"
3403
+ }[value] ?? (value || "trae-unknown");
3404
+ }
3405
+ async function readJson2(filePath) {
3406
+ try {
3407
+ return JSON.parse(await readFile12(filePath, "utf8"));
3408
+ } catch {
3409
+ return null;
3410
+ }
3411
+ }
3412
+ function tokenValue(value) {
3413
+ let number = typeof value == "number" ? value : Number(value);
3414
+ return Number.isFinite(number) && number > 0 ? Math.floor(number) : 0;
3415
+ }
3416
+ function positiveNumber(value) {
3417
+ let number = typeof value == "number" ? value : Number(value);
3418
+ return Number.isFinite(number) && number > 0 ? number : void 0;
3419
+ }
3420
+ function tokenTotal2(tokens) {
3421
+ return tokens.input + tokens.cached + tokens.cacheWrite + tokens.output + tokens.reasoning;
3422
+ }
3423
+ function stringValue2(value) {
3424
+ return typeof value == "string" ? value.trim() : "";
3425
+ }
3426
+ function isRecord2(value) {
3427
+ return value != null && typeof value == "object" && !Array.isArray(value);
3428
+ }
3429
+
3256
3430
  // src/scan.ts
3257
3431
  async function scanDate(targetDate, options = {}) {
3258
3432
  let [result] = await scanDates([targetDate], options);
@@ -3278,7 +3452,8 @@ async function scanDates(targetDates, options = {}) {
3278
3452
  scanAmpDates(uniqueDates, void 0, options.projectAliases),
3279
3453
  scanDroidDates(uniqueDates, void 0, options.projectAliases),
3280
3454
  scanOpencodeDates(uniqueDates, void 0, options.projectAliases),
3281
- scanPiDates(uniqueDates, void 0, options.projectAliases)
3455
+ scanPiDates(uniqueDates, void 0, options.projectAliases),
3456
+ scanTraeDates(uniqueDates, { projectAliases: options.projectAliases })
3282
3457
  ], results = await Promise.all(scanners);
3283
3458
  return uniqueDates.map((usageDate) => {
3284
3459
  let breakdowns = results.flatMap((m) => m.get(usageDate) ?? []), totals = breakdowns.reduce(
@@ -3387,7 +3562,7 @@ function chunkDateRange(startDate, endDate) {
3387
3562
  }
3388
3563
 
3389
3564
  // src/scanners/anthropic-csv.ts
3390
- import { readFile as readFile12 } from "node:fs/promises";
3565
+ import { readFile as readFile13 } from "node:fs/promises";
3391
3566
  async function scanAnthropicCsvDates(targetDates, csvFilePaths) {
3392
3567
  if (!targetDates.length) return /* @__PURE__ */ new Map();
3393
3568
  let targetDateSet = new Set(targetDates), grouped = new Map(
@@ -3396,7 +3571,7 @@ async function scanAnthropicCsvDates(targetDates, csvFilePaths) {
3396
3571
  for (let filePath of csvFilePaths) {
3397
3572
  let content;
3398
3573
  try {
3399
- content = await readFile12(filePath, "utf-8");
3574
+ content = await readFile13(filePath, "utf-8");
3400
3575
  } catch {
3401
3576
  continue;
3402
3577
  }
@@ -3454,9 +3629,9 @@ function parseCsv(content) {
3454
3629
  }
3455
3630
 
3456
3631
  // src/report.ts
3457
- import { readdir as readdir5, readFile as readFile13 } from "node:fs/promises";
3458
- import { homedir as homedir14 } from "node:os";
3459
- import { basename as basename11, dirname as dirname6, join as join15 } from "node:path";
3632
+ import { readdir as readdir5, readFile as readFile14 } from "node:fs/promises";
3633
+ import { homedir as homedir15 } from "node:os";
3634
+ import { basename as basename11, dirname as dirname6, join as join16 } from "node:path";
3460
3635
  async function buildLocalReport(range, options = {}) {
3461
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 });
3462
3637
  for (let result of results) {
@@ -3524,24 +3699,24 @@ function buildPresetDates(range) {
3524
3699
  return result;
3525
3700
  }
3526
3701
  async function discoverAllDates() {
3527
- let dates = /* @__PURE__ */ new Set(), home = homedir14();
3702
+ let dates = /* @__PURE__ */ new Set(), home = homedir15();
3528
3703
  await Promise.all([
3529
3704
  discoverClaudeDates(dates),
3530
3705
  discoverCodexDates(dates),
3531
3706
  discoverGeminiDates(dates),
3532
3707
  discoverCopilotVscodeDates(dates),
3533
3708
  discoverAntigravityDates(dates),
3534
- discoverGenericJsonlDates(join15(home, ".copilot", "session-state"), dates),
3535
- discoverGenericJsonlDates(join15(home, ".copilot", "otel"), dates),
3536
- discoverGenericJsonlDates(join15(home, ".qwen", "tmp"), dates),
3537
- discoverGenericJsonlDates(join15(home, ".qwen", "projects"), dates),
3538
- discoverGenericJsonlDates(join15(home, ".kimi", "sessions"), dates),
3539
- discoverGenericJsonlDates(join15(resolveKimiCodeHome(home), "sessions"), dates),
3540
- discoverGenericJsonDates(join15(home, ".local", "share", "amp", "threads"), dates),
3541
- discoverGenericJsonDates(join15(home, ".factory", "sessions"), 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),
3542
3717
  discoverOpenCodeUsageDates().then((found) => found.forEach((date) => dates.add(date))),
3543
- discoverGenericJsonlDates(join15(home, ".pi", "agent", "sessions"), dates),
3544
- discoverGenericJsonlDates(join15(home, ".omp", "agent", "sessions"), dates)
3718
+ discoverGenericJsonlDates(join16(home, ".pi", "agent", "sessions"), dates),
3719
+ discoverGenericJsonlDates(join16(home, ".omp", "agent", "sessions"), dates)
3545
3720
  ]);
3546
3721
  let explicitCopilotOtel = process.env.COPILOT_OTEL_FILE_EXPORTER_PATH?.trim();
3547
3722
  return explicitCopilotOtel && await discoverJsonlFileDates(explicitCopilotOtel, dates), [...dates].sort();
@@ -3654,20 +3829,20 @@ async function walkForFiles(dir, ext, result) {
3654
3829
  return;
3655
3830
  }
3656
3831
  for (let entry of entries) {
3657
- let fullPath = join15(dir, entry.name);
3832
+ let fullPath = join16(dir, entry.name);
3658
3833
  entry.isDirectory() ? await walkForFiles(fullPath, ext, result) : entry.name.endsWith(ext) && result.push(fullPath);
3659
3834
  }
3660
3835
  }
3661
3836
  async function discoverGeminiDates(dates) {
3662
- let baseDir = join15(homedir14(), ".gemini", "tmp");
3837
+ let baseDir = join16(homedir15(), ".gemini", "tmp");
3663
3838
  await Promise.all([
3664
3839
  discoverGenericJsonDates(baseDir, dates),
3665
3840
  discoverGenericJsonlDates(baseDir, dates)
3666
3841
  ]);
3667
3842
  }
3668
3843
  async function discoverCopilotVscodeDates(dates) {
3669
- let home = homedir14(), logFiles = [];
3670
- await walkForFiles(join15(home, "Library", "Application Support", "Code", "logs"), ".log", logFiles);
3844
+ let home = homedir15(), logFiles = [];
3845
+ await walkForFiles(join16(home, "Library", "Application Support", "Code", "logs"), ".log", logFiles);
3671
3846
  for (let filePath of logFiles) {
3672
3847
  if (basename11(filePath) !== "GitHub Copilot Chat.log") continue;
3673
3848
  let content = await safeReadUtf8(filePath);
@@ -3680,7 +3855,7 @@ async function discoverCopilotVscodeDates(dates) {
3680
3855
  }
3681
3856
  }
3682
3857
  let sessionFiles = [];
3683
- await walkForFiles(join15(home, "Library", "Application Support", "Code", "User", "workspaceStorage"), ".json", sessionFiles);
3858
+ await walkForFiles(join16(home, "Library", "Application Support", "Code", "User", "workspaceStorage"), ".json", sessionFiles);
3684
3859
  for (let filePath of sessionFiles) {
3685
3860
  if (!isChatSessionFile2(filePath)) continue;
3686
3861
  let content = await safeReadUtf8(filePath);
@@ -3699,7 +3874,7 @@ async function discoverCopilotVscodeDates(dates) {
3699
3874
  }
3700
3875
  let crdtFiles = [];
3701
3876
  await walkForFiles(
3702
- join15(home, "Library", "Application Support", "Code", "User", "workspaceStorage"),
3877
+ join16(home, "Library", "Application Support", "Code", "User", "workspaceStorage"),
3703
3878
  ".jsonl",
3704
3879
  crdtFiles
3705
3880
  );
@@ -3731,8 +3906,8 @@ function isChatSessionFile2(filePath) {
3731
3906
  return basename11(dirname6(filePath)) === "chatSessions";
3732
3907
  }
3733
3908
  async function discoverAntigravityDates(dates) {
3734
- let home = homedir14(), brainFiles = [], browserFiles = [];
3735
- await walkForFiles(join15(home, ".gemini", "antigravity", "brain"), ".json", brainFiles), await walkForFiles(join15(home, ".gemini", "antigravity", "browser_recordings"), ".json", browserFiles);
3909
+ let home = homedir15(), brainFiles = [], browserFiles = [];
3910
+ await walkForFiles(join16(home, ".gemini", "antigravity", "brain"), ".json", brainFiles), await walkForFiles(join16(home, ".gemini", "antigravity", "browser_recordings"), ".json", browserFiles);
3736
3911
  for (let filePath of brainFiles) {
3737
3912
  if (basename11(filePath) !== "task.md.metadata.json") continue;
3738
3913
  let content = await safeReadUtf8(filePath);
@@ -3761,9 +3936,9 @@ async function discoverAntigravityDates(dates) {
3761
3936
  }
3762
3937
  }
3763
3938
  async function discoverClaudeDates(dates) {
3764
- let home = homedir14(), baseDirs = [
3765
- join15(home, ".config", "claude", "projects"),
3766
- join15(home, ".claude", "projects")
3939
+ let home = homedir15(), baseDirs = [
3940
+ join16(home, ".config", "claude", "projects"),
3941
+ join16(home, ".claude", "projects")
3767
3942
  ];
3768
3943
  for (let baseDir of baseDirs) {
3769
3944
  let projectDirs;
@@ -3775,7 +3950,7 @@ async function discoverClaudeDates(dates) {
3775
3950
  for (let projectDir of projectDirs) {
3776
3951
  let jsonlFiles = [];
3777
3952
  try {
3778
- await walkForClaudeJsonl(join15(baseDir, projectDir), jsonlFiles);
3953
+ await walkForClaudeJsonl(join16(baseDir, projectDir), jsonlFiles);
3779
3954
  } catch {
3780
3955
  continue;
3781
3956
  }
@@ -3799,7 +3974,7 @@ async function discoverClaudeDates(dates) {
3799
3974
  }
3800
3975
  }
3801
3976
  async function discoverCodexDates(dates) {
3802
- let baseDir = join15(homedir14(), ".codex"), files = await collectCodexSessionFiles(baseDir);
3977
+ let baseDir = join16(homedir15(), ".codex"), files = await collectCodexSessionFiles(baseDir);
3803
3978
  for (let filePath of files) {
3804
3979
  let content = await safeReadUtf8(filePath);
3805
3980
  if (content)
@@ -3821,17 +3996,17 @@ async function discoverCodexDates(dates) {
3821
3996
  async function collectCodexSessionFiles(baseDir) {
3822
3997
  let paths = [];
3823
3998
  try {
3824
- let archivedFiles = await readdir5(join15(baseDir, "archived_sessions"));
3999
+ let archivedFiles = await readdir5(join16(baseDir, "archived_sessions"));
3825
4000
  for (let file of archivedFiles)
3826
- file.endsWith(".jsonl") && paths.push(join15(baseDir, "archived_sessions", file));
4001
+ file.endsWith(".jsonl") && paths.push(join16(baseDir, "archived_sessions", file));
3827
4002
  } catch {
3828
4003
  }
3829
- return await walkForCodexJsonl(join15(baseDir, "sessions"), paths), paths;
4004
+ return await walkForCodexJsonl(join16(baseDir, "sessions"), paths), paths;
3830
4005
  }
3831
4006
  async function walkForClaudeJsonl(dir, result) {
3832
4007
  let entries = await readdir5(dir, { withFileTypes: !0 });
3833
4008
  for (let entry of entries) {
3834
- let fullPath = join15(dir, entry.name);
4009
+ let fullPath = join16(dir, entry.name);
3835
4010
  entry.isDirectory() ? await walkForClaudeJsonl(fullPath, result) : entry.name.endsWith(".jsonl") && result.push(fullPath);
3836
4011
  }
3837
4012
  }
@@ -3843,13 +4018,13 @@ async function walkForCodexJsonl(dir, result) {
3843
4018
  return;
3844
4019
  }
3845
4020
  for (let entry of entries) {
3846
- let fullPath = join15(dir, entry.name);
4021
+ let fullPath = join16(dir, entry.name);
3847
4022
  entry.isDirectory() ? await walkForCodexJsonl(fullPath, result) : entry.name.startsWith("rollout-") && entry.name.endsWith(".jsonl") && result.push(fullPath);
3848
4023
  }
3849
4024
  }
3850
4025
  async function safeReadUtf8(filePath) {
3851
4026
  try {
3852
- return await readFile13(filePath, "utf-8");
4027
+ return await readFile14(filePath, "utf-8");
3853
4028
  } catch {
3854
4029
  return null;
3855
4030
  }
@@ -4135,8 +4310,8 @@ function fmtDateShort(dateStr) {
4135
4310
  // src/activity.ts
4136
4311
  import { open, readdir as readdir6 } from "node:fs/promises";
4137
4312
  import { createInterface as createInterface3 } from "node:readline";
4138
- import { homedir as homedir15 } from "node:os";
4139
- import { basename as basename12, join as join16 } from "node:path";
4313
+ import { homedir as homedir16 } from "node:os";
4314
+ import { basename as basename12, join as join17 } from "node:path";
4140
4315
  var FILE_CONCURRENCY3 = 16, MAX_LINE_BYTES3 = 64 * 1024 * 1024;
4141
4316
  async function buildActivityReport(range, options = {}) {
4142
4317
  let targetDates = options.dates ? new Set(options.dates) : void 0, [codex, claude] = await Promise.all([
@@ -4233,7 +4408,7 @@ function renderActivityReport(report, opts) {
4233
4408
  `);
4234
4409
  }
4235
4410
  async function scanCodexActivity(targetDates, options) {
4236
- let baseDir = options.codexDir ?? join16(homedir15(), ".codex"), acc = createAccumulator(targetDates, options.projectAliases), files = await collectCodexSessionFiles2(baseDir);
4411
+ let baseDir = options.codexDir ?? join17(homedir16(), ".codex"), acc = createAccumulator(targetDates, options.projectAliases), files = await collectCodexSessionFiles2(baseDir);
4237
4412
  return acc.stats.filesScanned = files.length, await runWithConcurrency(files, FILE_CONCURRENCY3, async (filePath) => {
4238
4413
  await processCodexFile2(filePath, acc);
4239
4414
  }), finalizeActivity(acc);
@@ -4260,12 +4435,12 @@ async function processCodexFile2(filePath, acc) {
4260
4435
  continue;
4261
4436
  }
4262
4437
  if (record.type === "session_meta") {
4263
- let id = stringValue2(record.payload?.id);
4438
+ let id = stringValue3(record.payload?.id);
4264
4439
  id && (sessionId = id), acc.stats.sessions.add(`codex:${sessionId}`);
4265
4440
  continue;
4266
4441
  }
4267
4442
  if (record.type === "turn_context") {
4268
- let cwd = stringValue2(record.payload?.cwd);
4443
+ let cwd = stringValue3(record.payload?.cwd);
4269
4444
  cwd && (projectFields = resolveProjectFields(cwd, acc.projectAliases));
4270
4445
  continue;
4271
4446
  }
@@ -4309,7 +4484,7 @@ function handleCodexResponseItem(item, usageDate, projectFields, sessionId, file
4309
4484
  projectFields,
4310
4485
  sessionId,
4311
4486
  kind,
4312
- name: kind === "agent_call" ? stringValue2(args.agent_type) ?? name : name,
4487
+ name: kind === "agent_call" ? stringValue3(args.agent_type) ?? name : name,
4313
4488
  confidence: "exact",
4314
4489
  dedupeKey: baseKey
4315
4490
  });
@@ -4363,14 +4538,14 @@ function handleCodexEvent(record, usageDate, projectFields, sessionId, filePath,
4363
4538
  projectFields,
4364
4539
  sessionId,
4365
4540
  timestamp: record.timestamp ?? "",
4366
- content: stringValue2(record.payload?.message),
4541
+ content: stringValue3(record.payload?.message),
4367
4542
  fallbackKey: `${filePath}:${usageDate}:${sessionId}:event_user_message:${record.timestamp ?? ""}`
4368
4543
  });
4369
4544
  return;
4370
4545
  }
4371
4546
  let kind = payloadType === "task_started" || payloadType === "task_complete" ? "task" : payloadType === "context_compacted" ? "compaction" : payloadType === "thread_rolled_back" ? "rollback" : payloadType === "turn_aborted" ? "interruption" : payloadType === "mcp_tool_call_end" ? "mcp_tool_call" : void 0;
4372
4547
  if (!kind) return;
4373
- let callId = stringValue2(record.payload?.call_id);
4548
+ let callId = stringValue3(record.payload?.call_id);
4374
4549
  addActivity(acc, {
4375
4550
  usageDate,
4376
4551
  provider: "openai",
@@ -4394,7 +4569,7 @@ async function scanClaudeActivity(targetDates, options) {
4394
4569
  }
4395
4570
  for (let entry of projectDirs) {
4396
4571
  if (!entry.isDirectory()) continue;
4397
- let projectPath = join16(baseDir, entry.name), jsonlFiles = [];
4572
+ let projectPath = join17(baseDir, entry.name), jsonlFiles = [];
4398
4573
  await walkJsonl(projectPath, jsonlFiles);
4399
4574
  let fields = resolveClaudeProject(projectPath, acc.projectAliases);
4400
4575
  for (let filePath of jsonlFiles) fileJobs.push({ filePath, projectFields: fields });
@@ -4532,22 +4707,22 @@ function acceptsDate(acc, usageDate) {
4532
4707
  async function collectCodexSessionFiles2(baseDir) {
4533
4708
  let paths = [];
4534
4709
  try {
4535
- let files = await readdir6(join16(baseDir, "archived_sessions"));
4710
+ let files = await readdir6(join17(baseDir, "archived_sessions"));
4536
4711
  for (let file of files)
4537
- file.endsWith(".jsonl") && paths.push(join16(baseDir, "archived_sessions", file));
4712
+ file.endsWith(".jsonl") && paths.push(join17(baseDir, "archived_sessions", file));
4538
4713
  } catch {
4539
4714
  }
4540
- return await walkJsonl(join16(baseDir, "sessions"), paths), paths;
4715
+ return await walkJsonl(join17(baseDir, "sessions"), paths), paths;
4541
4716
  }
4542
4717
  function getClaudeProjectDirs2(configured) {
4543
4718
  if (configured?.length) return configured;
4544
4719
  let envVar = process.env.CLAUDE_CONFIG_DIR?.trim();
4545
4720
  if (envVar)
4546
- return envVar.split(",").map((p) => p.trim()).filter(Boolean).map((p) => join16(p, "projects"));
4547
- let home = homedir15();
4721
+ return envVar.split(",").map((p) => p.trim()).filter(Boolean).map((p) => join17(p, "projects"));
4722
+ let home = homedir16();
4548
4723
  return [
4549
- join16(home, ".config", "claude", "projects"),
4550
- join16(home, ".claude", "projects")
4724
+ join17(home, ".config", "claude", "projects"),
4725
+ join17(home, ".claude", "projects")
4551
4726
  ];
4552
4727
  }
4553
4728
  async function walkJsonl(dir, result) {
@@ -4558,7 +4733,7 @@ async function walkJsonl(dir, result) {
4558
4733
  return;
4559
4734
  }
4560
4735
  for (let entry of entries) {
4561
- let fullPath = join16(dir, entry.name);
4736
+ let fullPath = join17(dir, entry.name);
4562
4737
  entry.isDirectory() ? await walkJsonl(fullPath, result) : entry.name.endsWith(".jsonl") && result.push(fullPath);
4563
4738
  }
4564
4739
  }
@@ -4574,22 +4749,22 @@ function classifyClaudeTool(name) {
4574
4749
  return name === "Skill" ? "skill_call" : name === "Agent" ? "agent_call" : name === "WebSearch" || name === "WebFetch" ? "web_search" : name === "ToolSearch" ? "tool_search" : name === "TaskCreate" || name === "TaskUpdate" || name === "TaskList" || name === "TaskStop" ? "task" : "tool_call";
4575
4750
  }
4576
4751
  function getClaudeMetricName(toolName, input) {
4577
- return toolName === "Skill" ? stringValue2(input?.skill) ?? "unknown" : toolName === "Agent" ? stringValue2(input?.description) ?? stringValue2(input?.subagent_type) ?? "unknown" : toolName;
4752
+ return toolName === "Skill" ? stringValue3(input?.skill) ?? "unknown" : toolName === "Agent" ? stringValue3(input?.description) ?? stringValue3(input?.subagent_type) ?? "unknown" : toolName;
4578
4753
  }
4579
4754
  function isClaudeUserMessage(record) {
4580
4755
  if (record.type !== "user" || record.message?.role !== "user" || record.isMeta || record.toolUseResult || record.sourceToolAssistantUUID || record.sourceToolUseID) return !1;
4581
4756
  let content = record.message.content;
4582
- return typeof content == "string" ? content.trim().length > 0 : !Array.isArray(content) || content.length === 0 || content.some((block) => block?.type === "tool_result") ? !1 : content.some((block) => block?.type === "text" && stringValue2(block.text));
4757
+ return typeof content == "string" ? content.trim().length > 0 : !Array.isArray(content) || content.length === 0 || content.some((block) => block?.type === "tool_result") ? !1 : content.some((block) => block?.type === "text" && stringValue3(block.text));
4583
4758
  }
4584
4759
  function hasCodexUserMessageContent(content) {
4585
4760
  return typeof content == "string" ? content.trim().length > 0 : !Array.isArray(content) || content.length === 0 ? !1 : content.some((block) => block?.type === "input_text" || block?.type === "text");
4586
4761
  }
4587
4762
  function extractCodexMessageText(content) {
4588
- return typeof content == "string" ? content : Array.isArray(content) && content.map((block) => stringValue2(block.text)).filter(Boolean).join(`
4763
+ return typeof content == "string" ? content : Array.isArray(content) && content.map((block) => stringValue3(block.text)).filter(Boolean).join(`
4589
4764
  `) || void 0;
4590
4765
  }
4591
4766
  function extractClaudeMessageText(content) {
4592
- return typeof content == "string" ? content : Array.isArray(content) && content.filter((block) => block?.type === "text").map((block) => stringValue2(block.text)).filter(Boolean).join(`
4767
+ return typeof content == "string" ? content : Array.isArray(content) && content.filter((block) => block?.type === "text").map((block) => stringValue3(block.text)).filter(Boolean).join(`
4593
4768
  `) || void 0;
4594
4769
  }
4595
4770
  function normalizeMessageText(value) {
@@ -4597,7 +4772,7 @@ function normalizeMessageText(value) {
4597
4772
  }
4598
4773
  function extractSkillProxyNames(rawArguments) {
4599
4774
  if (!rawArguments) return [];
4600
- let args = parseJsonObject(rawArguments), command2 = stringValue2(args.cmd) ?? stringValue2(args.command) ?? "";
4775
+ let args = parseJsonObject(rawArguments), command2 = stringValue3(args.cmd) ?? stringValue3(args.command) ?? "";
4601
4776
  if (!command2.includes("SKILL.md")) return [];
4602
4777
  let names = /* @__PURE__ */ new Set();
4603
4778
  for (let match of command2.matchAll(/([^\s'"]*SKILL\.md)/g))
@@ -4617,7 +4792,7 @@ function skillNameFromPath(rawPath) {
4617
4792
  let parts = rawPath.replace(/^[`'"]+|[`'"]+$/g, "").split("/").filter(Boolean), idx = parts.lastIndexOf("SKILL.md"), name = idx > 0 ? parts[idx - 1] : void 0;
4618
4793
  return !name || name === "$d" || name === "s#" ? "unknown-skill" : name;
4619
4794
  }
4620
- function stringValue2(value) {
4795
+ function stringValue3(value) {
4621
4796
  return typeof value == "string" && value.length > 0 ? value : void 0;
4622
4797
  }
4623
4798
  function summarize(items, keyFn, labelFn, limit) {
@@ -4710,10 +4885,10 @@ function stripAnsi(s) {
4710
4885
  }
4711
4886
 
4712
4887
  // src/config.ts
4713
- import { mkdir, readFile as readFile14, writeFile } from "node:fs/promises";
4714
- import { homedir as homedir16, hostname } from "node:os";
4715
- import { basename as basename13, join as join17 } from "node:path";
4716
- var CONFIG_DIR = join17(homedir16(), ".aiusage"), CONFIG_PATH = join17(CONFIG_DIR, "config.json");
4888
+ import { mkdir, readFile as readFile15, writeFile } from "node:fs/promises";
4889
+ import { homedir as homedir17, hostname } from "node:os";
4890
+ import { basename as basename13, join as join18 } from "node:path";
4891
+ var CONFIG_DIR = join18(homedir17(), ".aiusage"), CONFIG_PATH = join18(CONFIG_DIR, "config.json");
4717
4892
  function getConfigPath() {
4718
4893
  return CONFIG_PATH;
4719
4894
  }
@@ -4740,7 +4915,7 @@ function migrateConfig(config) {
4740
4915
  }
4741
4916
  async function readConfig() {
4742
4917
  try {
4743
- let raw = await readFile14(CONFIG_PATH, "utf-8");
4918
+ let raw = await readFile15(CONFIG_PATH, "utf-8");
4744
4919
  return migrateConfig(JSON.parse(raw));
4745
4920
  } catch {
4746
4921
  return {};
@@ -4848,13 +5023,13 @@ import { hostname as hostname2 } from "node:os";
4848
5023
 
4849
5024
  // src/version.ts
4850
5025
  import { readFileSync } from "node:fs";
4851
- import { resolve as resolve2, dirname as dirname7 } from "node:path";
5026
+ import { resolve as resolve3, dirname as dirname7 } from "node:path";
4852
5027
  import { fileURLToPath } from "node:url";
4853
5028
  var cached;
4854
5029
  function getVersion() {
4855
5030
  if (cached !== void 0) return cached;
4856
5031
  try {
4857
- let pkg = resolve2(dirname7(fileURLToPath(import.meta.url)), "..", "package.json");
5032
+ let pkg = resolve3(dirname7(fileURLToPath(import.meta.url)), "..", "package.json");
4858
5033
  cached = JSON.parse(readFileSync(pkg, "utf-8")).version;
4859
5034
  } catch {
4860
5035
  cached = "unknown";
@@ -4927,12 +5102,12 @@ async function requestJson(url, init) {
4927
5102
  }
4928
5103
 
4929
5104
  // src/schedule.ts
4930
- import { mkdir as mkdir2, readFile as readFile15, stat as stat3, unlink, writeFile as writeFile2 } from "node:fs/promises";
5105
+ import { mkdir as mkdir2, readFile as readFile16, stat as stat3, unlink, writeFile as writeFile2 } from "node:fs/promises";
4931
5106
  import { execFile as execFile2 } from "node:child_process";
4932
5107
  import { promisify } from "node:util";
4933
- import { homedir as homedir17, platform, tmpdir as tmpdir2 } from "node:os";
4934
- import { join as join18, resolve as resolve3 } from "node:path";
4935
- var execFileAsync = promisify(execFile2), LABEL = "com.aiusage.sync", PLIST_PATH = join18(homedir17(), "Library", "LaunchAgents", `${LABEL}.plist`), LOG_PATH = join18(homedir17(), ".aiusage", "sync.log"), CRON_MARKER = "# aiusage-sync";
5108
+ import { homedir as homedir18, platform, tmpdir as tmpdir2 } from "node:os";
5109
+ import { join as join19, resolve as resolve4 } from "node:path";
5110
+ var execFileAsync = promisify(execFile2), LABEL = "com.aiusage.sync", PLIST_PATH = join19(homedir18(), "Library", "LaunchAgents", `${LABEL}.plist`), LOG_PATH = join19(homedir18(), ".aiusage", "sync.log"), CRON_MARKER = "# aiusage-sync";
4936
5111
  function parseInterval(value) {
4937
5112
  let match = value.match(/^(\d+)(m|h|d)$/);
4938
5113
  if (!match) throw new Error("--every \u683C\u5F0F\u9519\u8BEF\uFF0C\u793A\u4F8B: 30m, 1h, 2h, 1d");
@@ -4967,7 +5142,7 @@ async function getScheduleStatus() {
4967
5142
  return platform() === "darwin" ? getLaunchdStatus() : getCronStatus();
4968
5143
  }
4969
5144
  function resolveCommandPaths() {
4970
- let scriptPath = resolve3(process.argv[1]);
5145
+ let scriptPath = resolve4(process.argv[1]);
4971
5146
  if (scriptPath.includes("_npx") || scriptPath.includes("/npx-"))
4972
5147
  throw new Error(
4973
5148
  `\u68C0\u6D4B\u5230\u901A\u8FC7 npx \u8FD0\u884C\uFF0C\u5B9A\u65F6\u4EFB\u52A1\u9700\u8981\u5168\u5C40\u5B89\u88C5\u3002
@@ -4977,7 +5152,7 @@ function resolveCommandPaths() {
4977
5152
  }
4978
5153
  async function enableLaunchd(intervalSeconds) {
4979
5154
  let { nodePath, scriptPath } = resolveCommandPaths();
4980
- await mkdir2(join18(homedir17(), ".aiusage"), { recursive: !0 });
5155
+ await mkdir2(join19(homedir18(), ".aiusage"), { recursive: !0 });
4981
5156
  let plist = [
4982
5157
  '<?xml version="1.0" encoding="UTF-8"?>',
4983
5158
  '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
@@ -5031,7 +5206,7 @@ async function getLaunchdStatus() {
5031
5206
  return { enabled: !1 };
5032
5207
  }
5033
5208
  try {
5034
- let content = await readFile15(PLIST_PATH, "utf-8"), match = content.match(/<key>StartInterval<\/key>\s*<integer>(\d+)<\/integer>/), interval = match ? parseInt(match[1], 10) : void 0, argMatches = [...content.matchAll(/<string>([^<]+)<\/string>/g)].map((m) => m[1]), command2 = argMatches.length > 0 ? argMatches.join(" ") : void 0, includeToday = content.includes("--today"), logPath = content.match(/<key>StandardOutPath<\/key>\s*<string>([^<]+)<\/string>/)?.[1];
5209
+ let content = await readFile16(PLIST_PATH, "utf-8"), match = content.match(/<key>StartInterval<\/key>\s*<integer>(\d+)<\/integer>/), interval = match ? parseInt(match[1], 10) : void 0, argMatches = [...content.matchAll(/<string>([^<]+)<\/string>/g)].map((m) => m[1]), command2 = argMatches.length > 0 ? argMatches.join(" ") : void 0, includeToday = content.includes("--today"), logPath = content.match(/<key>StandardOutPath<\/key>\s*<string>([^<]+)<\/string>/)?.[1];
5035
5210
  return {
5036
5211
  enabled: !0,
5037
5212
  interval,
@@ -5046,8 +5221,8 @@ async function getLaunchdStatus() {
5046
5221
  }
5047
5222
  }
5048
5223
  async function enableCron(intervalSeconds) {
5049
- let { nodePath, scriptPath } = resolveCommandPaths(), cronExpr = secondsToCron(intervalSeconds), logPath = join18(homedir17(), ".aiusage", "sync.log"), cronLine = `${cronExpr} ${nodePath} ${scriptPath} sync --today >> ${logPath} 2>&1 ${CRON_MARKER}`;
5050
- await mkdir2(join18(homedir17(), ".aiusage"), { recursive: !0 });
5224
+ let { nodePath, scriptPath } = resolveCommandPaths(), cronExpr = secondsToCron(intervalSeconds), logPath = join19(homedir18(), ".aiusage", "sync.log"), cronLine = `${cronExpr} ${nodePath} ${scriptPath} sync --today >> ${logPath} 2>&1 ${CRON_MARKER}`;
5225
+ await mkdir2(join19(homedir18(), ".aiusage"), { recursive: !0 });
5051
5226
  let existing = "";
5052
5227
  try {
5053
5228
  let { stdout } = await execFileAsync("crontab", ["-l"]);
@@ -5105,7 +5280,7 @@ async function getCronStatus() {
5105
5280
  }
5106
5281
  }
5107
5282
  async function writeCrontab(content) {
5108
- let tmpFile = join18(tmpdir2(), `aiusage-cron-${Date.now()}`);
5283
+ let tmpFile = join19(tmpdir2(), `aiusage-cron-${Date.now()}`);
5109
5284
  await writeFile2(tmpFile, content, "utf-8");
5110
5285
  try {
5111
5286
  await execFileAsync("crontab", [tmpFile]);
@@ -5137,8 +5312,8 @@ function escapeXml(value) {
5137
5312
 
5138
5313
  // src/doctor.ts
5139
5314
  import { readdir as readdir7, stat as stat4 } from "node:fs/promises";
5140
- import { homedir as homedir18 } from "node:os";
5141
- import { join as join19 } from "node:path";
5315
+ import { homedir as homedir19 } from "node:os";
5316
+ import { join as join20 } from "node:path";
5142
5317
  var msgs = {
5143
5318
  en: {
5144
5319
  groupConfig: "Configuration",
@@ -5200,7 +5375,7 @@ async function countFiles(dir, exts, cap = 1e3) {
5200
5375
  }
5201
5376
  for (let e of entries) {
5202
5377
  if (count >= cap) break;
5203
- let full = join19(current, e.name);
5378
+ let full = join20(current, e.name);
5204
5379
  e.isDirectory() ? queue.push(full) : exts.some((ext) => e.name.endsWith(ext)) && count++;
5205
5380
  }
5206
5381
  }
@@ -5229,28 +5404,29 @@ async function runDoctor(lang = "zh") {
5229
5404
  }
5230
5405
  target.lastSuccessfulUploadAt ? checks.push({ group: g2, name: `${prefix} ${s.lastSync}`, status: "ok", message: target.lastSuccessfulUploadAt }) : checks.push({ group: g2, name: `${prefix} ${s.lastSync}`, status: "warn", message: s.lastSyncNone });
5231
5406
  }
5232
- let g3 = s.groupTools, home = homedir18(), tools = [
5233
- { dirs: [join19(home, ".config", "claude", "projects"), join19(home, ".claude", "projects")], label: "Claude Code", exts: [".jsonl"] },
5234
- { dirs: [join19(home, ".codex")], label: "Codex CLI", exts: [".jsonl"] },
5235
- { dirs: [join19(home, "Library", "Application Support", "Cursor", "User", "globalStorage")], label: "Cursor", exts: [".vscdb"] },
5236
- { dirs: [join19(home, ".copilot", "session-state"), join19(home, ".copilot", "otel")], label: "Copilot CLI", exts: [".jsonl"] },
5407
+ let g3 = s.groupTools, home = homedir19(), tools = [
5408
+ { dirs: [join20(home, ".config", "claude", "projects"), join20(home, ".claude", "projects")], label: "Claude Code", exts: [".jsonl"] },
5409
+ { dirs: [join20(home, ".codex")], label: "Codex CLI", exts: [".jsonl"] },
5410
+ { dirs: [join20(home, "Library", "Application Support", "Cursor", "User", "globalStorage")], label: "Cursor", exts: [".vscdb"] },
5411
+ { dirs: [join20(home, ".copilot", "session-state"), join20(home, ".copilot", "otel")], label: "Copilot CLI", exts: [".jsonl"] },
5237
5412
  {
5238
5413
  dirs: [
5239
- join19(home, "Library", "Application Support", "Code", "logs"),
5240
- join19(home, "Library", "Application Support", "Code", "User", "workspaceStorage")
5414
+ join20(home, "Library", "Application Support", "Code", "logs"),
5415
+ join20(home, "Library", "Application Support", "Code", "User", "workspaceStorage")
5241
5416
  ],
5242
5417
  label: "Copilot VS Code",
5243
5418
  exts: [".log", ".json", ".jsonl"]
5244
5419
  },
5245
- { dirs: [join19(home, ".gemini", "tmp")], label: "Gemini CLI", exts: [".json", ".jsonl"] },
5246
- { dirs: [join19(home, ".gemini", "antigravity")], label: "Antigravity", exts: [".json"] },
5247
- { dirs: [join19(home, ".qwen", "projects"), join19(home, ".qwen", "tmp")], label: "Qwen Code", exts: [".jsonl"] },
5248
- { dirs: [join19(resolveKimiCodeHome(home), "sessions")], label: "Kimi Code", exts: [".jsonl"] },
5249
- { dirs: [join19(home, ".kimi", "sessions")], label: "Kimi CLI (legacy)", exts: [".jsonl"] },
5250
- { dirs: [join19(home, ".local", "share", "amp", "threads")], label: "Amp", exts: [".json"] },
5251
- { dirs: [join19(home, ".factory", "sessions")], label: "Droid", exts: [".settings.json"] },
5252
- { dirs: [join19(home, ".local", "share", "opencode")], label: "OpenCode", exts: [".db", ".json"] },
5253
- { dirs: [join19(home, ".pi", "agent", "sessions"), join19(home, ".omp", "agent", "sessions")], label: "Pi / OMP", exts: [".jsonl"] }
5420
+ { dirs: [join20(home, ".gemini", "tmp")], label: "Gemini CLI", exts: [".json", ".jsonl"] },
5421
+ { dirs: [join20(home, ".gemini", "antigravity")], label: "Antigravity", exts: [".json"] },
5422
+ { dirs: [join20(home, ".qwen", "projects"), join20(home, ".qwen", "tmp")], label: "Qwen Code", exts: [".jsonl"] },
5423
+ { dirs: [join20(resolveKimiCodeHome(home), "sessions")], label: "Kimi Code", exts: [".jsonl"] },
5424
+ { dirs: [join20(home, ".kimi", "sessions")], label: "Kimi CLI (legacy)", exts: [".jsonl"] },
5425
+ { dirs: [join20(home, ".local", "share", "amp", "threads")], label: "Amp", exts: [".json"] },
5426
+ { dirs: [join20(home, ".factory", "sessions")], label: "Droid", exts: [".settings.json"] },
5427
+ { dirs: [join20(home, ".local", "share", "opencode")], label: "OpenCode", exts: [".db", ".json"] },
5428
+ { dirs: [join20(home, ".pi", "agent", "sessions"), join20(home, ".omp", "agent", "sessions")], label: "Pi / OMP", exts: [".jsonl"] },
5429
+ { dirs: [resolveTraeNativeCacheDir(home), resolveTokscaleTraeCacheDir(home)], label: "Trae", exts: [".json"] }
5254
5430
  ];
5255
5431
  for (let tool of tools) {
5256
5432
  let installed = !1, n = 0;
@@ -5275,9 +5451,9 @@ async function runDoctor(lang = "zh") {
5275
5451
  }
5276
5452
 
5277
5453
  // src/project.ts
5278
- import { open as open2, readdir as readdir8, readFile as readFile16 } from "node:fs/promises";
5279
- import { basename as basename14, join as join20 } from "node:path";
5280
- import { homedir as homedir19 } from "node:os";
5454
+ import { open as open2, readdir as readdir8, readFile as readFile17 } from "node:fs/promises";
5455
+ import { basename as basename14, join as join21 } from "node:path";
5456
+ import { homedir as homedir20 } from "node:os";
5281
5457
  async function discoverProjects(projectAliases) {
5282
5458
  let projectMap = /* @__PURE__ */ new Map();
5283
5459
  function add(name, source) {
@@ -5305,7 +5481,9 @@ async function discoverProjects(projectAliases) {
5305
5481
  // 仅读取知识项元数据标题,不读取对话内容
5306
5482
  discoverAntigravityProjects().then((names) => names.forEach((n) => add(n, "antigravity"))),
5307
5483
  // Kimi CLI / Kimi Code: legacy workspace map + new session metadata.
5308
- discoverKimiProjects().then((names) => names.forEach((n) => add(n, "kimi")))
5484
+ discoverKimiProjects().then((names) => names.forEach((n) => add(n, "kimi"))),
5485
+ // Trae CN: privacy-minimized cache written by `aiusage trae sync`.
5486
+ discoverTraeProjects().then((names) => names.forEach((n) => add(n, "trae")))
5309
5487
  ]);
5310
5488
  let results = [];
5311
5489
  for (let [name, sources] of projectMap) {
@@ -5329,14 +5507,14 @@ async function discoverClaudeProjects() {
5329
5507
  }
5330
5508
  for (let entry of entries) {
5331
5509
  if (!entry.isDirectory() || entry.name.startsWith(".")) continue;
5332
- let projectDir = join20(baseDir, entry.name), name = await extractCwdFromFirstJsonl(projectDir);
5510
+ let projectDir = join21(baseDir, entry.name), name = await extractCwdFromFirstJsonl(projectDir);
5333
5511
  name && name !== "unknown" && names.push(name);
5334
5512
  }
5335
5513
  }
5336
5514
  return names;
5337
5515
  }
5338
5516
  async function discoverCodexProjects() {
5339
- let sessionsDir = join20(homedir19(), ".codex", "sessions"), files = await walkJsonlFiles(sessionsDir), projects = /* @__PURE__ */ new Set();
5517
+ let sessionsDir = join21(homedir20(), ".codex", "sessions"), files = await walkJsonlFiles(sessionsDir), projects = /* @__PURE__ */ new Set();
5340
5518
  for (let filePath of files) {
5341
5519
  let name = await extractCwdFromSessionMeta(filePath);
5342
5520
  name && name !== "unknown" && projects.add(name);
@@ -5373,7 +5551,7 @@ async function walkFiles2(dir, ext) {
5373
5551
  return;
5374
5552
  }
5375
5553
  for (let entry of entries) {
5376
- let full = join20(d, entry.name);
5554
+ let full = join21(d, entry.name);
5377
5555
  entry.isDirectory() ? await walk2(full) : entry.name.endsWith(ext) && result.push(full);
5378
5556
  }
5379
5557
  }
@@ -5415,18 +5593,18 @@ async function findFirstJsonl(dir) {
5415
5593
  return;
5416
5594
  }
5417
5595
  let topJsonl = entries.find((e) => e.isFile() && e.name.endsWith(".jsonl"));
5418
- if (topJsonl) return join20(dir, topJsonl.name);
5596
+ if (topJsonl) return join21(dir, topJsonl.name);
5419
5597
  for (let entry of entries)
5420
5598
  if (!(!entry.isDirectory() || entry.name.startsWith(".")))
5421
5599
  try {
5422
- let sub = (await readdir8(join20(dir, entry.name))).find((f) => f.endsWith(".jsonl"));
5423
- if (sub) return join20(dir, entry.name, sub);
5600
+ let sub = (await readdir8(join21(dir, entry.name))).find((f) => f.endsWith(".jsonl"));
5601
+ if (sub) return join21(dir, entry.name, sub);
5424
5602
  } catch {
5425
5603
  continue;
5426
5604
  }
5427
5605
  }
5428
5606
  async function discoverCopilotProjects() {
5429
- let dir = join20(homedir19(), ".copilot", "session-state"), files = await walkJsonlFiles(dir), projects = /* @__PURE__ */ new Set();
5607
+ let dir = join21(homedir20(), ".copilot", "session-state"), files = await walkJsonlFiles(dir), projects = /* @__PURE__ */ new Set();
5430
5608
  for (let filePath of files) {
5431
5609
  let fh;
5432
5610
  try {
@@ -5448,9 +5626,9 @@ async function discoverCopilotProjects() {
5448
5626
  return [...projects];
5449
5627
  }
5450
5628
  async function discoverGeminiProjects() {
5451
- let filePath = join20(homedir19(), ".gemini", "projects.json");
5629
+ let filePath = join21(homedir20(), ".gemini", "projects.json");
5452
5630
  try {
5453
- let raw = await readFile16(filePath, "utf-8"), projects = JSON.parse(raw)?.projects;
5631
+ let raw = await readFile17(filePath, "utf-8"), projects = JSON.parse(raw)?.projects;
5454
5632
  if (!projects || typeof projects != "object") return [];
5455
5633
  let names = [];
5456
5634
  for (let [path, _name] of Object.entries(projects)) {
@@ -5463,9 +5641,9 @@ async function discoverGeminiProjects() {
5463
5641
  }
5464
5642
  }
5465
5643
  async function discoverCursorProjects() {
5466
- let storagePath = join20(homedir19(), "Library", "Application Support", "Cursor", "User", "globalStorage", "storage.json");
5644
+ let storagePath = join21(homedir20(), "Library", "Application Support", "Cursor", "User", "globalStorage", "storage.json");
5467
5645
  try {
5468
- let raw = await readFile16(storagePath, "utf-8"), data = JSON.parse(raw), projects = /* @__PURE__ */ new Set(), workspaceUris = Object.keys(data.profileAssociations?.workspaces ?? {});
5646
+ let raw = await readFile17(storagePath, "utf-8"), data = JSON.parse(raw), projects = /* @__PURE__ */ new Set(), workspaceUris = Object.keys(data.profileAssociations?.workspaces ?? {});
5469
5647
  for (let uri of workspaceUris) {
5470
5648
  let name = nameFromFileUri(uri);
5471
5649
  name && projects.add(name);
@@ -5480,11 +5658,11 @@ async function discoverCursorProjects() {
5480
5658
  }
5481
5659
  }
5482
5660
  async function discoverCopilotVscodeProjects() {
5483
- let dir = join20(homedir19(), "Library", "Application Support", "Code", "logs"), files = (await walkFiles2(dir, ".log")).filter((filePath) => filePath.endsWith("GitHub Copilot Chat.log")), projects = /* @__PURE__ */ new Set();
5661
+ let dir = join21(homedir20(), "Library", "Application Support", "Code", "logs"), files = (await walkFiles2(dir, ".log")).filter((filePath) => filePath.endsWith("GitHub Copilot Chat.log")), projects = /* @__PURE__ */ new Set();
5484
5662
  for (let filePath of files) {
5485
5663
  let content;
5486
5664
  try {
5487
- content = await readFile16(filePath, "utf-8");
5665
+ content = await readFile17(filePath, "utf-8");
5488
5666
  } catch {
5489
5667
  continue;
5490
5668
  }
@@ -5497,7 +5675,7 @@ async function discoverCopilotVscodeProjects() {
5497
5675
  return [...projects];
5498
5676
  }
5499
5677
  async function discoverAntigravityProjects() {
5500
- let dir = join20(homedir19(), ".gemini", "antigravity", "knowledge"), entries;
5678
+ let dir = join21(homedir20(), ".gemini", "antigravity", "knowledge"), entries;
5501
5679
  try {
5502
5680
  entries = await readdir8(dir, { withFileTypes: !0 });
5503
5681
  } catch {
@@ -5506,9 +5684,9 @@ async function discoverAntigravityProjects() {
5506
5684
  let projects = /* @__PURE__ */ new Set();
5507
5685
  for (let entry of entries) {
5508
5686
  if (!entry.isDirectory()) continue;
5509
- let metadataPath = join20(dir, entry.name, "metadata.json");
5687
+ let metadataPath = join21(dir, entry.name, "metadata.json");
5510
5688
  try {
5511
- let raw = await readFile16(metadataPath, "utf-8"), name = JSON.parse(raw).title?.trim() || entry.name.trim();
5689
+ let raw = await readFile17(metadataPath, "utf-8"), name = JSON.parse(raw).title?.trim() || entry.name.trim();
5512
5690
  name && name !== "unknown" && projects.add(name);
5513
5691
  } catch {
5514
5692
  continue;
@@ -5517,9 +5695,9 @@ async function discoverAntigravityProjects() {
5517
5695
  return [...projects];
5518
5696
  }
5519
5697
  async function discoverKimiProjects() {
5520
- let projects = /* @__PURE__ */ new Set(), home = homedir19();
5698
+ let projects = /* @__PURE__ */ new Set(), home = homedir20();
5521
5699
  try {
5522
- let raw = await readFile16(join20(home, ".kimi", "kimi.json"), "utf-8"), data = JSON.parse(raw);
5700
+ let raw = await readFile17(join21(home, ".kimi", "kimi.json"), "utf-8"), data = JSON.parse(raw);
5523
5701
  for (let workspace of Object.values(data.workspaces ?? {})) {
5524
5702
  let name = basename14(workspace.path?.trim() ?? "");
5525
5703
  name && name !== "unknown" && projects.add(name);
@@ -5528,7 +5706,7 @@ async function discoverKimiProjects() {
5528
5706
  }
5529
5707
  let codeHome = resolveKimiCodeHome(home);
5530
5708
  try {
5531
- let raw = await readFile16(join20(codeHome, "session_index.jsonl"), "utf-8");
5709
+ let raw = await readFile17(join21(codeHome, "session_index.jsonl"), "utf-8");
5532
5710
  for (let line of raw.split(`
5533
5711
  `))
5534
5712
  if (line.trim())
@@ -5540,10 +5718,21 @@ async function discoverKimiProjects() {
5540
5718
  }
5541
5719
  } catch {
5542
5720
  }
5543
- let stateFiles = (await walkFiles2(join20(codeHome, "sessions"), ".json")).filter((filePath) => basename14(filePath) === "state.json");
5721
+ let stateFiles = (await walkFiles2(join21(codeHome, "sessions"), ".json")).filter((filePath) => basename14(filePath) === "state.json");
5544
5722
  for (let filePath of stateFiles)
5545
5723
  try {
5546
- let raw = await readFile16(filePath, "utf-8"), state = JSON.parse(raw), name = basename14(state.workDir?.trim() ?? "");
5724
+ let raw = await readFile17(filePath, "utf-8"), state = JSON.parse(raw), name = basename14(state.workDir?.trim() ?? "");
5725
+ name && name !== "unknown" && projects.add(name);
5726
+ } catch {
5727
+ continue;
5728
+ }
5729
+ return [...projects];
5730
+ }
5731
+ async function discoverTraeProjects() {
5732
+ let projects = /* @__PURE__ */ new Set();
5733
+ for (let filePath of await walkFiles2(resolveTraeNativeCacheDir(), ".json"))
5734
+ try {
5735
+ let data = JSON.parse(await readFile17(filePath, "utf8")), name = basename14(data.project?.trim() ?? "");
5547
5736
  name && name !== "unknown" && projects.add(name);
5548
5737
  } catch {
5549
5738
  continue;
@@ -5572,11 +5761,11 @@ function pathFromFileUri(raw) {
5572
5761
  function getClaudeDirs() {
5573
5762
  let envVar = process.env.CLAUDE_CONFIG_DIR?.trim();
5574
5763
  if (envVar)
5575
- return envVar.split(",").map((p) => p.trim()).filter(Boolean).map((p) => join20(p, "projects"));
5576
- let home = homedir19();
5764
+ return envVar.split(",").map((p) => p.trim()).filter(Boolean).map((p) => join21(p, "projects"));
5765
+ let home = homedir20();
5577
5766
  return [
5578
- join20(home, ".config", "claude", "projects"),
5579
- join20(home, ".claude", "projects")
5767
+ join21(home, ".config", "claude", "projects"),
5768
+ join21(home, ".claude", "projects")
5580
5769
  ];
5581
5770
  }
5582
5771
 
@@ -5621,10 +5810,10 @@ function shortHash(p) {
5621
5810
  }
5622
5811
 
5623
5812
  // src/pricing.ts
5624
- import { mkdir as mkdir3, readFile as readFile17, writeFile as writeFile3 } from "node:fs/promises";
5625
- import { homedir as homedir20 } from "node:os";
5626
- import { join as join21 } from "node:path";
5627
- var CACHE_DIR = join21(homedir20(), ".aiusage"), CACHE_PATH = join21(CACHE_DIR, "pricing-cache.json"), DEFAULT_CACHE_TTL_HOURS = 24, FETCH_TIMEOUT_MS = 5e3, NPM_CDN_URLS = [
5813
+ import { mkdir as mkdir3, readFile as readFile18, writeFile as writeFile3 } from "node:fs/promises";
5814
+ import { homedir as homedir21 } from "node:os";
5815
+ import { join as join22 } from "node:path";
5816
+ var CACHE_DIR = join22(homedir21(), ".aiusage"), CACHE_PATH = join22(CACHE_DIR, "pricing-cache.json"), DEFAULT_CACHE_TTL_HOURS = 24, FETCH_TIMEOUT_MS = 5e3, NPM_CDN_URLS = [
5628
5817
  "https://cdn.jsdelivr.net/npm/@aiusage/cli@latest/pricing-catalog.json",
5629
5818
  "https://unpkg.com/@aiusage/cli@latest/pricing-catalog.json",
5630
5819
  "https://cdn.jsdelivr.net/npm/@aiusage/pricing@latest/catalog.json",
@@ -5693,7 +5882,7 @@ function fromCache(cache) {
5693
5882
  }
5694
5883
  async function readPricingCache() {
5695
5884
  try {
5696
- let raw = await readFile17(CACHE_PATH, "utf-8"), cache = JSON.parse(raw);
5885
+ let raw = await readFile18(CACHE_PATH, "utf-8"), cache = JSON.parse(raw);
5697
5886
  return assertPricingCatalog(cache.catalog), !cache.fetchedAt || !cache.sourceUrl ? null : cache;
5698
5887
  } catch {
5699
5888
  return null;
@@ -5720,6 +5909,436 @@ function assertPricingCatalog(value) {
5720
5909
  if (!catalog2.providers.openai?.codex?.models) throw new Error("invalid OpenAI pricing catalog");
5721
5910
  }
5722
5911
 
5912
+ // src/trae-sync.ts
5913
+ import { execFile as execFile3 } from "node:child_process";
5914
+ import { createHash as createHash2 } from "node:crypto";
5915
+ import { existsSync as existsSync2 } from "node:fs";
5916
+ import { mkdir as mkdir4, open as open3, readdir as readdir9, rename, stat as stat5, writeFile as writeFile4 } from "node:fs/promises";
5917
+ import { createServer } from "node:net";
5918
+ import { homedir as homedir22 } from "node:os";
5919
+ import { join as join23 } from "node:path";
5920
+ import { promisify as promisify2 } from "node:util";
5921
+ import WebSocket from "ws";
5922
+ var execFileAsync2 = promisify2(execFile3), DEFAULT_DEBUG_PORT = 9230, DEFAULT_APP_PATH = "/Applications/TRAE.app", JWT_PATTERN = /eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g;
5923
+ async function syncTraeCnUsage(options = {}) {
5924
+ let timeoutMs = clampTimeout(options.timeoutMs), userDataDir = options.userDataDir ?? resolveTraeCnUserDataDir(), cacheDir = options.cacheDir ?? resolveTraeNativeCacheDir(), appPath = options.appPath ?? DEFAULT_APP_PATH, port = normalizePort(options.port) ?? DEFAULT_DEBUG_PORT, target = await findWorkbenchTarget(port), launched = !1;
5925
+ try {
5926
+ if (!target) {
5927
+ if (options.launch === !1)
5928
+ throw new Error(`\u672A\u8FDE\u63A5\u5230 Trae CN \u672C\u5730\u8C03\u8BD5\u63A5\u53E3 (127.0.0.1:${port})`);
5929
+ if (process.platform !== "darwin")
5930
+ throw new Error("Trae CN \u81EA\u52A8\u540C\u6B65\u76EE\u524D\u4EC5\u652F\u6301 macOS\uFF1B\u5176\u4ED6\u7CFB\u7EDF\u53EF\u7528 --port \u8FDE\u63A5\u5DF2\u5F00\u542F\u8C03\u8BD5\u7AEF\u53E3\u7684 Trae");
5931
+ if (await isTraeRunning())
5932
+ throw new Error("\u68C0\u6D4B\u5230 Trae CN \u6B63\u5728\u8FD0\u884C\u4F46\u672A\u5F00\u653E\u672C\u5730\u8BFB\u53D6\u63A5\u53E3\u3002\u8BF7\u5148\u9000\u51FA Trae\uFF0C\u518D\u6267\u884C aiusage trae sync");
5933
+ if (!existsSync2(appPath)) throw new Error(`\u672A\u627E\u5230 Trae CN: ${appPath}`);
5934
+ options.port == null && !await isPortAvailable(port) && (port = await findFreePort()), await launchTrae(appPath, port), launched = !0, target = await waitForWorkbench(port, timeoutMs);
5935
+ }
5936
+ let userIds = await waitForTraeUserIds(userDataDir, timeoutMs);
5937
+ if (userIds.length === 0)
5938
+ throw new Error("\u672A\u80FD\u4ECE Trae CN \u672C\u5730\u65E5\u5FD7\u8BC6\u522B\u8D26\u53F7\uFF0C\u8BF7\u786E\u8BA4 Trae \u5DF2\u767B\u5F55\u540E\u91CD\u8BD5");
5939
+ let raw = await readTraeUsageWithRetry(port, target, userIds, timeoutMs), normalized = normalizeSyncResult(raw);
5940
+ if (normalized.sessions.length === 0 && (raw.errors?.length ?? 0) > 0)
5941
+ throw new Error(`Trae CN \u672C\u5730\u8BFB\u53D6\u5931\u8D25: ${sanitizeMessage(raw.errors?.[0]?.message)}`);
5942
+ await writeCache(normalized.sessions, cacheDir);
5943
+ let totals = normalized.sessions.flatMap((session) => session.events).reduce(
5944
+ (sum, event) => (sum.inputTokens += event.inputTokens, sum.cachedInputTokens += event.cachedInputTokens, sum.cacheWriteTokens += event.cacheWriteTokens, sum.outputTokens += event.outputTokens, sum.reasoningOutputTokens += event.reasoningOutputTokens, sum.totalTokens += event.inputTokens + event.cachedInputTokens + event.cacheWriteTokens + event.outputTokens + event.reasoningOutputTokens, sum),
5945
+ {
5946
+ inputTokens: 0,
5947
+ cachedInputTokens: 0,
5948
+ cacheWriteTokens: 0,
5949
+ outputTokens: 0,
5950
+ reasoningOutputTokens: 0,
5951
+ totalTokens: 0
5952
+ }
5953
+ );
5954
+ return {
5955
+ cacheDir,
5956
+ accounts: raw.accounts ?? userIds.length,
5957
+ sessions: normalized.sessions.length,
5958
+ events: normalized.sessions.reduce((sum, session) => sum + session.events.length, 0),
5959
+ totals,
5960
+ warnings: (raw.errors ?? []).map((error) => sanitizeMessage(error.message)).filter(Boolean)
5961
+ };
5962
+ } finally {
5963
+ launched && await quitTrae();
5964
+ }
5965
+ }
5966
+ function normalizeTraeCnUsage(raw) {
5967
+ let prompt2 = tokenValue2(raw.promptTokens), completion = tokenValue2(raw.completionTokens), cached2 = Math.min(tokenValue2(raw.cacheReadInputTokens), prompt2), cacheWrite = Math.min(tokenValue2(raw.cacheCreationInputTokens), Math.max(0, prompt2 - cached2)), reportedTotal = tokenValue2(raw.totalTokens), reportedReasoning = tokenValue2(raw.reasoningTokens), reasoning = reportedTotal > 0 && prompt2 + completion > 0 ? Math.max(0, reportedTotal - prompt2 - completion) : reportedReasoning, input = Math.max(0, prompt2 - cached2 - cacheWrite), output = completion;
5968
+ if (prompt2 + completion + reportedReasoning === 0 && reportedTotal > 0 && (input = reportedTotal, reasoning = 0), input + cached2 + cacheWrite + output + reasoning === 0) return null;
5969
+ let messageId = stringValue4(raw.messageId), timestamp = raw.timestamp;
5970
+ return !messageId || timestamp == null || timestamp === "" ? null : {
5971
+ messageId,
5972
+ timestamp,
5973
+ model: normalizeTraeModel(stringValue4(raw.model)),
5974
+ inputTokens: input,
5975
+ cachedInputTokens: cached2,
5976
+ cacheWriteTokens: cacheWrite,
5977
+ outputTokens: output,
5978
+ reasoningOutputTokens: reasoning
5979
+ };
5980
+ }
5981
+ function normalizeSyncResult(raw) {
5982
+ let syncedAt = (/* @__PURE__ */ new Date()).toISOString(), sessions = [], seenMessages = /* @__PURE__ */ new Set();
5983
+ for (let rawSession of raw.sessions ?? []) {
5984
+ let sessionId = stringValue4(rawSession.sessionId);
5985
+ if (!sessionId) continue;
5986
+ let events = [];
5987
+ for (let rawEvent of rawSession.events ?? []) {
5988
+ let event = normalizeTraeCnUsage(rawEvent);
5989
+ !event || seenMessages.has(event.messageId) || (seenMessages.add(event.messageId), events.push(event));
5990
+ }
5991
+ events.length !== 0 && sessions.push({
5992
+ schemaVersion: 1,
5993
+ source: "trae-cn-local-rpc",
5994
+ syncedAt,
5995
+ sessionId,
5996
+ project: stringValue4(rawSession.project) || "unknown",
5997
+ events
5998
+ });
5999
+ }
6000
+ return { sessions };
6001
+ }
6002
+ async function readTraeUsage(webSocketDebuggerUrl, userIds, timeoutMs) {
6003
+ if (!webSocketDebuggerUrl) throw new Error("Trae CN \u8C03\u8BD5\u76EE\u6807\u7F3A\u5C11 WebSocket \u5730\u5740");
6004
+ let client = await CdpClient.connect(webSocketDebuggerUrl, timeoutMs);
6005
+ try {
6006
+ let result = await client.call("Runtime.evaluate", {
6007
+ expression: buildSyncExpression(userIds),
6008
+ awaitPromise: !0,
6009
+ returnByValue: !0
6010
+ }, timeoutMs), exception = result?.exceptionDetails?.exception?.description ?? result?.exceptionDetails?.text;
6011
+ if (exception) throw new Error(sanitizeMessage(exception));
6012
+ return result?.result?.value ?? {};
6013
+ } finally {
6014
+ client.close();
6015
+ }
6016
+ }
6017
+ async function readTraeUsageWithRetry(port, initialTarget, userIds, timeoutMs) {
6018
+ let deadline = Date.now() + timeoutMs, target = initialTarget, lastError;
6019
+ for (; Date.now() < deadline; )
6020
+ try {
6021
+ let remaining = Math.max(5e3, deadline - Date.now());
6022
+ return await readTraeUsage(target.webSocketDebuggerUrl, userIds, Math.min(6e4, remaining));
6023
+ } catch (error) {
6024
+ if (lastError = error instanceof Error ? error : new Error(String(error)), Date.now() + 1e3 >= deadline) break;
6025
+ await delay(1e3), target = await findWorkbenchTarget(port) ?? target;
6026
+ }
6027
+ throw lastError ?? new Error("Trae CN \u672C\u5730\u670D\u52A1\u672A\u5C31\u7EEA");
6028
+ }
6029
+ function buildSyncExpression(userIds) {
6030
+ return `(async()=>{
6031
+ const userIds=${JSON.stringify(userIds)};
6032
+ const connection=await vscode.ahaIpc.connect('ai-agent');
6033
+ let sequence=0;
6034
+ const rpc=(method,data,sessionId='')=>new Promise((resolve,reject)=>{
6035
+ const id='aiusage-trae-'+Date.now()+'-'+(++sequence);
6036
+ const timer=setTimeout(()=>{connection.off('message',handler);reject(new Error('Trae RPC timeout'))},15000);
6037
+ const handler=raw=>{
6038
+ let message;
6039
+ try{message=typeof raw==='string'?JSON.parse(raw):raw}catch{return}
6040
+ if(message.id!==id)return;
6041
+ clearTimeout(timer);
6042
+ connection.off('message',handler);
6043
+ const params=message.result&&message.result.params||{};
6044
+ let responseData=params.data;
6045
+ try{if(typeof responseData==='string')responseData=JSON.parse(responseData)}catch{}
6046
+ resolve({code:params.code,message:params.message,data:responseData||{}});
6047
+ };
6048
+ connection.on('message',handler);
6049
+ connection.send(JSON.stringify({jsonrpc:'2.0',id,method:'request',params:[{
6050
+ packet_type:'request',session_id:sessionId,channel_id:id,params:{
6051
+ service:'chat',method,data:JSON.stringify(data),common_params:{},
6052
+ user_info:{name:'',token:'',region:'',is_internal:false,user_id:'',scope:''},
6053
+ streamlined_common_params:{},client_info:{connect_session_id:''}
6054
+ }
6055
+ }]}));
6056
+ });
6057
+ const number=value=>{const parsed=Number(value);return Number.isFinite(parsed)&&parsed>0?Math.floor(parsed):0};
6058
+ const errors=[];
6059
+ const sessionMap=new Map();
6060
+ const loadSession=async(session,userId)=>{
6061
+ const sessionId=String(session.session_id||session.id||'');
6062
+ if(!sessionId)return null;
6063
+ const loaded={
6064
+ sessionId,
6065
+ project:typeof session.main_folder==='string'?session.main_folder:'unknown',
6066
+ events:[]
6067
+ };
6068
+ const seenMessages=new Set();
6069
+ let messageCursor='';
6070
+ const seenMessageCursors=new Set();
6071
+ for(let messagePage=0;messagePage<100;messagePage++){
6072
+ const messageRequest={user_id:userId,session_id:sessionId,page_size:100};
6073
+ if(messageCursor)messageRequest.next_page_token=messageCursor;
6074
+ const messageResponse=await rpc('get_messages',messageRequest,sessionId);
6075
+ if(messageResponse.code!==0){errors.push({code:messageResponse.code,message:messageResponse.message});break}
6076
+ const messageData=messageResponse.data||{};
6077
+ for(const message of Array.isArray(messageData.messages)?messageData.messages:[]){
6078
+ const usage=message.token_usage;
6079
+ if(!usage)continue;
6080
+ const messageId=String(message.message_id||message.id||'');
6081
+ if(!messageId||seenMessages.has(messageId))continue;
6082
+ const meta=message.model_smart_selection_meta||{};
6083
+ loaded.events.push({
6084
+ messageId,
6085
+ timestamp:message.created_at||message.timestamp||session.update_at||session.created_at,
6086
+ model:typeof meta.config_name==='string'&&meta.config_name?meta.config_name:
6087
+ (typeof meta.mode==='string'&&meta.mode?'trae-'+meta.mode.toLowerCase():'trae-unknown'),
6088
+ promptTokens:number(usage.prompt_tokens||usage.prompt_tokens_total),
6089
+ completionTokens:number(usage.completion_tokens||usage.completion_tokens_total),
6090
+ reasoningTokens:number(usage.reasoning_tokens),
6091
+ cacheReadInputTokens:number(usage.cache_read_input_tokens),
6092
+ cacheCreationInputTokens:number(usage.cache_creation_input_tokens),
6093
+ totalTokens:number(usage.total_tokens)
6094
+ });
6095
+ seenMessages.add(messageId);
6096
+ }
6097
+ const next=typeof messageData.next_page_token==='string'?messageData.next_page_token:'';
6098
+ if(!next||seenMessageCursors.has(next))break;
6099
+ seenMessageCursors.add(next);
6100
+ messageCursor=next;
6101
+ }
6102
+ return loaded;
6103
+ };
6104
+ try{
6105
+ for(const userId of userIds){
6106
+ let sessionCursor='';
6107
+ const seenSessionCursors=new Set();
6108
+ for(let sessionPage=0;sessionPage<100;sessionPage++){
6109
+ const sessionRequest={user_id:userId,page_size:100};
6110
+ if(sessionCursor)sessionRequest.next_page_token=sessionCursor;
6111
+ const sessionResponse=await rpc('get_lite_sessions',sessionRequest);
6112
+ if(sessionResponse.code!==0){errors.push({code:sessionResponse.code,message:sessionResponse.message});break}
6113
+ const data=sessionResponse.data||{};
6114
+ const sessions=Array.isArray(data.sessions)?data.sessions:[];
6115
+ for(let index=0;index<sessions.length;index+=6){
6116
+ const loaded=await Promise.all(sessions.slice(index,index+6).map(session=>loadSession(session,userId)));
6117
+ for(const session of loaded){
6118
+ if(!session)continue;
6119
+ const existing=sessionMap.get(session.sessionId);
6120
+ if(!existing){sessionMap.set(session.sessionId,session);continue}
6121
+ const seen=new Set(existing.events.map(event=>event.messageId));
6122
+ for(const event of session.events)if(!seen.has(event.messageId))existing.events.push(event);
6123
+ }
6124
+ }
6125
+ const next=typeof data.next_page_token==='string'?data.next_page_token:'';
6126
+ if(!next||seenSessionCursors.has(next))break;
6127
+ seenSessionCursors.add(next);
6128
+ sessionCursor=next;
6129
+ }
6130
+ }
6131
+ return {accounts:userIds.length,sessions:[...sessionMap.values()],errors};
6132
+ }finally{connection.disconnect()}
6133
+ })()`;
6134
+ }
6135
+ var CdpClient = class _CdpClient {
6136
+ constructor(socket) {
6137
+ this.socket = socket;
6138
+ socket.on("message", (raw) => {
6139
+ let message;
6140
+ try {
6141
+ message = JSON.parse(String(raw));
6142
+ } catch {
6143
+ return;
6144
+ }
6145
+ let entry = this.pending.get(message.id);
6146
+ entry && (clearTimeout(entry.timer), this.pending.delete(message.id), message.error ? entry.reject(new Error(sanitizeMessage(message.error.message))) : entry.resolve(message.result));
6147
+ }), socket.on("error", (error) => this.rejectAll(error)), socket.on("close", () => this.rejectAll(new Error("Trae CN \u672C\u5730\u8FDE\u63A5\u5DF2\u5173\u95ED")));
6148
+ }
6149
+ sequence = 0;
6150
+ pending = /* @__PURE__ */ new Map();
6151
+ static async connect(url, timeoutMs) {
6152
+ let socket = new WebSocket(url);
6153
+ return await new Promise((resolve5, reject) => {
6154
+ let timer = setTimeout(() => {
6155
+ socket.close(), reject(new Error("\u8FDE\u63A5 Trae CN \u672C\u5730\u63A5\u53E3\u8D85\u65F6"));
6156
+ }, timeoutMs);
6157
+ socket.once("open", () => {
6158
+ clearTimeout(timer), resolve5();
6159
+ }), socket.once("error", (error) => {
6160
+ clearTimeout(timer), reject(error);
6161
+ });
6162
+ }), new _CdpClient(socket);
6163
+ }
6164
+ call(method, params, timeoutMs) {
6165
+ let id = ++this.sequence;
6166
+ return new Promise((resolve5, reject) => {
6167
+ let timer = setTimeout(() => {
6168
+ this.pending.delete(id), reject(new Error(`Trae CN \u672C\u5730\u8C03\u7528\u8D85\u65F6: ${method}`));
6169
+ }, timeoutMs);
6170
+ this.pending.set(id, { resolve: resolve5, reject, timer }), this.socket.send(JSON.stringify({ id, method, params }));
6171
+ });
6172
+ }
6173
+ close() {
6174
+ this.socket.close();
6175
+ }
6176
+ rejectAll(error) {
6177
+ for (let entry of this.pending.values())
6178
+ clearTimeout(entry.timer), entry.reject(error);
6179
+ this.pending.clear();
6180
+ }
6181
+ };
6182
+ async function findWorkbenchTarget(port) {
6183
+ try {
6184
+ let response = await fetchWithTimeout(`http://127.0.0.1:${port}/json/list`, 1500);
6185
+ return response.ok ? (await response.json()).find((target) => target.type === "page" && target.url?.includes("workbench.html")) ?? null : null;
6186
+ } catch {
6187
+ return null;
6188
+ }
6189
+ }
6190
+ async function waitForWorkbench(port, timeoutMs) {
6191
+ let deadline = Date.now() + timeoutMs;
6192
+ for (; Date.now() < deadline; ) {
6193
+ let target = await findWorkbenchTarget(port);
6194
+ if (target) return target;
6195
+ await delay(500);
6196
+ }
6197
+ throw new Error("\u7B49\u5F85 Trae CN \u542F\u52A8\u8D85\u65F6");
6198
+ }
6199
+ async function waitForTraeUserIds(userDataDir, timeoutMs) {
6200
+ let deadline = Date.now() + timeoutMs;
6201
+ for (; Date.now() < deadline; ) {
6202
+ let ids = await findTraeUserIds(userDataDir);
6203
+ if (ids.length > 0) return ids;
6204
+ await delay(500);
6205
+ }
6206
+ return [];
6207
+ }
6208
+ async function findTraeUserIds(userDataDir) {
6209
+ let candidates = (await findCompletionLogs(join23(userDataDir, "logs"))).sort((a, b) => b.mtimeMs - a.mtimeMs).slice(0, 30), ids = /* @__PURE__ */ new Set(), legacyTokenPath = join23(homedir22(), ".trae-cn", "trae-jwt-token");
6210
+ if (existsSync2(legacyTokenPath))
6211
+ try {
6212
+ collectJwtUserIds(await readFileTail(legacyTokenPath), ids);
6213
+ } catch {
6214
+ }
6215
+ for (let candidate of candidates) {
6216
+ try {
6217
+ collectJwtUserIds(await readFileTail(candidate.path), ids);
6218
+ } catch {
6219
+ }
6220
+ if (ids.size >= 10) break;
6221
+ }
6222
+ return [...ids];
6223
+ }
6224
+ async function findCompletionLogs(dir) {
6225
+ let entries;
6226
+ try {
6227
+ entries = await readdir9(dir, { withFileTypes: !0 });
6228
+ } catch {
6229
+ return [];
6230
+ }
6231
+ let files = [];
6232
+ for (let entry of entries) {
6233
+ let path = join23(dir, entry.name);
6234
+ if (entry.isDirectory()) files.push(...await findCompletionLogs(path));
6235
+ else if (entry.name === "completion.log" && path.includes("trae.ai-code-completion"))
6236
+ try {
6237
+ files.push({ path, mtimeMs: (await stat5(path)).mtimeMs });
6238
+ } catch {
6239
+ }
6240
+ }
6241
+ return files;
6242
+ }
6243
+ async function readFileTail(path, maxBytes = 2 * 1024 * 1024) {
6244
+ let handle = await open3(path, "r");
6245
+ try {
6246
+ let size = (await handle.stat()).size, length = Math.min(size, maxBytes), buffer = Buffer.alloc(length);
6247
+ return await handle.read(buffer, 0, length, Math.max(0, size - length)), buffer.toString("utf8");
6248
+ } finally {
6249
+ await handle.close();
6250
+ }
6251
+ }
6252
+ function collectJwtUserIds(content, ids) {
6253
+ for (let token of content.match(JWT_PATTERN) ?? []) {
6254
+ let payloadPart = token.split(".")[1];
6255
+ if (payloadPart)
6256
+ try {
6257
+ let id = JSON.parse(Buffer.from(payloadPart, "base64url").toString("utf8")).data?.id;
6258
+ (typeof id == "string" || typeof id == "number") && String(id).trim() && ids.add(String(id));
6259
+ } catch {
6260
+ }
6261
+ }
6262
+ }
6263
+ async function writeCache(sessions, cacheDir) {
6264
+ await mkdir4(cacheDir, { recursive: !0, mode: 448 });
6265
+ for (let session of sessions) {
6266
+ let hash = createHash2("sha256").update(session.sessionId).digest("hex").slice(0, 32), destination = join23(cacheDir, `${hash}.json`), temporary = join23(cacheDir, `.${hash}.${process.pid}.tmp`);
6267
+ await writeFile4(temporary, `${JSON.stringify(session, null, 2)}
6268
+ `, { encoding: "utf8", mode: 384 }), await rename(temporary, destination);
6269
+ }
6270
+ }
6271
+ async function launchTrae(appPath, port) {
6272
+ await execFileAsync2("open", [
6273
+ "-g",
6274
+ "-j",
6275
+ "-na",
6276
+ appPath,
6277
+ "--args",
6278
+ `--remote-debugging-port=${port}`
6279
+ ]);
6280
+ }
6281
+ async function quitTrae() {
6282
+ if (process.platform === "darwin")
6283
+ try {
6284
+ await execFileAsync2("osascript", ["-e", 'tell application id "cn.trae.app" to quit']);
6285
+ } catch {
6286
+ }
6287
+ }
6288
+ async function isTraeRunning() {
6289
+ try {
6290
+ return await execFileAsync2("pgrep", ["-x", "TRAE"]), !0;
6291
+ } catch {
6292
+ return !1;
6293
+ }
6294
+ }
6295
+ async function isPortAvailable(port) {
6296
+ return new Promise((resolve5) => {
6297
+ let server = createServer();
6298
+ server.once("error", () => resolve5(!1)), server.listen(port, "127.0.0.1", () => server.close(() => resolve5(!0)));
6299
+ });
6300
+ }
6301
+ async function findFreePort() {
6302
+ return new Promise((resolve5, reject) => {
6303
+ let server = createServer();
6304
+ server.once("error", reject), server.listen(0, "127.0.0.1", () => {
6305
+ let address = server.address(), port = typeof address == "object" && address ? address.port : 0;
6306
+ server.close((error) => error ? reject(error) : resolve5(port));
6307
+ });
6308
+ });
6309
+ }
6310
+ function resolveTraeCnUserDataDir() {
6311
+ return process.platform === "darwin" ? join23(homedir22(), "Library", "Application Support", "Trae CN") : process.platform === "win32" ? join23(process.env.APPDATA?.trim() || join23(homedir22(), "AppData", "Roaming"), "Trae CN") : join23(process.env.XDG_CONFIG_HOME?.trim() || join23(homedir22(), ".config"), "Trae CN");
6312
+ }
6313
+ async function fetchWithTimeout(url, timeoutMs) {
6314
+ let controller = new AbortController(), timer = setTimeout(() => controller.abort(), timeoutMs);
6315
+ try {
6316
+ return await fetch(url, { signal: controller.signal });
6317
+ } finally {
6318
+ clearTimeout(timer);
6319
+ }
6320
+ }
6321
+ function normalizePort(value) {
6322
+ if (value != null)
6323
+ return Number.isInteger(value) && value > 0 && value <= 65535 ? value : void 0;
6324
+ }
6325
+ function clampTimeout(value) {
6326
+ return Number.isFinite(value) ? Math.min(18e4, Math.max(5e3, Math.floor(value))) : 12e4;
6327
+ }
6328
+ function sanitizeMessage(value) {
6329
+ return String(value ?? "").replace(/eyJ[A-Za-z0-9_.-]+/g, "<token>").replace(/[A-Za-z0-9_-]{24,}/g, "<id>").slice(0, 300);
6330
+ }
6331
+ function tokenValue2(value) {
6332
+ let number = typeof value == "number" ? value : Number(value);
6333
+ return Number.isFinite(number) && number > 0 ? Math.floor(number) : 0;
6334
+ }
6335
+ function stringValue4(value) {
6336
+ return typeof value == "string" ? value.trim() : "";
6337
+ }
6338
+ function delay(ms) {
6339
+ return new Promise((resolve5) => setTimeout(resolve5, ms));
6340
+ }
6341
+
5723
6342
  // src/cli.ts
5724
6343
  var argv = process.argv.slice(2), command = argv[0];
5725
6344
  await (async () => {
@@ -5750,6 +6369,15 @@ await (async () => {
5750
6369
  let parsed = parseArgs(argv.slice(1));
5751
6370
  if (parsed.flags.help) return helpForSubcommand("sync");
5752
6371
  await runSync(parsed.flags, parsed.positionals);
6372
+ } else if (command === "trae") {
6373
+ let sub = argv[1], parsed = parseArgs(argv.slice(2));
6374
+ if (sub === "--help" || sub === "-h" || parsed.flags.help) return helpForSubcommand("trae");
6375
+ if (sub === "sync")
6376
+ await runTraeSync(parsed.flags, parsed.positionals);
6377
+ else {
6378
+ 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]");
6380
+ }
5753
6381
  } else if (command === "init") {
5754
6382
  let parsed = parseArgs(argv.slice(1));
5755
6383
  if (parsed.flags.help) return helpForSubcommand("init");
@@ -5931,9 +6559,9 @@ async function runEnroll(flags) {
5931
6559
  }
5932
6560
  function prompt(question) {
5933
6561
  let rl = createInterface4({ input: process.stdin, output: process.stdout });
5934
- return new Promise((resolve4) => {
6562
+ return new Promise((resolve5) => {
5935
6563
  rl.question(question, (answer) => {
5936
- rl.close(), resolve4(answer.trim());
6564
+ rl.close(), resolve5(answer.trim());
5937
6565
  });
5938
6566
  });
5939
6567
  }
@@ -5988,6 +6616,24 @@ async function runSync(flags, positionals = []) {
5988
6616
  results: uploadResults
5989
6617
  }, null, 2));
5990
6618
  }
6619
+ async function runTraeSync(flags, positionals = []) {
6620
+ let zh2 = (await readConfig()).lang === "zh";
6621
+ assertNoPositionals("trae sync", positionals, zh2);
6622
+ let portFlag = resolveOptionalString(flags.port, void 0), port = portFlag ? parsePositiveInt2(portFlag, "--port") : void 0;
6623
+ 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
+ });
6630
+ if (flags.json) {
6631
+ console.log(JSON.stringify(result, null, 2));
6632
+ return;
6633
+ }
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}`);
6636
+ }
5991
6637
  function buildActivityPayloadByDate(items, visibility) {
5992
6638
  let map = /* @__PURE__ */ new Map(), sanitized = applyProjectPrivacy(items, visibility);
5993
6639
  for (let item of sanitized) {
@@ -6190,6 +6836,7 @@ function printHelp(zh2 = !1) {
6190
6836
  ["report [--today] [--range 7d|1m|3m|all] [--detail] [--json]", "\u672C\u5730\u7528\u91CF\u62A5\u544A"],
6191
6837
  ["activity [--today] [--range 7d|1m|3m|all] [--detail] [--json]", "\u672C\u5730\u4EA4\u4E92\u6307\u6807"],
6192
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"],
6193
6840
  ["scan/report/sync --from YYYY-MM-DD [--to YYYY-MM-DD]", "\u6307\u5B9A\u65E5\u671F\u8303\u56F4\uFF08--start/--end \u540C\u4E49\uFF09"],
6194
6841
  ["project [list|alias]", "\u9879\u76EE\u7BA1\u7406\u4E0E\u522B\u540D\u8BBE\u7F6E"],
6195
6842
  ["pricing [status|update] [--url URL]", "\u67E5\u770B/\u66F4\u65B0\u5B9A\u4EF7\u76EE\u5F55"],
@@ -6204,6 +6851,7 @@ function printHelp(zh2 = !1) {
6204
6851
  ["report [--today] [--range 7d|1m|3m|all] [--detail] [--json]", "Local usage report"],
6205
6852
  ["activity [--today] [--range 7d|1m|3m|all] [--detail] [--json]", "Local interaction metrics"],
6206
6853
  ["sync [--today] [--range 7d|1m|3m]", "Upload usage to server"],
6854
+ ["trae sync [--port 9230] [--no-launch]", "Sync local Trae CN history"],
6207
6855
  ["scan/report/sync --from YYYY-MM-DD [--to YYYY-MM-DD]", "Date range (--start/--end aliases)"],
6208
6856
  ["project [list|alias]", "Project management & aliases"],
6209
6857
  ["pricing [status|update] [--url URL]", "Pricing catalog management"],
@@ -6227,6 +6875,7 @@ function printUsageHint(zh2 = !1) {
6227
6875
  ["report [--today] [--range 7d|1m|3m|all]", "\u672C\u5730\u7528\u91CF\u62A5\u544A"],
6228
6876
  ["activity [--range 7d|1m|3m|all]", "\u672C\u5730\u4EA4\u4E92\u6307\u6807"],
6229
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"],
6230
6879
  ["project [list|alias]", "\u9879\u76EE\u7BA1\u7406\u4E0E\u522B\u540D\u8BBE\u7F6E"],
6231
6880
  ["pricing [status|update]", "\u67E5\u770B/\u66F4\u65B0\u5B9A\u4EF7\u76EE\u5F55"],
6232
6881
  ["schedule [on|off|status]", "\u5B9A\u65F6\u540C\u6B65\u7BA1\u7406"],
@@ -6237,6 +6886,7 @@ function printUsageHint(zh2 = !1) {
6237
6886
  ["report [--today] [--range 7d|1m|3m|all]", "Local usage report"],
6238
6887
  ["activity [--range 7d|1m|3m|all]", "Local interaction metrics"],
6239
6888
  ["sync [--today] [--range 7d|1m|3m]", "Upload usage to server"],
6889
+ ["trae sync", "Sync local Trae CN history"],
6240
6890
  ["project [list|alias]", "Project management & aliases"],
6241
6891
  ["pricing [status|update]", "Pricing catalog management"],
6242
6892
  ["schedule [on|off|status]", "Scheduled sync management"],