@aiusage/cli 1.7.4 → 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 +32 -4
- package/README.zh-CN.md +43 -3
- package/THIRD_PARTY_NOTICES.md +29 -0
- package/dist/cli.js +1303 -187
- package/package.json +5 -1
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((
|
|
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) :
|
|
3109
|
+
(error, stdout) => error ? reject(error) : resolve5(stdout)
|
|
3110
3110
|
);
|
|
3111
3111
|
});
|
|
3112
3112
|
}
|
|
@@ -3253,7 +3253,229 @@ 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
|
+
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
|
+
}
|
|
3272
|
+
async function scanTraeDates(targetDates, options = {}) {
|
|
3273
|
+
let dates = new Set(targetDates);
|
|
3274
|
+
if (dates.size === 0) return /* @__PURE__ */ new Map();
|
|
3275
|
+
let nativeDir = options.nativeCacheDir ?? resolveTraeNativeCacheDir(), intlDir = options.intlCacheDir ?? resolveTraeIntlCacheDir(), tokscaleDir = options.tokscaleCacheDir ?? resolveTokscaleTraeCacheDir(), cacheSources = [.../* @__PURE__ */ new Set([
|
|
3276
|
+
`${nativeDir}\0native`,
|
|
3277
|
+
`${intlDir}\0intl`,
|
|
3278
|
+
`${tokscaleDir}\0tokscale`
|
|
3279
|
+
])], files = (await Promise.all(cacheSources.map(async (source) => {
|
|
3280
|
+
let [dir, kind] = source.split("\0");
|
|
3281
|
+
return (await walkFiles(dir, ".json")).map((filePath) => ({ filePath, kind }));
|
|
3282
|
+
}))).flat();
|
|
3283
|
+
if (files.length === 0) return emptyResult(dates);
|
|
3284
|
+
let grouped = initDateMap(dates), selectedEvents = /* @__PURE__ */ new Map(), sessionSets = /* @__PURE__ */ new Map();
|
|
3285
|
+
for (let { filePath, kind } of files) {
|
|
3286
|
+
let value = await readJson2(filePath);
|
|
3287
|
+
if (value == null) continue;
|
|
3288
|
+
let events = kind === "native" ? parseNativeCache(value) : parseIntlCache(value);
|
|
3289
|
+
for (let event of events) {
|
|
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);
|
|
3322
|
+
}
|
|
3323
|
+
let sessionKey = `${usageDate}|${breakdownKey}`, sessions = sessionSets.get(sessionKey);
|
|
3324
|
+
sessions || (sessions = /* @__PURE__ */ new Set(), sessionSets.set(sessionKey, sessions)), sessions.add(event.sessionId);
|
|
3325
|
+
}
|
|
3326
|
+
let result = finalize(grouped);
|
|
3327
|
+
for (let [usageDate, breakdowns] of result)
|
|
3328
|
+
for (let breakdown of breakdowns) {
|
|
3329
|
+
let key = `${usageDate}|${breakdown.product}|${breakdown.provider}|${breakdown.model}|${breakdown.project}`;
|
|
3330
|
+
breakdown.sessionCount = sessionSets.get(key)?.size ?? 0;
|
|
3331
|
+
}
|
|
3332
|
+
return result;
|
|
3333
|
+
}
|
|
3334
|
+
function parseNativeCache(value) {
|
|
3335
|
+
if (!isRecord2(value) || value.schemaVersion !== 1 || value.source !== "trae-cn-local-rpc") return [];
|
|
3336
|
+
let sessionId = stringValue2(value.sessionId), project = stringValue2(value.project) || "unknown";
|
|
3337
|
+
if (!sessionId || !Array.isArray(value.events)) return [];
|
|
3338
|
+
let events = [];
|
|
3339
|
+
for (let raw of value.events) {
|
|
3340
|
+
if (!isRecord2(raw)) continue;
|
|
3341
|
+
let messageId = stringValue2(raw.messageId), timestamp = parseTs(raw.timestamp);
|
|
3342
|
+
if (!messageId || !timestamp) continue;
|
|
3343
|
+
let model = normalizeTraeModel(stringValue2(raw.model)), tokens = {
|
|
3344
|
+
input: tokenValue(raw.inputTokens),
|
|
3345
|
+
cached: tokenValue(raw.cachedInputTokens),
|
|
3346
|
+
cacheWrite: tokenValue(raw.cacheWriteTokens),
|
|
3347
|
+
output: tokenValue(raw.outputTokens),
|
|
3348
|
+
reasoning: tokenValue(raw.reasoningOutputTokens)
|
|
3349
|
+
};
|
|
3350
|
+
tokenTotal2(tokens) !== 0 && events.push({
|
|
3351
|
+
dedupKey: `trae-cn:${messageId}`,
|
|
3352
|
+
sessionId,
|
|
3353
|
+
timestamp,
|
|
3354
|
+
product: "trae-cn",
|
|
3355
|
+
provider: inferProviderFromModel(model, "trae"),
|
|
3356
|
+
model,
|
|
3357
|
+
project,
|
|
3358
|
+
...tokens
|
|
3359
|
+
});
|
|
3360
|
+
}
|
|
3361
|
+
return events;
|
|
3362
|
+
}
|
|
3363
|
+
function parseIntlCache(value) {
|
|
3364
|
+
if (!Array.isArray(value)) return [];
|
|
3365
|
+
let events = [];
|
|
3366
|
+
for (let raw of value) {
|
|
3367
|
+
if (!isRecord2(raw)) continue;
|
|
3368
|
+
let session = raw, sessionId = stringValue2(session.session_id), timestamp = parseTs(session.usage_time);
|
|
3369
|
+
if (!sessionId || !timestamp || !session.usage_time || session.usage_time <= 0) continue;
|
|
3370
|
+
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 = {
|
|
3371
|
+
input: tokenValue(extra.input_token),
|
|
3372
|
+
cached: tokenValue(extra.cache_read_token),
|
|
3373
|
+
cacheWrite: tokenValue(extra.cache_write_token),
|
|
3374
|
+
output: tokenValue(extra.output_token),
|
|
3375
|
+
reasoning: 0
|
|
3376
|
+
};
|
|
3377
|
+
tokenTotal2(tokens) !== 0 && events.push({
|
|
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}`,
|
|
3381
|
+
sessionId,
|
|
3382
|
+
timestamp,
|
|
3383
|
+
product: "trae-intl",
|
|
3384
|
+
provider: inferProviderFromModel(model, "trae"),
|
|
3385
|
+
model,
|
|
3386
|
+
project: "unknown",
|
|
3387
|
+
...tokens,
|
|
3388
|
+
costUSD: positiveNumber(session.dollar_float)
|
|
3389
|
+
});
|
|
3390
|
+
}
|
|
3391
|
+
return events;
|
|
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
|
+
}
|
|
3399
|
+
function normalizeTraeModel(name) {
|
|
3400
|
+
let value = name?.trim() ?? "";
|
|
3401
|
+
return {
|
|
3402
|
+
"GPT-5.4": "gpt-5.4",
|
|
3403
|
+
"GPT-5.3-Codex": "gpt-5.3-codex",
|
|
3404
|
+
"GPT-5.3 Codex": "gpt-5.3-codex",
|
|
3405
|
+
"GPT-5.3": "gpt-5.3",
|
|
3406
|
+
"GPT-5.2-Codex": "gpt-5.2-codex",
|
|
3407
|
+
"GPT-5.2 Codex": "gpt-5.2-codex",
|
|
3408
|
+
"GPT-5.2": "gpt-5.2",
|
|
3409
|
+
"GPT-5.1-Codex": "gpt-5.1-codex",
|
|
3410
|
+
"GPT-5.1 Codex": "gpt-5.1-codex",
|
|
3411
|
+
"GPT-5.1": "gpt-5.1",
|
|
3412
|
+
"Gemini 3.1 Pro": "gemini-3.1-pro",
|
|
3413
|
+
"Gemini 3.1": "gemini-3.1",
|
|
3414
|
+
"GLM 5.1": "glm-5.1",
|
|
3415
|
+
"GLM-5.1": "glm-5.1",
|
|
3416
|
+
"Claude Sonnet 4.6": "claude-sonnet-4.6",
|
|
3417
|
+
"Claude-Sonnet-4.6": "claude-sonnet-4.6",
|
|
3418
|
+
"Claude Sonnet 4.5": "claude-sonnet-4.5",
|
|
3419
|
+
"Claude-Sonnet-4.5": "claude-sonnet-4.5"
|
|
3420
|
+
}[value] ?? (value || "trae-unknown");
|
|
3421
|
+
}
|
|
3422
|
+
async function readJson2(filePath) {
|
|
3423
|
+
try {
|
|
3424
|
+
return JSON.parse(await readFile12(filePath, "utf8"));
|
|
3425
|
+
} catch {
|
|
3426
|
+
return null;
|
|
3427
|
+
}
|
|
3428
|
+
}
|
|
3429
|
+
function tokenValue(value) {
|
|
3430
|
+
let number = typeof value == "number" ? value : Number(value);
|
|
3431
|
+
return Number.isFinite(number) && number > 0 ? Math.floor(number) : 0;
|
|
3432
|
+
}
|
|
3433
|
+
function positiveNumber(value) {
|
|
3434
|
+
let number = typeof value == "number" ? value : Number(value);
|
|
3435
|
+
return Number.isFinite(number) && number > 0 ? number : void 0;
|
|
3436
|
+
}
|
|
3437
|
+
function tokenTotal2(tokens) {
|
|
3438
|
+
return tokens.input + tokens.cached + tokens.cacheWrite + tokens.output + tokens.reasoning;
|
|
3439
|
+
}
|
|
3440
|
+
function stringValue2(value) {
|
|
3441
|
+
return typeof value == "string" ? value.trim() : "";
|
|
3442
|
+
}
|
|
3443
|
+
function isRecord2(value) {
|
|
3444
|
+
return value != null && typeof value == "object" && !Array.isArray(value);
|
|
3445
|
+
}
|
|
3446
|
+
|
|
3256
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
|
+
}
|
|
3257
3479
|
async function scanDate(targetDate, options = {}) {
|
|
3258
3480
|
let [result] = await scanDates([targetDate], options);
|
|
3259
3481
|
return result ?? {
|
|
@@ -3265,23 +3487,27 @@ async function scanDate(targetDate, options = {}) {
|
|
|
3265
3487
|
async function scanDates(targetDates, options = {}) {
|
|
3266
3488
|
let uniqueDates = [...new Set(targetDates)];
|
|
3267
3489
|
if (uniqueDates.length === 0) return [];
|
|
3268
|
-
let scanners = [
|
|
3269
|
-
scanAntigravityDates(uniqueDates),
|
|
3270
|
-
scanClaudeDates(uniqueDates, void 0, options.projectAliases),
|
|
3271
|
-
scanCodexDates(uniqueDates, void 0, options.projectAliases),
|
|
3272
|
-
scanCopilotDates(uniqueDates, void 0, options.projectAliases),
|
|
3273
|
-
scanCopilotVscodeDates(uniqueDates, void 0, options.projectAliases),
|
|
3274
|
-
scanCursorDates(uniqueDates),
|
|
3275
|
-
scanGeminiDates(uniqueDates, void 0, options.projectAliases),
|
|
3276
|
-
scanQwenDates(uniqueDates, void 0, options.projectAliases),
|
|
3277
|
-
scanKimiDates(uniqueDates, void 0, options.projectAliases),
|
|
3278
|
-
scanAmpDates(uniqueDates, void 0, options.projectAliases),
|
|
3279
|
-
scanDroidDates(uniqueDates, void 0, options.projectAliases),
|
|
3280
|
-
scanOpencodeDates(uniqueDates, void 0, options.projectAliases),
|
|
3281
|
-
scanPiDates(uniqueDates, void 0, options.projectAliases)
|
|
3282
|
-
|
|
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);
|
|
3283
3509
|
return uniqueDates.map((usageDate) => {
|
|
3284
|
-
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(
|
|
3285
3511
|
(acc, b) => ({
|
|
3286
3512
|
eventCount: acc.eventCount + b.eventCount,
|
|
3287
3513
|
inputTokens: acc.inputTokens + b.inputTokens,
|
|
@@ -3387,7 +3613,7 @@ function chunkDateRange(startDate, endDate) {
|
|
|
3387
3613
|
}
|
|
3388
3614
|
|
|
3389
3615
|
// src/scanners/anthropic-csv.ts
|
|
3390
|
-
import { readFile as
|
|
3616
|
+
import { readFile as readFile13 } from "node:fs/promises";
|
|
3391
3617
|
async function scanAnthropicCsvDates(targetDates, csvFilePaths) {
|
|
3392
3618
|
if (!targetDates.length) return /* @__PURE__ */ new Map();
|
|
3393
3619
|
let targetDateSet = new Set(targetDates), grouped = new Map(
|
|
@@ -3396,7 +3622,7 @@ async function scanAnthropicCsvDates(targetDates, csvFilePaths) {
|
|
|
3396
3622
|
for (let filePath of csvFilePaths) {
|
|
3397
3623
|
let content;
|
|
3398
3624
|
try {
|
|
3399
|
-
content = await
|
|
3625
|
+
content = await readFile13(filePath, "utf-8");
|
|
3400
3626
|
} catch {
|
|
3401
3627
|
continue;
|
|
3402
3628
|
}
|
|
@@ -3454,11 +3680,14 @@ function parseCsv(content) {
|
|
|
3454
3680
|
}
|
|
3455
3681
|
|
|
3456
3682
|
// src/report.ts
|
|
3457
|
-
import { readdir as readdir5, readFile as
|
|
3458
|
-
import { homedir as
|
|
3459
|
-
import { basename as basename11, dirname as dirname6, join as
|
|
3683
|
+
import { readdir as readdir5, readFile as readFile14 } from "node:fs/promises";
|
|
3684
|
+
import { homedir as homedir15 } from "node:os";
|
|
3685
|
+
import { basename as basename11, dirname as dirname6, join as join16 } from "node:path";
|
|
3460
3686
|
async function buildLocalReport(range, options = {}) {
|
|
3461
|
-
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, {
|
|
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
|
+
});
|
|
3462
3691
|
for (let result of results) {
|
|
3463
3692
|
let usageDate = result.usageDate, dayTotals = withTotalTokens(result.totals), hasData = result.breakdowns.length > 0 || dayTotals.eventCount > 0 || dayTotals.totalTokens > 0;
|
|
3464
3693
|
if (hasData) {
|
|
@@ -3492,14 +3721,15 @@ async function buildLocalReport(range, options = {}) {
|
|
|
3492
3721
|
source: "bundled",
|
|
3493
3722
|
version: options.pricingCatalog?.version ?? "bundled"
|
|
3494
3723
|
},
|
|
3495
|
-
pricingWarnings: [...pricingWarnings].sort()
|
|
3724
|
+
pricingWarnings: [...pricingWarnings].sort(),
|
|
3725
|
+
...options.tools ? { tools: [...options.tools] } : {}
|
|
3496
3726
|
};
|
|
3497
3727
|
}
|
|
3498
3728
|
function parseReportRange(value, today) {
|
|
3499
3729
|
if (today) return "today";
|
|
3500
3730
|
if (value === void 0 || value === !0) return "7d";
|
|
3501
|
-
if (value === "7d" || value === "1m" || value === "3m" || value === "all" || value === "today") return value;
|
|
3502
|
-
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");
|
|
3503
3733
|
}
|
|
3504
3734
|
function getRangeLabel(range) {
|
|
3505
3735
|
switch (range) {
|
|
@@ -3509,6 +3739,8 @@ function getRangeLabel(range) {
|
|
|
3509
3739
|
return "\u6700\u8FD1 30 \u5929";
|
|
3510
3740
|
case "3m":
|
|
3511
3741
|
return "\u6700\u8FD1 90 \u5929";
|
|
3742
|
+
case "6m":
|
|
3743
|
+
return "\u6700\u8FD1 180 \u5929";
|
|
3512
3744
|
case "all":
|
|
3513
3745
|
return "\u5168\u90E8\u5386\u53F2";
|
|
3514
3746
|
case "today":
|
|
@@ -3516,35 +3748,20 @@ function getRangeLabel(range) {
|
|
|
3516
3748
|
}
|
|
3517
3749
|
}
|
|
3518
3750
|
function buildPresetDates(range) {
|
|
3519
|
-
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 = [];
|
|
3520
3752
|
for (let offset = days - 1; offset >= 0; offset -= 1) {
|
|
3521
3753
|
let day = new Date(today);
|
|
3522
3754
|
day.setDate(today.getDate() - offset), result.push(dateKey(day));
|
|
3523
3755
|
}
|
|
3524
3756
|
return result;
|
|
3525
3757
|
}
|
|
3526
|
-
async function discoverAllDates() {
|
|
3527
|
-
let dates = /* @__PURE__ */ new Set(), home =
|
|
3528
|
-
|
|
3529
|
-
|
|
3530
|
-
|
|
3531
|
-
discoverGeminiDates(dates),
|
|
3532
|
-
discoverCopilotVscodeDates(dates),
|
|
3533
|
-
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),
|
|
3542
|
-
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)
|
|
3545
|
-
]);
|
|
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);
|
|
3546
3763
|
let explicitCopilotOtel = process.env.COPILOT_OTEL_FILE_EXPORTER_PATH?.trim();
|
|
3547
|
-
return explicitCopilotOtel && await discoverJsonlFileDates(explicitCopilotOtel, dates), [...dates].sort();
|
|
3764
|
+
return explicitCopilotOtel && includes("copilot-cli") && await discoverJsonlFileDates(explicitCopilotOtel, dates), [...dates].sort();
|
|
3548
3765
|
}
|
|
3549
3766
|
async function discoverGenericJsonlDates(baseDir, dates) {
|
|
3550
3767
|
let files = [];
|
|
@@ -3592,6 +3809,7 @@ async function discoverGenericJsonDates(baseDir, dates) {
|
|
|
3592
3809
|
} catch {
|
|
3593
3810
|
continue;
|
|
3594
3811
|
}
|
|
3812
|
+
if (Array.isArray(data) && data.length === 0) continue;
|
|
3595
3813
|
(Array.isArray(data) ? data.reduce((found, row) => collectRecordDates(row, dates) || found, !1) : collectRecordDates(data, dates)) || await addFileModifiedDate(filePath, dates);
|
|
3596
3814
|
}
|
|
3597
3815
|
}
|
|
@@ -3611,6 +3829,7 @@ function collectRecordDates(record, dates) {
|
|
|
3611
3829
|
record._hrTime,
|
|
3612
3830
|
record.observedTimestamp,
|
|
3613
3831
|
record.timeUnixNano,
|
|
3832
|
+
record.usage_time,
|
|
3614
3833
|
record.time?.created
|
|
3615
3834
|
];
|
|
3616
3835
|
for (let value of candidates) {
|
|
@@ -3623,7 +3842,8 @@ function collectRecordDates(record, dates) {
|
|
|
3623
3842
|
...Array.isArray(record.data?.messages) ? record.data.messages : [],
|
|
3624
3843
|
...Array.isArray(record.data?.history) ? record.data.history : [],
|
|
3625
3844
|
...Array.isArray(record.$set?.messages) ? record.$set.messages : [],
|
|
3626
|
-
...Array.isArray(record.usageLedger?.events) ? record.usageLedger.events : []
|
|
3845
|
+
...Array.isArray(record.usageLedger?.events) ? record.usageLedger.events : [],
|
|
3846
|
+
...Array.isArray(record.events) ? record.events : []
|
|
3627
3847
|
];
|
|
3628
3848
|
for (let row of nestedRows) found = collectRecordDates(row, dates) || found;
|
|
3629
3849
|
return found;
|
|
@@ -3654,20 +3874,20 @@ async function walkForFiles(dir, ext, result) {
|
|
|
3654
3874
|
return;
|
|
3655
3875
|
}
|
|
3656
3876
|
for (let entry of entries) {
|
|
3657
|
-
let fullPath =
|
|
3877
|
+
let fullPath = join16(dir, entry.name);
|
|
3658
3878
|
entry.isDirectory() ? await walkForFiles(fullPath, ext, result) : entry.name.endsWith(ext) && result.push(fullPath);
|
|
3659
3879
|
}
|
|
3660
3880
|
}
|
|
3661
3881
|
async function discoverGeminiDates(dates) {
|
|
3662
|
-
let baseDir =
|
|
3882
|
+
let baseDir = join16(homedir15(), ".gemini", "tmp");
|
|
3663
3883
|
await Promise.all([
|
|
3664
3884
|
discoverGenericJsonDates(baseDir, dates),
|
|
3665
3885
|
discoverGenericJsonlDates(baseDir, dates)
|
|
3666
3886
|
]);
|
|
3667
3887
|
}
|
|
3668
3888
|
async function discoverCopilotVscodeDates(dates) {
|
|
3669
|
-
let home =
|
|
3670
|
-
await walkForFiles(
|
|
3889
|
+
let home = homedir15(), logFiles = [];
|
|
3890
|
+
await walkForFiles(join16(home, "Library", "Application Support", "Code", "logs"), ".log", logFiles);
|
|
3671
3891
|
for (let filePath of logFiles) {
|
|
3672
3892
|
if (basename11(filePath) !== "GitHub Copilot Chat.log") continue;
|
|
3673
3893
|
let content = await safeReadUtf8(filePath);
|
|
@@ -3680,7 +3900,7 @@ async function discoverCopilotVscodeDates(dates) {
|
|
|
3680
3900
|
}
|
|
3681
3901
|
}
|
|
3682
3902
|
let sessionFiles = [];
|
|
3683
|
-
await walkForFiles(
|
|
3903
|
+
await walkForFiles(join16(home, "Library", "Application Support", "Code", "User", "workspaceStorage"), ".json", sessionFiles);
|
|
3684
3904
|
for (let filePath of sessionFiles) {
|
|
3685
3905
|
if (!isChatSessionFile2(filePath)) continue;
|
|
3686
3906
|
let content = await safeReadUtf8(filePath);
|
|
@@ -3699,7 +3919,7 @@ async function discoverCopilotVscodeDates(dates) {
|
|
|
3699
3919
|
}
|
|
3700
3920
|
let crdtFiles = [];
|
|
3701
3921
|
await walkForFiles(
|
|
3702
|
-
|
|
3922
|
+
join16(home, "Library", "Application Support", "Code", "User", "workspaceStorage"),
|
|
3703
3923
|
".jsonl",
|
|
3704
3924
|
crdtFiles
|
|
3705
3925
|
);
|
|
@@ -3731,8 +3951,8 @@ function isChatSessionFile2(filePath) {
|
|
|
3731
3951
|
return basename11(dirname6(filePath)) === "chatSessions";
|
|
3732
3952
|
}
|
|
3733
3953
|
async function discoverAntigravityDates(dates) {
|
|
3734
|
-
let home =
|
|
3735
|
-
await walkForFiles(
|
|
3954
|
+
let home = homedir15(), brainFiles = [], browserFiles = [];
|
|
3955
|
+
await walkForFiles(join16(home, ".gemini", "antigravity", "brain"), ".json", brainFiles), await walkForFiles(join16(home, ".gemini", "antigravity", "browser_recordings"), ".json", browserFiles);
|
|
3736
3956
|
for (let filePath of brainFiles) {
|
|
3737
3957
|
if (basename11(filePath) !== "task.md.metadata.json") continue;
|
|
3738
3958
|
let content = await safeReadUtf8(filePath);
|
|
@@ -3761,9 +3981,9 @@ async function discoverAntigravityDates(dates) {
|
|
|
3761
3981
|
}
|
|
3762
3982
|
}
|
|
3763
3983
|
async function discoverClaudeDates(dates) {
|
|
3764
|
-
let home =
|
|
3765
|
-
|
|
3766
|
-
|
|
3984
|
+
let home = homedir15(), baseDirs = [
|
|
3985
|
+
join16(home, ".config", "claude", "projects"),
|
|
3986
|
+
join16(home, ".claude", "projects")
|
|
3767
3987
|
];
|
|
3768
3988
|
for (let baseDir of baseDirs) {
|
|
3769
3989
|
let projectDirs;
|
|
@@ -3775,7 +3995,7 @@ async function discoverClaudeDates(dates) {
|
|
|
3775
3995
|
for (let projectDir of projectDirs) {
|
|
3776
3996
|
let jsonlFiles = [];
|
|
3777
3997
|
try {
|
|
3778
|
-
await walkForClaudeJsonl(
|
|
3998
|
+
await walkForClaudeJsonl(join16(baseDir, projectDir), jsonlFiles);
|
|
3779
3999
|
} catch {
|
|
3780
4000
|
continue;
|
|
3781
4001
|
}
|
|
@@ -3799,7 +4019,7 @@ async function discoverClaudeDates(dates) {
|
|
|
3799
4019
|
}
|
|
3800
4020
|
}
|
|
3801
4021
|
async function discoverCodexDates(dates) {
|
|
3802
|
-
let baseDir =
|
|
4022
|
+
let baseDir = join16(homedir15(), ".codex"), files = await collectCodexSessionFiles(baseDir);
|
|
3803
4023
|
for (let filePath of files) {
|
|
3804
4024
|
let content = await safeReadUtf8(filePath);
|
|
3805
4025
|
if (content)
|
|
@@ -3821,17 +4041,17 @@ async function discoverCodexDates(dates) {
|
|
|
3821
4041
|
async function collectCodexSessionFiles(baseDir) {
|
|
3822
4042
|
let paths = [];
|
|
3823
4043
|
try {
|
|
3824
|
-
let archivedFiles = await readdir5(
|
|
4044
|
+
let archivedFiles = await readdir5(join16(baseDir, "archived_sessions"));
|
|
3825
4045
|
for (let file of archivedFiles)
|
|
3826
|
-
file.endsWith(".jsonl") && paths.push(
|
|
4046
|
+
file.endsWith(".jsonl") && paths.push(join16(baseDir, "archived_sessions", file));
|
|
3827
4047
|
} catch {
|
|
3828
4048
|
}
|
|
3829
|
-
return await walkForCodexJsonl(
|
|
4049
|
+
return await walkForCodexJsonl(join16(baseDir, "sessions"), paths), paths;
|
|
3830
4050
|
}
|
|
3831
4051
|
async function walkForClaudeJsonl(dir, result) {
|
|
3832
4052
|
let entries = await readdir5(dir, { withFileTypes: !0 });
|
|
3833
4053
|
for (let entry of entries) {
|
|
3834
|
-
let fullPath =
|
|
4054
|
+
let fullPath = join16(dir, entry.name);
|
|
3835
4055
|
entry.isDirectory() ? await walkForClaudeJsonl(fullPath, result) : entry.name.endsWith(".jsonl") && result.push(fullPath);
|
|
3836
4056
|
}
|
|
3837
4057
|
}
|
|
@@ -3843,13 +4063,13 @@ async function walkForCodexJsonl(dir, result) {
|
|
|
3843
4063
|
return;
|
|
3844
4064
|
}
|
|
3845
4065
|
for (let entry of entries) {
|
|
3846
|
-
let fullPath =
|
|
4066
|
+
let fullPath = join16(dir, entry.name);
|
|
3847
4067
|
entry.isDirectory() ? await walkForCodexJsonl(fullPath, result) : entry.name.startsWith("rollout-") && entry.name.endsWith(".jsonl") && result.push(fullPath);
|
|
3848
4068
|
}
|
|
3849
4069
|
}
|
|
3850
4070
|
async function safeReadUtf8(filePath) {
|
|
3851
4071
|
try {
|
|
3852
|
-
return await
|
|
4072
|
+
return await readFile14(filePath, "utf-8");
|
|
3853
4073
|
} catch {
|
|
3854
4074
|
return null;
|
|
3855
4075
|
}
|
|
@@ -3900,7 +4120,7 @@ function toBreakdownTotals(breakdown, warnings, pricingCatalog) {
|
|
|
3900
4120
|
};
|
|
3901
4121
|
}
|
|
3902
4122
|
function calculateBreakdownCost(breakdown, warnings, pricingCatalog) {
|
|
3903
|
-
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;
|
|
3904
4124
|
if (breakdown.costUSD != null && breakdown.costUSD > 0 && sourceCostMatchesCatalog)
|
|
3905
4125
|
return breakdown.costUSD;
|
|
3906
4126
|
let result = calculateCost(
|
|
@@ -4135,8 +4355,8 @@ function fmtDateShort(dateStr) {
|
|
|
4135
4355
|
// src/activity.ts
|
|
4136
4356
|
import { open, readdir as readdir6 } from "node:fs/promises";
|
|
4137
4357
|
import { createInterface as createInterface3 } from "node:readline";
|
|
4138
|
-
import { homedir as
|
|
4139
|
-
import { basename as basename12, join as
|
|
4358
|
+
import { homedir as homedir16 } from "node:os";
|
|
4359
|
+
import { basename as basename12, join as join17 } from "node:path";
|
|
4140
4360
|
var FILE_CONCURRENCY3 = 16, MAX_LINE_BYTES3 = 64 * 1024 * 1024;
|
|
4141
4361
|
async function buildActivityReport(range, options = {}) {
|
|
4142
4362
|
let targetDates = options.dates ? new Set(options.dates) : void 0, [codex, claude] = await Promise.all([
|
|
@@ -4233,7 +4453,7 @@ function renderActivityReport(report, opts) {
|
|
|
4233
4453
|
`);
|
|
4234
4454
|
}
|
|
4235
4455
|
async function scanCodexActivity(targetDates, options) {
|
|
4236
|
-
let baseDir = options.codexDir ??
|
|
4456
|
+
let baseDir = options.codexDir ?? join17(homedir16(), ".codex"), acc = createAccumulator(targetDates, options.projectAliases), files = await collectCodexSessionFiles2(baseDir);
|
|
4237
4457
|
return acc.stats.filesScanned = files.length, await runWithConcurrency(files, FILE_CONCURRENCY3, async (filePath) => {
|
|
4238
4458
|
await processCodexFile2(filePath, acc);
|
|
4239
4459
|
}), finalizeActivity(acc);
|
|
@@ -4260,12 +4480,12 @@ async function processCodexFile2(filePath, acc) {
|
|
|
4260
4480
|
continue;
|
|
4261
4481
|
}
|
|
4262
4482
|
if (record.type === "session_meta") {
|
|
4263
|
-
let id =
|
|
4483
|
+
let id = stringValue3(record.payload?.id);
|
|
4264
4484
|
id && (sessionId = id), acc.stats.sessions.add(`codex:${sessionId}`);
|
|
4265
4485
|
continue;
|
|
4266
4486
|
}
|
|
4267
4487
|
if (record.type === "turn_context") {
|
|
4268
|
-
let cwd =
|
|
4488
|
+
let cwd = stringValue3(record.payload?.cwd);
|
|
4269
4489
|
cwd && (projectFields = resolveProjectFields(cwd, acc.projectAliases));
|
|
4270
4490
|
continue;
|
|
4271
4491
|
}
|
|
@@ -4309,7 +4529,7 @@ function handleCodexResponseItem(item, usageDate, projectFields, sessionId, file
|
|
|
4309
4529
|
projectFields,
|
|
4310
4530
|
sessionId,
|
|
4311
4531
|
kind,
|
|
4312
|
-
name: kind === "agent_call" ?
|
|
4532
|
+
name: kind === "agent_call" ? stringValue3(args.agent_type) ?? name : name,
|
|
4313
4533
|
confidence: "exact",
|
|
4314
4534
|
dedupeKey: baseKey
|
|
4315
4535
|
});
|
|
@@ -4363,14 +4583,14 @@ function handleCodexEvent(record, usageDate, projectFields, sessionId, filePath,
|
|
|
4363
4583
|
projectFields,
|
|
4364
4584
|
sessionId,
|
|
4365
4585
|
timestamp: record.timestamp ?? "",
|
|
4366
|
-
content:
|
|
4586
|
+
content: stringValue3(record.payload?.message),
|
|
4367
4587
|
fallbackKey: `${filePath}:${usageDate}:${sessionId}:event_user_message:${record.timestamp ?? ""}`
|
|
4368
4588
|
});
|
|
4369
4589
|
return;
|
|
4370
4590
|
}
|
|
4371
4591
|
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
4592
|
if (!kind) return;
|
|
4373
|
-
let callId =
|
|
4593
|
+
let callId = stringValue3(record.payload?.call_id);
|
|
4374
4594
|
addActivity(acc, {
|
|
4375
4595
|
usageDate,
|
|
4376
4596
|
provider: "openai",
|
|
@@ -4394,7 +4614,7 @@ async function scanClaudeActivity(targetDates, options) {
|
|
|
4394
4614
|
}
|
|
4395
4615
|
for (let entry of projectDirs) {
|
|
4396
4616
|
if (!entry.isDirectory()) continue;
|
|
4397
|
-
let projectPath =
|
|
4617
|
+
let projectPath = join17(baseDir, entry.name), jsonlFiles = [];
|
|
4398
4618
|
await walkJsonl(projectPath, jsonlFiles);
|
|
4399
4619
|
let fields = resolveClaudeProject(projectPath, acc.projectAliases);
|
|
4400
4620
|
for (let filePath of jsonlFiles) fileJobs.push({ filePath, projectFields: fields });
|
|
@@ -4532,22 +4752,22 @@ function acceptsDate(acc, usageDate) {
|
|
|
4532
4752
|
async function collectCodexSessionFiles2(baseDir) {
|
|
4533
4753
|
let paths = [];
|
|
4534
4754
|
try {
|
|
4535
|
-
let files = await readdir6(
|
|
4755
|
+
let files = await readdir6(join17(baseDir, "archived_sessions"));
|
|
4536
4756
|
for (let file of files)
|
|
4537
|
-
file.endsWith(".jsonl") && paths.push(
|
|
4757
|
+
file.endsWith(".jsonl") && paths.push(join17(baseDir, "archived_sessions", file));
|
|
4538
4758
|
} catch {
|
|
4539
4759
|
}
|
|
4540
|
-
return await walkJsonl(
|
|
4760
|
+
return await walkJsonl(join17(baseDir, "sessions"), paths), paths;
|
|
4541
4761
|
}
|
|
4542
4762
|
function getClaudeProjectDirs2(configured) {
|
|
4543
4763
|
if (configured?.length) return configured;
|
|
4544
4764
|
let envVar = process.env.CLAUDE_CONFIG_DIR?.trim();
|
|
4545
4765
|
if (envVar)
|
|
4546
|
-
return envVar.split(",").map((p) => p.trim()).filter(Boolean).map((p) =>
|
|
4547
|
-
let home =
|
|
4766
|
+
return envVar.split(",").map((p) => p.trim()).filter(Boolean).map((p) => join17(p, "projects"));
|
|
4767
|
+
let home = homedir16();
|
|
4548
4768
|
return [
|
|
4549
|
-
|
|
4550
|
-
|
|
4769
|
+
join17(home, ".config", "claude", "projects"),
|
|
4770
|
+
join17(home, ".claude", "projects")
|
|
4551
4771
|
];
|
|
4552
4772
|
}
|
|
4553
4773
|
async function walkJsonl(dir, result) {
|
|
@@ -4558,7 +4778,7 @@ async function walkJsonl(dir, result) {
|
|
|
4558
4778
|
return;
|
|
4559
4779
|
}
|
|
4560
4780
|
for (let entry of entries) {
|
|
4561
|
-
let fullPath =
|
|
4781
|
+
let fullPath = join17(dir, entry.name);
|
|
4562
4782
|
entry.isDirectory() ? await walkJsonl(fullPath, result) : entry.name.endsWith(".jsonl") && result.push(fullPath);
|
|
4563
4783
|
}
|
|
4564
4784
|
}
|
|
@@ -4574,22 +4794,22 @@ function classifyClaudeTool(name) {
|
|
|
4574
4794
|
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
4795
|
}
|
|
4576
4796
|
function getClaudeMetricName(toolName, input) {
|
|
4577
|
-
return toolName === "Skill" ?
|
|
4797
|
+
return toolName === "Skill" ? stringValue3(input?.skill) ?? "unknown" : toolName === "Agent" ? stringValue3(input?.description) ?? stringValue3(input?.subagent_type) ?? "unknown" : toolName;
|
|
4578
4798
|
}
|
|
4579
4799
|
function isClaudeUserMessage(record) {
|
|
4580
4800
|
if (record.type !== "user" || record.message?.role !== "user" || record.isMeta || record.toolUseResult || record.sourceToolAssistantUUID || record.sourceToolUseID) return !1;
|
|
4581
4801
|
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" &&
|
|
4802
|
+
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
4803
|
}
|
|
4584
4804
|
function hasCodexUserMessageContent(content) {
|
|
4585
4805
|
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
4806
|
}
|
|
4587
4807
|
function extractCodexMessageText(content) {
|
|
4588
|
-
return typeof content == "string" ? content : Array.isArray(content) && content.map((block) =>
|
|
4808
|
+
return typeof content == "string" ? content : Array.isArray(content) && content.map((block) => stringValue3(block.text)).filter(Boolean).join(`
|
|
4589
4809
|
`) || void 0;
|
|
4590
4810
|
}
|
|
4591
4811
|
function extractClaudeMessageText(content) {
|
|
4592
|
-
return typeof content == "string" ? content : Array.isArray(content) && content.filter((block) => block?.type === "text").map((block) =>
|
|
4812
|
+
return typeof content == "string" ? content : Array.isArray(content) && content.filter((block) => block?.type === "text").map((block) => stringValue3(block.text)).filter(Boolean).join(`
|
|
4593
4813
|
`) || void 0;
|
|
4594
4814
|
}
|
|
4595
4815
|
function normalizeMessageText(value) {
|
|
@@ -4597,7 +4817,7 @@ function normalizeMessageText(value) {
|
|
|
4597
4817
|
}
|
|
4598
4818
|
function extractSkillProxyNames(rawArguments) {
|
|
4599
4819
|
if (!rawArguments) return [];
|
|
4600
|
-
let args = parseJsonObject(rawArguments), command2 =
|
|
4820
|
+
let args = parseJsonObject(rawArguments), command2 = stringValue3(args.cmd) ?? stringValue3(args.command) ?? "";
|
|
4601
4821
|
if (!command2.includes("SKILL.md")) return [];
|
|
4602
4822
|
let names = /* @__PURE__ */ new Set();
|
|
4603
4823
|
for (let match of command2.matchAll(/([^\s'"]*SKILL\.md)/g))
|
|
@@ -4617,7 +4837,7 @@ function skillNameFromPath(rawPath) {
|
|
|
4617
4837
|
let parts = rawPath.replace(/^[`'"]+|[`'"]+$/g, "").split("/").filter(Boolean), idx = parts.lastIndexOf("SKILL.md"), name = idx > 0 ? parts[idx - 1] : void 0;
|
|
4618
4838
|
return !name || name === "$d" || name === "s#" ? "unknown-skill" : name;
|
|
4619
4839
|
}
|
|
4620
|
-
function
|
|
4840
|
+
function stringValue3(value) {
|
|
4621
4841
|
return typeof value == "string" && value.length > 0 ? value : void 0;
|
|
4622
4842
|
}
|
|
4623
4843
|
function summarize(items, keyFn, labelFn, limit) {
|
|
@@ -4690,6 +4910,8 @@ function getRangeLabel3(range) {
|
|
|
4690
4910
|
return "\u6700\u8FD1 30 \u5929";
|
|
4691
4911
|
case "3m":
|
|
4692
4912
|
return "\u6700\u8FD1 90 \u5929";
|
|
4913
|
+
case "6m":
|
|
4914
|
+
return "\u6700\u8FD1 180 \u5929";
|
|
4693
4915
|
case "all":
|
|
4694
4916
|
return "\u5168\u90E8\u5386\u53F2";
|
|
4695
4917
|
case "today":
|
|
@@ -4710,10 +4932,10 @@ function stripAnsi(s) {
|
|
|
4710
4932
|
}
|
|
4711
4933
|
|
|
4712
4934
|
// src/config.ts
|
|
4713
|
-
import { mkdir, readFile as
|
|
4714
|
-
import { homedir as
|
|
4715
|
-
import { basename as basename13, join as
|
|
4716
|
-
var CONFIG_DIR =
|
|
4935
|
+
import { mkdir, readFile as readFile15, writeFile } from "node:fs/promises";
|
|
4936
|
+
import { homedir as homedir17, hostname } from "node:os";
|
|
4937
|
+
import { basename as basename13, join as join18 } from "node:path";
|
|
4938
|
+
var CONFIG_DIR = join18(homedir17(), ".aiusage"), CONFIG_PATH = join18(CONFIG_DIR, "config.json");
|
|
4717
4939
|
function getConfigPath() {
|
|
4718
4940
|
return CONFIG_PATH;
|
|
4719
4941
|
}
|
|
@@ -4740,7 +4962,7 @@ function migrateConfig(config) {
|
|
|
4740
4962
|
}
|
|
4741
4963
|
async function readConfig() {
|
|
4742
4964
|
try {
|
|
4743
|
-
let raw = await
|
|
4965
|
+
let raw = await readFile15(CONFIG_PATH, "utf-8");
|
|
4744
4966
|
return migrateConfig(JSON.parse(raw));
|
|
4745
4967
|
} catch {
|
|
4746
4968
|
return {};
|
|
@@ -4848,13 +5070,13 @@ import { hostname as hostname2 } from "node:os";
|
|
|
4848
5070
|
|
|
4849
5071
|
// src/version.ts
|
|
4850
5072
|
import { readFileSync } from "node:fs";
|
|
4851
|
-
import { resolve as
|
|
5073
|
+
import { resolve as resolve3, dirname as dirname7 } from "node:path";
|
|
4852
5074
|
import { fileURLToPath } from "node:url";
|
|
4853
5075
|
var cached;
|
|
4854
5076
|
function getVersion() {
|
|
4855
5077
|
if (cached !== void 0) return cached;
|
|
4856
5078
|
try {
|
|
4857
|
-
let pkg =
|
|
5079
|
+
let pkg = resolve3(dirname7(fileURLToPath(import.meta.url)), "..", "package.json");
|
|
4858
5080
|
cached = JSON.parse(readFileSync(pkg, "utf-8")).version;
|
|
4859
5081
|
} catch {
|
|
4860
5082
|
cached = "unknown";
|
|
@@ -4927,12 +5149,12 @@ async function requestJson(url, init) {
|
|
|
4927
5149
|
}
|
|
4928
5150
|
|
|
4929
5151
|
// src/schedule.ts
|
|
4930
|
-
import { mkdir as mkdir2, readFile as
|
|
5152
|
+
import { mkdir as mkdir2, readFile as readFile16, stat as stat3, unlink, writeFile as writeFile2 } from "node:fs/promises";
|
|
4931
5153
|
import { execFile as execFile2 } from "node:child_process";
|
|
4932
5154
|
import { promisify } from "node:util";
|
|
4933
|
-
import { homedir as
|
|
4934
|
-
import { join as
|
|
4935
|
-
var execFileAsync = promisify(execFile2), LABEL = "com.aiusage.sync", PLIST_PATH =
|
|
5155
|
+
import { homedir as homedir18, platform, tmpdir as tmpdir2 } from "node:os";
|
|
5156
|
+
import { join as join19, resolve as resolve4 } from "node:path";
|
|
5157
|
+
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
5158
|
function parseInterval(value) {
|
|
4937
5159
|
let match = value.match(/^(\d+)(m|h|d)$/);
|
|
4938
5160
|
if (!match) throw new Error("--every \u683C\u5F0F\u9519\u8BEF\uFF0C\u793A\u4F8B: 30m, 1h, 2h, 1d");
|
|
@@ -4967,7 +5189,7 @@ async function getScheduleStatus() {
|
|
|
4967
5189
|
return platform() === "darwin" ? getLaunchdStatus() : getCronStatus();
|
|
4968
5190
|
}
|
|
4969
5191
|
function resolveCommandPaths() {
|
|
4970
|
-
let scriptPath =
|
|
5192
|
+
let scriptPath = resolve4(process.argv[1]);
|
|
4971
5193
|
if (scriptPath.includes("_npx") || scriptPath.includes("/npx-"))
|
|
4972
5194
|
throw new Error(
|
|
4973
5195
|
`\u68C0\u6D4B\u5230\u901A\u8FC7 npx \u8FD0\u884C\uFF0C\u5B9A\u65F6\u4EFB\u52A1\u9700\u8981\u5168\u5C40\u5B89\u88C5\u3002
|
|
@@ -4977,7 +5199,7 @@ function resolveCommandPaths() {
|
|
|
4977
5199
|
}
|
|
4978
5200
|
async function enableLaunchd(intervalSeconds) {
|
|
4979
5201
|
let { nodePath, scriptPath } = resolveCommandPaths();
|
|
4980
|
-
await mkdir2(
|
|
5202
|
+
await mkdir2(join19(homedir18(), ".aiusage"), { recursive: !0 });
|
|
4981
5203
|
let plist = [
|
|
4982
5204
|
'<?xml version="1.0" encoding="UTF-8"?>',
|
|
4983
5205
|
'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
|
|
@@ -5031,7 +5253,7 @@ async function getLaunchdStatus() {
|
|
|
5031
5253
|
return { enabled: !1 };
|
|
5032
5254
|
}
|
|
5033
5255
|
try {
|
|
5034
|
-
let content = await
|
|
5256
|
+
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
5257
|
return {
|
|
5036
5258
|
enabled: !0,
|
|
5037
5259
|
interval,
|
|
@@ -5046,8 +5268,8 @@ async function getLaunchdStatus() {
|
|
|
5046
5268
|
}
|
|
5047
5269
|
}
|
|
5048
5270
|
async function enableCron(intervalSeconds) {
|
|
5049
|
-
let { nodePath, scriptPath } = resolveCommandPaths(), cronExpr = secondsToCron(intervalSeconds), logPath =
|
|
5050
|
-
await mkdir2(
|
|
5271
|
+
let { nodePath, scriptPath } = resolveCommandPaths(), cronExpr = secondsToCron(intervalSeconds), logPath = join19(homedir18(), ".aiusage", "sync.log"), cronLine = `${cronExpr} ${nodePath} ${scriptPath} sync --today >> ${logPath} 2>&1 ${CRON_MARKER}`;
|
|
5272
|
+
await mkdir2(join19(homedir18(), ".aiusage"), { recursive: !0 });
|
|
5051
5273
|
let existing = "";
|
|
5052
5274
|
try {
|
|
5053
5275
|
let { stdout } = await execFileAsync("crontab", ["-l"]);
|
|
@@ -5105,7 +5327,7 @@ async function getCronStatus() {
|
|
|
5105
5327
|
}
|
|
5106
5328
|
}
|
|
5107
5329
|
async function writeCrontab(content) {
|
|
5108
|
-
let tmpFile =
|
|
5330
|
+
let tmpFile = join19(tmpdir2(), `aiusage-cron-${Date.now()}`);
|
|
5109
5331
|
await writeFile2(tmpFile, content, "utf-8");
|
|
5110
5332
|
try {
|
|
5111
5333
|
await execFileAsync("crontab", [tmpFile]);
|
|
@@ -5137,8 +5359,8 @@ function escapeXml(value) {
|
|
|
5137
5359
|
|
|
5138
5360
|
// src/doctor.ts
|
|
5139
5361
|
import { readdir as readdir7, stat as stat4 } from "node:fs/promises";
|
|
5140
|
-
import { homedir as
|
|
5141
|
-
import { join as
|
|
5362
|
+
import { homedir as homedir19 } from "node:os";
|
|
5363
|
+
import { join as join20 } from "node:path";
|
|
5142
5364
|
var msgs = {
|
|
5143
5365
|
en: {
|
|
5144
5366
|
groupConfig: "Configuration",
|
|
@@ -5200,7 +5422,7 @@ async function countFiles(dir, exts, cap = 1e3) {
|
|
|
5200
5422
|
}
|
|
5201
5423
|
for (let e of entries) {
|
|
5202
5424
|
if (count >= cap) break;
|
|
5203
|
-
let full =
|
|
5425
|
+
let full = join20(current, e.name);
|
|
5204
5426
|
e.isDirectory() ? queue.push(full) : exts.some((ext) => e.name.endsWith(ext)) && count++;
|
|
5205
5427
|
}
|
|
5206
5428
|
}
|
|
@@ -5229,28 +5451,29 @@ async function runDoctor(lang = "zh") {
|
|
|
5229
5451
|
}
|
|
5230
5452
|
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
5453
|
}
|
|
5232
|
-
let g3 = s.groupTools, home =
|
|
5233
|
-
{ dirs: [
|
|
5234
|
-
{ dirs: [
|
|
5235
|
-
{ dirs: [
|
|
5236
|
-
{ dirs: [
|
|
5454
|
+
let g3 = s.groupTools, home = homedir19(), tools = [
|
|
5455
|
+
{ dirs: [join20(home, ".config", "claude", "projects"), join20(home, ".claude", "projects")], label: "Claude Code", exts: [".jsonl"] },
|
|
5456
|
+
{ dirs: [join20(home, ".codex")], label: "Codex CLI", exts: [".jsonl"] },
|
|
5457
|
+
{ dirs: [join20(home, "Library", "Application Support", "Cursor", "User", "globalStorage")], label: "Cursor", exts: [".vscdb"] },
|
|
5458
|
+
{ dirs: [join20(home, ".copilot", "session-state"), join20(home, ".copilot", "otel")], label: "Copilot CLI", exts: [".jsonl"] },
|
|
5237
5459
|
{
|
|
5238
5460
|
dirs: [
|
|
5239
|
-
|
|
5240
|
-
|
|
5461
|
+
join20(home, "Library", "Application Support", "Code", "logs"),
|
|
5462
|
+
join20(home, "Library", "Application Support", "Code", "User", "workspaceStorage")
|
|
5241
5463
|
],
|
|
5242
5464
|
label: "Copilot VS Code",
|
|
5243
5465
|
exts: [".log", ".json", ".jsonl"]
|
|
5244
5466
|
},
|
|
5245
|
-
{ dirs: [
|
|
5246
|
-
{ dirs: [
|
|
5247
|
-
{ dirs: [
|
|
5248
|
-
{ dirs: [
|
|
5249
|
-
{ dirs: [
|
|
5250
|
-
{ dirs: [
|
|
5251
|
-
{ dirs: [
|
|
5252
|
-
{ dirs: [
|
|
5253
|
-
{ dirs: [
|
|
5467
|
+
{ dirs: [join20(home, ".gemini", "tmp")], label: "Gemini CLI", exts: [".json", ".jsonl"] },
|
|
5468
|
+
{ dirs: [join20(home, ".gemini", "antigravity")], label: "Antigravity", exts: [".json"] },
|
|
5469
|
+
{ dirs: [join20(home, ".qwen", "projects"), join20(home, ".qwen", "tmp")], label: "Qwen Code", exts: [".jsonl"] },
|
|
5470
|
+
{ dirs: [join20(resolveKimiCodeHome(home), "sessions")], label: "Kimi Code", exts: [".jsonl"] },
|
|
5471
|
+
{ dirs: [join20(home, ".kimi", "sessions")], label: "Kimi CLI (legacy)", exts: [".jsonl"] },
|
|
5472
|
+
{ dirs: [join20(home, ".local", "share", "amp", "threads")], label: "Amp", exts: [".json"] },
|
|
5473
|
+
{ dirs: [join20(home, ".factory", "sessions")], label: "Droid", exts: [".settings.json"] },
|
|
5474
|
+
{ dirs: [join20(home, ".local", "share", "opencode")], label: "OpenCode", exts: [".db", ".json"] },
|
|
5475
|
+
{ dirs: [join20(home, ".pi", "agent", "sessions"), join20(home, ".omp", "agent", "sessions")], label: "Pi / OMP", exts: [".jsonl"] },
|
|
5476
|
+
{ dirs: [resolveTraeNativeCacheDir(home), resolveTokscaleTraeCacheDir(home)], label: "Trae", exts: [".json"] }
|
|
5254
5477
|
];
|
|
5255
5478
|
for (let tool of tools) {
|
|
5256
5479
|
let installed = !1, n = 0;
|
|
@@ -5275,9 +5498,9 @@ async function runDoctor(lang = "zh") {
|
|
|
5275
5498
|
}
|
|
5276
5499
|
|
|
5277
5500
|
// src/project.ts
|
|
5278
|
-
import { open as open2, readdir as readdir8, readFile as
|
|
5279
|
-
import { basename as basename14, join as
|
|
5280
|
-
import { homedir as
|
|
5501
|
+
import { open as open2, readdir as readdir8, readFile as readFile17 } from "node:fs/promises";
|
|
5502
|
+
import { basename as basename14, join as join21 } from "node:path";
|
|
5503
|
+
import { homedir as homedir20 } from "node:os";
|
|
5281
5504
|
async function discoverProjects(projectAliases) {
|
|
5282
5505
|
let projectMap = /* @__PURE__ */ new Map();
|
|
5283
5506
|
function add(name, source) {
|
|
@@ -5305,7 +5528,9 @@ async function discoverProjects(projectAliases) {
|
|
|
5305
5528
|
// 仅读取知识项元数据标题,不读取对话内容
|
|
5306
5529
|
discoverAntigravityProjects().then((names) => names.forEach((n) => add(n, "antigravity"))),
|
|
5307
5530
|
// Kimi CLI / Kimi Code: legacy workspace map + new session metadata.
|
|
5308
|
-
discoverKimiProjects().then((names) => names.forEach((n) => add(n, "kimi")))
|
|
5531
|
+
discoverKimiProjects().then((names) => names.forEach((n) => add(n, "kimi"))),
|
|
5532
|
+
// Trae CN: privacy-minimized cache written by `aiusage trae sync`.
|
|
5533
|
+
discoverTraeProjects().then((names) => names.forEach((n) => add(n, "trae")))
|
|
5309
5534
|
]);
|
|
5310
5535
|
let results = [];
|
|
5311
5536
|
for (let [name, sources] of projectMap) {
|
|
@@ -5329,14 +5554,14 @@ async function discoverClaudeProjects() {
|
|
|
5329
5554
|
}
|
|
5330
5555
|
for (let entry of entries) {
|
|
5331
5556
|
if (!entry.isDirectory() || entry.name.startsWith(".")) continue;
|
|
5332
|
-
let projectDir =
|
|
5557
|
+
let projectDir = join21(baseDir, entry.name), name = await extractCwdFromFirstJsonl(projectDir);
|
|
5333
5558
|
name && name !== "unknown" && names.push(name);
|
|
5334
5559
|
}
|
|
5335
5560
|
}
|
|
5336
5561
|
return names;
|
|
5337
5562
|
}
|
|
5338
5563
|
async function discoverCodexProjects() {
|
|
5339
|
-
let sessionsDir =
|
|
5564
|
+
let sessionsDir = join21(homedir20(), ".codex", "sessions"), files = await walkJsonlFiles(sessionsDir), projects = /* @__PURE__ */ new Set();
|
|
5340
5565
|
for (let filePath of files) {
|
|
5341
5566
|
let name = await extractCwdFromSessionMeta(filePath);
|
|
5342
5567
|
name && name !== "unknown" && projects.add(name);
|
|
@@ -5373,7 +5598,7 @@ async function walkFiles2(dir, ext) {
|
|
|
5373
5598
|
return;
|
|
5374
5599
|
}
|
|
5375
5600
|
for (let entry of entries) {
|
|
5376
|
-
let full =
|
|
5601
|
+
let full = join21(d, entry.name);
|
|
5377
5602
|
entry.isDirectory() ? await walk2(full) : entry.name.endsWith(ext) && result.push(full);
|
|
5378
5603
|
}
|
|
5379
5604
|
}
|
|
@@ -5415,18 +5640,18 @@ async function findFirstJsonl(dir) {
|
|
|
5415
5640
|
return;
|
|
5416
5641
|
}
|
|
5417
5642
|
let topJsonl = entries.find((e) => e.isFile() && e.name.endsWith(".jsonl"));
|
|
5418
|
-
if (topJsonl) return
|
|
5643
|
+
if (topJsonl) return join21(dir, topJsonl.name);
|
|
5419
5644
|
for (let entry of entries)
|
|
5420
5645
|
if (!(!entry.isDirectory() || entry.name.startsWith(".")))
|
|
5421
5646
|
try {
|
|
5422
|
-
let sub = (await readdir8(
|
|
5423
|
-
if (sub) return
|
|
5647
|
+
let sub = (await readdir8(join21(dir, entry.name))).find((f) => f.endsWith(".jsonl"));
|
|
5648
|
+
if (sub) return join21(dir, entry.name, sub);
|
|
5424
5649
|
} catch {
|
|
5425
5650
|
continue;
|
|
5426
5651
|
}
|
|
5427
5652
|
}
|
|
5428
5653
|
async function discoverCopilotProjects() {
|
|
5429
|
-
let dir =
|
|
5654
|
+
let dir = join21(homedir20(), ".copilot", "session-state"), files = await walkJsonlFiles(dir), projects = /* @__PURE__ */ new Set();
|
|
5430
5655
|
for (let filePath of files) {
|
|
5431
5656
|
let fh;
|
|
5432
5657
|
try {
|
|
@@ -5448,9 +5673,9 @@ async function discoverCopilotProjects() {
|
|
|
5448
5673
|
return [...projects];
|
|
5449
5674
|
}
|
|
5450
5675
|
async function discoverGeminiProjects() {
|
|
5451
|
-
let filePath =
|
|
5676
|
+
let filePath = join21(homedir20(), ".gemini", "projects.json");
|
|
5452
5677
|
try {
|
|
5453
|
-
let raw = await
|
|
5678
|
+
let raw = await readFile17(filePath, "utf-8"), projects = JSON.parse(raw)?.projects;
|
|
5454
5679
|
if (!projects || typeof projects != "object") return [];
|
|
5455
5680
|
let names = [];
|
|
5456
5681
|
for (let [path, _name] of Object.entries(projects)) {
|
|
@@ -5463,9 +5688,9 @@ async function discoverGeminiProjects() {
|
|
|
5463
5688
|
}
|
|
5464
5689
|
}
|
|
5465
5690
|
async function discoverCursorProjects() {
|
|
5466
|
-
let storagePath =
|
|
5691
|
+
let storagePath = join21(homedir20(), "Library", "Application Support", "Cursor", "User", "globalStorage", "storage.json");
|
|
5467
5692
|
try {
|
|
5468
|
-
let raw = await
|
|
5693
|
+
let raw = await readFile17(storagePath, "utf-8"), data = JSON.parse(raw), projects = /* @__PURE__ */ new Set(), workspaceUris = Object.keys(data.profileAssociations?.workspaces ?? {});
|
|
5469
5694
|
for (let uri of workspaceUris) {
|
|
5470
5695
|
let name = nameFromFileUri(uri);
|
|
5471
5696
|
name && projects.add(name);
|
|
@@ -5480,11 +5705,11 @@ async function discoverCursorProjects() {
|
|
|
5480
5705
|
}
|
|
5481
5706
|
}
|
|
5482
5707
|
async function discoverCopilotVscodeProjects() {
|
|
5483
|
-
let dir =
|
|
5708
|
+
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
5709
|
for (let filePath of files) {
|
|
5485
5710
|
let content;
|
|
5486
5711
|
try {
|
|
5487
|
-
content = await
|
|
5712
|
+
content = await readFile17(filePath, "utf-8");
|
|
5488
5713
|
} catch {
|
|
5489
5714
|
continue;
|
|
5490
5715
|
}
|
|
@@ -5497,7 +5722,7 @@ async function discoverCopilotVscodeProjects() {
|
|
|
5497
5722
|
return [...projects];
|
|
5498
5723
|
}
|
|
5499
5724
|
async function discoverAntigravityProjects() {
|
|
5500
|
-
let dir =
|
|
5725
|
+
let dir = join21(homedir20(), ".gemini", "antigravity", "knowledge"), entries;
|
|
5501
5726
|
try {
|
|
5502
5727
|
entries = await readdir8(dir, { withFileTypes: !0 });
|
|
5503
5728
|
} catch {
|
|
@@ -5506,9 +5731,9 @@ async function discoverAntigravityProjects() {
|
|
|
5506
5731
|
let projects = /* @__PURE__ */ new Set();
|
|
5507
5732
|
for (let entry of entries) {
|
|
5508
5733
|
if (!entry.isDirectory()) continue;
|
|
5509
|
-
let metadataPath =
|
|
5734
|
+
let metadataPath = join21(dir, entry.name, "metadata.json");
|
|
5510
5735
|
try {
|
|
5511
|
-
let raw = await
|
|
5736
|
+
let raw = await readFile17(metadataPath, "utf-8"), name = JSON.parse(raw).title?.trim() || entry.name.trim();
|
|
5512
5737
|
name && name !== "unknown" && projects.add(name);
|
|
5513
5738
|
} catch {
|
|
5514
5739
|
continue;
|
|
@@ -5517,9 +5742,9 @@ async function discoverAntigravityProjects() {
|
|
|
5517
5742
|
return [...projects];
|
|
5518
5743
|
}
|
|
5519
5744
|
async function discoverKimiProjects() {
|
|
5520
|
-
let projects = /* @__PURE__ */ new Set(), home =
|
|
5745
|
+
let projects = /* @__PURE__ */ new Set(), home = homedir20();
|
|
5521
5746
|
try {
|
|
5522
|
-
let raw = await
|
|
5747
|
+
let raw = await readFile17(join21(home, ".kimi", "kimi.json"), "utf-8"), data = JSON.parse(raw);
|
|
5523
5748
|
for (let workspace of Object.values(data.workspaces ?? {})) {
|
|
5524
5749
|
let name = basename14(workspace.path?.trim() ?? "");
|
|
5525
5750
|
name && name !== "unknown" && projects.add(name);
|
|
@@ -5528,7 +5753,7 @@ async function discoverKimiProjects() {
|
|
|
5528
5753
|
}
|
|
5529
5754
|
let codeHome = resolveKimiCodeHome(home);
|
|
5530
5755
|
try {
|
|
5531
|
-
let raw = await
|
|
5756
|
+
let raw = await readFile17(join21(codeHome, "session_index.jsonl"), "utf-8");
|
|
5532
5757
|
for (let line of raw.split(`
|
|
5533
5758
|
`))
|
|
5534
5759
|
if (line.trim())
|
|
@@ -5540,10 +5765,21 @@ async function discoverKimiProjects() {
|
|
|
5540
5765
|
}
|
|
5541
5766
|
} catch {
|
|
5542
5767
|
}
|
|
5543
|
-
let stateFiles = (await walkFiles2(
|
|
5768
|
+
let stateFiles = (await walkFiles2(join21(codeHome, "sessions"), ".json")).filter((filePath) => basename14(filePath) === "state.json");
|
|
5544
5769
|
for (let filePath of stateFiles)
|
|
5545
5770
|
try {
|
|
5546
|
-
let raw = await
|
|
5771
|
+
let raw = await readFile17(filePath, "utf-8"), state = JSON.parse(raw), name = basename14(state.workDir?.trim() ?? "");
|
|
5772
|
+
name && name !== "unknown" && projects.add(name);
|
|
5773
|
+
} catch {
|
|
5774
|
+
continue;
|
|
5775
|
+
}
|
|
5776
|
+
return [...projects];
|
|
5777
|
+
}
|
|
5778
|
+
async function discoverTraeProjects() {
|
|
5779
|
+
let projects = /* @__PURE__ */ new Set();
|
|
5780
|
+
for (let filePath of await walkFiles2(resolveTraeNativeCacheDir(), ".json"))
|
|
5781
|
+
try {
|
|
5782
|
+
let data = JSON.parse(await readFile17(filePath, "utf8")), name = basename14(data.project?.trim() ?? "");
|
|
5547
5783
|
name && name !== "unknown" && projects.add(name);
|
|
5548
5784
|
} catch {
|
|
5549
5785
|
continue;
|
|
@@ -5572,11 +5808,11 @@ function pathFromFileUri(raw) {
|
|
|
5572
5808
|
function getClaudeDirs() {
|
|
5573
5809
|
let envVar = process.env.CLAUDE_CONFIG_DIR?.trim();
|
|
5574
5810
|
if (envVar)
|
|
5575
|
-
return envVar.split(",").map((p) => p.trim()).filter(Boolean).map((p) =>
|
|
5576
|
-
let home =
|
|
5811
|
+
return envVar.split(",").map((p) => p.trim()).filter(Boolean).map((p) => join21(p, "projects"));
|
|
5812
|
+
let home = homedir20();
|
|
5577
5813
|
return [
|
|
5578
|
-
|
|
5579
|
-
|
|
5814
|
+
join21(home, ".config", "claude", "projects"),
|
|
5815
|
+
join21(home, ".claude", "projects")
|
|
5580
5816
|
];
|
|
5581
5817
|
}
|
|
5582
5818
|
|
|
@@ -5621,10 +5857,10 @@ function shortHash(p) {
|
|
|
5621
5857
|
}
|
|
5622
5858
|
|
|
5623
5859
|
// src/pricing.ts
|
|
5624
|
-
import { mkdir as mkdir3, readFile as
|
|
5625
|
-
import { homedir as
|
|
5626
|
-
import { join as
|
|
5627
|
-
var CACHE_DIR =
|
|
5860
|
+
import { mkdir as mkdir3, readFile as readFile18, writeFile as writeFile3 } from "node:fs/promises";
|
|
5861
|
+
import { homedir as homedir21 } from "node:os";
|
|
5862
|
+
import { join as join22 } from "node:path";
|
|
5863
|
+
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
5864
|
"https://cdn.jsdelivr.net/npm/@aiusage/cli@latest/pricing-catalog.json",
|
|
5629
5865
|
"https://unpkg.com/@aiusage/cli@latest/pricing-catalog.json",
|
|
5630
5866
|
"https://cdn.jsdelivr.net/npm/@aiusage/pricing@latest/catalog.json",
|
|
@@ -5693,7 +5929,7 @@ function fromCache(cache) {
|
|
|
5693
5929
|
}
|
|
5694
5930
|
async function readPricingCache() {
|
|
5695
5931
|
try {
|
|
5696
|
-
let raw = await
|
|
5932
|
+
let raw = await readFile18(CACHE_PATH, "utf-8"), cache = JSON.parse(raw);
|
|
5697
5933
|
return assertPricingCatalog(cache.catalog), !cache.fetchedAt || !cache.sourceUrl ? null : cache;
|
|
5698
5934
|
} catch {
|
|
5699
5935
|
return null;
|
|
@@ -5720,6 +5956,822 @@ function assertPricingCatalog(value) {
|
|
|
5720
5956
|
if (!catalog2.providers.openai?.codex?.models) throw new Error("invalid OpenAI pricing catalog");
|
|
5721
5957
|
}
|
|
5722
5958
|
|
|
5959
|
+
// src/trae-sync.ts
|
|
5960
|
+
import { execFile as execFile3 } from "node:child_process";
|
|
5961
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
5962
|
+
import { existsSync as existsSync2 } from "node:fs";
|
|
5963
|
+
import { mkdir as mkdir4, open as open3, readdir as readdir9, rename, stat as stat5, writeFile as writeFile4 } from "node:fs/promises";
|
|
5964
|
+
import { createServer } from "node:net";
|
|
5965
|
+
import { homedir as homedir22 } from "node:os";
|
|
5966
|
+
import { join as join23 } from "node:path";
|
|
5967
|
+
import { promisify as promisify2 } from "node:util";
|
|
5968
|
+
import WebSocket from "ws";
|
|
5969
|
+
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;
|
|
5970
|
+
async function syncTraeCnUsage(options = {}) {
|
|
5971
|
+
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;
|
|
5972
|
+
try {
|
|
5973
|
+
if (!target) {
|
|
5974
|
+
if (options.launch === !1)
|
|
5975
|
+
throw new Error(`\u672A\u8FDE\u63A5\u5230 Trae CN \u672C\u5730\u8C03\u8BD5\u63A5\u53E3 (127.0.0.1:${port})`);
|
|
5976
|
+
if (process.platform !== "darwin")
|
|
5977
|
+
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");
|
|
5978
|
+
if (await isTraeRunning())
|
|
5979
|
+
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");
|
|
5980
|
+
if (!existsSync2(appPath)) throw new Error(`\u672A\u627E\u5230 Trae CN: ${appPath}`);
|
|
5981
|
+
options.port == null && !await isPortAvailable(port) && (port = await findFreePort()), await launchTrae(appPath, port), launched = !0, target = await waitForWorkbench(port, timeoutMs);
|
|
5982
|
+
}
|
|
5983
|
+
let userIds = await waitForTraeUserIds(userDataDir, timeoutMs);
|
|
5984
|
+
if (userIds.length === 0)
|
|
5985
|
+
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");
|
|
5986
|
+
let raw = await readTraeUsageWithRetry(port, target, userIds, timeoutMs), normalized = normalizeSyncResult(raw);
|
|
5987
|
+
if (normalized.sessions.length === 0 && (raw.errors?.length ?? 0) > 0)
|
|
5988
|
+
throw new Error(`Trae CN \u672C\u5730\u8BFB\u53D6\u5931\u8D25: ${sanitizeMessage(raw.errors?.[0]?.message)}`);
|
|
5989
|
+
await writeCache(normalized.sessions, cacheDir);
|
|
5990
|
+
let totals = normalized.sessions.flatMap((session) => session.events).reduce(
|
|
5991
|
+
(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),
|
|
5992
|
+
{
|
|
5993
|
+
inputTokens: 0,
|
|
5994
|
+
cachedInputTokens: 0,
|
|
5995
|
+
cacheWriteTokens: 0,
|
|
5996
|
+
outputTokens: 0,
|
|
5997
|
+
reasoningOutputTokens: 0,
|
|
5998
|
+
totalTokens: 0
|
|
5999
|
+
}
|
|
6000
|
+
);
|
|
6001
|
+
return {
|
|
6002
|
+
cacheDir,
|
|
6003
|
+
accounts: raw.accounts ?? userIds.length,
|
|
6004
|
+
sessions: normalized.sessions.length,
|
|
6005
|
+
events: normalized.sessions.reduce((sum, session) => sum + session.events.length, 0),
|
|
6006
|
+
totals,
|
|
6007
|
+
warnings: (raw.errors ?? []).map((error) => sanitizeMessage(error.message)).filter(Boolean)
|
|
6008
|
+
};
|
|
6009
|
+
} finally {
|
|
6010
|
+
launched && await quitTrae();
|
|
6011
|
+
}
|
|
6012
|
+
}
|
|
6013
|
+
function normalizeTraeCnUsage(raw) {
|
|
6014
|
+
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;
|
|
6015
|
+
if (prompt2 + completion + reportedReasoning === 0 && reportedTotal > 0 && (input = reportedTotal, reasoning = 0), input + cached2 + cacheWrite + output + reasoning === 0) return null;
|
|
6016
|
+
let messageId = stringValue4(raw.messageId), timestamp = raw.timestamp;
|
|
6017
|
+
return !messageId || timestamp == null || timestamp === "" ? null : {
|
|
6018
|
+
messageId,
|
|
6019
|
+
timestamp,
|
|
6020
|
+
model: normalizeTraeModel(stringValue4(raw.model)),
|
|
6021
|
+
inputTokens: input,
|
|
6022
|
+
cachedInputTokens: cached2,
|
|
6023
|
+
cacheWriteTokens: cacheWrite,
|
|
6024
|
+
outputTokens: output,
|
|
6025
|
+
reasoningOutputTokens: reasoning
|
|
6026
|
+
};
|
|
6027
|
+
}
|
|
6028
|
+
function normalizeSyncResult(raw) {
|
|
6029
|
+
let syncedAt = (/* @__PURE__ */ new Date()).toISOString(), sessions = [], seenMessages = /* @__PURE__ */ new Set();
|
|
6030
|
+
for (let rawSession of raw.sessions ?? []) {
|
|
6031
|
+
let sessionId = stringValue4(rawSession.sessionId);
|
|
6032
|
+
if (!sessionId) continue;
|
|
6033
|
+
let events = [];
|
|
6034
|
+
for (let rawEvent of rawSession.events ?? []) {
|
|
6035
|
+
let event = normalizeTraeCnUsage(rawEvent);
|
|
6036
|
+
!event || seenMessages.has(event.messageId) || (seenMessages.add(event.messageId), events.push(event));
|
|
6037
|
+
}
|
|
6038
|
+
events.length !== 0 && sessions.push({
|
|
6039
|
+
schemaVersion: 1,
|
|
6040
|
+
source: "trae-cn-local-rpc",
|
|
6041
|
+
syncedAt,
|
|
6042
|
+
sessionId,
|
|
6043
|
+
project: stringValue4(rawSession.project) || "unknown",
|
|
6044
|
+
events
|
|
6045
|
+
});
|
|
6046
|
+
}
|
|
6047
|
+
return { sessions };
|
|
6048
|
+
}
|
|
6049
|
+
async function readTraeUsage(webSocketDebuggerUrl, userIds, timeoutMs) {
|
|
6050
|
+
if (!webSocketDebuggerUrl) throw new Error("Trae CN \u8C03\u8BD5\u76EE\u6807\u7F3A\u5C11 WebSocket \u5730\u5740");
|
|
6051
|
+
let client = await CdpClient.connect(webSocketDebuggerUrl, timeoutMs);
|
|
6052
|
+
try {
|
|
6053
|
+
let result = await client.call("Runtime.evaluate", {
|
|
6054
|
+
expression: buildSyncExpression(userIds),
|
|
6055
|
+
awaitPromise: !0,
|
|
6056
|
+
returnByValue: !0
|
|
6057
|
+
}, timeoutMs), exception = result?.exceptionDetails?.exception?.description ?? result?.exceptionDetails?.text;
|
|
6058
|
+
if (exception) throw new Error(sanitizeMessage(exception));
|
|
6059
|
+
return result?.result?.value ?? {};
|
|
6060
|
+
} finally {
|
|
6061
|
+
client.close();
|
|
6062
|
+
}
|
|
6063
|
+
}
|
|
6064
|
+
async function readTraeUsageWithRetry(port, initialTarget, userIds, timeoutMs) {
|
|
6065
|
+
let deadline = Date.now() + timeoutMs, target = initialTarget, lastError;
|
|
6066
|
+
for (; Date.now() < deadline; )
|
|
6067
|
+
try {
|
|
6068
|
+
let remaining = Math.max(5e3, deadline - Date.now());
|
|
6069
|
+
return await readTraeUsage(target.webSocketDebuggerUrl, userIds, Math.min(6e4, remaining));
|
|
6070
|
+
} catch (error) {
|
|
6071
|
+
if (lastError = error instanceof Error ? error : new Error(String(error)), Date.now() + 1e3 >= deadline) break;
|
|
6072
|
+
await delay(1e3), target = await findWorkbenchTarget(port) ?? target;
|
|
6073
|
+
}
|
|
6074
|
+
throw lastError ?? new Error("Trae CN \u672C\u5730\u670D\u52A1\u672A\u5C31\u7EEA");
|
|
6075
|
+
}
|
|
6076
|
+
function buildSyncExpression(userIds) {
|
|
6077
|
+
return `(async()=>{
|
|
6078
|
+
const userIds=${JSON.stringify(userIds)};
|
|
6079
|
+
const connection=await vscode.ahaIpc.connect('ai-agent');
|
|
6080
|
+
let sequence=0;
|
|
6081
|
+
const rpc=(method,data,sessionId='')=>new Promise((resolve,reject)=>{
|
|
6082
|
+
const id='aiusage-trae-'+Date.now()+'-'+(++sequence);
|
|
6083
|
+
const timer=setTimeout(()=>{connection.off('message',handler);reject(new Error('Trae RPC timeout'))},15000);
|
|
6084
|
+
const handler=raw=>{
|
|
6085
|
+
let message;
|
|
6086
|
+
try{message=typeof raw==='string'?JSON.parse(raw):raw}catch{return}
|
|
6087
|
+
if(message.id!==id)return;
|
|
6088
|
+
clearTimeout(timer);
|
|
6089
|
+
connection.off('message',handler);
|
|
6090
|
+
const params=message.result&&message.result.params||{};
|
|
6091
|
+
let responseData=params.data;
|
|
6092
|
+
try{if(typeof responseData==='string')responseData=JSON.parse(responseData)}catch{}
|
|
6093
|
+
resolve({code:params.code,message:params.message,data:responseData||{}});
|
|
6094
|
+
};
|
|
6095
|
+
connection.on('message',handler);
|
|
6096
|
+
connection.send(JSON.stringify({jsonrpc:'2.0',id,method:'request',params:[{
|
|
6097
|
+
packet_type:'request',session_id:sessionId,channel_id:id,params:{
|
|
6098
|
+
service:'chat',method,data:JSON.stringify(data),common_params:{},
|
|
6099
|
+
user_info:{name:'',token:'',region:'',is_internal:false,user_id:'',scope:''},
|
|
6100
|
+
streamlined_common_params:{},client_info:{connect_session_id:''}
|
|
6101
|
+
}
|
|
6102
|
+
}]}));
|
|
6103
|
+
});
|
|
6104
|
+
const number=value=>{const parsed=Number(value);return Number.isFinite(parsed)&&parsed>0?Math.floor(parsed):0};
|
|
6105
|
+
const errors=[];
|
|
6106
|
+
const sessionMap=new Map();
|
|
6107
|
+
const loadSession=async(session,userId)=>{
|
|
6108
|
+
const sessionId=String(session.session_id||session.id||'');
|
|
6109
|
+
if(!sessionId)return null;
|
|
6110
|
+
const loaded={
|
|
6111
|
+
sessionId,
|
|
6112
|
+
project:typeof session.main_folder==='string'?session.main_folder:'unknown',
|
|
6113
|
+
events:[]
|
|
6114
|
+
};
|
|
6115
|
+
const seenMessages=new Set();
|
|
6116
|
+
let messageCursor='';
|
|
6117
|
+
const seenMessageCursors=new Set();
|
|
6118
|
+
for(let messagePage=0;messagePage<100;messagePage++){
|
|
6119
|
+
const messageRequest={user_id:userId,session_id:sessionId,page_size:100};
|
|
6120
|
+
if(messageCursor)messageRequest.next_page_token=messageCursor;
|
|
6121
|
+
const messageResponse=await rpc('get_messages',messageRequest,sessionId);
|
|
6122
|
+
if(messageResponse.code!==0){errors.push({code:messageResponse.code,message:messageResponse.message});break}
|
|
6123
|
+
const messageData=messageResponse.data||{};
|
|
6124
|
+
for(const message of Array.isArray(messageData.messages)?messageData.messages:[]){
|
|
6125
|
+
const usage=message.token_usage;
|
|
6126
|
+
if(!usage)continue;
|
|
6127
|
+
const messageId=String(message.message_id||message.id||'');
|
|
6128
|
+
if(!messageId||seenMessages.has(messageId))continue;
|
|
6129
|
+
const meta=message.model_smart_selection_meta||{};
|
|
6130
|
+
loaded.events.push({
|
|
6131
|
+
messageId,
|
|
6132
|
+
timestamp:message.created_at||message.timestamp||session.update_at||session.created_at,
|
|
6133
|
+
model:typeof meta.config_name==='string'&&meta.config_name?meta.config_name:
|
|
6134
|
+
(typeof meta.mode==='string'&&meta.mode?'trae-'+meta.mode.toLowerCase():'trae-unknown'),
|
|
6135
|
+
promptTokens:number(usage.prompt_tokens||usage.prompt_tokens_total),
|
|
6136
|
+
completionTokens:number(usage.completion_tokens||usage.completion_tokens_total),
|
|
6137
|
+
reasoningTokens:number(usage.reasoning_tokens),
|
|
6138
|
+
cacheReadInputTokens:number(usage.cache_read_input_tokens),
|
|
6139
|
+
cacheCreationInputTokens:number(usage.cache_creation_input_tokens),
|
|
6140
|
+
totalTokens:number(usage.total_tokens)
|
|
6141
|
+
});
|
|
6142
|
+
seenMessages.add(messageId);
|
|
6143
|
+
}
|
|
6144
|
+
const next=typeof messageData.next_page_token==='string'?messageData.next_page_token:'';
|
|
6145
|
+
if(!next||seenMessageCursors.has(next))break;
|
|
6146
|
+
seenMessageCursors.add(next);
|
|
6147
|
+
messageCursor=next;
|
|
6148
|
+
}
|
|
6149
|
+
return loaded;
|
|
6150
|
+
};
|
|
6151
|
+
try{
|
|
6152
|
+
for(const userId of userIds){
|
|
6153
|
+
let sessionCursor='';
|
|
6154
|
+
const seenSessionCursors=new Set();
|
|
6155
|
+
for(let sessionPage=0;sessionPage<100;sessionPage++){
|
|
6156
|
+
const sessionRequest={user_id:userId,page_size:100};
|
|
6157
|
+
if(sessionCursor)sessionRequest.next_page_token=sessionCursor;
|
|
6158
|
+
const sessionResponse=await rpc('get_lite_sessions',sessionRequest);
|
|
6159
|
+
if(sessionResponse.code!==0){errors.push({code:sessionResponse.code,message:sessionResponse.message});break}
|
|
6160
|
+
const data=sessionResponse.data||{};
|
|
6161
|
+
const sessions=Array.isArray(data.sessions)?data.sessions:[];
|
|
6162
|
+
for(let index=0;index<sessions.length;index+=6){
|
|
6163
|
+
const loaded=await Promise.all(sessions.slice(index,index+6).map(session=>loadSession(session,userId)));
|
|
6164
|
+
for(const session of loaded){
|
|
6165
|
+
if(!session)continue;
|
|
6166
|
+
const existing=sessionMap.get(session.sessionId);
|
|
6167
|
+
if(!existing){sessionMap.set(session.sessionId,session);continue}
|
|
6168
|
+
const seen=new Set(existing.events.map(event=>event.messageId));
|
|
6169
|
+
for(const event of session.events)if(!seen.has(event.messageId))existing.events.push(event);
|
|
6170
|
+
}
|
|
6171
|
+
}
|
|
6172
|
+
const next=typeof data.next_page_token==='string'?data.next_page_token:'';
|
|
6173
|
+
if(!next||seenSessionCursors.has(next))break;
|
|
6174
|
+
seenSessionCursors.add(next);
|
|
6175
|
+
sessionCursor=next;
|
|
6176
|
+
}
|
|
6177
|
+
}
|
|
6178
|
+
return {accounts:userIds.length,sessions:[...sessionMap.values()],errors};
|
|
6179
|
+
}finally{connection.disconnect()}
|
|
6180
|
+
})()`;
|
|
6181
|
+
}
|
|
6182
|
+
var CdpClient = class _CdpClient {
|
|
6183
|
+
constructor(socket) {
|
|
6184
|
+
this.socket = socket;
|
|
6185
|
+
socket.on("message", (raw) => {
|
|
6186
|
+
let message;
|
|
6187
|
+
try {
|
|
6188
|
+
message = JSON.parse(String(raw));
|
|
6189
|
+
} catch {
|
|
6190
|
+
return;
|
|
6191
|
+
}
|
|
6192
|
+
let entry = this.pending.get(message.id);
|
|
6193
|
+
entry && (clearTimeout(entry.timer), this.pending.delete(message.id), message.error ? entry.reject(new Error(sanitizeMessage(message.error.message))) : entry.resolve(message.result));
|
|
6194
|
+
}), socket.on("error", (error) => this.rejectAll(error)), socket.on("close", () => this.rejectAll(new Error("Trae CN \u672C\u5730\u8FDE\u63A5\u5DF2\u5173\u95ED")));
|
|
6195
|
+
}
|
|
6196
|
+
sequence = 0;
|
|
6197
|
+
pending = /* @__PURE__ */ new Map();
|
|
6198
|
+
static async connect(url, timeoutMs) {
|
|
6199
|
+
let socket = new WebSocket(url);
|
|
6200
|
+
return await new Promise((resolve5, reject) => {
|
|
6201
|
+
let timer = setTimeout(() => {
|
|
6202
|
+
socket.close(), reject(new Error("\u8FDE\u63A5 Trae CN \u672C\u5730\u63A5\u53E3\u8D85\u65F6"));
|
|
6203
|
+
}, timeoutMs);
|
|
6204
|
+
socket.once("open", () => {
|
|
6205
|
+
clearTimeout(timer), resolve5();
|
|
6206
|
+
}), socket.once("error", (error) => {
|
|
6207
|
+
clearTimeout(timer), reject(error);
|
|
6208
|
+
});
|
|
6209
|
+
}), new _CdpClient(socket);
|
|
6210
|
+
}
|
|
6211
|
+
call(method, params, timeoutMs) {
|
|
6212
|
+
let id = ++this.sequence;
|
|
6213
|
+
return new Promise((resolve5, reject) => {
|
|
6214
|
+
let timer = setTimeout(() => {
|
|
6215
|
+
this.pending.delete(id), reject(new Error(`Trae CN \u672C\u5730\u8C03\u7528\u8D85\u65F6: ${method}`));
|
|
6216
|
+
}, timeoutMs);
|
|
6217
|
+
this.pending.set(id, { resolve: resolve5, reject, timer }), this.socket.send(JSON.stringify({ id, method, params }));
|
|
6218
|
+
});
|
|
6219
|
+
}
|
|
6220
|
+
close() {
|
|
6221
|
+
this.socket.close();
|
|
6222
|
+
}
|
|
6223
|
+
rejectAll(error) {
|
|
6224
|
+
for (let entry of this.pending.values())
|
|
6225
|
+
clearTimeout(entry.timer), entry.reject(error);
|
|
6226
|
+
this.pending.clear();
|
|
6227
|
+
}
|
|
6228
|
+
};
|
|
6229
|
+
async function findWorkbenchTarget(port) {
|
|
6230
|
+
try {
|
|
6231
|
+
let response = await fetchWithTimeout(`http://127.0.0.1:${port}/json/list`, 1500);
|
|
6232
|
+
return response.ok ? (await response.json()).find((target) => target.type === "page" && target.url?.includes("workbench.html")) ?? null : null;
|
|
6233
|
+
} catch {
|
|
6234
|
+
return null;
|
|
6235
|
+
}
|
|
6236
|
+
}
|
|
6237
|
+
async function waitForWorkbench(port, timeoutMs) {
|
|
6238
|
+
let deadline = Date.now() + timeoutMs;
|
|
6239
|
+
for (; Date.now() < deadline; ) {
|
|
6240
|
+
let target = await findWorkbenchTarget(port);
|
|
6241
|
+
if (target) return target;
|
|
6242
|
+
await delay(500);
|
|
6243
|
+
}
|
|
6244
|
+
throw new Error("\u7B49\u5F85 Trae CN \u542F\u52A8\u8D85\u65F6");
|
|
6245
|
+
}
|
|
6246
|
+
async function waitForTraeUserIds(userDataDir, timeoutMs) {
|
|
6247
|
+
let deadline = Date.now() + timeoutMs;
|
|
6248
|
+
for (; Date.now() < deadline; ) {
|
|
6249
|
+
let ids = await findTraeUserIds(userDataDir);
|
|
6250
|
+
if (ids.length > 0) return ids;
|
|
6251
|
+
await delay(500);
|
|
6252
|
+
}
|
|
6253
|
+
return [];
|
|
6254
|
+
}
|
|
6255
|
+
async function findTraeUserIds(userDataDir) {
|
|
6256
|
+
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");
|
|
6257
|
+
if (existsSync2(legacyTokenPath))
|
|
6258
|
+
try {
|
|
6259
|
+
collectJwtUserIds(await readFileTail(legacyTokenPath), ids);
|
|
6260
|
+
} catch {
|
|
6261
|
+
}
|
|
6262
|
+
for (let candidate of candidates) {
|
|
6263
|
+
try {
|
|
6264
|
+
collectJwtUserIds(await readFileTail(candidate.path), ids);
|
|
6265
|
+
} catch {
|
|
6266
|
+
}
|
|
6267
|
+
if (ids.size >= 10) break;
|
|
6268
|
+
}
|
|
6269
|
+
return [...ids];
|
|
6270
|
+
}
|
|
6271
|
+
async function findCompletionLogs(dir) {
|
|
6272
|
+
let entries;
|
|
6273
|
+
try {
|
|
6274
|
+
entries = await readdir9(dir, { withFileTypes: !0 });
|
|
6275
|
+
} catch {
|
|
6276
|
+
return [];
|
|
6277
|
+
}
|
|
6278
|
+
let files = [];
|
|
6279
|
+
for (let entry of entries) {
|
|
6280
|
+
let path = join23(dir, entry.name);
|
|
6281
|
+
if (entry.isDirectory()) files.push(...await findCompletionLogs(path));
|
|
6282
|
+
else if (entry.name === "completion.log" && path.includes("trae.ai-code-completion"))
|
|
6283
|
+
try {
|
|
6284
|
+
files.push({ path, mtimeMs: (await stat5(path)).mtimeMs });
|
|
6285
|
+
} catch {
|
|
6286
|
+
}
|
|
6287
|
+
}
|
|
6288
|
+
return files;
|
|
6289
|
+
}
|
|
6290
|
+
async function readFileTail(path, maxBytes = 2 * 1024 * 1024) {
|
|
6291
|
+
let handle = await open3(path, "r");
|
|
6292
|
+
try {
|
|
6293
|
+
let size = (await handle.stat()).size, length = Math.min(size, maxBytes), buffer = Buffer.alloc(length);
|
|
6294
|
+
return await handle.read(buffer, 0, length, Math.max(0, size - length)), buffer.toString("utf8");
|
|
6295
|
+
} finally {
|
|
6296
|
+
await handle.close();
|
|
6297
|
+
}
|
|
6298
|
+
}
|
|
6299
|
+
function collectJwtUserIds(content, ids) {
|
|
6300
|
+
for (let token of content.match(JWT_PATTERN) ?? []) {
|
|
6301
|
+
let payloadPart = token.split(".")[1];
|
|
6302
|
+
if (payloadPart)
|
|
6303
|
+
try {
|
|
6304
|
+
let id = JSON.parse(Buffer.from(payloadPart, "base64url").toString("utf8")).data?.id;
|
|
6305
|
+
(typeof id == "string" || typeof id == "number") && String(id).trim() && ids.add(String(id));
|
|
6306
|
+
} catch {
|
|
6307
|
+
}
|
|
6308
|
+
}
|
|
6309
|
+
}
|
|
6310
|
+
async function writeCache(sessions, cacheDir) {
|
|
6311
|
+
await mkdir4(cacheDir, { recursive: !0, mode: 448 });
|
|
6312
|
+
for (let session of sessions) {
|
|
6313
|
+
let hash = createHash2("sha256").update(session.sessionId).digest("hex").slice(0, 32), destination = join23(cacheDir, `${hash}.json`), temporary = join23(cacheDir, `.${hash}.${process.pid}.tmp`);
|
|
6314
|
+
await writeFile4(temporary, `${JSON.stringify(session, null, 2)}
|
|
6315
|
+
`, { encoding: "utf8", mode: 384 }), await rename(temporary, destination);
|
|
6316
|
+
}
|
|
6317
|
+
}
|
|
6318
|
+
async function launchTrae(appPath, port) {
|
|
6319
|
+
await execFileAsync2("open", [
|
|
6320
|
+
"-g",
|
|
6321
|
+
"-j",
|
|
6322
|
+
"-na",
|
|
6323
|
+
appPath,
|
|
6324
|
+
"--args",
|
|
6325
|
+
`--remote-debugging-port=${port}`
|
|
6326
|
+
]);
|
|
6327
|
+
}
|
|
6328
|
+
async function quitTrae() {
|
|
6329
|
+
if (process.platform === "darwin")
|
|
6330
|
+
try {
|
|
6331
|
+
await execFileAsync2("osascript", ["-e", 'tell application id "cn.trae.app" to quit']);
|
|
6332
|
+
} catch {
|
|
6333
|
+
}
|
|
6334
|
+
}
|
|
6335
|
+
async function isTraeRunning() {
|
|
6336
|
+
try {
|
|
6337
|
+
return await execFileAsync2("pgrep", ["-x", "TRAE"]), !0;
|
|
6338
|
+
} catch {
|
|
6339
|
+
return !1;
|
|
6340
|
+
}
|
|
6341
|
+
}
|
|
6342
|
+
async function isPortAvailable(port) {
|
|
6343
|
+
return new Promise((resolve5) => {
|
|
6344
|
+
let server = createServer();
|
|
6345
|
+
server.once("error", () => resolve5(!1)), server.listen(port, "127.0.0.1", () => server.close(() => resolve5(!0)));
|
|
6346
|
+
});
|
|
6347
|
+
}
|
|
6348
|
+
async function findFreePort() {
|
|
6349
|
+
return new Promise((resolve5, reject) => {
|
|
6350
|
+
let server = createServer();
|
|
6351
|
+
server.once("error", reject), server.listen(0, "127.0.0.1", () => {
|
|
6352
|
+
let address = server.address(), port = typeof address == "object" && address ? address.port : 0;
|
|
6353
|
+
server.close((error) => error ? reject(error) : resolve5(port));
|
|
6354
|
+
});
|
|
6355
|
+
});
|
|
6356
|
+
}
|
|
6357
|
+
function resolveTraeCnUserDataDir() {
|
|
6358
|
+
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");
|
|
6359
|
+
}
|
|
6360
|
+
async function fetchWithTimeout(url, timeoutMs) {
|
|
6361
|
+
let controller = new AbortController(), timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
6362
|
+
try {
|
|
6363
|
+
return await fetch(url, { signal: controller.signal });
|
|
6364
|
+
} finally {
|
|
6365
|
+
clearTimeout(timer);
|
|
6366
|
+
}
|
|
6367
|
+
}
|
|
6368
|
+
function normalizePort(value) {
|
|
6369
|
+
if (value != null)
|
|
6370
|
+
return Number.isInteger(value) && value > 0 && value <= 65535 ? value : void 0;
|
|
6371
|
+
}
|
|
6372
|
+
function clampTimeout(value) {
|
|
6373
|
+
return Number.isFinite(value) ? Math.min(18e4, Math.max(5e3, Math.floor(value))) : 12e4;
|
|
6374
|
+
}
|
|
6375
|
+
function sanitizeMessage(value) {
|
|
6376
|
+
return String(value ?? "").replace(/eyJ[A-Za-z0-9_.-]+/g, "<token>").replace(/[A-Za-z0-9_-]{24,}/g, "<id>").slice(0, 300);
|
|
6377
|
+
}
|
|
6378
|
+
function tokenValue2(value) {
|
|
6379
|
+
let number = typeof value == "number" ? value : Number(value);
|
|
6380
|
+
return Number.isFinite(number) && number > 0 ? Math.floor(number) : 0;
|
|
6381
|
+
}
|
|
6382
|
+
function stringValue4(value) {
|
|
6383
|
+
return typeof value == "string" ? value.trim() : "";
|
|
6384
|
+
}
|
|
6385
|
+
function delay(ms) {
|
|
6386
|
+
return new Promise((resolve5) => setTimeout(resolve5, ms));
|
|
6387
|
+
}
|
|
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
|
+
|
|
5723
6775
|
// src/cli.ts
|
|
5724
6776
|
var argv = process.argv.slice(2), command = argv[0];
|
|
5725
6777
|
await (async () => {
|
|
@@ -5750,6 +6802,15 @@ await (async () => {
|
|
|
5750
6802
|
let parsed = parseArgs(argv.slice(1));
|
|
5751
6803
|
if (parsed.flags.help) return helpForSubcommand("sync");
|
|
5752
6804
|
await runSync(parsed.flags, parsed.positionals);
|
|
6805
|
+
} else if (command === "trae") {
|
|
6806
|
+
let sub = argv[1], parsed = parseArgs(argv.slice(2));
|
|
6807
|
+
if (sub === "--help" || sub === "-h" || parsed.flags.help) return helpForSubcommand("trae");
|
|
6808
|
+
if (sub === "sync")
|
|
6809
|
+
await runTraeSync(parsed.flags, parsed.positionals);
|
|
6810
|
+
else {
|
|
6811
|
+
let zh2 = (await readConfig()).lang === "zh";
|
|
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]");
|
|
6813
|
+
}
|
|
5753
6814
|
} else if (command === "init") {
|
|
5754
6815
|
let parsed = parseArgs(argv.slice(1));
|
|
5755
6816
|
if (parsed.flags.help) return helpForSubcommand("init");
|
|
@@ -5823,7 +6884,7 @@ await (async () => {
|
|
|
5823
6884
|
async function runScan(flags, positionals = []) {
|
|
5824
6885
|
let config = await readConfig(), zh2 = config.lang === "zh";
|
|
5825
6886
|
assertNoPositionals("scan", positionals, zh2);
|
|
5826
|
-
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 });
|
|
5827
6888
|
if (isJson) {
|
|
5828
6889
|
console.log(JSON.stringify(results.length === 1 ? results[0] : results, null, 2));
|
|
5829
6890
|
return;
|
|
@@ -5862,14 +6923,15 @@ function printScanResult(result, zh2) {
|
|
|
5862
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();
|
|
5863
6924
|
}
|
|
5864
6925
|
async function runReport(flags, positionals = []) {
|
|
5865
|
-
let config = await readConfig();
|
|
5866
|
-
assertNoPositionals("report", positionals,
|
|
5867
|
-
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, {
|
|
5868
6929
|
explicitUrl: resolveOptionalString(flags["pricing-url"], void 0),
|
|
5869
6930
|
target: pricingTarget
|
|
5870
6931
|
}), report = await buildLocalReport(range, {
|
|
5871
6932
|
projectAliases: config.projectAliases,
|
|
5872
6933
|
dates,
|
|
6934
|
+
tools,
|
|
5873
6935
|
pricingCatalog: pricing.catalog,
|
|
5874
6936
|
pricingInfo: pricing.info
|
|
5875
6937
|
});
|
|
@@ -5931,15 +6993,16 @@ async function runEnroll(flags) {
|
|
|
5931
6993
|
}
|
|
5932
6994
|
function prompt(question) {
|
|
5933
6995
|
let rl = createInterface4({ input: process.stdin, output: process.stdout });
|
|
5934
|
-
return new Promise((
|
|
6996
|
+
return new Promise((resolve5) => {
|
|
5935
6997
|
rl.question(question, (answer) => {
|
|
5936
|
-
rl.close(),
|
|
6998
|
+
rl.close(), resolve5(answer.trim());
|
|
5937
6999
|
});
|
|
5938
7000
|
});
|
|
5939
7001
|
}
|
|
5940
7002
|
async function runSync(flags, positionals = []) {
|
|
5941
7003
|
let config = await readConfig();
|
|
5942
|
-
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");
|
|
5943
7006
|
let allTargets = config.targets ?? [];
|
|
5944
7007
|
if (allTargets.length === 0)
|
|
5945
7008
|
throw new Error("\u672A\u914D\u7F6E\u4EFB\u4F55\u4E0A\u62A5\u76EE\u6807\uFF0C\u8BF7\u5148\u6267\u884C aiusage enroll");
|
|
@@ -5988,6 +7051,55 @@ async function runSync(flags, positionals = []) {
|
|
|
5988
7051
|
results: uploadResults
|
|
5989
7052
|
}, null, 2));
|
|
5990
7053
|
}
|
|
7054
|
+
async function runTraeSync(flags, positionals = []) {
|
|
7055
|
+
let zh2 = (await readConfig()).lang === "zh";
|
|
7056
|
+
assertNoPositionals("trae sync", positionals, zh2);
|
|
7057
|
+
let portFlag = resolveOptionalString(flags.port, void 0), port = portFlag ? parsePositiveInt2(portFlag, "--port") : void 0;
|
|
7058
|
+
if (port != null && port > 65535) throw new Error("--port \u5FC5\u987B\u5728 1 \u5230 65535 \u4E4B\u95F4");
|
|
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");
|
|
7082
|
+
if (flags.json) {
|
|
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));
|
|
7089
|
+
return;
|
|
7090
|
+
}
|
|
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");
|
|
7102
|
+
}
|
|
5991
7103
|
function buildActivityPayloadByDate(items, visibility) {
|
|
5992
7104
|
let map = /* @__PURE__ */ new Map(), sanitized = applyProjectPrivacy(items, visibility);
|
|
5993
7105
|
for (let item of sanitized) {
|
|
@@ -6186,10 +7298,11 @@ function printHelp(zh2 = !1) {
|
|
|
6186
7298
|
console.log(`aiusage v${getVersion()}
|
|
6187
7299
|
`);
|
|
6188
7300
|
let cmds = zh2 ? [
|
|
6189
|
-
["scan [--date YYYY-MM-DD|--today|--range 7d|1m|3m] [--json]", "\u626B\u63CF\u7528\u91CF\u660E\u7EC6"],
|
|
6190
|
-
["report [--
|
|
6191
|
-
["activity [--today] [--range 7d|1m|3m|all] [--detail] [--json]", "\u672C\u5730\u4EA4\u4E92\u6307\u6807"],
|
|
6192
|
-
["sync [--today] [--range 7d|1m|3m]", "\u4E0A\u4F20\u7528\u91CF\u5230\u670D\u52A1\u7AEF"],
|
|
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"],
|
|
6193
7306
|
["scan/report/sync --from YYYY-MM-DD [--to YYYY-MM-DD]", "\u6307\u5B9A\u65E5\u671F\u8303\u56F4\uFF08--start/--end \u540C\u4E49\uFF09"],
|
|
6194
7307
|
["project [list|alias]", "\u9879\u76EE\u7BA1\u7406\u4E0E\u522B\u540D\u8BBE\u7F6E"],
|
|
6195
7308
|
["pricing [status|update] [--url URL]", "\u67E5\u770B/\u66F4\u65B0\u5B9A\u4EF7\u76EE\u5F55"],
|
|
@@ -6200,10 +7313,11 @@ function printHelp(zh2 = !1) {
|
|
|
6200
7313
|
["enroll --server URL --site-id ID --enroll-token TOKEN", "\u6CE8\u518C\u8BBE\u5907\u5230\u670D\u52A1\u7AEF"],
|
|
6201
7314
|
["health [--server URL]", "\u6D4B\u8BD5\u670D\u52A1\u7AEF\u8FDE\u901A\u6027"]
|
|
6202
7315
|
] : [
|
|
6203
|
-
["scan [--date YYYY-MM-DD|--today|--range 7d|1m|3m] [--json]", "Scan usage breakdown"],
|
|
6204
|
-
["report [--
|
|
6205
|
-
["activity [--today] [--range 7d|1m|3m|all] [--detail] [--json]", "Local interaction metrics"],
|
|
6206
|
-
["sync [--today] [--range 7d|1m|3m]", "Upload usage to server"],
|
|
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"],
|
|
6207
7321
|
["scan/report/sync --from YYYY-MM-DD [--to YYYY-MM-DD]", "Date range (--start/--end aliases)"],
|
|
6208
7322
|
["project [list|alias]", "Project management & aliases"],
|
|
6209
7323
|
["pricing [status|update] [--url URL]", "Pricing catalog management"],
|
|
@@ -6223,20 +7337,22 @@ function printUsageHint(zh2 = !1) {
|
|
|
6223
7337
|
console.log(`aiusage v${getVersion()}
|
|
6224
7338
|
`);
|
|
6225
7339
|
let cmds = zh2 ? [
|
|
6226
|
-
["scan [--date YYYY-MM-DD|--range 1m]", "\u626B\u63CF\u7528\u91CF\u660E\u7EC6"],
|
|
6227
|
-
["report [--
|
|
6228
|
-
["activity [--range 7d|1m|3m|all]", "\u672C\u5730\u4EA4\u4E92\u6307\u6807"],
|
|
6229
|
-
["sync [--today] [--range 7d|1m|3m]", "\u4E0A\u4F20\u7528\u91CF\u5230\u670D\u52A1\u7AEF"],
|
|
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"],
|
|
6230
7345
|
["project [list|alias]", "\u9879\u76EE\u7BA1\u7406\u4E0E\u522B\u540D\u8BBE\u7F6E"],
|
|
6231
7346
|
["pricing [status|update]", "\u67E5\u770B/\u66F4\u65B0\u5B9A\u4EF7\u76EE\u5F55"],
|
|
6232
7347
|
["schedule [on|off|status]", "\u5B9A\u65F6\u540C\u6B65\u7BA1\u7406"],
|
|
6233
7348
|
["doctor", "\u8BCA\u65AD\u68C0\u67E5"],
|
|
6234
7349
|
["config set <key> <value>", "\u4FEE\u6539\u914D\u7F6E"]
|
|
6235
7350
|
] : [
|
|
6236
|
-
["scan [--date YYYY-MM-DD|--range 1m]", "Scan usage breakdown"],
|
|
6237
|
-
["report [--
|
|
6238
|
-
["activity [--range 7d|1m|3m|all]", "Local interaction metrics"],
|
|
6239
|
-
["sync [--today] [--range 7d|1m|3m]", "Upload usage to server"],
|
|
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"],
|
|
6240
7356
|
["project [list|alias]", "Project management & aliases"],
|
|
6241
7357
|
["pricing [status|update]", "Pricing catalog management"],
|
|
6242
7358
|
["schedule [on|off|status]", "Scheduled sync management"],
|
|
@@ -6297,7 +7413,7 @@ function resolveDateParams(flags, config) {
|
|
|
6297
7413
|
let rangeFlag = flags.range;
|
|
6298
7414
|
if (typeof rangeFlag == "string") {
|
|
6299
7415
|
let range = parseReportRange(rangeFlag);
|
|
6300
|
-
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 };
|
|
6301
7417
|
}
|
|
6302
7418
|
if (typeof flags.lookback == "string") {
|
|
6303
7419
|
let lookbackDays2 = parsePositiveInt2(flags.lookback, "--lookback"), dates2 = getClosedDates(lookbackDays2);
|