@aiusage/cli 1.7.6 → 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 +2 -1
- package/README.zh-CN.md +12 -0
- package/THIRD_PARTY_NOTICES.md +2 -2
- package/dist/cli.js +375 -129
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -29,7 +29,7 @@ differ, rather than treating every local record as billable token usage.
|
|
|
29
29
|
| Kimi CLI / Kimi Code | Legacy `~/.kimi/sessions/` and `$KIMI_CODE_HOME/sessions/` (default `~/.kimi-code/sessions/`) `wire.jsonl`; handles progressive status snapshots and nested agent sessions. |
|
|
30
30
|
| Qwen Code | Current `~/.qwen/projects/` and legacy `~/.qwen/tmp/` chat JSONL, with session/position deduplication and cache-aware input accounting. |
|
|
31
31
|
| Droid | `~/.factory/sessions/*.settings.json`; uses persisted token totals first and the transcript only as a model fallback. |
|
|
32
|
-
| OpenCode |
|
|
32
|
+
| OpenCode | All XDG `opencode*.db` channel databases, including v1 `message` and v2 `session_message`, plus legacy `storage/message/*.json`; deduplicates dual writes/forks and preserves provider-reported cost. Node 22.13+ uses built-in read-only SQLite, with system `sqlite3` as the older-Node fallback. |
|
|
33
33
|
| Pi / Oh My Pi | `~/.pi/agent/sessions/` and `~/.omp/agent/sessions/` JSONL, including provider, cache-write, and session metadata. |
|
|
34
34
|
| Trae CN | `aiusage trae sync --edition cn` reads local history through Trae's official `ai-agent` RPC and writes a privacy-minimized cache under `~/.aiusage/trae-cache/sessions/`. The encrypted SQLCipher database is never opened directly. |
|
|
35
35
|
| Trae / Trae Solo (international) | `aiusage trae sync --edition intl` reads the older plain-JSON or decrypts the newer desktop credential format, then queries Trae's official account usage API once; IDE and Solo share the same account-level data. Numeric session data is cached under `~/.aiusage/trae-cache/intl/sessions/`. Existing tokscale caches under `~/.config/tokscale/trae-cache/sessions/` remain compatible and are deduplicated by session. |
|
|
@@ -239,6 +239,7 @@ aiusage config set emoji false # disable emoji in repor
|
|
|
239
239
|
aiusage config set device.alias "MacBook Pro 工作机" # device display name on dashboard
|
|
240
240
|
aiusage config set privacy.projectVisibility masked # hidden | masked | plain
|
|
241
241
|
aiusage config set project.alias MyApp "我的应用" # prefer: aiusage project alias
|
|
242
|
+
aiusage config set scanner.opencodeDbPaths "/custom/opencode-next.db" # extra OpenCode DB
|
|
242
243
|
aiusage config set anthropic-admin-key sk-ant-admin... # for aiusage import
|
|
243
244
|
```
|
|
244
245
|
|
package/README.zh-CN.md
CHANGED
|
@@ -14,6 +14,17 @@ Kimi 同时支持旧版 Kimi CLI 的 `~/.kimi/sessions/` 与新版 Kimi Code 的
|
|
|
14
14
|
`wire.jsonl` 中的 Token 计数与会话元数据,不上传对话正文;新版格式参考了
|
|
15
15
|
[tokscale](https://github.com/junhoyeo/tokscale) 的 MIT 开源实现。
|
|
16
16
|
|
|
17
|
+
OpenCode 同时读取 XDG 数据目录中的全部 `opencode*.db`:兼容 v1 `message`
|
|
18
|
+
与 v2 `session_message`,并保留旧版 `storage/message/*.json` 兜底。扫描器会对
|
|
19
|
+
多渠道数据库、迁移期双写和 fork 副本去重,采用消息内的供应商费用。支持
|
|
20
|
+
`XDG_DATA_HOME` 与 `OPENCODE_DB`。Node 22.13+ 使用内置只读 SQLite;更早的
|
|
21
|
+
受支持 Node 版本回退系统 `sqlite3`。数据库位于其他自定义目录时可配置:
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
aiusage config set scanner.opencodeDbPaths "/custom/opencode-next.db" "/custom/opencode-stable.db"
|
|
25
|
+
aiusage config set scanner.opencodeDbPaths default # 清除自定义路径
|
|
26
|
+
```
|
|
27
|
+
|
|
17
28
|
Trae CN 通过 `aiusage trae sync --edition cn` 调用 Trae 自己的本地 `ai-agent`
|
|
18
29
|
接口读取历史 Token 计数,缓存到 `~/.aiusage/trae-cache/sessions/`;不会直接破解
|
|
19
30
|
加密数据库。国际版通过 `--edition intl` 在本机读取 Trae IDE 或 Trae Solo 的登录
|
|
@@ -227,6 +238,7 @@ aiusage config set emoji false # 禁用报告标题 emo
|
|
|
227
238
|
aiusage config set device.alias "MacBook Pro 工作机" # Dashboard 上显示的设备名称
|
|
228
239
|
aiusage config set privacy.projectVisibility masked # hidden | masked | plain
|
|
229
240
|
aiusage config set project.alias MyApp "我的应用" # 推荐用 aiusage project alias
|
|
241
|
+
aiusage config set scanner.opencodeDbPaths "/custom/opencode-next.db" # 额外 OpenCode 数据库
|
|
230
242
|
aiusage config set anthropic-admin-key sk-ant-admin... # 用于 aiusage import
|
|
231
243
|
```
|
|
232
244
|
|
package/THIRD_PARTY_NOTICES.md
CHANGED
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
## tokscale
|
|
4
4
|
|
|
5
|
-
Portions of the Kimi and
|
|
6
|
-
and Trae account usage synchronization are adapted from
|
|
5
|
+
Portions of the Kimi, Trae, and OpenCode local usage parsers, Trae credential
|
|
6
|
+
decryption, and Trae account usage synchronization are adapted from
|
|
7
7
|
[junhoyeo/tokscale](https://github.com/junhoyeo/tokscale).
|
|
8
8
|
|
|
9
9
|
MIT License
|
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
|
-
|
|
3050
|
-
|
|
3051
|
-
return
|
|
3085
|
+
return result;
|
|
3086
|
+
}
|
|
3087
|
+
function isOpenCodeDatabaseFilename(name) {
|
|
3088
|
+
return /^opencode(?:-[A-Za-z0-9._-]+)?\.db$/.test(name);
|
|
3052
3089
|
}
|
|
3053
|
-
async function
|
|
3054
|
-
|
|
3055
|
-
|
|
3056
|
-
result.add(dateKey(record.timestamp));
|
|
3057
|
-
for (let filePath of await walkFiles(legacyDir, ".json"))
|
|
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)
|
|
3096
3158
|
try {
|
|
3097
|
-
let
|
|
3098
|
-
|
|
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)
|
|
3207
|
+
try {
|
|
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,18 +3462,18 @@ 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");
|
|
3267
3473
|
}
|
|
3268
3474
|
function resolveTraeIntlCacheDir(home = homedir14()) {
|
|
3269
3475
|
let explicit = process.env.AIUSAGE_TRAE_INTL_CACHE_DIR?.trim();
|
|
3270
|
-
return explicit ?
|
|
3476
|
+
return explicit ? resolve3(explicit) : join15(home, ".aiusage", "trae-cache", "intl", "sessions");
|
|
3271
3477
|
}
|
|
3272
3478
|
async function scanTraeDates(targetDates, options = {}) {
|
|
3273
3479
|
let dates = new Set(targetDates);
|
|
@@ -3499,7 +3705,13 @@ async function scanDates(targetDates, options = {}) {
|
|
|
3499
3705
|
{ products: ["kimi-code"], scan: () => scanKimiDates(uniqueDates, void 0, options.projectAliases) },
|
|
3500
3706
|
{ products: ["amp"], scan: () => scanAmpDates(uniqueDates, void 0, options.projectAliases) },
|
|
3501
3707
|
{ products: ["droid"], scan: () => scanDroidDates(uniqueDates, void 0, options.projectAliases) },
|
|
3502
|
-
{
|
|
3708
|
+
{
|
|
3709
|
+
products: ["opencode"],
|
|
3710
|
+
scan: () => scanOpencodeDates(uniqueDates, {
|
|
3711
|
+
projectAliases: options.projectAliases,
|
|
3712
|
+
dbPaths: options.opencodeDbPaths
|
|
3713
|
+
})
|
|
3714
|
+
},
|
|
3503
3715
|
{ products: ["pi"], scan: () => scanPiDates(uniqueDates, void 0, options.projectAliases) },
|
|
3504
3716
|
{
|
|
3505
3717
|
products: ["trae-cn", "trae-intl", "trae"],
|
|
@@ -3680,12 +3892,13 @@ function parseCsv(content) {
|
|
|
3680
3892
|
}
|
|
3681
3893
|
|
|
3682
3894
|
// src/report.ts
|
|
3683
|
-
import { readdir as
|
|
3895
|
+
import { readdir as readdir6, readFile as readFile14 } from "node:fs/promises";
|
|
3684
3896
|
import { homedir as homedir15 } from "node:os";
|
|
3685
|
-
import { basename as basename11, dirname as
|
|
3897
|
+
import { basename as basename11, dirname as dirname7, join as join16 } from "node:path";
|
|
3686
3898
|
async function buildLocalReport(range, options = {}) {
|
|
3687
|
-
let requestedDates = options.dates ? options.dates : range === "all" ? await discoverAllDates(options.tools) : range === "today" ? [dateKey(getTodayLocalDate())] : buildPresetDates(range), daily = [], totals = createEmptyTotals2(), bySource = /* @__PURE__ */ new Map(), byModel = /* @__PURE__ */ new Map(), pricingWarnings = /* @__PURE__ */ new Set(), daysWithData = 0, results = await scanDates(requestedDates, {
|
|
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, {
|
|
3688
3900
|
projectAliases: options.projectAliases,
|
|
3901
|
+
opencodeDbPaths: options.opencodeDbPaths,
|
|
3689
3902
|
tools: options.tools
|
|
3690
3903
|
});
|
|
3691
3904
|
for (let result of results) {
|
|
@@ -3755,9 +3968,9 @@ function buildPresetDates(range) {
|
|
|
3755
3968
|
}
|
|
3756
3969
|
return result;
|
|
3757
3970
|
}
|
|
3758
|
-
async function discoverAllDates(tools) {
|
|
3971
|
+
async function discoverAllDates(tools, opencodeDbPaths) {
|
|
3759
3972
|
let dates = /* @__PURE__ */ new Set(), home = homedir15(), selected = tools ? new Set(tools) : null, includes = (...products) => !selected || products.some((product) => selected.has(product)), discoveries = [];
|
|
3760
|
-
includes("claude-code") && discoveries.push(discoverClaudeDates(dates)), includes("codex") && discoveries.push(discoverCodexDates(dates)), includes("gemini-cli") && discoveries.push(discoverGeminiDates(dates)), includes("copilot-vscode") && discoveries.push(discoverCopilotVscodeDates(dates)), includes("antigravity") && discoveries.push(discoverAntigravityDates(dates)), includes("copilot-cli") && (discoveries.push(discoverGenericJsonlDates(join16(home, ".copilot", "session-state"), dates)), discoveries.push(discoverGenericJsonlDates(join16(home, ".copilot", "otel"), dates))), includes("qwen-code") && (discoveries.push(discoverGenericJsonlDates(join16(home, ".qwen", "tmp"), dates)), discoveries.push(discoverGenericJsonlDates(join16(home, ".qwen", "projects"), dates))), includes("kimi-code") && (discoveries.push(discoverGenericJsonlDates(join16(home, ".kimi", "sessions"), dates)), discoveries.push(discoverGenericJsonlDates(join16(resolveKimiCodeHome(home), "sessions"), dates))), includes("amp") && discoveries.push(discoverGenericJsonDates(join16(home, ".local", "share", "amp", "threads"), dates)), includes("droid") && discoveries.push(discoverGenericJsonDates(join16(home, ".factory", "sessions"), dates)), includes("opencode") && discoveries.push(discoverOpenCodeUsageDates().then((found) => {
|
|
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) => {
|
|
3761
3974
|
found.forEach((date) => dates.add(date));
|
|
3762
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);
|
|
3763
3976
|
let explicitCopilotOtel = process.env.COPILOT_OTEL_FILE_EXPORTER_PATH?.trim();
|
|
@@ -3869,7 +4082,7 @@ async function addFileModifiedDate(filePath, dates) {
|
|
|
3869
4082
|
async function walkForFiles(dir, ext, result) {
|
|
3870
4083
|
let entries;
|
|
3871
4084
|
try {
|
|
3872
|
-
entries = await
|
|
4085
|
+
entries = await readdir6(dir, { withFileTypes: !0 });
|
|
3873
4086
|
} catch {
|
|
3874
4087
|
return;
|
|
3875
4088
|
}
|
|
@@ -3948,7 +4161,7 @@ async function discoverCopilotVscodeDates(dates) {
|
|
|
3948
4161
|
}
|
|
3949
4162
|
}
|
|
3950
4163
|
function isChatSessionFile2(filePath) {
|
|
3951
|
-
return basename11(
|
|
4164
|
+
return basename11(dirname7(filePath)) === "chatSessions";
|
|
3952
4165
|
}
|
|
3953
4166
|
async function discoverAntigravityDates(dates) {
|
|
3954
4167
|
let home = homedir15(), brainFiles = [], browserFiles = [];
|
|
@@ -3988,7 +4201,7 @@ async function discoverClaudeDates(dates) {
|
|
|
3988
4201
|
for (let baseDir of baseDirs) {
|
|
3989
4202
|
let projectDirs;
|
|
3990
4203
|
try {
|
|
3991
|
-
projectDirs = await
|
|
4204
|
+
projectDirs = await readdir6(baseDir);
|
|
3992
4205
|
} catch {
|
|
3993
4206
|
continue;
|
|
3994
4207
|
}
|
|
@@ -4041,7 +4254,7 @@ async function discoverCodexDates(dates) {
|
|
|
4041
4254
|
async function collectCodexSessionFiles(baseDir) {
|
|
4042
4255
|
let paths = [];
|
|
4043
4256
|
try {
|
|
4044
|
-
let archivedFiles = await
|
|
4257
|
+
let archivedFiles = await readdir6(join16(baseDir, "archived_sessions"));
|
|
4045
4258
|
for (let file of archivedFiles)
|
|
4046
4259
|
file.endsWith(".jsonl") && paths.push(join16(baseDir, "archived_sessions", file));
|
|
4047
4260
|
} catch {
|
|
@@ -4049,7 +4262,7 @@ async function collectCodexSessionFiles(baseDir) {
|
|
|
4049
4262
|
return await walkForCodexJsonl(join16(baseDir, "sessions"), paths), paths;
|
|
4050
4263
|
}
|
|
4051
4264
|
async function walkForClaudeJsonl(dir, result) {
|
|
4052
|
-
let entries = await
|
|
4265
|
+
let entries = await readdir6(dir, { withFileTypes: !0 });
|
|
4053
4266
|
for (let entry of entries) {
|
|
4054
4267
|
let fullPath = join16(dir, entry.name);
|
|
4055
4268
|
entry.isDirectory() ? await walkForClaudeJsonl(fullPath, result) : entry.name.endsWith(".jsonl") && result.push(fullPath);
|
|
@@ -4058,7 +4271,7 @@ async function walkForClaudeJsonl(dir, result) {
|
|
|
4058
4271
|
async function walkForCodexJsonl(dir, result) {
|
|
4059
4272
|
let entries;
|
|
4060
4273
|
try {
|
|
4061
|
-
entries = await
|
|
4274
|
+
entries = await readdir6(dir, { withFileTypes: !0 });
|
|
4062
4275
|
} catch {
|
|
4063
4276
|
return;
|
|
4064
4277
|
}
|
|
@@ -4120,7 +4333,7 @@ function toBreakdownTotals(breakdown, warnings, pricingCatalog) {
|
|
|
4120
4333
|
};
|
|
4121
4334
|
}
|
|
4122
4335
|
function calculateBreakdownCost(breakdown, warnings, pricingCatalog) {
|
|
4123
|
-
let effectivePricingVersion = pricingCatalog?.version ?? PRICING_VERSION, sourceCostMatchesCatalog = breakdown.product === "trae-intl" || 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;
|
|
4124
4337
|
if (breakdown.costUSD != null && breakdown.costUSD > 0 && sourceCostMatchesCatalog)
|
|
4125
4338
|
return breakdown.costUSD;
|
|
4126
4339
|
let result = calculateCost(
|
|
@@ -4353,7 +4566,7 @@ function fmtDateShort(dateStr) {
|
|
|
4353
4566
|
}
|
|
4354
4567
|
|
|
4355
4568
|
// src/activity.ts
|
|
4356
|
-
import { open, readdir as
|
|
4569
|
+
import { open, readdir as readdir7 } from "node:fs/promises";
|
|
4357
4570
|
import { createInterface as createInterface3 } from "node:readline";
|
|
4358
4571
|
import { homedir as homedir16 } from "node:os";
|
|
4359
4572
|
import { basename as basename12, join as join17 } from "node:path";
|
|
@@ -4608,7 +4821,7 @@ async function scanClaudeActivity(targetDates, options) {
|
|
|
4608
4821
|
for (let baseDir of getClaudeProjectDirs2(options.claudeProjectsDirs)) {
|
|
4609
4822
|
let projectDirs;
|
|
4610
4823
|
try {
|
|
4611
|
-
projectDirs = await
|
|
4824
|
+
projectDirs = await readdir7(baseDir, { withFileTypes: !0 });
|
|
4612
4825
|
} catch {
|
|
4613
4826
|
continue;
|
|
4614
4827
|
}
|
|
@@ -4752,7 +4965,7 @@ function acceptsDate(acc, usageDate) {
|
|
|
4752
4965
|
async function collectCodexSessionFiles2(baseDir) {
|
|
4753
4966
|
let paths = [];
|
|
4754
4967
|
try {
|
|
4755
|
-
let files = await
|
|
4968
|
+
let files = await readdir7(join17(baseDir, "archived_sessions"));
|
|
4756
4969
|
for (let file of files)
|
|
4757
4970
|
file.endsWith(".jsonl") && paths.push(join17(baseDir, "archived_sessions", file));
|
|
4758
4971
|
} catch {
|
|
@@ -4773,7 +4986,7 @@ function getClaudeProjectDirs2(configured) {
|
|
|
4773
4986
|
async function walkJsonl(dir, result) {
|
|
4774
4987
|
let entries;
|
|
4775
4988
|
try {
|
|
4776
|
-
entries = await
|
|
4989
|
+
entries = await readdir7(dir, { withFileTypes: !0 });
|
|
4777
4990
|
} catch {
|
|
4778
4991
|
return;
|
|
4779
4992
|
}
|
|
@@ -4955,6 +5168,7 @@ function migrateConfig(config) {
|
|
|
4955
5168
|
projectAliases: config.projectAliases,
|
|
4956
5169
|
privacy: config.privacy,
|
|
4957
5170
|
pricing: config.pricing,
|
|
5171
|
+
scanner: config.scanner,
|
|
4958
5172
|
lang: config.lang,
|
|
4959
5173
|
emoji: config.emoji,
|
|
4960
5174
|
targets: [target]
|
|
@@ -5026,6 +5240,12 @@ function setConfigValue(config, keyPath, values) {
|
|
|
5026
5240
|
...next.pricing ?? {},
|
|
5027
5241
|
cacheTtlHours: parsePositiveInt(requireSingleValue(keyPath, values), keyPath)
|
|
5028
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
|
+
}
|
|
5029
5249
|
if (keyPath === "project.alias") {
|
|
5030
5250
|
if (values.length < 2)
|
|
5031
5251
|
throw new Error("project.alias \u9700\u8981\u4E24\u4E2A\u53C2\u6570\uFF1A\u539F\u59CB\u8DEF\u5F84/\u540D\u79F0 \u4E0E \u522B\u540D");
|
|
@@ -5070,13 +5290,13 @@ import { hostname as hostname2 } from "node:os";
|
|
|
5070
5290
|
|
|
5071
5291
|
// src/version.ts
|
|
5072
5292
|
import { readFileSync } from "node:fs";
|
|
5073
|
-
import { resolve as
|
|
5293
|
+
import { resolve as resolve4, dirname as dirname8 } from "node:path";
|
|
5074
5294
|
import { fileURLToPath } from "node:url";
|
|
5075
5295
|
var cached;
|
|
5076
5296
|
function getVersion() {
|
|
5077
5297
|
if (cached !== void 0) return cached;
|
|
5078
5298
|
try {
|
|
5079
|
-
let pkg =
|
|
5299
|
+
let pkg = resolve4(dirname8(fileURLToPath(import.meta.url)), "..", "package.json");
|
|
5080
5300
|
cached = JSON.parse(readFileSync(pkg, "utf-8")).version;
|
|
5081
5301
|
} catch {
|
|
5082
5302
|
cached = "unknown";
|
|
@@ -5149,11 +5369,11 @@ async function requestJson(url, init) {
|
|
|
5149
5369
|
}
|
|
5150
5370
|
|
|
5151
5371
|
// src/schedule.ts
|
|
5152
|
-
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";
|
|
5153
5373
|
import { execFile as execFile2 } from "node:child_process";
|
|
5154
5374
|
import { promisify } from "node:util";
|
|
5155
5375
|
import { homedir as homedir18, platform, tmpdir as tmpdir2 } from "node:os";
|
|
5156
|
-
import { join as join19, resolve as
|
|
5376
|
+
import { join as join19, resolve as resolve5 } from "node:path";
|
|
5157
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";
|
|
5158
5378
|
function parseInterval(value) {
|
|
5159
5379
|
let match = value.match(/^(\d+)(m|h|d)$/);
|
|
@@ -5189,7 +5409,7 @@ async function getScheduleStatus() {
|
|
|
5189
5409
|
return platform() === "darwin" ? getLaunchdStatus() : getCronStatus();
|
|
5190
5410
|
}
|
|
5191
5411
|
function resolveCommandPaths() {
|
|
5192
|
-
let scriptPath =
|
|
5412
|
+
let scriptPath = resolve5(process.argv[1]);
|
|
5193
5413
|
if (scriptPath.includes("_npx") || scriptPath.includes("/npx-"))
|
|
5194
5414
|
throw new Error(
|
|
5195
5415
|
`\u68C0\u6D4B\u5230\u901A\u8FC7 npx \u8FD0\u884C\uFF0C\u5B9A\u65F6\u4EFB\u52A1\u9700\u8981\u5168\u5C40\u5B89\u88C5\u3002
|
|
@@ -5248,7 +5468,7 @@ async function disableLaunchd() {
|
|
|
5248
5468
|
}
|
|
5249
5469
|
async function getLaunchdStatus() {
|
|
5250
5470
|
try {
|
|
5251
|
-
await
|
|
5471
|
+
await stat4(PLIST_PATH);
|
|
5252
5472
|
} catch {
|
|
5253
5473
|
return { enabled: !1 };
|
|
5254
5474
|
}
|
|
@@ -5358,7 +5578,7 @@ function escapeXml(value) {
|
|
|
5358
5578
|
}
|
|
5359
5579
|
|
|
5360
5580
|
// src/doctor.ts
|
|
5361
|
-
import { readdir as
|
|
5581
|
+
import { readdir as readdir8, stat as stat5 } from "node:fs/promises";
|
|
5362
5582
|
import { homedir as homedir19 } from "node:os";
|
|
5363
5583
|
import { join as join20 } from "node:path";
|
|
5364
5584
|
var msgs = {
|
|
@@ -5381,6 +5601,8 @@ var msgs = {
|
|
|
5381
5601
|
notInstalled: "Not installed",
|
|
5382
5602
|
installedNoData: "Installed, no usage data yet",
|
|
5383
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",
|
|
5384
5606
|
schedule: "Schedule",
|
|
5385
5607
|
scheduleEvery: "every",
|
|
5386
5608
|
scheduleEnabled: "Enabled",
|
|
@@ -5405,6 +5627,8 @@ var msgs = {
|
|
|
5405
5627
|
notInstalled: "\u672A\u5B89\u88C5",
|
|
5406
5628
|
installedNoData: "\u5DF2\u5B89\u88C5\uFF0C\u6682\u65E0\u4F7F\u7528\u6570\u636E",
|
|
5407
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",
|
|
5408
5632
|
schedule: "\u5B9A\u65F6\u540C\u6B65",
|
|
5409
5633
|
scheduleEvery: "\u6BCF",
|
|
5410
5634
|
scheduleEnabled: "\u5DF2\u542F\u7528",
|
|
@@ -5416,7 +5640,7 @@ async function countFiles(dir, exts, cap = 1e3) {
|
|
|
5416
5640
|
for (; queue.length > 0 && count < cap; ) {
|
|
5417
5641
|
let current = queue.pop(), entries;
|
|
5418
5642
|
try {
|
|
5419
|
-
entries = await
|
|
5643
|
+
entries = await readdir8(current, { withFileTypes: !0 });
|
|
5420
5644
|
} catch {
|
|
5421
5645
|
continue;
|
|
5422
5646
|
}
|
|
@@ -5431,7 +5655,7 @@ async function countFiles(dir, exts, cap = 1e3) {
|
|
|
5431
5655
|
async function runDoctor(lang = "zh") {
|
|
5432
5656
|
let s = msgs[lang], checks = [], config = await readConfig(), g1 = s.groupConfig, configPath = getConfigPath();
|
|
5433
5657
|
try {
|
|
5434
|
-
await
|
|
5658
|
+
await stat5(configPath), checks.push({ group: g1, name: s.config, status: "ok", message: configPath });
|
|
5435
5659
|
} catch {
|
|
5436
5660
|
checks.push({ group: g1, name: s.config, status: "fail", message: s.configMissing });
|
|
5437
5661
|
}
|
|
@@ -5471,7 +5695,6 @@ async function runDoctor(lang = "zh") {
|
|
|
5471
5695
|
{ dirs: [join20(home, ".kimi", "sessions")], label: "Kimi CLI (legacy)", exts: [".jsonl"] },
|
|
5472
5696
|
{ dirs: [join20(home, ".local", "share", "amp", "threads")], label: "Amp", exts: [".json"] },
|
|
5473
5697
|
{ dirs: [join20(home, ".factory", "sessions")], label: "Droid", exts: [".settings.json"] },
|
|
5474
|
-
{ dirs: [join20(home, ".local", "share", "opencode")], label: "OpenCode", exts: [".db", ".json"] },
|
|
5475
5698
|
{ dirs: [join20(home, ".pi", "agent", "sessions"), join20(home, ".omp", "agent", "sessions")], label: "Pi / OMP", exts: [".jsonl"] },
|
|
5476
5699
|
{ dirs: [resolveTraeNativeCacheDir(home), resolveTokscaleTraeCacheDir(home)], label: "Trae", exts: [".json"] }
|
|
5477
5700
|
];
|
|
@@ -5479,7 +5702,7 @@ async function runDoctor(lang = "zh") {
|
|
|
5479
5702
|
let installed = !1, n = 0;
|
|
5480
5703
|
for (let dir of tool.dirs)
|
|
5481
5704
|
try {
|
|
5482
|
-
await
|
|
5705
|
+
await stat5(dir), installed = !0, n += await countFiles(dir, tool.exts);
|
|
5483
5706
|
} catch {
|
|
5484
5707
|
}
|
|
5485
5708
|
if (!installed) {
|
|
@@ -5488,6 +5711,25 @@ async function runDoctor(lang = "zh") {
|
|
|
5488
5711
|
}
|
|
5489
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 });
|
|
5490
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 });
|
|
5491
5733
|
let g4 = s.groupSchedule, schedule = await getScheduleStatus();
|
|
5492
5734
|
return schedule.enabled ? checks.push({
|
|
5493
5735
|
group: g4,
|
|
@@ -5498,7 +5740,7 @@ async function runDoctor(lang = "zh") {
|
|
|
5498
5740
|
}
|
|
5499
5741
|
|
|
5500
5742
|
// src/project.ts
|
|
5501
|
-
import { open as open2, readdir as
|
|
5743
|
+
import { open as open2, readdir as readdir9, readFile as readFile17 } from "node:fs/promises";
|
|
5502
5744
|
import { basename as basename14, join as join21 } from "node:path";
|
|
5503
5745
|
import { homedir as homedir20 } from "node:os";
|
|
5504
5746
|
async function discoverProjects(projectAliases) {
|
|
@@ -5548,7 +5790,7 @@ async function discoverClaudeProjects() {
|
|
|
5548
5790
|
for (let baseDir of getClaudeDirs()) {
|
|
5549
5791
|
let entries;
|
|
5550
5792
|
try {
|
|
5551
|
-
entries = await
|
|
5793
|
+
entries = await readdir9(baseDir, { withFileTypes: !0 });
|
|
5552
5794
|
} catch {
|
|
5553
5795
|
continue;
|
|
5554
5796
|
}
|
|
@@ -5593,7 +5835,7 @@ async function walkFiles2(dir, ext) {
|
|
|
5593
5835
|
async function walk2(d) {
|
|
5594
5836
|
let entries;
|
|
5595
5837
|
try {
|
|
5596
|
-
entries = await
|
|
5838
|
+
entries = await readdir9(d, { withFileTypes: !0 });
|
|
5597
5839
|
} catch {
|
|
5598
5840
|
return;
|
|
5599
5841
|
}
|
|
@@ -5635,7 +5877,7 @@ async function extractCwdFromFirstJsonl(dir) {
|
|
|
5635
5877
|
async function findFirstJsonl(dir) {
|
|
5636
5878
|
let entries;
|
|
5637
5879
|
try {
|
|
5638
|
-
entries = await
|
|
5880
|
+
entries = await readdir9(dir, { withFileTypes: !0 });
|
|
5639
5881
|
} catch {
|
|
5640
5882
|
return;
|
|
5641
5883
|
}
|
|
@@ -5644,7 +5886,7 @@ async function findFirstJsonl(dir) {
|
|
|
5644
5886
|
for (let entry of entries)
|
|
5645
5887
|
if (!(!entry.isDirectory() || entry.name.startsWith(".")))
|
|
5646
5888
|
try {
|
|
5647
|
-
let sub = (await
|
|
5889
|
+
let sub = (await readdir9(join21(dir, entry.name))).find((f) => f.endsWith(".jsonl"));
|
|
5648
5890
|
if (sub) return join21(dir, entry.name, sub);
|
|
5649
5891
|
} catch {
|
|
5650
5892
|
continue;
|
|
@@ -5724,7 +5966,7 @@ async function discoverCopilotVscodeProjects() {
|
|
|
5724
5966
|
async function discoverAntigravityProjects() {
|
|
5725
5967
|
let dir = join21(homedir20(), ".gemini", "antigravity", "knowledge"), entries;
|
|
5726
5968
|
try {
|
|
5727
|
-
entries = await
|
|
5969
|
+
entries = await readdir9(dir, { withFileTypes: !0 });
|
|
5728
5970
|
} catch {
|
|
5729
5971
|
return [];
|
|
5730
5972
|
}
|
|
@@ -5960,7 +6202,7 @@ function assertPricingCatalog(value) {
|
|
|
5960
6202
|
import { execFile as execFile3 } from "node:child_process";
|
|
5961
6203
|
import { createHash as createHash2 } from "node:crypto";
|
|
5962
6204
|
import { existsSync as existsSync2 } from "node:fs";
|
|
5963
|
-
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";
|
|
5964
6206
|
import { createServer } from "node:net";
|
|
5965
6207
|
import { homedir as homedir22 } from "node:os";
|
|
5966
6208
|
import { join as join23 } from "node:path";
|
|
@@ -6197,12 +6439,12 @@ var CdpClient = class _CdpClient {
|
|
|
6197
6439
|
pending = /* @__PURE__ */ new Map();
|
|
6198
6440
|
static async connect(url, timeoutMs) {
|
|
6199
6441
|
let socket = new WebSocket(url);
|
|
6200
|
-
return await new Promise((
|
|
6442
|
+
return await new Promise((resolve6, reject) => {
|
|
6201
6443
|
let timer = setTimeout(() => {
|
|
6202
6444
|
socket.close(), reject(new Error("\u8FDE\u63A5 Trae CN \u672C\u5730\u63A5\u53E3\u8D85\u65F6"));
|
|
6203
6445
|
}, timeoutMs);
|
|
6204
6446
|
socket.once("open", () => {
|
|
6205
|
-
clearTimeout(timer),
|
|
6447
|
+
clearTimeout(timer), resolve6();
|
|
6206
6448
|
}), socket.once("error", (error) => {
|
|
6207
6449
|
clearTimeout(timer), reject(error);
|
|
6208
6450
|
});
|
|
@@ -6210,11 +6452,11 @@ var CdpClient = class _CdpClient {
|
|
|
6210
6452
|
}
|
|
6211
6453
|
call(method, params, timeoutMs) {
|
|
6212
6454
|
let id = ++this.sequence;
|
|
6213
|
-
return new Promise((
|
|
6455
|
+
return new Promise((resolve6, reject) => {
|
|
6214
6456
|
let timer = setTimeout(() => {
|
|
6215
6457
|
this.pending.delete(id), reject(new Error(`Trae CN \u672C\u5730\u8C03\u7528\u8D85\u65F6: ${method}`));
|
|
6216
6458
|
}, timeoutMs);
|
|
6217
|
-
this.pending.set(id, { resolve:
|
|
6459
|
+
this.pending.set(id, { resolve: resolve6, reject, timer }), this.socket.send(JSON.stringify({ id, method, params }));
|
|
6218
6460
|
});
|
|
6219
6461
|
}
|
|
6220
6462
|
close() {
|
|
@@ -6271,7 +6513,7 @@ async function findTraeUserIds(userDataDir) {
|
|
|
6271
6513
|
async function findCompletionLogs(dir) {
|
|
6272
6514
|
let entries;
|
|
6273
6515
|
try {
|
|
6274
|
-
entries = await
|
|
6516
|
+
entries = await readdir10(dir, { withFileTypes: !0 });
|
|
6275
6517
|
} catch {
|
|
6276
6518
|
return [];
|
|
6277
6519
|
}
|
|
@@ -6281,7 +6523,7 @@ async function findCompletionLogs(dir) {
|
|
|
6281
6523
|
if (entry.isDirectory()) files.push(...await findCompletionLogs(path));
|
|
6282
6524
|
else if (entry.name === "completion.log" && path.includes("trae.ai-code-completion"))
|
|
6283
6525
|
try {
|
|
6284
|
-
files.push({ path, mtimeMs: (await
|
|
6526
|
+
files.push({ path, mtimeMs: (await stat6(path)).mtimeMs });
|
|
6285
6527
|
} catch {
|
|
6286
6528
|
}
|
|
6287
6529
|
}
|
|
@@ -6340,17 +6582,17 @@ async function isTraeRunning() {
|
|
|
6340
6582
|
}
|
|
6341
6583
|
}
|
|
6342
6584
|
async function isPortAvailable(port) {
|
|
6343
|
-
return new Promise((
|
|
6585
|
+
return new Promise((resolve6) => {
|
|
6344
6586
|
let server = createServer();
|
|
6345
|
-
server.once("error", () =>
|
|
6587
|
+
server.once("error", () => resolve6(!1)), server.listen(port, "127.0.0.1", () => server.close(() => resolve6(!0)));
|
|
6346
6588
|
});
|
|
6347
6589
|
}
|
|
6348
6590
|
async function findFreePort() {
|
|
6349
|
-
return new Promise((
|
|
6591
|
+
return new Promise((resolve6, reject) => {
|
|
6350
6592
|
let server = createServer();
|
|
6351
6593
|
server.once("error", reject), server.listen(0, "127.0.0.1", () => {
|
|
6352
6594
|
let address = server.address(), port = typeof address == "object" && address ? address.port : 0;
|
|
6353
|
-
server.close((error) => error ? reject(error) :
|
|
6595
|
+
server.close((error) => error ? reject(error) : resolve6(port));
|
|
6354
6596
|
});
|
|
6355
6597
|
});
|
|
6356
6598
|
}
|
|
@@ -6383,7 +6625,7 @@ function stringValue4(value) {
|
|
|
6383
6625
|
return typeof value == "string" ? value.trim() : "";
|
|
6384
6626
|
}
|
|
6385
6627
|
function delay(ms) {
|
|
6386
|
-
return new Promise((
|
|
6628
|
+
return new Promise((resolve6) => setTimeout(resolve6, ms));
|
|
6387
6629
|
}
|
|
6388
6630
|
|
|
6389
6631
|
// src/trae-intl-sync.ts
|
|
@@ -6391,13 +6633,13 @@ import { createDecipheriv, createHash as createHash3, timingSafeEqual } from "no
|
|
|
6391
6633
|
import { existsSync as existsSync3 } from "node:fs";
|
|
6392
6634
|
import { chmod, mkdir as mkdir5, open as open4, readFile as readFile20, rename as rename2, unlink as unlink2 } from "node:fs/promises";
|
|
6393
6635
|
import { homedir as homedir23 } from "node:os";
|
|
6394
|
-
import { dirname as
|
|
6636
|
+
import { dirname as dirname9, join as join24 } from "node:path";
|
|
6395
6637
|
var DEFAULT_HOST = "https://api-sg-central.trae.ai", CLIENT_IDS = {
|
|
6396
6638
|
ide: "ono9krqynydwx5",
|
|
6397
6639
|
solo: "en1oxy7wnw8j9n"
|
|
6398
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;
|
|
6399
6641
|
async function syncTraeIntlUsage(options = {}) {
|
|
6400
|
-
let sinceDays = normalizeSinceDays(options.sinceDays), cacheDir = options.cacheDir ?? resolveTraeIntlCacheDir(), fetchImpl = options.fetchImpl ?? fetch, now = options.now ?? /* @__PURE__ */ new Date(), releaseLock = await acquireTraeIntlSyncLock(
|
|
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));
|
|
6401
6643
|
try {
|
|
6402
6644
|
return await performTraeIntlSync(options, sinceDays, cacheDir, fetchImpl, now);
|
|
6403
6645
|
} finally {
|
|
@@ -6657,10 +6899,10 @@ async function requestJson2(url, init, fetchImpl, timeoutMs) {
|
|
|
6657
6899
|
}
|
|
6658
6900
|
}
|
|
6659
6901
|
async function loadCredentials(variant, cacheDir) {
|
|
6660
|
-
return readCredentialFile(join24(
|
|
6902
|
+
return readCredentialFile(join24(dirname9(cacheDir), `credentials-${variant}.json`), variant);
|
|
6661
6903
|
}
|
|
6662
6904
|
async function loadTokscaleCredentials(variant) {
|
|
6663
|
-
let root =
|
|
6905
|
+
let root = dirname9(resolveTokscaleTraeCacheDir());
|
|
6664
6906
|
return readCredentialFile(join24(root, `credentials-${variant}.json`), variant);
|
|
6665
6907
|
}
|
|
6666
6908
|
async function readCredentialFile(path, fallbackVariant) {
|
|
@@ -6683,7 +6925,7 @@ async function readCredentialFile(path, fallbackVariant) {
|
|
|
6683
6925
|
}
|
|
6684
6926
|
}
|
|
6685
6927
|
async function saveCredentials(credentials, cacheDir) {
|
|
6686
|
-
let path = join24(
|
|
6928
|
+
let path = join24(dirname9(cacheDir), `credentials-${credentials.variant}.json`);
|
|
6687
6929
|
await writePrivateJson(path, credentials);
|
|
6688
6930
|
}
|
|
6689
6931
|
async function readSessionArray(path) {
|
|
@@ -6695,7 +6937,7 @@ async function readSessionArray(path) {
|
|
|
6695
6937
|
}
|
|
6696
6938
|
}
|
|
6697
6939
|
async function writePrivateJson(path, value) {
|
|
6698
|
-
let dir =
|
|
6940
|
+
let dir = dirname9(path);
|
|
6699
6941
|
await mkdir5(dir, { recursive: !0, mode: 448 }), await chmod(dir, 448).catch(() => {
|
|
6700
6942
|
});
|
|
6701
6943
|
let tempPath = join24(dir, `.${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}.tmp`), handle = await open4(tempPath, "w", 384);
|
|
@@ -6769,7 +7011,7 @@ function sanitizeError(error) {
|
|
|
6769
7011
|
return sanitizeResponse(parts.join(": "));
|
|
6770
7012
|
}
|
|
6771
7013
|
function delay2(ms) {
|
|
6772
|
-
return new Promise((
|
|
7014
|
+
return new Promise((resolve6) => setTimeout(resolve6, ms));
|
|
6773
7015
|
}
|
|
6774
7016
|
|
|
6775
7017
|
// src/cli.ts
|
|
@@ -6884,7 +7126,7 @@ await (async () => {
|
|
|
6884
7126
|
async function runScan(flags, positionals = []) {
|
|
6885
7127
|
let config = await readConfig(), zh2 = config.lang === "zh";
|
|
6886
7128
|
assertNoPositionals("scan", positionals, zh2);
|
|
6887
|
-
let isJson = !!flags.json, dates = resolveScanDates(flags, config), tools = parseToolSelection(flags.tool, zh2), results = dates.length === 1 ? [await scanDate(dates[0], { projectAliases: config.projectAliases, tools })] : await scanDates(dates, { projectAliases: config.projectAliases, tools });
|
|
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 });
|
|
6888
7130
|
if (isJson) {
|
|
6889
7131
|
console.log(JSON.stringify(results.length === 1 ? results[0] : results, null, 2));
|
|
6890
7132
|
return;
|
|
@@ -6930,6 +7172,7 @@ async function runReport(flags, positionals = []) {
|
|
|
6930
7172
|
target: pricingTarget
|
|
6931
7173
|
}), report = await buildLocalReport(range, {
|
|
6932
7174
|
projectAliases: config.projectAliases,
|
|
7175
|
+
opencodeDbPaths: config.scanner?.opencodeDbPaths,
|
|
6933
7176
|
dates,
|
|
6934
7177
|
tools,
|
|
6935
7178
|
pricingCatalog: pricing.catalog,
|
|
@@ -6993,9 +7236,9 @@ async function runEnroll(flags) {
|
|
|
6993
7236
|
}
|
|
6994
7237
|
function prompt(question) {
|
|
6995
7238
|
let rl = createInterface4({ input: process.stdin, output: process.stdout });
|
|
6996
|
-
return new Promise((
|
|
7239
|
+
return new Promise((resolve6) => {
|
|
6997
7240
|
rl.question(question, (answer) => {
|
|
6998
|
-
rl.close(),
|
|
7241
|
+
rl.close(), resolve6(answer.trim());
|
|
6999
7242
|
});
|
|
7000
7243
|
});
|
|
7001
7244
|
}
|
|
@@ -7011,7 +7254,10 @@ async function runSync(flags, positionals = []) {
|
|
|
7011
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");
|
|
7012
7255
|
console.log(`\u626B\u63CF ${targetDates.length} \u5929 (${targetDates[0]} ~ ${targetDates[targetDates.length - 1]}) ...`);
|
|
7013
7256
|
let [results, activityReport] = await Promise.all([
|
|
7014
|
-
scanDates(targetDates, {
|
|
7257
|
+
scanDates(targetDates, {
|
|
7258
|
+
projectAliases: config.projectAliases,
|
|
7259
|
+
opencodeDbPaths: config.scanner?.opencodeDbPaths
|
|
7260
|
+
}),
|
|
7015
7261
|
buildActivityReport("all", { dates: targetDates, projectAliases: config.projectAliases })
|
|
7016
7262
|
]), visibility = config.privacy?.projectVisibility, resultsByDate = new Map(results.map((result) => [result.usageDate, result])), activityByDate = buildActivityPayloadByDate(activityReport.items, visibility), allDays = targetDates.map((usageDate) => {
|
|
7017
7263
|
let breakdowns = applyPrivacy(resultsByDate.get(usageDate)?.breakdowns ?? [], visibility), activity = activityByDate.get(usageDate);
|