@aiusage/cli 1.7.5 → 1.7.7
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 +23 -8
- package/README.zh-CN.md +42 -10
- package/THIRD_PARTY_NOTICES.md +29 -0
- package/dist/cli.js +946 -234
- package/package.json +2 -1
package/dist/cli.js
CHANGED
|
@@ -3030,42 +3030,74 @@ async function extractModelFromTranscript(filePath) {
|
|
|
3030
3030
|
|
|
3031
3031
|
// src/scanners/opencode.ts
|
|
3032
3032
|
import { execFile } from "node:child_process";
|
|
3033
|
-
import { readFile as readFile10 } from "node:fs/promises";
|
|
3034
|
-
import { basename as basename9, join as join13 } from "node:path";
|
|
3033
|
+
import { readdir as readdir5, readFile as readFile10, realpath, stat as stat3 } from "node:fs/promises";
|
|
3035
3034
|
import { homedir as homedir12 } from "node:os";
|
|
3036
|
-
|
|
3037
|
-
|
|
3038
|
-
|
|
3039
|
-
|
|
3040
|
-
|
|
3041
|
-
|
|
3042
|
-
|
|
3035
|
+
import { basename as basename9, dirname as dirname5, isAbsolute, join as join13, resolve as resolve2 } from "node:path";
|
|
3036
|
+
var nodeSqliteModulePromise, sqliteRuntimePromise;
|
|
3037
|
+
async function scanOpencodeDates(targetDates, options = {}) {
|
|
3038
|
+
let dates = new Set(targetDates), { records, sourceCount } = await loadOpenCodeRecords(options);
|
|
3039
|
+
if (sourceCount === 0) return emptyResult(dates);
|
|
3040
|
+
let grouped = initDateMap(dates), sessionsByBreakdown = /* @__PURE__ */ new Map();
|
|
3041
|
+
for (let record of records)
|
|
3042
|
+
addOpenCodeRecord(record, grouped, sessionsByBreakdown, options.projectAliases);
|
|
3043
|
+
for (let [compoundKey, sessions] of sessionsByBreakdown) {
|
|
3044
|
+
let separator = compoundKey.indexOf("\0"), usageDate = compoundKey.slice(0, separator), breakdownKey = compoundKey.slice(separator + 1), breakdown = grouped.get(usageDate)?.get(breakdownKey);
|
|
3045
|
+
breakdown && sessions.size > 0 && (breakdown.sessionCount = sessions.size);
|
|
3046
|
+
}
|
|
3047
|
+
return finalize(grouped);
|
|
3048
|
+
}
|
|
3049
|
+
async function discoverOpenCodeUsageDates(options = {}) {
|
|
3050
|
+
let result = /* @__PURE__ */ new Set(), { records } = await loadOpenCodeRecords(options);
|
|
3051
|
+
for (let record of records) result.add(dateKey(record.timestamp));
|
|
3052
|
+
return result;
|
|
3053
|
+
}
|
|
3054
|
+
function resolveOpenCodeDataDir(home = homedir12(), env = process.env) {
|
|
3055
|
+
let xdgDataHome = env.XDG_DATA_HOME?.trim();
|
|
3056
|
+
return join13(xdgDataHome || join13(home, ".local", "share"), "opencode");
|
|
3057
|
+
}
|
|
3058
|
+
async function resolveOpenCodeSources(options = {}) {
|
|
3059
|
+
let home = options.homeDir ?? homedir12(), env = options.env ?? process.env, dataDir = options.dataDir ?? resolveOpenCodeDataDir(home, env), legacyDir = options.legacyDir ?? join13(dataDir, "storage", "message"), configuredPaths = [...options.dbPaths ?? []];
|
|
3060
|
+
env.OPENCODE_DB?.trim() && configuredPaths.push(env.OPENCODE_DB.trim());
|
|
3061
|
+
let dbPaths = await discoverOpenCodeDatabases(dataDir, configuredPaths, home);
|
|
3062
|
+
return { dataDir, legacyDir, dbPaths };
|
|
3063
|
+
}
|
|
3064
|
+
async function discoverOpenCodeDatabases(dataDir, extraPaths = [], home = homedir12()) {
|
|
3065
|
+
let candidates = [];
|
|
3066
|
+
try {
|
|
3067
|
+
let entries = await readdir5(dataDir, { withFileTypes: !0 });
|
|
3068
|
+
for (let entry of entries)
|
|
3069
|
+
isOpenCodeDatabaseFilename(entry.name) && candidates.push(join13(dataDir, entry.name));
|
|
3070
|
+
} catch {
|
|
3071
|
+
}
|
|
3072
|
+
for (let rawPath of extraPaths) {
|
|
3073
|
+
let path = expandConfiguredPath(rawPath, home);
|
|
3074
|
+
path && isOpenCodeDatabaseFilename(basename9(path)) && candidates.push(path);
|
|
3075
|
+
}
|
|
3076
|
+
let result = [], seen = /* @__PURE__ */ new Set();
|
|
3077
|
+
for (let path of candidates.sort((a, b) => a.localeCompare(b)))
|
|
3043
3078
|
try {
|
|
3044
|
-
|
|
3079
|
+
if (!(await stat3(path)).isFile()) continue;
|
|
3080
|
+
let canonical = await realpath(path).catch(() => path);
|
|
3081
|
+
if (seen.has(canonical)) continue;
|
|
3082
|
+
seen.add(canonical), result.push(path);
|
|
3045
3083
|
} catch {
|
|
3046
|
-
continue;
|
|
3047
3084
|
}
|
|
3048
|
-
|
|
3049
|
-
record && addOpenCodeRecord(record, grouped, seenIds, seenFingerprints, projectAliases);
|
|
3050
|
-
}
|
|
3051
|
-
return sqliteRows.length === 0 && files.length === 0 ? emptyResult(dates) : finalize(grouped);
|
|
3085
|
+
return result;
|
|
3052
3086
|
}
|
|
3053
|
-
|
|
3054
|
-
|
|
3055
|
-
|
|
3056
|
-
|
|
3057
|
-
|
|
3087
|
+
function isOpenCodeDatabaseFilename(name) {
|
|
3088
|
+
return /^opencode(?:-[A-Za-z0-9._-]+)?\.db$/.test(name);
|
|
3089
|
+
}
|
|
3090
|
+
async function detectOpenCodeSqliteRuntime() {
|
|
3091
|
+
return sqliteRuntimePromise ??= (async () => {
|
|
3092
|
+
if (await loadNodeSqlite()) return "node";
|
|
3058
3093
|
try {
|
|
3059
|
-
|
|
3060
|
-
JSON.parse(await readFile10(filePath, "utf-8")),
|
|
3061
|
-
basename9(filePath, ".json")
|
|
3062
|
-
);
|
|
3063
|
-
record && result.add(dateKey(record.timestamp));
|
|
3094
|
+
return await runExternalSqlite(["-version"]), "external";
|
|
3064
3095
|
} catch {
|
|
3096
|
+
return "unavailable";
|
|
3065
3097
|
}
|
|
3066
|
-
|
|
3098
|
+
})(), sqliteRuntimePromise;
|
|
3067
3099
|
}
|
|
3068
|
-
function parseOpenCodeSqliteRows(rows) {
|
|
3100
|
+
function parseOpenCodeSqliteRows(rows, options = {}) {
|
|
3069
3101
|
return rows.flatMap((row) => {
|
|
3070
3102
|
if (!row.data) return [];
|
|
3071
3103
|
let message;
|
|
@@ -3074,83 +3106,193 @@ function parseOpenCodeSqliteRows(rows) {
|
|
|
3074
3106
|
} catch {
|
|
3075
3107
|
return [];
|
|
3076
3108
|
}
|
|
3077
|
-
message.
|
|
3078
|
-
let record = parseOpenCodeMessage(
|
|
3079
|
-
|
|
3109
|
+
if (!message || typeof message != "object" || Array.isArray(message)) return [];
|
|
3110
|
+
let record = parseOpenCodeMessage(
|
|
3111
|
+
message,
|
|
3112
|
+
row.id,
|
|
3113
|
+
row.session_id,
|
|
3114
|
+
options.assistantGuaranteed === !0
|
|
3115
|
+
);
|
|
3116
|
+
return record ? (record.sessionId = cleanString(row.session_id) || record.sessionId, record.projectRoot = normalizeOpenCodeProjectRoot(row.workspace_root) || record.projectRoot, [record]) : [];
|
|
3080
3117
|
});
|
|
3081
3118
|
}
|
|
3082
|
-
|
|
3083
|
-
let
|
|
3084
|
-
|
|
3085
|
-
|
|
3086
|
-
|
|
3087
|
-
|
|
3088
|
-
|
|
3089
|
-
|
|
3090
|
-
|
|
3091
|
-
|
|
3092
|
-
|
|
3093
|
-
|
|
3094
|
-
|
|
3095
|
-
|
|
3119
|
+
function deduplicateOpenCodeRecords(records) {
|
|
3120
|
+
let entries = [], idIndices = /* @__PURE__ */ new Map(), fingerprintIndices = /* @__PURE__ */ new Map();
|
|
3121
|
+
for (let rawRecord of records) {
|
|
3122
|
+
let record = {
|
|
3123
|
+
...rawRecord,
|
|
3124
|
+
tokens: { ...rawRecord.tokens }
|
|
3125
|
+
};
|
|
3126
|
+
if (record.id) {
|
|
3127
|
+
let existingIndex = idIndices.get(record.id);
|
|
3128
|
+
if (existingIndex !== void 0) {
|
|
3129
|
+
mergeDuplicateProject(entries[existingIndex], record.projectRoot), addFingerprintIndex(fingerprintIndices, record.fingerprint, existingIndex);
|
|
3130
|
+
continue;
|
|
3131
|
+
}
|
|
3132
|
+
}
|
|
3133
|
+
let duplicateIndex = (fingerprintIndices.get(record.fingerprint) ?? []).find((index2) => {
|
|
3134
|
+
let existingId = entries[index2].record.id;
|
|
3135
|
+
return !existingId || !record.id || existingId === record.id;
|
|
3136
|
+
});
|
|
3137
|
+
if (duplicateIndex !== void 0) {
|
|
3138
|
+
let entry = entries[duplicateIndex];
|
|
3139
|
+
record.id && !entry.record.id && (entry.record.id = record.id, idIndices.set(record.id, duplicateIndex)), mergeDuplicateProject(entry, record.projectRoot);
|
|
3140
|
+
continue;
|
|
3141
|
+
}
|
|
3142
|
+
let index = entries.length;
|
|
3143
|
+
entries.push({ record, hasProjectConflict: !1 }), record.id && idIndices.set(record.id, index), addFingerprintIndex(fingerprintIndices, record.fingerprint, index);
|
|
3144
|
+
}
|
|
3145
|
+
return entries.map((entry) => entry.record);
|
|
3146
|
+
}
|
|
3147
|
+
async function loadOpenCodeRecords(options) {
|
|
3148
|
+
let sources = await resolveOpenCodeSources(options), sqliteRecords = [];
|
|
3149
|
+
for (let dbPath of sources.dbPaths) {
|
|
3150
|
+
let { v2Rows, v1Rows } = await queryOpenCodeDatabase(dbPath);
|
|
3151
|
+
sqliteRecords.push(...deduplicateOpenCodeRecords([
|
|
3152
|
+
...parseOpenCodeSqliteRows(v2Rows, { assistantGuaranteed: !0 }),
|
|
3153
|
+
...parseOpenCodeSqliteRows(v1Rows)
|
|
3154
|
+
]));
|
|
3155
|
+
}
|
|
3156
|
+
let files = await walkFiles(sources.legacyDir, ".json"), legacyRecords = [];
|
|
3157
|
+
for (let filePath of files)
|
|
3158
|
+
try {
|
|
3159
|
+
let message = JSON.parse(await readFile10(filePath, "utf-8")), record = parseOpenCodeMessage(
|
|
3160
|
+
message,
|
|
3161
|
+
basename9(filePath, ".json"),
|
|
3162
|
+
message.sessionID ?? basename9(dirname5(filePath)),
|
|
3163
|
+
!1
|
|
3164
|
+
);
|
|
3165
|
+
record && legacyRecords.push(record);
|
|
3166
|
+
} catch {
|
|
3167
|
+
}
|
|
3168
|
+
return {
|
|
3169
|
+
records: deduplicateOpenCodeSources([...sqliteRecords, ...legacyRecords]),
|
|
3170
|
+
sourceCount: sources.dbPaths.length + files.length
|
|
3171
|
+
};
|
|
3172
|
+
}
|
|
3173
|
+
async function queryOpenCodeDatabase(dbPath) {
|
|
3174
|
+
let v2Rows = await queryFirstSupported(dbPath, [
|
|
3175
|
+
`SELECT sm.id, sm.session_id, sm.data, NULLIF(s.directory, '') AS workspace_root
|
|
3176
|
+
FROM session_message sm
|
|
3177
|
+
LEFT JOIN session s ON s.id = sm.session_id
|
|
3178
|
+
WHERE sm.type = 'assistant'
|
|
3179
|
+
AND CASE WHEN json_valid(sm.data)
|
|
3180
|
+
THEN json_extract(sm.data, '$.tokens') IS NOT NULL ELSE 0 END
|
|
3181
|
+
ORDER BY sm.id, sm.session_id`,
|
|
3182
|
+
`SELECT sm.id, sm.session_id, sm.data, NULL AS workspace_root
|
|
3183
|
+
FROM session_message sm
|
|
3184
|
+
WHERE sm.type = 'assistant'
|
|
3185
|
+
AND CASE WHEN json_valid(sm.data)
|
|
3186
|
+
THEN json_extract(sm.data, '$.tokens') IS NOT NULL ELSE 0 END
|
|
3187
|
+
ORDER BY sm.id, sm.session_id`
|
|
3188
|
+
]), v1Rows = await queryFirstSupported(dbPath, [
|
|
3189
|
+
`SELECT m.id, m.session_id, m.data, NULLIF(s.directory, '') AS workspace_root
|
|
3190
|
+
FROM message m
|
|
3191
|
+
LEFT JOIN session s ON s.id = m.session_id
|
|
3192
|
+
WHERE CASE WHEN json_valid(m.data) THEN
|
|
3193
|
+
json_extract(m.data, '$.role') = 'assistant'
|
|
3194
|
+
AND json_extract(m.data, '$.tokens') IS NOT NULL ELSE 0 END
|
|
3195
|
+
ORDER BY m.id, m.session_id`,
|
|
3196
|
+
`SELECT m.id, m.session_id, m.data, NULL AS workspace_root
|
|
3197
|
+
FROM message m
|
|
3198
|
+
WHERE CASE WHEN json_valid(m.data) THEN
|
|
3199
|
+
json_extract(m.data, '$.role') = 'assistant'
|
|
3200
|
+
AND json_extract(m.data, '$.tokens') IS NOT NULL ELSE 0 END
|
|
3201
|
+
ORDER BY m.id, m.session_id`
|
|
3202
|
+
]);
|
|
3203
|
+
return { v2Rows, v1Rows };
|
|
3204
|
+
}
|
|
3205
|
+
async function queryFirstSupported(dbPath, queries) {
|
|
3206
|
+
for (let query of queries)
|
|
3096
3207
|
try {
|
|
3097
|
-
|
|
3098
|
-
if (Array.isArray(rows)) return rows.filter(isSqliteRow);
|
|
3208
|
+
return await runSqliteQuery(dbPath, query);
|
|
3099
3209
|
} catch {
|
|
3100
3210
|
}
|
|
3101
3211
|
return [];
|
|
3102
3212
|
}
|
|
3103
|
-
function
|
|
3104
|
-
|
|
3213
|
+
async function runSqliteQuery(dbPath, query) {
|
|
3214
|
+
let nodeSqlite = await loadNodeSqlite();
|
|
3215
|
+
if (nodeSqlite) {
|
|
3216
|
+
let db = new nodeSqlite.DatabaseSync(dbPath, { readOnly: !0 });
|
|
3217
|
+
try {
|
|
3218
|
+
return db.prepare(query).all().filter(isSqliteRow);
|
|
3219
|
+
} finally {
|
|
3220
|
+
db.close();
|
|
3221
|
+
}
|
|
3222
|
+
}
|
|
3223
|
+
let stdout = await runExternalSqlite(["-readonly", "-json", dbPath, query]), rows = JSON.parse(stdout || "[]");
|
|
3224
|
+
return Array.isArray(rows) ? rows.filter(isSqliteRow) : [];
|
|
3225
|
+
}
|
|
3226
|
+
async function loadNodeSqlite() {
|
|
3227
|
+
return nodeSqliteModulePromise ??= (async () => {
|
|
3228
|
+
try {
|
|
3229
|
+
let module = await import("node:sqlite");
|
|
3230
|
+
return typeof module.DatabaseSync == "function" ? module : null;
|
|
3231
|
+
} catch {
|
|
3232
|
+
return null;
|
|
3233
|
+
}
|
|
3234
|
+
})(), nodeSqliteModulePromise;
|
|
3235
|
+
}
|
|
3236
|
+
function runExternalSqlite(args) {
|
|
3237
|
+
return new Promise((resolve6, reject) => {
|
|
3105
3238
|
execFile(
|
|
3106
3239
|
"sqlite3",
|
|
3107
3240
|
args,
|
|
3108
|
-
{ encoding: "utf8", maxBuffer:
|
|
3109
|
-
(error, stdout) => error ? reject(error) :
|
|
3241
|
+
{ encoding: "utf8", maxBuffer: 256 * 1024 * 1024 },
|
|
3242
|
+
(error, stdout) => error ? reject(error) : resolve6(stdout)
|
|
3110
3243
|
);
|
|
3111
3244
|
});
|
|
3112
3245
|
}
|
|
3113
|
-
function parseOpenCodeMessage(message, fallbackId) {
|
|
3114
|
-
if (message.role !== "assistant" || !message.tokens) return;
|
|
3246
|
+
function parseOpenCodeMessage(message, fallbackId, fallbackSessionId, assistantGuaranteed = !1) {
|
|
3247
|
+
if (message.role != null && message.role !== "assistant" || !assistantGuaranteed && message.role !== "assistant" || !message.tokens) return;
|
|
3115
3248
|
let timestamp = parseTs(message.time?.created);
|
|
3116
3249
|
if (!timestamp) return;
|
|
3117
|
-
let model = message.modelID
|
|
3250
|
+
let model = cleanString(message.modelID) || cleanString(message.model?.id);
|
|
3251
|
+
if (!model) return;
|
|
3252
|
+
let rawProvider = cleanString(message.providerID) || cleanString(message.model?.providerID), provider = canonicalizeOpenCodeProvider(rawProvider) || inferProviderFromModel(model, "opencode"), tokens = {
|
|
3118
3253
|
input: clamp3(message.tokens.input),
|
|
3119
3254
|
cached: clamp3(message.tokens.cache?.read),
|
|
3120
3255
|
cacheWrite: clamp3(message.tokens.cache?.write),
|
|
3121
3256
|
output: clamp3(message.tokens.output),
|
|
3122
3257
|
reasoning: clamp3(message.tokens.reasoning)
|
|
3123
|
-
};
|
|
3124
|
-
if (Object.values(tokens).every((value) => value === 0)) return;
|
|
3125
|
-
let
|
|
3258
|
+
}, completed = parseTs(message.time?.completed)?.getTime() ?? "", costUSD = clampCost(message.cost);
|
|
3259
|
+
if (Object.values(tokens).every((value) => value === 0) && costUSD === 0) return;
|
|
3260
|
+
let agent = (cleanString(message.mode) || cleanString(message.agent))?.toLowerCase(), projectRoot = normalizeOpenCodeProjectRoot(
|
|
3261
|
+
typeof message.path == "string" ? message.path : message.path?.root
|
|
3262
|
+
), id = cleanString(message.id), sessionId = cleanString(message.sessionID) || cleanString(fallbackSessionId);
|
|
3126
3263
|
return {
|
|
3127
|
-
id
|
|
3264
|
+
id,
|
|
3265
|
+
fallbackId,
|
|
3266
|
+
sessionId,
|
|
3128
3267
|
timestamp,
|
|
3129
3268
|
model,
|
|
3130
3269
|
provider,
|
|
3131
3270
|
projectRoot,
|
|
3132
3271
|
tokens,
|
|
3133
|
-
|
|
3272
|
+
costUSD,
|
|
3273
|
+
agent,
|
|
3274
|
+
fingerprint: JSON.stringify([
|
|
3134
3275
|
timestamp.getTime(),
|
|
3276
|
+
completed,
|
|
3135
3277
|
model,
|
|
3136
3278
|
provider,
|
|
3137
3279
|
tokens.input,
|
|
3138
3280
|
tokens.cached,
|
|
3139
3281
|
tokens.cacheWrite,
|
|
3140
3282
|
tokens.output,
|
|
3141
|
-
tokens.reasoning
|
|
3142
|
-
|
|
3283
|
+
tokens.reasoning,
|
|
3284
|
+
costUSD,
|
|
3285
|
+
agent ?? ""
|
|
3286
|
+
])
|
|
3143
3287
|
};
|
|
3144
3288
|
}
|
|
3145
|
-
function addOpenCodeRecord(record, grouped,
|
|
3146
|
-
|
|
3147
|
-
record.id && seenIds.add(record.id), seenFingerprints.add(record.fingerprint);
|
|
3148
|
-
let dayMap = grouped.get(dateKey(record.timestamp));
|
|
3289
|
+
function addOpenCodeRecord(record, grouped, sessionsByBreakdown, aliases2) {
|
|
3290
|
+
let usageDate = dateKey(record.timestamp), dayMap = grouped.get(usageDate);
|
|
3149
3291
|
if (!dayMap) return;
|
|
3150
|
-
let fields = record.projectRoot ? resolveProjectFields(record.projectRoot, aliases2) : { project: "unknown", projectDisplay: "unknown" }
|
|
3292
|
+
let fields = record.projectRoot ? resolveProjectFields(record.projectRoot, aliases2) : { project: "unknown", projectDisplay: "unknown" }, breakdownKey = `${record.provider}|${record.model}|${fields.project}`;
|
|
3151
3293
|
accumulate(
|
|
3152
3294
|
dayMap,
|
|
3153
|
-
|
|
3295
|
+
breakdownKey,
|
|
3154
3296
|
{
|
|
3155
3297
|
provider: record.provider,
|
|
3156
3298
|
product: "opencode",
|
|
@@ -3167,6 +3309,67 @@ function addOpenCodeRecord(record, grouped, seenIds, seenFingerprints, aliases2)
|
|
|
3167
3309
|
},
|
|
3168
3310
|
record.tokens
|
|
3169
3311
|
);
|
|
3312
|
+
let breakdown = dayMap.get(breakdownKey);
|
|
3313
|
+
if (record.costUSD > 0 && (breakdown.costUSD = (breakdown.costUSD ?? 0) + record.costUSD), record.sessionId) {
|
|
3314
|
+
let sessionKey = `${usageDate}\0${breakdownKey}`, sessions = sessionsByBreakdown.get(sessionKey) ?? /* @__PURE__ */ new Set();
|
|
3315
|
+
sessions.add(record.sessionId), sessionsByBreakdown.set(sessionKey, sessions);
|
|
3316
|
+
}
|
|
3317
|
+
}
|
|
3318
|
+
function mergeDuplicateProject(entry, incomingRoot) {
|
|
3319
|
+
if (entry.hasProjectConflict || !incomingRoot) return;
|
|
3320
|
+
let existingRoot = entry.record.projectRoot;
|
|
3321
|
+
existingRoot ? existingRoot !== incomingRoot && (entry.hasProjectConflict = !0, entry.record.projectRoot = void 0) : entry.record.projectRoot = incomingRoot;
|
|
3322
|
+
}
|
|
3323
|
+
function addFingerprintIndex(map, fingerprint, index) {
|
|
3324
|
+
let indices = map.get(fingerprint) ?? [];
|
|
3325
|
+
indices.includes(index) || indices.push(index), map.set(fingerprint, indices);
|
|
3326
|
+
}
|
|
3327
|
+
function deduplicateOpenCodeSources(records) {
|
|
3328
|
+
let seen = /* @__PURE__ */ new Set();
|
|
3329
|
+
return records.filter((record) => {
|
|
3330
|
+
let key = record.id || record.fallbackId;
|
|
3331
|
+
return !key || seen.add(key);
|
|
3332
|
+
});
|
|
3333
|
+
}
|
|
3334
|
+
function canonicalizeOpenCodeProvider(raw) {
|
|
3335
|
+
if (!raw) return;
|
|
3336
|
+
let normalized = raw.trim().replace(/\/+$/, "").toLowerCase().replaceAll("-", "_");
|
|
3337
|
+
if (!normalized || normalized === "unknown" || normalized.startsWith("<") && normalized.endsWith(">"))
|
|
3338
|
+
return;
|
|
3339
|
+
let first = normalized.split("/")[0].split(".")[0];
|
|
3340
|
+
return {
|
|
3341
|
+
x_ai: "xai",
|
|
3342
|
+
z_ai: "zai",
|
|
3343
|
+
moonshotai: "moonshot",
|
|
3344
|
+
meta: "meta_llama",
|
|
3345
|
+
azure: "azure_ai",
|
|
3346
|
+
vertex: "anthropic",
|
|
3347
|
+
vertex_ai: "anthropic",
|
|
3348
|
+
together: "together_ai",
|
|
3349
|
+
fireworks: "fireworks_ai",
|
|
3350
|
+
gemini: "google",
|
|
3351
|
+
openai_codex: "openai",
|
|
3352
|
+
minimaxai: "minimax",
|
|
3353
|
+
minimax_ai: "minimax",
|
|
3354
|
+
mistral: "mistralai"
|
|
3355
|
+
}[first] ?? first;
|
|
3356
|
+
}
|
|
3357
|
+
function expandConfiguredPath(rawPath, home) {
|
|
3358
|
+
let value = rawPath.trim();
|
|
3359
|
+
if (value)
|
|
3360
|
+
return value === "~" ? home : value.startsWith("~/") || value.startsWith("~\\") ? join13(home, value.slice(2)) : isAbsolute(value) ? value : resolve2(value);
|
|
3361
|
+
}
|
|
3362
|
+
function normalizeOpenCodeProjectRoot(raw) {
|
|
3363
|
+
let trimmed = cleanString(raw);
|
|
3364
|
+
if (!trimmed) return;
|
|
3365
|
+
let preserveUncPrefix = trimmed.startsWith("\\\\") || trimmed.startsWith("//"), normalized = trimmed.replaceAll("\\", "/");
|
|
3366
|
+
preserveUncPrefix ? normalized = `//${normalized.replace(/^\/+/, "").replace(/\/{2,}/g, "/")}` : normalized = normalized.replace(/\/{2,}/g, "/");
|
|
3367
|
+
let minimumLength = preserveUncPrefix ? 2 : 1;
|
|
3368
|
+
return normalized.length > minimumLength && (normalized = normalized.replace(/\/+$/, "")), normalized || void 0;
|
|
3369
|
+
}
|
|
3370
|
+
function cleanString(value) {
|
|
3371
|
+
if (typeof value == "string")
|
|
3372
|
+
return value.trim() || void 0;
|
|
3170
3373
|
}
|
|
3171
3374
|
function isSqliteRow(value) {
|
|
3172
3375
|
return typeof value == "object" && value !== null && !Array.isArray(value);
|
|
@@ -3174,10 +3377,13 @@ function isSqliteRow(value) {
|
|
|
3174
3377
|
function clamp3(value) {
|
|
3175
3378
|
return Math.max(Number.isFinite(value) ? value : 0, 0);
|
|
3176
3379
|
}
|
|
3380
|
+
function clampCost(value) {
|
|
3381
|
+
return Number.isFinite(value) && value > 0 ? value : 0;
|
|
3382
|
+
}
|
|
3177
3383
|
|
|
3178
3384
|
// src/scanners/pi.ts
|
|
3179
3385
|
import { readFile as readFile11 } from "node:fs/promises";
|
|
3180
|
-
import { join as join14, basename as basename10, dirname as
|
|
3386
|
+
import { join as join14, basename as basename10, dirname as dirname6 } from "node:path";
|
|
3181
3387
|
import { homedir as homedir13 } from "node:os";
|
|
3182
3388
|
async function scanPiDates(targetDates, baseDir, projectAliases) {
|
|
3183
3389
|
let dates = new Set(targetDates), sessionDirs = baseDir ? [baseDir] : getSessionDirs(), files = [...new Set((await Promise.all(sessionDirs.map((dir) => walkFiles(dir, ".jsonl")))).flat())];
|
|
@@ -3190,7 +3396,7 @@ async function scanPiDates(targetDates, baseDir, projectAliases) {
|
|
|
3190
3396
|
} catch {
|
|
3191
3397
|
continue;
|
|
3192
3398
|
}
|
|
3193
|
-
let parentDir =
|
|
3399
|
+
let parentDir = dirname6(filePath), encodedCwd = basename10(parentDir), sessionProjectFields = { project: extractProjectFromEncoded(encodedCwd), projectDisplay: extractProjectFromEncoded(encodedCwd) }, sessionId = basename10(filePath, ".jsonl"), messageIndex = 0, fallbackTs = await fileModifiedTs(filePath);
|
|
3194
3400
|
for (let line of content.split(`
|
|
3195
3401
|
`)) {
|
|
3196
3402
|
if (!line.trim()) continue;
|
|
@@ -3256,70 +3462,77 @@ function extractProjectFromEncoded(encoded) {
|
|
|
3256
3462
|
// src/scanners/trae.ts
|
|
3257
3463
|
import { readFile as readFile12 } from "node:fs/promises";
|
|
3258
3464
|
import { homedir as homedir14 } from "node:os";
|
|
3259
|
-
import { join as join15, resolve as
|
|
3465
|
+
import { join as join15, resolve as resolve3 } from "node:path";
|
|
3260
3466
|
function resolveTraeNativeCacheDir(home = homedir14()) {
|
|
3261
3467
|
let explicit = process.env.AIUSAGE_TRAE_CACHE_DIR?.trim();
|
|
3262
|
-
return explicit ?
|
|
3468
|
+
return explicit ? resolve3(explicit) : join15(home, ".aiusage", "trae-cache", "sessions");
|
|
3263
3469
|
}
|
|
3264
3470
|
function resolveTokscaleTraeCacheDir(home = homedir14()) {
|
|
3265
3471
|
let configDir = process.env.TOKSCALE_CONFIG_DIR?.trim();
|
|
3266
|
-
return configDir ? join15(
|
|
3472
|
+
return configDir ? join15(resolve3(configDir), "trae-cache", "sessions") : join15(home, ".config", "tokscale", "trae-cache", "sessions");
|
|
3473
|
+
}
|
|
3474
|
+
function resolveTraeIntlCacheDir(home = homedir14()) {
|
|
3475
|
+
let explicit = process.env.AIUSAGE_TRAE_INTL_CACHE_DIR?.trim();
|
|
3476
|
+
return explicit ? resolve3(explicit) : join15(home, ".aiusage", "trae-cache", "intl", "sessions");
|
|
3267
3477
|
}
|
|
3268
3478
|
async function scanTraeDates(targetDates, options = {}) {
|
|
3269
3479
|
let dates = new Set(targetDates);
|
|
3270
3480
|
if (dates.size === 0) return /* @__PURE__ */ new Map();
|
|
3271
|
-
let nativeDir = options.nativeCacheDir ?? resolveTraeNativeCacheDir(), tokscaleDir = options.tokscaleCacheDir ?? resolveTokscaleTraeCacheDir(), cacheSources = [.../* @__PURE__ */ new Set([
|
|
3481
|
+
let nativeDir = options.nativeCacheDir ?? resolveTraeNativeCacheDir(), intlDir = options.intlCacheDir ?? resolveTraeIntlCacheDir(), tokscaleDir = options.tokscaleCacheDir ?? resolveTokscaleTraeCacheDir(), cacheSources = [.../* @__PURE__ */ new Set([
|
|
3272
3482
|
`${nativeDir}\0native`,
|
|
3483
|
+
`${intlDir}\0intl`,
|
|
3273
3484
|
`${tokscaleDir}\0tokscale`
|
|
3274
3485
|
])], files = (await Promise.all(cacheSources.map(async (source) => {
|
|
3275
3486
|
let [dir, kind] = source.split("\0");
|
|
3276
3487
|
return (await walkFiles(dir, ".json")).map((filePath) => ({ filePath, kind }));
|
|
3277
3488
|
}))).flat();
|
|
3278
3489
|
if (files.length === 0) return emptyResult(dates);
|
|
3279
|
-
let grouped = initDateMap(dates),
|
|
3490
|
+
let grouped = initDateMap(dates), selectedEvents = /* @__PURE__ */ new Map(), sessionSets = /* @__PURE__ */ new Map();
|
|
3280
3491
|
for (let { filePath, kind } of files) {
|
|
3281
3492
|
let value = await readJson2(filePath);
|
|
3282
3493
|
if (value == null) continue;
|
|
3283
|
-
let events = kind === "native" ? parseNativeCache(value) :
|
|
3494
|
+
let events = kind === "native" ? parseNativeCache(value) : parseIntlCache(value);
|
|
3284
3495
|
for (let event of events) {
|
|
3285
|
-
|
|
3286
|
-
|
|
3287
|
-
|
|
3288
|
-
|
|
3289
|
-
|
|
3290
|
-
|
|
3291
|
-
|
|
3292
|
-
|
|
3293
|
-
|
|
3294
|
-
|
|
3295
|
-
|
|
3296
|
-
|
|
3297
|
-
|
|
3298
|
-
|
|
3299
|
-
|
|
3300
|
-
|
|
3301
|
-
|
|
3302
|
-
|
|
3303
|
-
|
|
3304
|
-
|
|
3305
|
-
|
|
3306
|
-
|
|
3307
|
-
|
|
3308
|
-
|
|
3309
|
-
|
|
3310
|
-
|
|
3311
|
-
|
|
3312
|
-
|
|
3313
|
-
|
|
3314
|
-
|
|
3315
|
-
let
|
|
3316
|
-
|
|
3496
|
+
let existing = selectedEvents.get(event.dedupKey);
|
|
3497
|
+
(!existing || shouldReplaceEvent(existing, event)) && selectedEvents.set(event.dedupKey, event);
|
|
3498
|
+
}
|
|
3499
|
+
}
|
|
3500
|
+
for (let event of selectedEvents.values()) {
|
|
3501
|
+
let usageDate = dateKey(event.timestamp);
|
|
3502
|
+
if (!dates.has(usageDate)) continue;
|
|
3503
|
+
let day = grouped.get(usageDate);
|
|
3504
|
+
if (!day) continue;
|
|
3505
|
+
let projectFields = resolveProjectFields(event.project, options.projectAliases), breakdownKey = `${event.product}|${event.provider}|${event.model}|${projectFields.project}`;
|
|
3506
|
+
if (accumulate(
|
|
3507
|
+
day,
|
|
3508
|
+
breakdownKey,
|
|
3509
|
+
{
|
|
3510
|
+
provider: event.provider,
|
|
3511
|
+
product: event.product,
|
|
3512
|
+
channel: "ide",
|
|
3513
|
+
model: event.model,
|
|
3514
|
+
project: projectFields.project,
|
|
3515
|
+
projectDisplay: projectFields.projectDisplay,
|
|
3516
|
+
projectAlias: projectFields.projectAlias,
|
|
3517
|
+
sessionCount: 0,
|
|
3518
|
+
inputTokens: 0,
|
|
3519
|
+
cachedInputTokens: 0,
|
|
3520
|
+
cacheWriteTokens: 0,
|
|
3521
|
+
outputTokens: 0,
|
|
3522
|
+
reasoningOutputTokens: 0
|
|
3523
|
+
},
|
|
3524
|
+
event
|
|
3525
|
+
), event.costUSD && event.costUSD > 0) {
|
|
3526
|
+
let breakdown = day.get(breakdownKey);
|
|
3527
|
+
breakdown && (breakdown.costUSD = (breakdown.costUSD ?? 0) + event.costUSD, breakdown.pricingVersion = PRICING_VERSION);
|
|
3317
3528
|
}
|
|
3529
|
+
let sessionKey = `${usageDate}|${breakdownKey}`, sessions = sessionSets.get(sessionKey);
|
|
3530
|
+
sessions || (sessions = /* @__PURE__ */ new Set(), sessionSets.set(sessionKey, sessions)), sessions.add(event.sessionId);
|
|
3318
3531
|
}
|
|
3319
3532
|
let result = finalize(grouped);
|
|
3320
3533
|
for (let [usageDate, breakdowns] of result)
|
|
3321
3534
|
for (let breakdown of breakdowns) {
|
|
3322
|
-
let key = `${usageDate}|${breakdown.provider}|${breakdown.model}|${breakdown.project}`;
|
|
3535
|
+
let key = `${usageDate}|${breakdown.product}|${breakdown.provider}|${breakdown.model}|${breakdown.project}`;
|
|
3323
3536
|
breakdown.sessionCount = sessionSets.get(key)?.size ?? 0;
|
|
3324
3537
|
}
|
|
3325
3538
|
return result;
|
|
@@ -3344,6 +3557,7 @@ function parseNativeCache(value) {
|
|
|
3344
3557
|
dedupKey: `trae-cn:${messageId}`,
|
|
3345
3558
|
sessionId,
|
|
3346
3559
|
timestamp,
|
|
3560
|
+
product: "trae-cn",
|
|
3347
3561
|
provider: inferProviderFromModel(model, "trae"),
|
|
3348
3562
|
model,
|
|
3349
3563
|
project,
|
|
@@ -3352,7 +3566,7 @@ function parseNativeCache(value) {
|
|
|
3352
3566
|
}
|
|
3353
3567
|
return events;
|
|
3354
3568
|
}
|
|
3355
|
-
function
|
|
3569
|
+
function parseIntlCache(value) {
|
|
3356
3570
|
if (!Array.isArray(value)) return [];
|
|
3357
3571
|
let events = [];
|
|
3358
3572
|
for (let raw of value) {
|
|
@@ -3367,9 +3581,12 @@ function parseTokscaleCache(value) {
|
|
|
3367
3581
|
reasoning: 0
|
|
3368
3582
|
};
|
|
3369
3583
|
tokenTotal2(tokens) !== 0 && events.push({
|
|
3370
|
-
|
|
3584
|
+
// The international API returns aggregate rows by session. Multiple
|
|
3585
|
+
// cache artifacts can contain newer snapshots of the same session.
|
|
3586
|
+
dedupKey: `trae-intl:${sessionId}`,
|
|
3371
3587
|
sessionId,
|
|
3372
3588
|
timestamp,
|
|
3589
|
+
product: "trae-intl",
|
|
3373
3590
|
provider: inferProviderFromModel(model, "trae"),
|
|
3374
3591
|
model,
|
|
3375
3592
|
project: "unknown",
|
|
@@ -3379,6 +3596,12 @@ function parseTokscaleCache(value) {
|
|
|
3379
3596
|
}
|
|
3380
3597
|
return events;
|
|
3381
3598
|
}
|
|
3599
|
+
function shouldReplaceEvent(existing, incoming) {
|
|
3600
|
+
if (incoming.timestamp.getTime() !== existing.timestamp.getTime())
|
|
3601
|
+
return incoming.timestamp > existing.timestamp;
|
|
3602
|
+
let incomingTotal = tokenTotal2(incoming), existingTotal = tokenTotal2(existing);
|
|
3603
|
+
return incomingTotal !== existingTotal ? incomingTotal > existingTotal : (incoming.costUSD ?? 0) > (existing.costUSD ?? 0);
|
|
3604
|
+
}
|
|
3382
3605
|
function normalizeTraeModel(name) {
|
|
3383
3606
|
let value = name?.trim() ?? "";
|
|
3384
3607
|
return {
|
|
@@ -3428,6 +3651,37 @@ function isRecord2(value) {
|
|
|
3428
3651
|
}
|
|
3429
3652
|
|
|
3430
3653
|
// src/scan.ts
|
|
3654
|
+
var TOOL_IDS = [
|
|
3655
|
+
"amp",
|
|
3656
|
+
"antigravity",
|
|
3657
|
+
"claude-code",
|
|
3658
|
+
"codex",
|
|
3659
|
+
"copilot-cli",
|
|
3660
|
+
"copilot-vscode",
|
|
3661
|
+
"cursor",
|
|
3662
|
+
"droid",
|
|
3663
|
+
"gemini-cli",
|
|
3664
|
+
"kimi-code",
|
|
3665
|
+
"opencode",
|
|
3666
|
+
"pi",
|
|
3667
|
+
"qwen-code",
|
|
3668
|
+
"trae",
|
|
3669
|
+
"trae-cn",
|
|
3670
|
+
"trae-intl"
|
|
3671
|
+
], TOOL_ID_SET = new Set(TOOL_IDS);
|
|
3672
|
+
function parseToolSelection(value, zh2 = !1) {
|
|
3673
|
+
if (value == null) return;
|
|
3674
|
+
if (typeof value != "string" || value.trim() === "")
|
|
3675
|
+
throw new Error(zh2 ? "--tool \u9700\u8981\u6307\u5B9A\u5DE5\u5177\u540D\u79F0" : "--tool requires a tool name");
|
|
3676
|
+
let selected = /* @__PURE__ */ new Set();
|
|
3677
|
+
for (let raw of value.split(",")) {
|
|
3678
|
+
let tool = raw.trim().toLowerCase();
|
|
3679
|
+
if (!TOOL_ID_SET.has(tool))
|
|
3680
|
+
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(", ")}`);
|
|
3681
|
+
tool === "trae" ? (selected.add("trae-cn"), selected.add("trae-intl"), selected.add("trae")) : selected.add(tool);
|
|
3682
|
+
}
|
|
3683
|
+
return [...selected];
|
|
3684
|
+
}
|
|
3431
3685
|
async function scanDate(targetDate, options = {}) {
|
|
3432
3686
|
let [result] = await scanDates([targetDate], options);
|
|
3433
3687
|
return result ?? {
|
|
@@ -3439,24 +3693,33 @@ async function scanDate(targetDate, options = {}) {
|
|
|
3439
3693
|
async function scanDates(targetDates, options = {}) {
|
|
3440
3694
|
let uniqueDates = [...new Set(targetDates)];
|
|
3441
3695
|
if (uniqueDates.length === 0) return [];
|
|
3442
|
-
let scanners = [
|
|
3443
|
-
scanAntigravityDates(uniqueDates),
|
|
3444
|
-
scanClaudeDates(uniqueDates, void 0, options.projectAliases),
|
|
3445
|
-
scanCodexDates(uniqueDates, void 0, options.projectAliases),
|
|
3446
|
-
scanCopilotDates(uniqueDates, void 0, options.projectAliases),
|
|
3447
|
-
scanCopilotVscodeDates(uniqueDates, void 0, options.projectAliases),
|
|
3448
|
-
scanCursorDates(uniqueDates),
|
|
3449
|
-
scanGeminiDates(uniqueDates, void 0, options.projectAliases),
|
|
3450
|
-
scanQwenDates(uniqueDates, void 0, options.projectAliases),
|
|
3451
|
-
scanKimiDates(uniqueDates, void 0, options.projectAliases),
|
|
3452
|
-
scanAmpDates(uniqueDates, void 0, options.projectAliases),
|
|
3453
|
-
scanDroidDates(uniqueDates, void 0, options.projectAliases),
|
|
3454
|
-
|
|
3455
|
-
|
|
3456
|
-
|
|
3457
|
-
|
|
3696
|
+
let selected = options.tools ? new Set(options.tools) : void 0, scanners = [
|
|
3697
|
+
{ products: ["antigravity"], scan: () => scanAntigravityDates(uniqueDates) },
|
|
3698
|
+
{ products: ["claude-code"], scan: () => scanClaudeDates(uniqueDates, void 0, options.projectAliases) },
|
|
3699
|
+
{ products: ["codex"], scan: () => scanCodexDates(uniqueDates, void 0, options.projectAliases) },
|
|
3700
|
+
{ products: ["copilot-cli"], scan: () => scanCopilotDates(uniqueDates, void 0, options.projectAliases) },
|
|
3701
|
+
{ products: ["copilot-vscode"], scan: () => scanCopilotVscodeDates(uniqueDates, void 0, options.projectAliases) },
|
|
3702
|
+
{ products: ["cursor"], scan: () => scanCursorDates(uniqueDates) },
|
|
3703
|
+
{ products: ["gemini-cli"], scan: () => scanGeminiDates(uniqueDates, void 0, options.projectAliases) },
|
|
3704
|
+
{ products: ["qwen-code"], scan: () => scanQwenDates(uniqueDates, void 0, options.projectAliases) },
|
|
3705
|
+
{ products: ["kimi-code"], scan: () => scanKimiDates(uniqueDates, void 0, options.projectAliases) },
|
|
3706
|
+
{ products: ["amp"], scan: () => scanAmpDates(uniqueDates, void 0, options.projectAliases) },
|
|
3707
|
+
{ products: ["droid"], scan: () => scanDroidDates(uniqueDates, void 0, options.projectAliases) },
|
|
3708
|
+
{
|
|
3709
|
+
products: ["opencode"],
|
|
3710
|
+
scan: () => scanOpencodeDates(uniqueDates, {
|
|
3711
|
+
projectAliases: options.projectAliases,
|
|
3712
|
+
dbPaths: options.opencodeDbPaths
|
|
3713
|
+
})
|
|
3714
|
+
},
|
|
3715
|
+
{ products: ["pi"], scan: () => scanPiDates(uniqueDates, void 0, options.projectAliases) },
|
|
3716
|
+
{
|
|
3717
|
+
products: ["trae-cn", "trae-intl", "trae"],
|
|
3718
|
+
scan: () => scanTraeDates(uniqueDates, { projectAliases: options.projectAliases })
|
|
3719
|
+
}
|
|
3720
|
+
].filter((definition) => !selected || definition.products.some((product) => selected.has(product))).map((definition) => definition.scan()), results = await Promise.all(scanners);
|
|
3458
3721
|
return uniqueDates.map((usageDate) => {
|
|
3459
|
-
let breakdowns = results.flatMap((m) => m.get(usageDate) ?? []), totals = breakdowns.reduce(
|
|
3722
|
+
let breakdowns = results.flatMap((m) => m.get(usageDate) ?? []).filter((breakdown) => !selected || selected.has(breakdown.product)), totals = breakdowns.reduce(
|
|
3460
3723
|
(acc, b) => ({
|
|
3461
3724
|
eventCount: acc.eventCount + b.eventCount,
|
|
3462
3725
|
inputTokens: acc.inputTokens + b.inputTokens,
|
|
@@ -3629,11 +3892,15 @@ function parseCsv(content) {
|
|
|
3629
3892
|
}
|
|
3630
3893
|
|
|
3631
3894
|
// src/report.ts
|
|
3632
|
-
import { readdir as
|
|
3895
|
+
import { readdir as readdir6, readFile as readFile14 } from "node:fs/promises";
|
|
3633
3896
|
import { homedir as homedir15 } from "node:os";
|
|
3634
|
-
import { basename as basename11, dirname as
|
|
3897
|
+
import { basename as basename11, dirname as dirname7, join as join16 } from "node:path";
|
|
3635
3898
|
async function buildLocalReport(range, options = {}) {
|
|
3636
|
-
let requestedDates = options.dates ? options.dates : range === "all" ? await discoverAllDates() : range === "today" ? [dateKey(getTodayLocalDate())] : buildPresetDates(range), daily = [], totals = createEmptyTotals2(), bySource = /* @__PURE__ */ new Map(), byModel = /* @__PURE__ */ new Map(), pricingWarnings = /* @__PURE__ */ new Set(), daysWithData = 0, results = await scanDates(requestedDates, {
|
|
3899
|
+
let requestedDates = options.dates ? options.dates : range === "all" ? await discoverAllDates(options.tools, options.opencodeDbPaths) : 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, {
|
|
3900
|
+
projectAliases: options.projectAliases,
|
|
3901
|
+
opencodeDbPaths: options.opencodeDbPaths,
|
|
3902
|
+
tools: options.tools
|
|
3903
|
+
});
|
|
3637
3904
|
for (let result of results) {
|
|
3638
3905
|
let usageDate = result.usageDate, dayTotals = withTotalTokens(result.totals), hasData = result.breakdowns.length > 0 || dayTotals.eventCount > 0 || dayTotals.totalTokens > 0;
|
|
3639
3906
|
if (hasData) {
|
|
@@ -3667,14 +3934,15 @@ async function buildLocalReport(range, options = {}) {
|
|
|
3667
3934
|
source: "bundled",
|
|
3668
3935
|
version: options.pricingCatalog?.version ?? "bundled"
|
|
3669
3936
|
},
|
|
3670
|
-
pricingWarnings: [...pricingWarnings].sort()
|
|
3937
|
+
pricingWarnings: [...pricingWarnings].sort(),
|
|
3938
|
+
...options.tools ? { tools: [...options.tools] } : {}
|
|
3671
3939
|
};
|
|
3672
3940
|
}
|
|
3673
3941
|
function parseReportRange(value, today) {
|
|
3674
3942
|
if (today) return "today";
|
|
3675
3943
|
if (value === void 0 || value === !0) return "7d";
|
|
3676
|
-
if (value === "7d" || value === "1m" || value === "3m" || value === "all" || value === "today") return value;
|
|
3677
|
-
throw new Error("--range \u4EC5\u652F\u6301 7d\u30011m\u30013m\u3001all\u3001today");
|
|
3944
|
+
if (value === "7d" || value === "1m" || value === "3m" || value === "6m" || value === "all" || value === "today") return value;
|
|
3945
|
+
throw new Error("--range \u4EC5\u652F\u6301 7d\u30011m\u30013m\u30016m\u3001all\u3001today");
|
|
3678
3946
|
}
|
|
3679
3947
|
function getRangeLabel(range) {
|
|
3680
3948
|
switch (range) {
|
|
@@ -3684,6 +3952,8 @@ function getRangeLabel(range) {
|
|
|
3684
3952
|
return "\u6700\u8FD1 30 \u5929";
|
|
3685
3953
|
case "3m":
|
|
3686
3954
|
return "\u6700\u8FD1 90 \u5929";
|
|
3955
|
+
case "6m":
|
|
3956
|
+
return "\u6700\u8FD1 180 \u5929";
|
|
3687
3957
|
case "all":
|
|
3688
3958
|
return "\u5168\u90E8\u5386\u53F2";
|
|
3689
3959
|
case "today":
|
|
@@ -3691,35 +3961,20 @@ function getRangeLabel(range) {
|
|
|
3691
3961
|
}
|
|
3692
3962
|
}
|
|
3693
3963
|
function buildPresetDates(range) {
|
|
3694
|
-
let days = range === "7d" ? 7 : range === "1m" ? 30 : 90, today = getTodayLocalDate(), result = [];
|
|
3964
|
+
let days = range === "7d" ? 7 : range === "1m" ? 30 : range === "3m" ? 90 : 180, today = getTodayLocalDate(), result = [];
|
|
3695
3965
|
for (let offset = days - 1; offset >= 0; offset -= 1) {
|
|
3696
3966
|
let day = new Date(today);
|
|
3697
3967
|
day.setDate(today.getDate() - offset), result.push(dateKey(day));
|
|
3698
3968
|
}
|
|
3699
3969
|
return result;
|
|
3700
3970
|
}
|
|
3701
|
-
async function discoverAllDates() {
|
|
3702
|
-
let dates = /* @__PURE__ */ new Set(), home = homedir15();
|
|
3703
|
-
|
|
3704
|
-
|
|
3705
|
-
|
|
3706
|
-
discoverGeminiDates(dates),
|
|
3707
|
-
discoverCopilotVscodeDates(dates),
|
|
3708
|
-
discoverAntigravityDates(dates),
|
|
3709
|
-
discoverGenericJsonlDates(join16(home, ".copilot", "session-state"), dates),
|
|
3710
|
-
discoverGenericJsonlDates(join16(home, ".copilot", "otel"), dates),
|
|
3711
|
-
discoverGenericJsonlDates(join16(home, ".qwen", "tmp"), dates),
|
|
3712
|
-
discoverGenericJsonlDates(join16(home, ".qwen", "projects"), dates),
|
|
3713
|
-
discoverGenericJsonlDates(join16(home, ".kimi", "sessions"), dates),
|
|
3714
|
-
discoverGenericJsonlDates(join16(resolveKimiCodeHome(home), "sessions"), dates),
|
|
3715
|
-
discoverGenericJsonDates(join16(home, ".local", "share", "amp", "threads"), dates),
|
|
3716
|
-
discoverGenericJsonDates(join16(home, ".factory", "sessions"), dates),
|
|
3717
|
-
discoverOpenCodeUsageDates().then((found) => found.forEach((date) => dates.add(date))),
|
|
3718
|
-
discoverGenericJsonlDates(join16(home, ".pi", "agent", "sessions"), dates),
|
|
3719
|
-
discoverGenericJsonlDates(join16(home, ".omp", "agent", "sessions"), dates)
|
|
3720
|
-
]);
|
|
3971
|
+
async function discoverAllDates(tools, opencodeDbPaths) {
|
|
3972
|
+
let dates = /* @__PURE__ */ new Set(), home = homedir15(), selected = tools ? new Set(tools) : null, includes = (...products) => !selected || products.some((product) => selected.has(product)), discoveries = [];
|
|
3973
|
+
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({ dbPaths: opencodeDbPaths }).then((found) => {
|
|
3974
|
+
found.forEach((date) => dates.add(date));
|
|
3975
|
+
})), includes("pi") && (discoveries.push(discoverGenericJsonlDates(join16(home, ".pi", "agent", "sessions"), dates)), discoveries.push(discoverGenericJsonlDates(join16(home, ".omp", "agent", "sessions"), dates))), includes("trae-cn", "trae") && discoveries.push(discoverGenericJsonDates(resolveTraeNativeCacheDir(home), dates)), includes("trae-intl", "trae") && (discoveries.push(discoverGenericJsonDates(resolveTraeIntlCacheDir(home), dates)), discoveries.push(discoverGenericJsonDates(resolveTokscaleTraeCacheDir(home), dates))), await Promise.all(discoveries);
|
|
3721
3976
|
let explicitCopilotOtel = process.env.COPILOT_OTEL_FILE_EXPORTER_PATH?.trim();
|
|
3722
|
-
return explicitCopilotOtel && await discoverJsonlFileDates(explicitCopilotOtel, dates), [...dates].sort();
|
|
3977
|
+
return explicitCopilotOtel && includes("copilot-cli") && await discoverJsonlFileDates(explicitCopilotOtel, dates), [...dates].sort();
|
|
3723
3978
|
}
|
|
3724
3979
|
async function discoverGenericJsonlDates(baseDir, dates) {
|
|
3725
3980
|
let files = [];
|
|
@@ -3767,6 +4022,7 @@ async function discoverGenericJsonDates(baseDir, dates) {
|
|
|
3767
4022
|
} catch {
|
|
3768
4023
|
continue;
|
|
3769
4024
|
}
|
|
4025
|
+
if (Array.isArray(data) && data.length === 0) continue;
|
|
3770
4026
|
(Array.isArray(data) ? data.reduce((found, row) => collectRecordDates(row, dates) || found, !1) : collectRecordDates(data, dates)) || await addFileModifiedDate(filePath, dates);
|
|
3771
4027
|
}
|
|
3772
4028
|
}
|
|
@@ -3786,6 +4042,7 @@ function collectRecordDates(record, dates) {
|
|
|
3786
4042
|
record._hrTime,
|
|
3787
4043
|
record.observedTimestamp,
|
|
3788
4044
|
record.timeUnixNano,
|
|
4045
|
+
record.usage_time,
|
|
3789
4046
|
record.time?.created
|
|
3790
4047
|
];
|
|
3791
4048
|
for (let value of candidates) {
|
|
@@ -3798,7 +4055,8 @@ function collectRecordDates(record, dates) {
|
|
|
3798
4055
|
...Array.isArray(record.data?.messages) ? record.data.messages : [],
|
|
3799
4056
|
...Array.isArray(record.data?.history) ? record.data.history : [],
|
|
3800
4057
|
...Array.isArray(record.$set?.messages) ? record.$set.messages : [],
|
|
3801
|
-
...Array.isArray(record.usageLedger?.events) ? record.usageLedger.events : []
|
|
4058
|
+
...Array.isArray(record.usageLedger?.events) ? record.usageLedger.events : [],
|
|
4059
|
+
...Array.isArray(record.events) ? record.events : []
|
|
3802
4060
|
];
|
|
3803
4061
|
for (let row of nestedRows) found = collectRecordDates(row, dates) || found;
|
|
3804
4062
|
return found;
|
|
@@ -3824,7 +4082,7 @@ async function addFileModifiedDate(filePath, dates) {
|
|
|
3824
4082
|
async function walkForFiles(dir, ext, result) {
|
|
3825
4083
|
let entries;
|
|
3826
4084
|
try {
|
|
3827
|
-
entries = await
|
|
4085
|
+
entries = await readdir6(dir, { withFileTypes: !0 });
|
|
3828
4086
|
} catch {
|
|
3829
4087
|
return;
|
|
3830
4088
|
}
|
|
@@ -3903,7 +4161,7 @@ async function discoverCopilotVscodeDates(dates) {
|
|
|
3903
4161
|
}
|
|
3904
4162
|
}
|
|
3905
4163
|
function isChatSessionFile2(filePath) {
|
|
3906
|
-
return basename11(
|
|
4164
|
+
return basename11(dirname7(filePath)) === "chatSessions";
|
|
3907
4165
|
}
|
|
3908
4166
|
async function discoverAntigravityDates(dates) {
|
|
3909
4167
|
let home = homedir15(), brainFiles = [], browserFiles = [];
|
|
@@ -3943,7 +4201,7 @@ async function discoverClaudeDates(dates) {
|
|
|
3943
4201
|
for (let baseDir of baseDirs) {
|
|
3944
4202
|
let projectDirs;
|
|
3945
4203
|
try {
|
|
3946
|
-
projectDirs = await
|
|
4204
|
+
projectDirs = await readdir6(baseDir);
|
|
3947
4205
|
} catch {
|
|
3948
4206
|
continue;
|
|
3949
4207
|
}
|
|
@@ -3996,7 +4254,7 @@ async function discoverCodexDates(dates) {
|
|
|
3996
4254
|
async function collectCodexSessionFiles(baseDir) {
|
|
3997
4255
|
let paths = [];
|
|
3998
4256
|
try {
|
|
3999
|
-
let archivedFiles = await
|
|
4257
|
+
let archivedFiles = await readdir6(join16(baseDir, "archived_sessions"));
|
|
4000
4258
|
for (let file of archivedFiles)
|
|
4001
4259
|
file.endsWith(".jsonl") && paths.push(join16(baseDir, "archived_sessions", file));
|
|
4002
4260
|
} catch {
|
|
@@ -4004,7 +4262,7 @@ async function collectCodexSessionFiles(baseDir) {
|
|
|
4004
4262
|
return await walkForCodexJsonl(join16(baseDir, "sessions"), paths), paths;
|
|
4005
4263
|
}
|
|
4006
4264
|
async function walkForClaudeJsonl(dir, result) {
|
|
4007
|
-
let entries = await
|
|
4265
|
+
let entries = await readdir6(dir, { withFileTypes: !0 });
|
|
4008
4266
|
for (let entry of entries) {
|
|
4009
4267
|
let fullPath = join16(dir, entry.name);
|
|
4010
4268
|
entry.isDirectory() ? await walkForClaudeJsonl(fullPath, result) : entry.name.endsWith(".jsonl") && result.push(fullPath);
|
|
@@ -4013,7 +4271,7 @@ async function walkForClaudeJsonl(dir, result) {
|
|
|
4013
4271
|
async function walkForCodexJsonl(dir, result) {
|
|
4014
4272
|
let entries;
|
|
4015
4273
|
try {
|
|
4016
|
-
entries = await
|
|
4274
|
+
entries = await readdir6(dir, { withFileTypes: !0 });
|
|
4017
4275
|
} catch {
|
|
4018
4276
|
return;
|
|
4019
4277
|
}
|
|
@@ -4075,7 +4333,7 @@ function toBreakdownTotals(breakdown, warnings, pricingCatalog) {
|
|
|
4075
4333
|
};
|
|
4076
4334
|
}
|
|
4077
4335
|
function calculateBreakdownCost(breakdown, warnings, pricingCatalog) {
|
|
4078
|
-
let effectivePricingVersion = pricingCatalog?.version ?? PRICING_VERSION, sourceCostMatchesCatalog = breakdown.pricingVersion == null || breakdown.pricingVersion === effectivePricingVersion;
|
|
4336
|
+
let effectivePricingVersion = pricingCatalog?.version ?? PRICING_VERSION, sourceCostMatchesCatalog = breakdown.product === "trae-intl" || breakdown.product === "opencode" || breakdown.pricingVersion == null || breakdown.pricingVersion === effectivePricingVersion;
|
|
4079
4337
|
if (breakdown.costUSD != null && breakdown.costUSD > 0 && sourceCostMatchesCatalog)
|
|
4080
4338
|
return breakdown.costUSD;
|
|
4081
4339
|
let result = calculateCost(
|
|
@@ -4308,7 +4566,7 @@ function fmtDateShort(dateStr) {
|
|
|
4308
4566
|
}
|
|
4309
4567
|
|
|
4310
4568
|
// src/activity.ts
|
|
4311
|
-
import { open, readdir as
|
|
4569
|
+
import { open, readdir as readdir7 } from "node:fs/promises";
|
|
4312
4570
|
import { createInterface as createInterface3 } from "node:readline";
|
|
4313
4571
|
import { homedir as homedir16 } from "node:os";
|
|
4314
4572
|
import { basename as basename12, join as join17 } from "node:path";
|
|
@@ -4563,7 +4821,7 @@ async function scanClaudeActivity(targetDates, options) {
|
|
|
4563
4821
|
for (let baseDir of getClaudeProjectDirs2(options.claudeProjectsDirs)) {
|
|
4564
4822
|
let projectDirs;
|
|
4565
4823
|
try {
|
|
4566
|
-
projectDirs = await
|
|
4824
|
+
projectDirs = await readdir7(baseDir, { withFileTypes: !0 });
|
|
4567
4825
|
} catch {
|
|
4568
4826
|
continue;
|
|
4569
4827
|
}
|
|
@@ -4707,7 +4965,7 @@ function acceptsDate(acc, usageDate) {
|
|
|
4707
4965
|
async function collectCodexSessionFiles2(baseDir) {
|
|
4708
4966
|
let paths = [];
|
|
4709
4967
|
try {
|
|
4710
|
-
let files = await
|
|
4968
|
+
let files = await readdir7(join17(baseDir, "archived_sessions"));
|
|
4711
4969
|
for (let file of files)
|
|
4712
4970
|
file.endsWith(".jsonl") && paths.push(join17(baseDir, "archived_sessions", file));
|
|
4713
4971
|
} catch {
|
|
@@ -4728,7 +4986,7 @@ function getClaudeProjectDirs2(configured) {
|
|
|
4728
4986
|
async function walkJsonl(dir, result) {
|
|
4729
4987
|
let entries;
|
|
4730
4988
|
try {
|
|
4731
|
-
entries = await
|
|
4989
|
+
entries = await readdir7(dir, { withFileTypes: !0 });
|
|
4732
4990
|
} catch {
|
|
4733
4991
|
return;
|
|
4734
4992
|
}
|
|
@@ -4865,6 +5123,8 @@ function getRangeLabel3(range) {
|
|
|
4865
5123
|
return "\u6700\u8FD1 30 \u5929";
|
|
4866
5124
|
case "3m":
|
|
4867
5125
|
return "\u6700\u8FD1 90 \u5929";
|
|
5126
|
+
case "6m":
|
|
5127
|
+
return "\u6700\u8FD1 180 \u5929";
|
|
4868
5128
|
case "all":
|
|
4869
5129
|
return "\u5168\u90E8\u5386\u53F2";
|
|
4870
5130
|
case "today":
|
|
@@ -4908,6 +5168,7 @@ function migrateConfig(config) {
|
|
|
4908
5168
|
projectAliases: config.projectAliases,
|
|
4909
5169
|
privacy: config.privacy,
|
|
4910
5170
|
pricing: config.pricing,
|
|
5171
|
+
scanner: config.scanner,
|
|
4911
5172
|
lang: config.lang,
|
|
4912
5173
|
emoji: config.emoji,
|
|
4913
5174
|
targets: [target]
|
|
@@ -4979,6 +5240,12 @@ function setConfigValue(config, keyPath, values) {
|
|
|
4979
5240
|
...next.pricing ?? {},
|
|
4980
5241
|
cacheTtlHours: parsePositiveInt(requireSingleValue(keyPath, values), keyPath)
|
|
4981
5242
|
}, next;
|
|
5243
|
+
if (keyPath === "scanner.opencodeDbPaths") {
|
|
5244
|
+
let paths = [...new Set(values.map((value) => value.trim()).filter(Boolean))];
|
|
5245
|
+
if (paths.length === 0)
|
|
5246
|
+
throw new Error("scanner.opencodeDbPaths \u81F3\u5C11\u9700\u8981\u4E00\u4E2A opencode*.db \u8DEF\u5F84");
|
|
5247
|
+
return paths.length === 1 && ["none", "off", "default"].includes(paths[0].toLowerCase()) ? (next.scanner = { ...next.scanner ?? {} }, delete next.scanner.opencodeDbPaths, next) : (next.scanner = { ...next.scanner ?? {}, opencodeDbPaths: paths }, next);
|
|
5248
|
+
}
|
|
4982
5249
|
if (keyPath === "project.alias") {
|
|
4983
5250
|
if (values.length < 2)
|
|
4984
5251
|
throw new Error("project.alias \u9700\u8981\u4E24\u4E2A\u53C2\u6570\uFF1A\u539F\u59CB\u8DEF\u5F84/\u540D\u79F0 \u4E0E \u522B\u540D");
|
|
@@ -5023,13 +5290,13 @@ import { hostname as hostname2 } from "node:os";
|
|
|
5023
5290
|
|
|
5024
5291
|
// src/version.ts
|
|
5025
5292
|
import { readFileSync } from "node:fs";
|
|
5026
|
-
import { resolve as
|
|
5293
|
+
import { resolve as resolve4, dirname as dirname8 } from "node:path";
|
|
5027
5294
|
import { fileURLToPath } from "node:url";
|
|
5028
5295
|
var cached;
|
|
5029
5296
|
function getVersion() {
|
|
5030
5297
|
if (cached !== void 0) return cached;
|
|
5031
5298
|
try {
|
|
5032
|
-
let pkg =
|
|
5299
|
+
let pkg = resolve4(dirname8(fileURLToPath(import.meta.url)), "..", "package.json");
|
|
5033
5300
|
cached = JSON.parse(readFileSync(pkg, "utf-8")).version;
|
|
5034
5301
|
} catch {
|
|
5035
5302
|
cached = "unknown";
|
|
@@ -5102,11 +5369,11 @@ async function requestJson(url, init) {
|
|
|
5102
5369
|
}
|
|
5103
5370
|
|
|
5104
5371
|
// src/schedule.ts
|
|
5105
|
-
import { mkdir as mkdir2, readFile as readFile16, stat as
|
|
5372
|
+
import { mkdir as mkdir2, readFile as readFile16, stat as stat4, unlink, writeFile as writeFile2 } from "node:fs/promises";
|
|
5106
5373
|
import { execFile as execFile2 } from "node:child_process";
|
|
5107
5374
|
import { promisify } from "node:util";
|
|
5108
5375
|
import { homedir as homedir18, platform, tmpdir as tmpdir2 } from "node:os";
|
|
5109
|
-
import { join as join19, resolve as
|
|
5376
|
+
import { join as join19, resolve as resolve5 } from "node:path";
|
|
5110
5377
|
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";
|
|
5111
5378
|
function parseInterval(value) {
|
|
5112
5379
|
let match = value.match(/^(\d+)(m|h|d)$/);
|
|
@@ -5142,7 +5409,7 @@ async function getScheduleStatus() {
|
|
|
5142
5409
|
return platform() === "darwin" ? getLaunchdStatus() : getCronStatus();
|
|
5143
5410
|
}
|
|
5144
5411
|
function resolveCommandPaths() {
|
|
5145
|
-
let scriptPath =
|
|
5412
|
+
let scriptPath = resolve5(process.argv[1]);
|
|
5146
5413
|
if (scriptPath.includes("_npx") || scriptPath.includes("/npx-"))
|
|
5147
5414
|
throw new Error(
|
|
5148
5415
|
`\u68C0\u6D4B\u5230\u901A\u8FC7 npx \u8FD0\u884C\uFF0C\u5B9A\u65F6\u4EFB\u52A1\u9700\u8981\u5168\u5C40\u5B89\u88C5\u3002
|
|
@@ -5201,7 +5468,7 @@ async function disableLaunchd() {
|
|
|
5201
5468
|
}
|
|
5202
5469
|
async function getLaunchdStatus() {
|
|
5203
5470
|
try {
|
|
5204
|
-
await
|
|
5471
|
+
await stat4(PLIST_PATH);
|
|
5205
5472
|
} catch {
|
|
5206
5473
|
return { enabled: !1 };
|
|
5207
5474
|
}
|
|
@@ -5311,7 +5578,7 @@ function escapeXml(value) {
|
|
|
5311
5578
|
}
|
|
5312
5579
|
|
|
5313
5580
|
// src/doctor.ts
|
|
5314
|
-
import { readdir as
|
|
5581
|
+
import { readdir as readdir8, stat as stat5 } from "node:fs/promises";
|
|
5315
5582
|
import { homedir as homedir19 } from "node:os";
|
|
5316
5583
|
import { join as join20 } from "node:path";
|
|
5317
5584
|
var msgs = {
|
|
@@ -5334,6 +5601,8 @@ var msgs = {
|
|
|
5334
5601
|
notInstalled: "Not installed",
|
|
5335
5602
|
installedNoData: "Installed, no usage data yet",
|
|
5336
5603
|
hasData: (n) => `${n} session${n > 1 ? "s" : ""} found`,
|
|
5604
|
+
openCodeData: (dbs, legacy) => `${dbs} database(s), ${legacy} legacy message(s) found`,
|
|
5605
|
+
openCodeSqliteUnavailable: "Database found, but this Node version requires the system sqlite3 executable",
|
|
5337
5606
|
schedule: "Schedule",
|
|
5338
5607
|
scheduleEvery: "every",
|
|
5339
5608
|
scheduleEnabled: "Enabled",
|
|
@@ -5358,6 +5627,8 @@ var msgs = {
|
|
|
5358
5627
|
notInstalled: "\u672A\u5B89\u88C5",
|
|
5359
5628
|
installedNoData: "\u5DF2\u5B89\u88C5\uFF0C\u6682\u65E0\u4F7F\u7528\u6570\u636E",
|
|
5360
5629
|
hasData: (n) => `\u53D1\u73B0 ${n} \u4E2A\u4F1A\u8BDD`,
|
|
5630
|
+
openCodeData: (dbs, legacy) => `\u53D1\u73B0 ${dbs} \u4E2A\u6570\u636E\u5E93\u3001${legacy} \u6761\u65E7\u7248\u6D88\u606F`,
|
|
5631
|
+
openCodeSqliteUnavailable: "\u5DF2\u53D1\u73B0\u6570\u636E\u5E93\uFF0C\u4F46\u5F53\u524D Node \u7248\u672C\u9700\u8981\u5B89\u88C5\u7CFB\u7EDF sqlite3 \u624D\u80FD\u8BFB\u53D6",
|
|
5361
5632
|
schedule: "\u5B9A\u65F6\u540C\u6B65",
|
|
5362
5633
|
scheduleEvery: "\u6BCF",
|
|
5363
5634
|
scheduleEnabled: "\u5DF2\u542F\u7528",
|
|
@@ -5369,7 +5640,7 @@ async function countFiles(dir, exts, cap = 1e3) {
|
|
|
5369
5640
|
for (; queue.length > 0 && count < cap; ) {
|
|
5370
5641
|
let current = queue.pop(), entries;
|
|
5371
5642
|
try {
|
|
5372
|
-
entries = await
|
|
5643
|
+
entries = await readdir8(current, { withFileTypes: !0 });
|
|
5373
5644
|
} catch {
|
|
5374
5645
|
continue;
|
|
5375
5646
|
}
|
|
@@ -5384,7 +5655,7 @@ async function countFiles(dir, exts, cap = 1e3) {
|
|
|
5384
5655
|
async function runDoctor(lang = "zh") {
|
|
5385
5656
|
let s = msgs[lang], checks = [], config = await readConfig(), g1 = s.groupConfig, configPath = getConfigPath();
|
|
5386
5657
|
try {
|
|
5387
|
-
await
|
|
5658
|
+
await stat5(configPath), checks.push({ group: g1, name: s.config, status: "ok", message: configPath });
|
|
5388
5659
|
} catch {
|
|
5389
5660
|
checks.push({ group: g1, name: s.config, status: "fail", message: s.configMissing });
|
|
5390
5661
|
}
|
|
@@ -5424,7 +5695,6 @@ async function runDoctor(lang = "zh") {
|
|
|
5424
5695
|
{ dirs: [join20(home, ".kimi", "sessions")], label: "Kimi CLI (legacy)", exts: [".jsonl"] },
|
|
5425
5696
|
{ dirs: [join20(home, ".local", "share", "amp", "threads")], label: "Amp", exts: [".json"] },
|
|
5426
5697
|
{ dirs: [join20(home, ".factory", "sessions")], label: "Droid", exts: [".settings.json"] },
|
|
5427
|
-
{ dirs: [join20(home, ".local", "share", "opencode")], label: "OpenCode", exts: [".db", ".json"] },
|
|
5428
5698
|
{ dirs: [join20(home, ".pi", "agent", "sessions"), join20(home, ".omp", "agent", "sessions")], label: "Pi / OMP", exts: [".jsonl"] },
|
|
5429
5699
|
{ dirs: [resolveTraeNativeCacheDir(home), resolveTokscaleTraeCacheDir(home)], label: "Trae", exts: [".json"] }
|
|
5430
5700
|
];
|
|
@@ -5432,7 +5702,7 @@ async function runDoctor(lang = "zh") {
|
|
|
5432
5702
|
let installed = !1, n = 0;
|
|
5433
5703
|
for (let dir of tool.dirs)
|
|
5434
5704
|
try {
|
|
5435
|
-
await
|
|
5705
|
+
await stat5(dir), installed = !0, n += await countFiles(dir, tool.exts);
|
|
5436
5706
|
} catch {
|
|
5437
5707
|
}
|
|
5438
5708
|
if (!installed) {
|
|
@@ -5441,6 +5711,25 @@ async function runDoctor(lang = "zh") {
|
|
|
5441
5711
|
}
|
|
5442
5712
|
n > 0 ? checks.push({ group: g3, name: tool.label, status: "ok", message: s.hasData(n) }) : checks.push({ group: g3, name: tool.label, status: "warn", message: s.installedNoData });
|
|
5443
5713
|
}
|
|
5714
|
+
let openCodeSources = await resolveOpenCodeSources({
|
|
5715
|
+
dbPaths: config.scanner?.opencodeDbPaths
|
|
5716
|
+
}), openCodeLegacyCount = await countFiles(openCodeSources.legacyDir, [".json"]), openCodeInstalled = openCodeSources.dbPaths.length > 0 || openCodeLegacyCount > 0;
|
|
5717
|
+
if (!openCodeInstalled)
|
|
5718
|
+
try {
|
|
5719
|
+
await stat5(openCodeSources.dataDir), openCodeInstalled = !0;
|
|
5720
|
+
} catch {
|
|
5721
|
+
}
|
|
5722
|
+
openCodeInstalled ? openCodeSources.dbPaths.length === 0 && openCodeLegacyCount === 0 ? checks.push({ group: g3, name: "OpenCode", status: "warn", message: s.installedNoData }) : openCodeSources.dbPaths.length > 0 && await detectOpenCodeSqliteRuntime() === "unavailable" ? checks.push({
|
|
5723
|
+
group: g3,
|
|
5724
|
+
name: "OpenCode",
|
|
5725
|
+
status: "warn",
|
|
5726
|
+
message: s.openCodeSqliteUnavailable
|
|
5727
|
+
}) : checks.push({
|
|
5728
|
+
group: g3,
|
|
5729
|
+
name: "OpenCode",
|
|
5730
|
+
status: "ok",
|
|
5731
|
+
message: s.openCodeData(openCodeSources.dbPaths.length, openCodeLegacyCount)
|
|
5732
|
+
}) : checks.push({ group: g3, name: "OpenCode", status: "warn", message: s.notInstalled });
|
|
5444
5733
|
let g4 = s.groupSchedule, schedule = await getScheduleStatus();
|
|
5445
5734
|
return schedule.enabled ? checks.push({
|
|
5446
5735
|
group: g4,
|
|
@@ -5451,7 +5740,7 @@ async function runDoctor(lang = "zh") {
|
|
|
5451
5740
|
}
|
|
5452
5741
|
|
|
5453
5742
|
// src/project.ts
|
|
5454
|
-
import { open as open2, readdir as
|
|
5743
|
+
import { open as open2, readdir as readdir9, readFile as readFile17 } from "node:fs/promises";
|
|
5455
5744
|
import { basename as basename14, join as join21 } from "node:path";
|
|
5456
5745
|
import { homedir as homedir20 } from "node:os";
|
|
5457
5746
|
async function discoverProjects(projectAliases) {
|
|
@@ -5501,7 +5790,7 @@ async function discoverClaudeProjects() {
|
|
|
5501
5790
|
for (let baseDir of getClaudeDirs()) {
|
|
5502
5791
|
let entries;
|
|
5503
5792
|
try {
|
|
5504
|
-
entries = await
|
|
5793
|
+
entries = await readdir9(baseDir, { withFileTypes: !0 });
|
|
5505
5794
|
} catch {
|
|
5506
5795
|
continue;
|
|
5507
5796
|
}
|
|
@@ -5546,7 +5835,7 @@ async function walkFiles2(dir, ext) {
|
|
|
5546
5835
|
async function walk2(d) {
|
|
5547
5836
|
let entries;
|
|
5548
5837
|
try {
|
|
5549
|
-
entries = await
|
|
5838
|
+
entries = await readdir9(d, { withFileTypes: !0 });
|
|
5550
5839
|
} catch {
|
|
5551
5840
|
return;
|
|
5552
5841
|
}
|
|
@@ -5588,7 +5877,7 @@ async function extractCwdFromFirstJsonl(dir) {
|
|
|
5588
5877
|
async function findFirstJsonl(dir) {
|
|
5589
5878
|
let entries;
|
|
5590
5879
|
try {
|
|
5591
|
-
entries = await
|
|
5880
|
+
entries = await readdir9(dir, { withFileTypes: !0 });
|
|
5592
5881
|
} catch {
|
|
5593
5882
|
return;
|
|
5594
5883
|
}
|
|
@@ -5597,7 +5886,7 @@ async function findFirstJsonl(dir) {
|
|
|
5597
5886
|
for (let entry of entries)
|
|
5598
5887
|
if (!(!entry.isDirectory() || entry.name.startsWith(".")))
|
|
5599
5888
|
try {
|
|
5600
|
-
let sub = (await
|
|
5889
|
+
let sub = (await readdir9(join21(dir, entry.name))).find((f) => f.endsWith(".jsonl"));
|
|
5601
5890
|
if (sub) return join21(dir, entry.name, sub);
|
|
5602
5891
|
} catch {
|
|
5603
5892
|
continue;
|
|
@@ -5677,7 +5966,7 @@ async function discoverCopilotVscodeProjects() {
|
|
|
5677
5966
|
async function discoverAntigravityProjects() {
|
|
5678
5967
|
let dir = join21(homedir20(), ".gemini", "antigravity", "knowledge"), entries;
|
|
5679
5968
|
try {
|
|
5680
|
-
entries = await
|
|
5969
|
+
entries = await readdir9(dir, { withFileTypes: !0 });
|
|
5681
5970
|
} catch {
|
|
5682
5971
|
return [];
|
|
5683
5972
|
}
|
|
@@ -5913,7 +6202,7 @@ function assertPricingCatalog(value) {
|
|
|
5913
6202
|
import { execFile as execFile3 } from "node:child_process";
|
|
5914
6203
|
import { createHash as createHash2 } from "node:crypto";
|
|
5915
6204
|
import { existsSync as existsSync2 } from "node:fs";
|
|
5916
|
-
import { mkdir as mkdir4, open as open3, readdir as
|
|
6205
|
+
import { mkdir as mkdir4, open as open3, readdir as readdir10, rename, stat as stat6, writeFile as writeFile4 } from "node:fs/promises";
|
|
5917
6206
|
import { createServer } from "node:net";
|
|
5918
6207
|
import { homedir as homedir22 } from "node:os";
|
|
5919
6208
|
import { join as join23 } from "node:path";
|
|
@@ -6150,12 +6439,12 @@ var CdpClient = class _CdpClient {
|
|
|
6150
6439
|
pending = /* @__PURE__ */ new Map();
|
|
6151
6440
|
static async connect(url, timeoutMs) {
|
|
6152
6441
|
let socket = new WebSocket(url);
|
|
6153
|
-
return await new Promise((
|
|
6442
|
+
return await new Promise((resolve6, reject) => {
|
|
6154
6443
|
let timer = setTimeout(() => {
|
|
6155
6444
|
socket.close(), reject(new Error("\u8FDE\u63A5 Trae CN \u672C\u5730\u63A5\u53E3\u8D85\u65F6"));
|
|
6156
6445
|
}, timeoutMs);
|
|
6157
6446
|
socket.once("open", () => {
|
|
6158
|
-
clearTimeout(timer),
|
|
6447
|
+
clearTimeout(timer), resolve6();
|
|
6159
6448
|
}), socket.once("error", (error) => {
|
|
6160
6449
|
clearTimeout(timer), reject(error);
|
|
6161
6450
|
});
|
|
@@ -6163,11 +6452,11 @@ var CdpClient = class _CdpClient {
|
|
|
6163
6452
|
}
|
|
6164
6453
|
call(method, params, timeoutMs) {
|
|
6165
6454
|
let id = ++this.sequence;
|
|
6166
|
-
return new Promise((
|
|
6455
|
+
return new Promise((resolve6, reject) => {
|
|
6167
6456
|
let timer = setTimeout(() => {
|
|
6168
6457
|
this.pending.delete(id), reject(new Error(`Trae CN \u672C\u5730\u8C03\u7528\u8D85\u65F6: ${method}`));
|
|
6169
6458
|
}, timeoutMs);
|
|
6170
|
-
this.pending.set(id, { resolve:
|
|
6459
|
+
this.pending.set(id, { resolve: resolve6, reject, timer }), this.socket.send(JSON.stringify({ id, method, params }));
|
|
6171
6460
|
});
|
|
6172
6461
|
}
|
|
6173
6462
|
close() {
|
|
@@ -6224,7 +6513,7 @@ async function findTraeUserIds(userDataDir) {
|
|
|
6224
6513
|
async function findCompletionLogs(dir) {
|
|
6225
6514
|
let entries;
|
|
6226
6515
|
try {
|
|
6227
|
-
entries = await
|
|
6516
|
+
entries = await readdir10(dir, { withFileTypes: !0 });
|
|
6228
6517
|
} catch {
|
|
6229
6518
|
return [];
|
|
6230
6519
|
}
|
|
@@ -6234,7 +6523,7 @@ async function findCompletionLogs(dir) {
|
|
|
6234
6523
|
if (entry.isDirectory()) files.push(...await findCompletionLogs(path));
|
|
6235
6524
|
else if (entry.name === "completion.log" && path.includes("trae.ai-code-completion"))
|
|
6236
6525
|
try {
|
|
6237
|
-
files.push({ path, mtimeMs: (await
|
|
6526
|
+
files.push({ path, mtimeMs: (await stat6(path)).mtimeMs });
|
|
6238
6527
|
} catch {
|
|
6239
6528
|
}
|
|
6240
6529
|
}
|
|
@@ -6293,17 +6582,17 @@ async function isTraeRunning() {
|
|
|
6293
6582
|
}
|
|
6294
6583
|
}
|
|
6295
6584
|
async function isPortAvailable(port) {
|
|
6296
|
-
return new Promise((
|
|
6585
|
+
return new Promise((resolve6) => {
|
|
6297
6586
|
let server = createServer();
|
|
6298
|
-
server.once("error", () =>
|
|
6587
|
+
server.once("error", () => resolve6(!1)), server.listen(port, "127.0.0.1", () => server.close(() => resolve6(!0)));
|
|
6299
6588
|
});
|
|
6300
6589
|
}
|
|
6301
6590
|
async function findFreePort() {
|
|
6302
|
-
return new Promise((
|
|
6591
|
+
return new Promise((resolve6, reject) => {
|
|
6303
6592
|
let server = createServer();
|
|
6304
6593
|
server.once("error", reject), server.listen(0, "127.0.0.1", () => {
|
|
6305
6594
|
let address = server.address(), port = typeof address == "object" && address ? address.port : 0;
|
|
6306
|
-
server.close((error) => error ? reject(error) :
|
|
6595
|
+
server.close((error) => error ? reject(error) : resolve6(port));
|
|
6307
6596
|
});
|
|
6308
6597
|
});
|
|
6309
6598
|
}
|
|
@@ -6336,7 +6625,393 @@ function stringValue4(value) {
|
|
|
6336
6625
|
return typeof value == "string" ? value.trim() : "";
|
|
6337
6626
|
}
|
|
6338
6627
|
function delay(ms) {
|
|
6339
|
-
return new Promise((
|
|
6628
|
+
return new Promise((resolve6) => setTimeout(resolve6, ms));
|
|
6629
|
+
}
|
|
6630
|
+
|
|
6631
|
+
// src/trae-intl-sync.ts
|
|
6632
|
+
import { createDecipheriv, createHash as createHash3, timingSafeEqual } from "node:crypto";
|
|
6633
|
+
import { existsSync as existsSync3 } from "node:fs";
|
|
6634
|
+
import { chmod, mkdir as mkdir5, open as open4, readFile as readFile20, rename as rename2, unlink as unlink2 } from "node:fs/promises";
|
|
6635
|
+
import { homedir as homedir23 } from "node:os";
|
|
6636
|
+
import { dirname as dirname9, join as join24 } from "node:path";
|
|
6637
|
+
var DEFAULT_HOST = "https://api-sg-central.trae.ai", CLIENT_IDS = {
|
|
6638
|
+
ide: "ono9krqynydwx5",
|
|
6639
|
+
solo: "en1oxy7wnw8j9n"
|
|
6640
|
+
}, 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;
|
|
6641
|
+
async function syncTraeIntlUsage(options = {}) {
|
|
6642
|
+
let sinceDays = normalizeSinceDays(options.sinceDays), cacheDir = options.cacheDir ?? resolveTraeIntlCacheDir(), fetchImpl = options.fetchImpl ?? fetch, now = options.now ?? /* @__PURE__ */ new Date(), releaseLock = await acquireTraeIntlSyncLock(dirname9(cacheDir));
|
|
6643
|
+
try {
|
|
6644
|
+
return await performTraeIntlSync(options, sinceDays, cacheDir, fetchImpl, now);
|
|
6645
|
+
} finally {
|
|
6646
|
+
await releaseLock();
|
|
6647
|
+
}
|
|
6648
|
+
}
|
|
6649
|
+
async function performTraeIntlSync(options, sinceDays, cacheDir, fetchImpl, now) {
|
|
6650
|
+
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;
|
|
6651
|
+
try {
|
|
6652
|
+
sessions = await fetchUsagePages(credentials.host, credentials.token, startTime, endTime, fetchImpl);
|
|
6653
|
+
} catch (error) {
|
|
6654
|
+
if (!(error instanceof TraeIntlHttpError) || error.status !== 401 || !credentials.refreshToken) throw error;
|
|
6655
|
+
credentials = await exchangeCredentials(credentials, fetchImpl), await saveCredentials(credentials, cacheDir), sessions = await fetchUsagePages(credentials.host, credentials.token, startTime, endTime, fetchImpl);
|
|
6656
|
+
}
|
|
6657
|
+
let canonicalPath = join24(cacheDir, "usage.json"), existing = await readSessionArray(canonicalPath), merged = mergeTraeIntlSessions(existing, sessions);
|
|
6658
|
+
await writePrivateJson(canonicalPath, merged);
|
|
6659
|
+
let totals = merged.reduce((sum, session) => {
|
|
6660
|
+
let extra = session.extra_info ?? {};
|
|
6661
|
+
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;
|
|
6662
|
+
}, {
|
|
6663
|
+
inputTokens: 0,
|
|
6664
|
+
cachedInputTokens: 0,
|
|
6665
|
+
cacheWriteTokens: 0,
|
|
6666
|
+
outputTokens: 0,
|
|
6667
|
+
totalTokens: 0,
|
|
6668
|
+
costUSD: 0
|
|
6669
|
+
});
|
|
6670
|
+
return totals.totalTokens = totals.inputTokens + totals.cachedInputTokens + totals.cacheWriteTokens + totals.outputTokens, totals.costUSD = Math.round(totals.costUSD * 1e6) / 1e6, {
|
|
6671
|
+
edition: "intl",
|
|
6672
|
+
scope: "account",
|
|
6673
|
+
credentialVariant: resolved.source,
|
|
6674
|
+
cacheDir,
|
|
6675
|
+
sinceDays,
|
|
6676
|
+
fetchedSessions: sessions.length,
|
|
6677
|
+
storedSessions: merged.length,
|
|
6678
|
+
totals
|
|
6679
|
+
};
|
|
6680
|
+
}
|
|
6681
|
+
async function acquireTraeIntlSyncLock(cacheRoot) {
|
|
6682
|
+
await mkdir5(cacheRoot, { recursive: !0, mode: 448 }), await chmod(cacheRoot, 448).catch(() => {
|
|
6683
|
+
});
|
|
6684
|
+
let lockPath = join24(cacheRoot, "sync.lock");
|
|
6685
|
+
for (let attempt = 0; attempt < 3; attempt += 1)
|
|
6686
|
+
try {
|
|
6687
|
+
let handle = await open4(lockPath, "wx", 384);
|
|
6688
|
+
try {
|
|
6689
|
+
await handle.writeFile(`${process.pid} ${Math.floor(Date.now() / 1e3)}
|
|
6690
|
+
`, "utf8");
|
|
6691
|
+
} finally {
|
|
6692
|
+
await handle.close();
|
|
6693
|
+
}
|
|
6694
|
+
return async () => {
|
|
6695
|
+
await unlink2(lockPath).catch(() => {
|
|
6696
|
+
});
|
|
6697
|
+
};
|
|
6698
|
+
} catch (error) {
|
|
6699
|
+
if (!isFileExistsError(error)) throw error;
|
|
6700
|
+
if (!await isStaleSyncLock(lockPath))
|
|
6701
|
+
throw new Error(`\u53E6\u4E00\u4E2A Trae \u56FD\u9645\u7248\u540C\u6B65\u6B63\u5728\u8FD0\u884C\uFF08\u9501\u6587\u4EF6: ${lockPath}\uFF09`);
|
|
6702
|
+
await unlink2(lockPath).catch(() => {
|
|
6703
|
+
});
|
|
6704
|
+
}
|
|
6705
|
+
throw new Error(`\u65E0\u6CD5\u83B7\u53D6 Trae \u56FD\u9645\u7248\u540C\u6B65\u9501\uFF08${lockPath}\uFF09`);
|
|
6706
|
+
}
|
|
6707
|
+
async function isStaleSyncLock(lockPath) {
|
|
6708
|
+
try {
|
|
6709
|
+
let pid = Number((await readFile20(lockPath, "utf8")).trim().split(/\s+/)[0]);
|
|
6710
|
+
if (!Number.isInteger(pid) || pid <= 0) return !0;
|
|
6711
|
+
try {
|
|
6712
|
+
return process.kill(pid, 0), !1;
|
|
6713
|
+
} catch (error) {
|
|
6714
|
+
return (isRecord3(error) ? stringValue5(error.code) : "") === "ESRCH";
|
|
6715
|
+
}
|
|
6716
|
+
} catch {
|
|
6717
|
+
return !0;
|
|
6718
|
+
}
|
|
6719
|
+
}
|
|
6720
|
+
function isFileExistsError(error) {
|
|
6721
|
+
return isRecord3(error) && stringValue5(error.code) === "EEXIST";
|
|
6722
|
+
}
|
|
6723
|
+
function mergeTraeIntlSessions(existing, incoming) {
|
|
6724
|
+
let sessions = /* @__PURE__ */ new Map();
|
|
6725
|
+
for (let session of [...existing, ...incoming]) {
|
|
6726
|
+
let id = stringValue5(session.session_id), usageTime = tokenValue3(session.usage_time);
|
|
6727
|
+
if (!id || usageTime === 0) continue;
|
|
6728
|
+
let previous = sessions.get(id), previousTime = tokenValue3(previous?.usage_time);
|
|
6729
|
+
(!previous || usageTime > previousTime || usageTime === previousTime && sessionWeight(session) >= sessionWeight(previous)) && sessions.set(id, session);
|
|
6730
|
+
}
|
|
6731
|
+
return [...sessions.values()].sort((a, b) => tokenValue3(a.usage_time) - tokenValue3(b.usage_time) || stringValue5(a.session_id).localeCompare(stringValue5(b.session_id)));
|
|
6732
|
+
}
|
|
6733
|
+
async function resolveCredentials(requested, fetchImpl, cacheDir) {
|
|
6734
|
+
let environmentToken = process.env.AIUSAGE_TRAE_INTL_TOKEN?.trim();
|
|
6735
|
+
if (environmentToken)
|
|
6736
|
+
return {
|
|
6737
|
+
source: "environment",
|
|
6738
|
+
credentials: {
|
|
6739
|
+
variant: requested === "solo" ? "solo" : "ide",
|
|
6740
|
+
token: stripAuthorizationPrefix(environmentToken),
|
|
6741
|
+
refreshToken: "",
|
|
6742
|
+
expiredAt: "",
|
|
6743
|
+
refreshExpiredAt: "",
|
|
6744
|
+
host: normalizeHost(process.env.AIUSAGE_TRAE_INTL_HOST || DEFAULT_HOST),
|
|
6745
|
+
clientId: process.env.AIUSAGE_TRAE_INTL_CLIENT_ID?.trim() || CLIENT_IDS[requested === "solo" ? "solo" : "ide"]
|
|
6746
|
+
}
|
|
6747
|
+
};
|
|
6748
|
+
let variants = requested === "auto" ? ["ide", "solo"] : [requested], errors = [];
|
|
6749
|
+
for (let variant of variants) {
|
|
6750
|
+
let cachedCandidates = [
|
|
6751
|
+
["AIUsage cache", await loadCredentials(variant, cacheDir)],
|
|
6752
|
+
["tokscale cache", await loadTokscaleCredentials(variant)]
|
|
6753
|
+
];
|
|
6754
|
+
for (let [source, cached2] of cachedCandidates)
|
|
6755
|
+
if (cached2)
|
|
6756
|
+
try {
|
|
6757
|
+
let credentials = await ensureUsableCredentials(cached2, fetchImpl);
|
|
6758
|
+
return await saveCredentials(credentials, cacheDir), { credentials, source: variant };
|
|
6759
|
+
} catch (error) {
|
|
6760
|
+
errors.push(`${variant} ${source}: ${sanitizeError(error)}`);
|
|
6761
|
+
}
|
|
6762
|
+
try {
|
|
6763
|
+
let credentials = await ensureUsableCredentials(await decryptDesktopCredentials(variant), fetchImpl);
|
|
6764
|
+
return await saveCredentials(credentials, cacheDir), { credentials, source: variant };
|
|
6765
|
+
} catch (error) {
|
|
6766
|
+
errors.push(`${variant}: ${sanitizeError(error)}`);
|
|
6767
|
+
}
|
|
6768
|
+
}
|
|
6769
|
+
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("; ")})` : ""}`);
|
|
6770
|
+
}
|
|
6771
|
+
async function ensureUsableCredentials(credentials, fetchImpl) {
|
|
6772
|
+
if (!isExpired(credentials.expiredAt, 3e5)) return credentials;
|
|
6773
|
+
if (!credentials.refreshToken) throw new Error("access token \u5DF2\u8FC7\u671F\u4E14\u6CA1\u6709 refresh token");
|
|
6774
|
+
if (isExpired(credentials.refreshExpiredAt, 864e5)) throw new Error("refresh token \u5DF2\u8FC7\u671F");
|
|
6775
|
+
return exchangeCredentials(credentials, fetchImpl);
|
|
6776
|
+
}
|
|
6777
|
+
async function decryptDesktopCredentials(variant) {
|
|
6778
|
+
if (process.platform !== "darwin")
|
|
6779
|
+
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");
|
|
6780
|
+
let appDir = variant === "ide" ? "Trae" : "TRAE SOLO", storagePath = join24(homedir23(), "Library", "Application Support", appDir, "User", "globalStorage", "storage.json");
|
|
6781
|
+
if (!existsSync3(storagePath)) throw new Error(`\u672A\u627E\u5230 ${appDir} storage.json`);
|
|
6782
|
+
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];
|
|
6783
|
+
if (!encoded) throw new Error("storage.json \u4E2D\u6CA1\u6709 iCubeAuthInfo");
|
|
6784
|
+
let raw = JSON.parse(decodeTraeIntlAuthInfo(encoded)), token = stringValue5(raw.token);
|
|
6785
|
+
if (!token) throw new Error("\u89E3\u5BC6\u7ED3\u679C\u7F3A\u5C11 token");
|
|
6786
|
+
return {
|
|
6787
|
+
variant,
|
|
6788
|
+
token,
|
|
6789
|
+
refreshToken: stringValue5(raw.refreshToken),
|
|
6790
|
+
expiredAt: stringValue5(raw.expiredAt),
|
|
6791
|
+
refreshExpiredAt: stringValue5(raw.refreshExpiredAt),
|
|
6792
|
+
host: normalizeHost(stringValue5(raw.host) || DEFAULT_HOST),
|
|
6793
|
+
clientId: process.env.AIUSAGE_TRAE_INTL_CLIENT_ID?.trim() || CLIENT_IDS[variant],
|
|
6794
|
+
userId: stringValue5(raw.userId) || void 0
|
|
6795
|
+
};
|
|
6796
|
+
}
|
|
6797
|
+
function decodeTraeIntlAuthInfo(encoded) {
|
|
6798
|
+
let value = encoded.trim();
|
|
6799
|
+
if (value.startsWith("{"))
|
|
6800
|
+
try {
|
|
6801
|
+
let parsed = JSON.parse(value);
|
|
6802
|
+
if (isRecord3(parsed)) return value;
|
|
6803
|
+
} catch {
|
|
6804
|
+
throw new Error("Trae \u56FD\u9645\u7248\u660E\u6587\u51ED\u8BC1 JSON \u65E0\u6548");
|
|
6805
|
+
}
|
|
6806
|
+
return decryptTraeIntlAuthBlob(value);
|
|
6807
|
+
}
|
|
6808
|
+
function decryptTraeIntlAuthBlob(encoded) {
|
|
6809
|
+
let blob = Buffer.from(encoded.trim(), "base64"), magic = Buffer.from([116, 99, 5, 16, 0, 0]);
|
|
6810
|
+
if (blob.length < magic.length + 32 + 16 || !blob.subarray(0, magic.length).equals(magic))
|
|
6811
|
+
throw new Error("Trae \u56FD\u9645\u7248\u51ED\u8BC1\u683C\u5F0F\u65E0\u6548");
|
|
6812
|
+
let salt = blob.subarray(magic.length, magic.length + 32), ciphertext = blob.subarray(magic.length + 32);
|
|
6813
|
+
if (ciphertext.length % 16 !== 0) throw new Error("Trae \u56FD\u9645\u7248\u51ED\u8BC1\u5BC6\u6587\u957F\u5EA6\u65E0\u6548");
|
|
6814
|
+
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()]);
|
|
6815
|
+
if (plaintext.length < 64) throw new Error("Trae \u56FD\u9645\u7248\u51ED\u8BC1\u660E\u6587\u957F\u5EA6\u65E0\u6548");
|
|
6816
|
+
let expectedHash = plaintext.subarray(0, 64), data = plaintext.subarray(64), actualHash = createHash3("sha512").update(data).digest();
|
|
6817
|
+
if (!timingSafeEqual(expectedHash, actualHash)) throw new Error("Trae \u56FD\u9645\u7248\u51ED\u8BC1\u5B8C\u6574\u6027\u6821\u9A8C\u5931\u8D25");
|
|
6818
|
+
return data.toString("utf8");
|
|
6819
|
+
}
|
|
6820
|
+
async function exchangeCredentials(credentials, fetchImpl) {
|
|
6821
|
+
if (!credentials.refreshToken) throw new Error("Trae \u56FD\u9645\u7248 refresh token \u4E0D\u53EF\u7528");
|
|
6822
|
+
if (credentials.refreshExpiredAt && isExpired(credentials.refreshExpiredAt, 864e5))
|
|
6823
|
+
throw new Error("Trae \u56FD\u9645\u7248 refresh token \u5DF2\u8FC7\u671F\uFF0C\u8BF7\u91CD\u65B0\u767B\u5F55\u5BA2\u6237\u7AEF");
|
|
6824
|
+
let response = await requestJson2(
|
|
6825
|
+
`${normalizeHost(credentials.host)}${EXCHANGE_TOKEN_PATH}`,
|
|
6826
|
+
{
|
|
6827
|
+
method: "POST",
|
|
6828
|
+
headers: {
|
|
6829
|
+
"Content-Type": "application/json",
|
|
6830
|
+
"x-cloudide-token": credentials.token
|
|
6831
|
+
},
|
|
6832
|
+
body: JSON.stringify({
|
|
6833
|
+
ClientID: credentials.clientId,
|
|
6834
|
+
RefreshToken: credentials.refreshToken,
|
|
6835
|
+
ClientSecret: "-",
|
|
6836
|
+
UserID: ""
|
|
6837
|
+
})
|
|
6838
|
+
},
|
|
6839
|
+
fetchImpl,
|
|
6840
|
+
15e3
|
|
6841
|
+
), result = isRecord3(response.Result) ? response.Result : {}, token = stringValue5(result.Token);
|
|
6842
|
+
if (!token) throw new Error("Trae \u56FD\u9645\u7248\u5237\u65B0\u63A5\u53E3\u6CA1\u6709\u8FD4\u56DE Token");
|
|
6843
|
+
return {
|
|
6844
|
+
...credentials,
|
|
6845
|
+
token,
|
|
6846
|
+
refreshToken: stringValue5(result.RefreshToken) || credentials.refreshToken,
|
|
6847
|
+
expiredAt: epochMsToIso(result.TokenExpireAt),
|
|
6848
|
+
refreshExpiredAt: epochMsToIso(result.RefreshExpireAt)
|
|
6849
|
+
};
|
|
6850
|
+
}
|
|
6851
|
+
async function fetchUsagePages(host, token, startTime, endTime, fetchImpl) {
|
|
6852
|
+
let all = [];
|
|
6853
|
+
for (let page = 1; page <= 500; page += 1) {
|
|
6854
|
+
let response = await requestJson2(
|
|
6855
|
+
`${normalizeHost(host)}${USAGE_PATH}`,
|
|
6856
|
+
{
|
|
6857
|
+
method: "POST",
|
|
6858
|
+
headers: {
|
|
6859
|
+
"Content-Type": "application/json",
|
|
6860
|
+
authorization: `Cloud-IDE-JWT ${token}`
|
|
6861
|
+
},
|
|
6862
|
+
body: JSON.stringify({
|
|
6863
|
+
start_time: startTime,
|
|
6864
|
+
end_time: endTime,
|
|
6865
|
+
page_size: PAGE_SIZE,
|
|
6866
|
+
page_num: page,
|
|
6867
|
+
usage_type: [5, 6]
|
|
6868
|
+
})
|
|
6869
|
+
},
|
|
6870
|
+
fetchImpl,
|
|
6871
|
+
3e4
|
|
6872
|
+
), batch = Array.isArray(response.user_usage_group_by_sessions) ? response.user_usage_group_by_sessions.filter(isRecord3) : [];
|
|
6873
|
+
all.push(...batch);
|
|
6874
|
+
let total = positiveInteger(response.total);
|
|
6875
|
+
if (batch.length === 0 || total != null && all.length >= total) break;
|
|
6876
|
+
await delay2(PAGE_DELAY_MS);
|
|
6877
|
+
}
|
|
6878
|
+
return all;
|
|
6879
|
+
}
|
|
6880
|
+
var TraeIntlHttpError = class extends Error {
|
|
6881
|
+
constructor(status, message) {
|
|
6882
|
+
super(message);
|
|
6883
|
+
this.status = status;
|
|
6884
|
+
}
|
|
6885
|
+
};
|
|
6886
|
+
async function requestJson2(url, init, fetchImpl, timeoutMs) {
|
|
6887
|
+
let controller = new AbortController(), timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
6888
|
+
try {
|
|
6889
|
+
let response = await fetchImpl(url, { ...init, signal: controller.signal }), text = await response.text();
|
|
6890
|
+
if (!response.ok)
|
|
6891
|
+
throw new TraeIntlHttpError(response.status, `Trae \u56FD\u9645\u7248\u63A5\u53E3\u8FD4\u56DE ${response.status}: ${sanitizeResponse(text)}`);
|
|
6892
|
+
try {
|
|
6893
|
+
return JSON.parse(text);
|
|
6894
|
+
} catch {
|
|
6895
|
+
throw new Error("Trae \u56FD\u9645\u7248\u63A5\u53E3\u8FD4\u56DE\u4E86\u65E0\u6548 JSON");
|
|
6896
|
+
}
|
|
6897
|
+
} finally {
|
|
6898
|
+
clearTimeout(timer);
|
|
6899
|
+
}
|
|
6900
|
+
}
|
|
6901
|
+
async function loadCredentials(variant, cacheDir) {
|
|
6902
|
+
return readCredentialFile(join24(dirname9(cacheDir), `credentials-${variant}.json`), variant);
|
|
6903
|
+
}
|
|
6904
|
+
async function loadTokscaleCredentials(variant) {
|
|
6905
|
+
let root = dirname9(resolveTokscaleTraeCacheDir());
|
|
6906
|
+
return readCredentialFile(join24(root, `credentials-${variant}.json`), variant);
|
|
6907
|
+
}
|
|
6908
|
+
async function readCredentialFile(path, fallbackVariant) {
|
|
6909
|
+
try {
|
|
6910
|
+
let raw = JSON.parse(await readFile20(path, "utf8")), token = stringValue5(raw.token);
|
|
6911
|
+
if (!token) return null;
|
|
6912
|
+
let serializedVariant = stringValue5(raw.variant).toLowerCase();
|
|
6913
|
+
return {
|
|
6914
|
+
variant: serializedVariant === "solo" ? "solo" : serializedVariant === "ide" ? "ide" : fallbackVariant,
|
|
6915
|
+
token,
|
|
6916
|
+
refreshToken: stringValue5(raw.refreshToken) || stringValue5(raw.refresh_token),
|
|
6917
|
+
expiredAt: stringValue5(raw.expiredAt) || stringValue5(raw.expired_at),
|
|
6918
|
+
refreshExpiredAt: stringValue5(raw.refreshExpiredAt) || stringValue5(raw.refresh_expired_at),
|
|
6919
|
+
host: normalizeHost(stringValue5(raw.host) || DEFAULT_HOST),
|
|
6920
|
+
clientId: stringValue5(raw.clientId) || stringValue5(raw.client_id) || CLIENT_IDS[fallbackVariant],
|
|
6921
|
+
userId: stringValue5(raw.userId) || stringValue5(raw.user_id) || void 0
|
|
6922
|
+
};
|
|
6923
|
+
} catch {
|
|
6924
|
+
return null;
|
|
6925
|
+
}
|
|
6926
|
+
}
|
|
6927
|
+
async function saveCredentials(credentials, cacheDir) {
|
|
6928
|
+
let path = join24(dirname9(cacheDir), `credentials-${credentials.variant}.json`);
|
|
6929
|
+
await writePrivateJson(path, credentials);
|
|
6930
|
+
}
|
|
6931
|
+
async function readSessionArray(path) {
|
|
6932
|
+
try {
|
|
6933
|
+
let value = JSON.parse(await readFile20(path, "utf8"));
|
|
6934
|
+
return Array.isArray(value) ? value.filter(isRecord3) : [];
|
|
6935
|
+
} catch {
|
|
6936
|
+
return [];
|
|
6937
|
+
}
|
|
6938
|
+
}
|
|
6939
|
+
async function writePrivateJson(path, value) {
|
|
6940
|
+
let dir = dirname9(path);
|
|
6941
|
+
await mkdir5(dir, { recursive: !0, mode: 448 }), await chmod(dir, 448).catch(() => {
|
|
6942
|
+
});
|
|
6943
|
+
let tempPath = join24(dir, `.${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}.tmp`), handle = await open4(tempPath, "w", 384);
|
|
6944
|
+
try {
|
|
6945
|
+
await handle.writeFile(`${JSON.stringify(value, null, 2)}
|
|
6946
|
+
`, "utf8");
|
|
6947
|
+
} finally {
|
|
6948
|
+
await handle.close();
|
|
6949
|
+
}
|
|
6950
|
+
await rename2(tempPath, path), await chmod(path, 384).catch(() => {
|
|
6951
|
+
});
|
|
6952
|
+
}
|
|
6953
|
+
function normalizeSinceDays(value) {
|
|
6954
|
+
if (value == null) return DEFAULT_SINCE_DAYS;
|
|
6955
|
+
if (!Number.isInteger(value) || value <= 0 || value > 3650)
|
|
6956
|
+
throw new Error("--since \u5FC5\u987B\u662F 1 \u5230 3650 \u4E4B\u95F4\u7684\u6574\u6570\u5929\u6570");
|
|
6957
|
+
return value;
|
|
6958
|
+
}
|
|
6959
|
+
function normalizeHost(value) {
|
|
6960
|
+
let normalized = value.trim().replace(/\/+$/, ""), url;
|
|
6961
|
+
try {
|
|
6962
|
+
url = new URL(normalized);
|
|
6963
|
+
} catch {
|
|
6964
|
+
throw new Error("Trae \u56FD\u9645\u7248 API host \u65E0\u6548");
|
|
6965
|
+
}
|
|
6966
|
+
if (url.protocol !== "https:") throw new Error("Trae \u56FD\u9645\u7248 API host \u5FC5\u987B\u4F7F\u7528 HTTPS");
|
|
6967
|
+
return url.origin;
|
|
6968
|
+
}
|
|
6969
|
+
function stripAuthorizationPrefix(value) {
|
|
6970
|
+
return value.replace(/^(?:Cloud-IDE-JWT|Bearer)\s+/i, "").trim();
|
|
6971
|
+
}
|
|
6972
|
+
function isExpired(value, marginMs) {
|
|
6973
|
+
let timestamp = Date.parse(value);
|
|
6974
|
+
return !Number.isFinite(timestamp) || Date.now() >= timestamp - marginMs;
|
|
6975
|
+
}
|
|
6976
|
+
function epochMsToIso(value) {
|
|
6977
|
+
let timestamp = Number(value);
|
|
6978
|
+
return Number.isFinite(timestamp) && timestamp > 0 ? new Date(timestamp).toISOString() : "";
|
|
6979
|
+
}
|
|
6980
|
+
function tokenValue3(value) {
|
|
6981
|
+
let number = Number(value);
|
|
6982
|
+
return Number.isFinite(number) && number > 0 ? Math.floor(number) : 0;
|
|
6983
|
+
}
|
|
6984
|
+
function positiveNumber2(value) {
|
|
6985
|
+
let number = Number(value);
|
|
6986
|
+
return Number.isFinite(number) && number > 0 ? number : 0;
|
|
6987
|
+
}
|
|
6988
|
+
function positiveInteger(value) {
|
|
6989
|
+
let number = Number(value);
|
|
6990
|
+
return Number.isInteger(number) && number >= 0 ? number : void 0;
|
|
6991
|
+
}
|
|
6992
|
+
function sessionWeight(session) {
|
|
6993
|
+
let extra = session.extra_info ?? {};
|
|
6994
|
+
return tokenValue3(extra.input_token) + tokenValue3(extra.output_token) + tokenValue3(extra.cache_read_token) + tokenValue3(extra.cache_write_token);
|
|
6995
|
+
}
|
|
6996
|
+
function stringValue5(value) {
|
|
6997
|
+
return typeof value == "string" ? value.trim() : "";
|
|
6998
|
+
}
|
|
6999
|
+
function isRecord3(value) {
|
|
7000
|
+
return value != null && typeof value == "object" && !Array.isArray(value);
|
|
7001
|
+
}
|
|
7002
|
+
function sanitizeResponse(value) {
|
|
7003
|
+
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);
|
|
7004
|
+
}
|
|
7005
|
+
function sanitizeError(error) {
|
|
7006
|
+
let parts = [], current = error;
|
|
7007
|
+
for (let depth = 0; depth < 3 && current != null; depth += 1) {
|
|
7008
|
+
let message = current instanceof Error ? current.message : String(current);
|
|
7009
|
+
message && !parts.includes(message) && parts.push(message), isRecord3(current) && stringValue5(current.code) && parts.push(stringValue5(current.code)), current = isRecord3(current) ? current.cause : void 0;
|
|
7010
|
+
}
|
|
7011
|
+
return sanitizeResponse(parts.join(": "));
|
|
7012
|
+
}
|
|
7013
|
+
function delay2(ms) {
|
|
7014
|
+
return new Promise((resolve6) => setTimeout(resolve6, ms));
|
|
6340
7015
|
}
|
|
6341
7016
|
|
|
6342
7017
|
// src/cli.ts
|
|
@@ -6376,7 +7051,7 @@ await (async () => {
|
|
|
6376
7051
|
await runTraeSync(parsed.flags, parsed.positionals);
|
|
6377
7052
|
else {
|
|
6378
7053
|
let zh2 = (await readConfig()).lang === "zh";
|
|
6379
|
-
throw new Error(zh2 ? "\u7528\u6CD5: aiusage trae sync [--port 9230] [--no-launch] [--json]" : "Usage: aiusage trae sync [--port 9230] [--no-launch] [--json]");
|
|
7054
|
+
throw new Error(zh2 ? "\u7528\u6CD5: aiusage trae sync [--edition cn|intl|all] [--since 180] [--port 9230] [--no-launch] [--json]" : "Usage: aiusage trae sync [--edition cn|intl|all] [--since 180] [--port 9230] [--no-launch] [--json]");
|
|
6380
7055
|
}
|
|
6381
7056
|
} else if (command === "init") {
|
|
6382
7057
|
let parsed = parseArgs(argv.slice(1));
|
|
@@ -6451,7 +7126,7 @@ await (async () => {
|
|
|
6451
7126
|
async function runScan(flags, positionals = []) {
|
|
6452
7127
|
let config = await readConfig(), zh2 = config.lang === "zh";
|
|
6453
7128
|
assertNoPositionals("scan", positionals, zh2);
|
|
6454
|
-
let isJson = !!flags.json, dates = resolveScanDates(flags, config), results = dates.length === 1 ? [await scanDate(dates[0], { projectAliases: config.projectAliases })] : await scanDates(dates, { projectAliases: config.projectAliases });
|
|
7129
|
+
let isJson = !!flags.json, dates = resolveScanDates(flags, config), tools = parseToolSelection(flags.tool, zh2), opencodeDbPaths = config.scanner?.opencodeDbPaths, results = dates.length === 1 ? [await scanDate(dates[0], { projectAliases: config.projectAliases, opencodeDbPaths, tools })] : await scanDates(dates, { projectAliases: config.projectAliases, opencodeDbPaths, tools });
|
|
6455
7130
|
if (isJson) {
|
|
6456
7131
|
console.log(JSON.stringify(results.length === 1 ? results[0] : results, null, 2));
|
|
6457
7132
|
return;
|
|
@@ -6490,14 +7165,16 @@ function printScanResult(result, zh2) {
|
|
|
6490
7165
|
console.log("\u2500\u2500 \u5408\u8BA1 \u2500\u2500"), console.log(` \u4E8B\u4EF6: ${result.totals.eventCount} \u8F93\u5165: ${fmt2(result.totals.inputTokens)} \u7F13\u5B58\u8BFB: ${fmt2(result.totals.cachedInputTokens)} \u7F13\u5B58\u5199: ${fmt2(result.totals.cacheWriteTokens)} \u8F93\u51FA: ${fmt2(result.totals.outputTokens)} \u63A8\u7406: ${fmt2(result.totals.reasoningOutputTokens)}`), console.log();
|
|
6491
7166
|
}
|
|
6492
7167
|
async function runReport(flags, positionals = []) {
|
|
6493
|
-
let config = await readConfig();
|
|
6494
|
-
assertNoPositionals("report", positionals,
|
|
6495
|
-
let { dates, range } = resolveDateParams(flags, config), targetName = resolveOptionalString(flags.target, void 0), pricingTarget = targetName ? findTargetOrThrow(config, targetName) : config.targets?.[0], pricing = await resolvePricingCatalog(config, {
|
|
7168
|
+
let config = await readConfig(), zh2 = config.lang === "zh";
|
|
7169
|
+
assertNoPositionals("report", positionals, zh2);
|
|
7170
|
+
let { dates, range } = resolveDateParams(flags, config), tools = parseToolSelection(flags.tool, zh2), targetName = resolveOptionalString(flags.target, void 0), pricingTarget = targetName ? findTargetOrThrow(config, targetName) : config.targets?.[0], pricing = await resolvePricingCatalog(config, {
|
|
6496
7171
|
explicitUrl: resolveOptionalString(flags["pricing-url"], void 0),
|
|
6497
7172
|
target: pricingTarget
|
|
6498
7173
|
}), report = await buildLocalReport(range, {
|
|
6499
7174
|
projectAliases: config.projectAliases,
|
|
7175
|
+
opencodeDbPaths: config.scanner?.opencodeDbPaths,
|
|
6500
7176
|
dates,
|
|
7177
|
+
tools,
|
|
6501
7178
|
pricingCatalog: pricing.catalog,
|
|
6502
7179
|
pricingInfo: pricing.info
|
|
6503
7180
|
});
|
|
@@ -6559,15 +7236,16 @@ async function runEnroll(flags) {
|
|
|
6559
7236
|
}
|
|
6560
7237
|
function prompt(question) {
|
|
6561
7238
|
let rl = createInterface4({ input: process.stdin, output: process.stdout });
|
|
6562
|
-
return new Promise((
|
|
7239
|
+
return new Promise((resolve6) => {
|
|
6563
7240
|
rl.question(question, (answer) => {
|
|
6564
|
-
rl.close(),
|
|
7241
|
+
rl.close(), resolve6(answer.trim());
|
|
6565
7242
|
});
|
|
6566
7243
|
});
|
|
6567
7244
|
}
|
|
6568
7245
|
async function runSync(flags, positionals = []) {
|
|
6569
7246
|
let config = await readConfig();
|
|
6570
|
-
assertNoPositionals("sync", positionals, config.lang === "zh")
|
|
7247
|
+
if (assertNoPositionals("sync", positionals, config.lang === "zh"), flags.tool != null)
|
|
7248
|
+
throw new Error(config.lang === "zh" ? "--tool \u4EC5\u7528\u4E8E scan/report\uFF1Bsync \u59CB\u7EC8\u4E0A\u4F20\u6240\u9009\u65E5\u671F\u7684\u5B8C\u6574\u5FEB\u7167" : "--tool is only available for scan/report; sync always uploads complete daily snapshots");
|
|
6571
7249
|
let allTargets = config.targets ?? [];
|
|
6572
7250
|
if (allTargets.length === 0)
|
|
6573
7251
|
throw new Error("\u672A\u914D\u7F6E\u4EFB\u4F55\u4E0A\u62A5\u76EE\u6807\uFF0C\u8BF7\u5148\u6267\u884C aiusage enroll");
|
|
@@ -6576,7 +7254,10 @@ async function runSync(flags, positionals = []) {
|
|
|
6576
7254
|
throw new Error("sync --range all \u9700\u8981\u660E\u786E\u65E5\u671F\u8303\u56F4\uFF0C\u8BF7\u6539\u7528 --from YYYY-MM-DD --to YYYY-MM-DD");
|
|
6577
7255
|
console.log(`\u626B\u63CF ${targetDates.length} \u5929 (${targetDates[0]} ~ ${targetDates[targetDates.length - 1]}) ...`);
|
|
6578
7256
|
let [results, activityReport] = await Promise.all([
|
|
6579
|
-
scanDates(targetDates, {
|
|
7257
|
+
scanDates(targetDates, {
|
|
7258
|
+
projectAliases: config.projectAliases,
|
|
7259
|
+
opencodeDbPaths: config.scanner?.opencodeDbPaths
|
|
7260
|
+
}),
|
|
6580
7261
|
buildActivityReport("all", { dates: targetDates, projectAliases: config.projectAliases })
|
|
6581
7262
|
]), visibility = config.privacy?.projectVisibility, resultsByDate = new Map(results.map((result) => [result.usageDate, result])), activityByDate = buildActivityPayloadByDate(activityReport.items, visibility), allDays = targetDates.map((usageDate) => {
|
|
6582
7263
|
let breakdowns = applyPrivacy(resultsByDate.get(usageDate)?.breakdowns ?? [], visibility), activity = activityByDate.get(usageDate);
|
|
@@ -6621,18 +7302,49 @@ async function runTraeSync(flags, positionals = []) {
|
|
|
6621
7302
|
assertNoPositionals("trae sync", positionals, zh2);
|
|
6622
7303
|
let portFlag = resolveOptionalString(flags.port, void 0), port = portFlag ? parsePositiveInt2(portFlag, "--port") : void 0;
|
|
6623
7304
|
if (port != null && port > 65535) throw new Error("--port \u5FC5\u987B\u5728 1 \u5230 65535 \u4E4B\u95F4");
|
|
6624
|
-
flags.
|
|
6625
|
-
|
|
6626
|
-
|
|
6627
|
-
|
|
6628
|
-
|
|
6629
|
-
|
|
7305
|
+
let edition = parseTraeEdition(flags.edition, zh2), sinceFlag = resolveOptionalString(flags.since, void 0), sinceDays = sinceFlag ? parsePositiveInt2(sinceFlag, "--since") : void 0;
|
|
7306
|
+
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"));
|
|
7307
|
+
let cnResult, intlResult, warnings = [];
|
|
7308
|
+
if (edition === "cn" || edition === "all")
|
|
7309
|
+
try {
|
|
7310
|
+
cnResult = await syncTraeCnUsage({
|
|
7311
|
+
port,
|
|
7312
|
+
appPath: resolveOptionalString(flags.app, void 0),
|
|
7313
|
+
launch: flags["no-launch"] !== !0
|
|
7314
|
+
});
|
|
7315
|
+
} catch (error) {
|
|
7316
|
+
if (edition === "cn") throw error;
|
|
7317
|
+
warnings.push(`Trae CN: ${error instanceof Error ? error.message : String(error)}`);
|
|
7318
|
+
}
|
|
7319
|
+
if (edition === "intl" || edition === "all")
|
|
7320
|
+
try {
|
|
7321
|
+
intlResult = await syncTraeIntlUsage({ sinceDays });
|
|
7322
|
+
} catch (error) {
|
|
7323
|
+
if (edition === "intl") throw error;
|
|
7324
|
+
warnings.push(`Trae International: ${error instanceof Error ? error.message : String(error)}`);
|
|
7325
|
+
}
|
|
7326
|
+
if (!cnResult && !intlResult) throw new Error(warnings.join(`
|
|
7327
|
+
`) || "\u6CA1\u6709\u53EF\u540C\u6B65\u7684 Trae \u6570\u636E\u6E90");
|
|
6630
7328
|
if (flags.json) {
|
|
6631
|
-
console.log(JSON.stringify(
|
|
7329
|
+
console.log(JSON.stringify(edition === "cn" ? cnResult : edition === "intl" ? intlResult : {
|
|
7330
|
+
edition: "all",
|
|
7331
|
+
cn: cnResult,
|
|
7332
|
+
intl: intlResult,
|
|
7333
|
+
warnings
|
|
7334
|
+
}, null, 2));
|
|
6632
7335
|
return;
|
|
6633
7336
|
}
|
|
6634
|
-
|
|
6635
|
-
|
|
7337
|
+
if (cnResult) {
|
|
7338
|
+
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}`);
|
|
7339
|
+
for (let warning of cnResult.warnings) warnings.push(`Trae CN: ${warning}`);
|
|
7340
|
+
}
|
|
7341
|
+
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}`));
|
|
7342
|
+
for (let warning of warnings) console.warn(`${zh2 ? "\u8B66\u544A" : "Warning"}: ${warning}`);
|
|
7343
|
+
}
|
|
7344
|
+
function parseTraeEdition(value, zh2) {
|
|
7345
|
+
if (value == null) return "cn";
|
|
7346
|
+
if (value === "cn" || value === "intl" || value === "all") return value;
|
|
7347
|
+
throw new Error(zh2 ? "--edition \u4EC5\u652F\u6301 cn\u3001intl\u3001all" : "--edition only supports cn, intl, or all");
|
|
6636
7348
|
}
|
|
6637
7349
|
function buildActivityPayloadByDate(items, visibility) {
|
|
6638
7350
|
let map = /* @__PURE__ */ new Map(), sanitized = applyProjectPrivacy(items, visibility);
|
|
@@ -6832,11 +7544,11 @@ function printHelp(zh2 = !1) {
|
|
|
6832
7544
|
console.log(`aiusage v${getVersion()}
|
|
6833
7545
|
`);
|
|
6834
7546
|
let cmds = zh2 ? [
|
|
6835
|
-
["scan [--date YYYY-MM-DD|--today|--range 7d|1m|3m] [--json]", "\u626B\u63CF\u7528\u91CF\u660E\u7EC6"],
|
|
6836
|
-
["report [--
|
|
6837
|
-
["activity [--today] [--range 7d|1m|3m|all] [--detail] [--json]", "\u672C\u5730\u4EA4\u4E92\u6307\u6807"],
|
|
6838
|
-
["sync [--today] [--range 7d|1m|3m]", "\u4E0A\u4F20\u7528\u91CF\u5230\u670D\u52A1\u7AEF"],
|
|
6839
|
-
["trae sync [--
|
|
7547
|
+
["scan [--tool \u5DE5\u5177] [--date YYYY-MM-DD|--today|--range 7d|1m|3m|6m] [--json]", "\u626B\u63CF\u7528\u91CF\u660E\u7EC6"],
|
|
7548
|
+
["report [--tool \u5DE5\u5177] [--range 7d|1m|3m|6m|all] [--detail] [--json]", "\u672C\u5730\u7528\u91CF\u62A5\u544A"],
|
|
7549
|
+
["activity [--today] [--range 7d|1m|3m|6m|all] [--detail] [--json]", "\u672C\u5730\u4EA4\u4E92\u6307\u6807"],
|
|
7550
|
+
["sync [--today] [--range 7d|1m|3m|6m]", "\u4E0A\u4F20\u7528\u91CF\u5230\u670D\u52A1\u7AEF"],
|
|
7551
|
+
["trae sync [--edition cn|intl|all] [--since 180]", "\u540C\u6B65 Trae CN/\u56FD\u9645\u7248\u7528\u91CF"],
|
|
6840
7552
|
["scan/report/sync --from YYYY-MM-DD [--to YYYY-MM-DD]", "\u6307\u5B9A\u65E5\u671F\u8303\u56F4\uFF08--start/--end \u540C\u4E49\uFF09"],
|
|
6841
7553
|
["project [list|alias]", "\u9879\u76EE\u7BA1\u7406\u4E0E\u522B\u540D\u8BBE\u7F6E"],
|
|
6842
7554
|
["pricing [status|update] [--url URL]", "\u67E5\u770B/\u66F4\u65B0\u5B9A\u4EF7\u76EE\u5F55"],
|
|
@@ -6847,11 +7559,11 @@ function printHelp(zh2 = !1) {
|
|
|
6847
7559
|
["enroll --server URL --site-id ID --enroll-token TOKEN", "\u6CE8\u518C\u8BBE\u5907\u5230\u670D\u52A1\u7AEF"],
|
|
6848
7560
|
["health [--server URL]", "\u6D4B\u8BD5\u670D\u52A1\u7AEF\u8FDE\u901A\u6027"]
|
|
6849
7561
|
] : [
|
|
6850
|
-
["scan [--date YYYY-MM-DD|--today|--range 7d|1m|3m] [--json]", "Scan usage breakdown"],
|
|
6851
|
-
["report [--
|
|
6852
|
-
["activity [--today] [--range 7d|1m|3m|all] [--detail] [--json]", "Local interaction metrics"],
|
|
6853
|
-
["sync [--today] [--range 7d|1m|3m]", "Upload usage to server"],
|
|
6854
|
-
["trae sync [--
|
|
7562
|
+
["scan [--tool TOOL] [--date YYYY-MM-DD|--today|--range 7d|1m|3m|6m] [--json]", "Scan usage breakdown"],
|
|
7563
|
+
["report [--tool TOOL] [--range 7d|1m|3m|6m|all] [--detail] [--json]", "Local usage report"],
|
|
7564
|
+
["activity [--today] [--range 7d|1m|3m|6m|all] [--detail] [--json]", "Local interaction metrics"],
|
|
7565
|
+
["sync [--today] [--range 7d|1m|3m|6m]", "Upload usage to server"],
|
|
7566
|
+
["trae sync [--edition cn|intl|all] [--since 180]", "Sync Trae CN/International usage"],
|
|
6855
7567
|
["scan/report/sync --from YYYY-MM-DD [--to YYYY-MM-DD]", "Date range (--start/--end aliases)"],
|
|
6856
7568
|
["project [list|alias]", "Project management & aliases"],
|
|
6857
7569
|
["pricing [status|update] [--url URL]", "Pricing catalog management"],
|
|
@@ -6871,22 +7583,22 @@ function printUsageHint(zh2 = !1) {
|
|
|
6871
7583
|
console.log(`aiusage v${getVersion()}
|
|
6872
7584
|
`);
|
|
6873
7585
|
let cmds = zh2 ? [
|
|
6874
|
-
["scan [--date YYYY-MM-DD|--range 1m]", "\u626B\u63CF\u7528\u91CF\u660E\u7EC6"],
|
|
6875
|
-
["report [--
|
|
6876
|
-
["activity [--range 7d|1m|3m|all]", "\u672C\u5730\u4EA4\u4E92\u6307\u6807"],
|
|
6877
|
-
["sync [--today] [--range 7d|1m|3m]", "\u4E0A\u4F20\u7528\u91CF\u5230\u670D\u52A1\u7AEF"],
|
|
6878
|
-
["trae sync", "\u540C\u6B65 Trae CN
|
|
7586
|
+
["scan [--tool \u5DE5\u5177] [--date YYYY-MM-DD|--range 1m|6m]", "\u626B\u63CF\u7528\u91CF\u660E\u7EC6"],
|
|
7587
|
+
["report [--tool \u5DE5\u5177] [--range 7d|1m|3m|6m|all]", "\u672C\u5730\u7528\u91CF\u62A5\u544A"],
|
|
7588
|
+
["activity [--range 7d|1m|3m|6m|all]", "\u672C\u5730\u4EA4\u4E92\u6307\u6807"],
|
|
7589
|
+
["sync [--today] [--range 7d|1m|3m|6m]", "\u4E0A\u4F20\u7528\u91CF\u5230\u670D\u52A1\u7AEF"],
|
|
7590
|
+
["trae sync [--edition cn|intl|all]", "\u540C\u6B65 Trae CN/\u56FD\u9645\u7248\u7528\u91CF"],
|
|
6879
7591
|
["project [list|alias]", "\u9879\u76EE\u7BA1\u7406\u4E0E\u522B\u540D\u8BBE\u7F6E"],
|
|
6880
7592
|
["pricing [status|update]", "\u67E5\u770B/\u66F4\u65B0\u5B9A\u4EF7\u76EE\u5F55"],
|
|
6881
7593
|
["schedule [on|off|status]", "\u5B9A\u65F6\u540C\u6B65\u7BA1\u7406"],
|
|
6882
7594
|
["doctor", "\u8BCA\u65AD\u68C0\u67E5"],
|
|
6883
7595
|
["config set <key> <value>", "\u4FEE\u6539\u914D\u7F6E"]
|
|
6884
7596
|
] : [
|
|
6885
|
-
["scan [--date YYYY-MM-DD|--range 1m]", "Scan usage breakdown"],
|
|
6886
|
-
["report [--
|
|
6887
|
-
["activity [--range 7d|1m|3m|all]", "Local interaction metrics"],
|
|
6888
|
-
["sync [--today] [--range 7d|1m|3m]", "Upload usage to server"],
|
|
6889
|
-
["trae sync", "Sync
|
|
7597
|
+
["scan [--tool TOOL] [--date YYYY-MM-DD|--range 1m|6m]", "Scan usage breakdown"],
|
|
7598
|
+
["report [--tool TOOL] [--range 7d|1m|3m|6m|all]", "Local usage report"],
|
|
7599
|
+
["activity [--range 7d|1m|3m|6m|all]", "Local interaction metrics"],
|
|
7600
|
+
["sync [--today] [--range 7d|1m|3m|6m]", "Upload usage to server"],
|
|
7601
|
+
["trae sync [--edition cn|intl|all]", "Sync Trae CN/International usage"],
|
|
6890
7602
|
["project [list|alias]", "Project management & aliases"],
|
|
6891
7603
|
["pricing [status|update]", "Pricing catalog management"],
|
|
6892
7604
|
["schedule [on|off|status]", "Scheduled sync management"],
|
|
@@ -6947,7 +7659,7 @@ function resolveDateParams(flags, config) {
|
|
|
6947
7659
|
let rangeFlag = flags.range;
|
|
6948
7660
|
if (typeof rangeFlag == "string") {
|
|
6949
7661
|
let range = parseReportRange(rangeFlag);
|
|
6950
|
-
return range === "today" ? { dates: [getTodayDate()], range } : range === "7d" ? { dates: [...getClosedDates(6), getTodayDate()], range } : range === "1m" ? { dates: [...getClosedDates(29), getTodayDate()], range } : range === "3m" ? { dates: [...getClosedDates(89), getTodayDate()], range } : { range };
|
|
7662
|
+
return range === "today" ? { dates: [getTodayDate()], range } : range === "7d" ? { dates: [...getClosedDates(6), getTodayDate()], range } : range === "1m" ? { dates: [...getClosedDates(29), getTodayDate()], range } : range === "3m" ? { dates: [...getClosedDates(89), getTodayDate()], range } : range === "6m" ? { dates: [...getClosedDates(179), getTodayDate()], range } : { range };
|
|
6951
7663
|
}
|
|
6952
7664
|
if (typeof flags.lookback == "string") {
|
|
6953
7665
|
let lookbackDays2 = parsePositiveInt2(flags.lookback, "--lookback"), dates2 = getClosedDates(lookbackDays2);
|