@aiusage/cli 1.7.6 → 1.7.8
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 +381 -131
- package/package.json +1 -1
- package/pricing-catalog.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
|
@@ -1310,7 +1310,7 @@ var inflection = {
|
|
|
1310
1310
|
};
|
|
1311
1311
|
|
|
1312
1312
|
// ../shared/src/pricing/catalog.ts
|
|
1313
|
-
var PRICING_VERSION = "2026-07-
|
|
1313
|
+
var PRICING_VERSION = "2026-07-20-gpt-5.6-kimi-k3-v1", aliases = {
|
|
1314
1314
|
"claude-opus-4-7-20260201": "claude-opus-4-7",
|
|
1315
1315
|
"claude-sonnet-4-6-20250301": "claude-sonnet-4-6",
|
|
1316
1316
|
"claude-opus-4-6-20250301": "claude-opus-4-6",
|
|
@@ -1976,7 +1976,11 @@ function extractSuccessEvent(line) {
|
|
|
1976
1976
|
let parts = line.split("|").map((part) => part.trim());
|
|
1977
1977
|
if (parts.length < 3 || parts[1] !== "success") return null;
|
|
1978
1978
|
let requestId = parts[0].match(/ccreq:([^.|\s]+)/)?.[1] ?? `${timestamp.getTime()}`, model = normalizeModel(parts[2]);
|
|
1979
|
-
return model ? { requestId, timestamp, model }
|
|
1979
|
+
return !model || isBackgroundRequest(parts[4], model) ? null : { requestId, timestamp, model };
|
|
1980
|
+
}
|
|
1981
|
+
function isBackgroundRequest(rawScope, model) {
|
|
1982
|
+
let scope = rawScope?.replace(/^\[|\]$/g, "").trim().toLowerCase();
|
|
1983
|
+
return scope === "xtabprovider" || scope === "settingseditorsearchsuggestions" ? !0 : model.startsWith("copilot-suggestions-") || model.startsWith("copilot-nes-") || model.startsWith("dd_");
|
|
1980
1984
|
}
|
|
1981
1985
|
function normalizeModel(raw) {
|
|
1982
1986
|
let parts = raw.split("->").map((part) => part.trim()).filter(Boolean);
|
|
@@ -3030,42 +3034,74 @@ async function extractModelFromTranscript(filePath) {
|
|
|
3030
3034
|
|
|
3031
3035
|
// src/scanners/opencode.ts
|
|
3032
3036
|
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";
|
|
3037
|
+
import { readdir as readdir5, readFile as readFile10, realpath, stat as stat3 } from "node:fs/promises";
|
|
3035
3038
|
import { homedir as homedir12 } from "node:os";
|
|
3036
|
-
|
|
3037
|
-
|
|
3038
|
-
|
|
3039
|
-
|
|
3040
|
-
|
|
3041
|
-
|
|
3042
|
-
|
|
3039
|
+
import { basename as basename9, dirname as dirname5, isAbsolute, join as join13, resolve as resolve2 } from "node:path";
|
|
3040
|
+
var nodeSqliteModulePromise, sqliteRuntimePromise;
|
|
3041
|
+
async function scanOpencodeDates(targetDates, options = {}) {
|
|
3042
|
+
let dates = new Set(targetDates), { records, sourceCount } = await loadOpenCodeRecords(options);
|
|
3043
|
+
if (sourceCount === 0) return emptyResult(dates);
|
|
3044
|
+
let grouped = initDateMap(dates), sessionsByBreakdown = /* @__PURE__ */ new Map();
|
|
3045
|
+
for (let record of records)
|
|
3046
|
+
addOpenCodeRecord(record, grouped, sessionsByBreakdown, options.projectAliases);
|
|
3047
|
+
for (let [compoundKey, sessions] of sessionsByBreakdown) {
|
|
3048
|
+
let separator = compoundKey.indexOf("\0"), usageDate = compoundKey.slice(0, separator), breakdownKey = compoundKey.slice(separator + 1), breakdown = grouped.get(usageDate)?.get(breakdownKey);
|
|
3049
|
+
breakdown && sessions.size > 0 && (breakdown.sessionCount = sessions.size);
|
|
3050
|
+
}
|
|
3051
|
+
return finalize(grouped);
|
|
3052
|
+
}
|
|
3053
|
+
async function discoverOpenCodeUsageDates(options = {}) {
|
|
3054
|
+
let result = /* @__PURE__ */ new Set(), { records } = await loadOpenCodeRecords(options);
|
|
3055
|
+
for (let record of records) result.add(dateKey(record.timestamp));
|
|
3056
|
+
return result;
|
|
3057
|
+
}
|
|
3058
|
+
function resolveOpenCodeDataDir(home = homedir12(), env = process.env) {
|
|
3059
|
+
let xdgDataHome = env.XDG_DATA_HOME?.trim();
|
|
3060
|
+
return join13(xdgDataHome || join13(home, ".local", "share"), "opencode");
|
|
3061
|
+
}
|
|
3062
|
+
async function resolveOpenCodeSources(options = {}) {
|
|
3063
|
+
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 ?? []];
|
|
3064
|
+
env.OPENCODE_DB?.trim() && configuredPaths.push(env.OPENCODE_DB.trim());
|
|
3065
|
+
let dbPaths = await discoverOpenCodeDatabases(dataDir, configuredPaths, home);
|
|
3066
|
+
return { dataDir, legacyDir, dbPaths };
|
|
3067
|
+
}
|
|
3068
|
+
async function discoverOpenCodeDatabases(dataDir, extraPaths = [], home = homedir12()) {
|
|
3069
|
+
let candidates = [];
|
|
3070
|
+
try {
|
|
3071
|
+
let entries = await readdir5(dataDir, { withFileTypes: !0 });
|
|
3072
|
+
for (let entry of entries)
|
|
3073
|
+
isOpenCodeDatabaseFilename(entry.name) && candidates.push(join13(dataDir, entry.name));
|
|
3074
|
+
} catch {
|
|
3075
|
+
}
|
|
3076
|
+
for (let rawPath of extraPaths) {
|
|
3077
|
+
let path = expandConfiguredPath(rawPath, home);
|
|
3078
|
+
path && isOpenCodeDatabaseFilename(basename9(path)) && candidates.push(path);
|
|
3079
|
+
}
|
|
3080
|
+
let result = [], seen = /* @__PURE__ */ new Set();
|
|
3081
|
+
for (let path of candidates.sort((a, b) => a.localeCompare(b)))
|
|
3043
3082
|
try {
|
|
3044
|
-
|
|
3083
|
+
if (!(await stat3(path)).isFile()) continue;
|
|
3084
|
+
let canonical = await realpath(path).catch(() => path);
|
|
3085
|
+
if (seen.has(canonical)) continue;
|
|
3086
|
+
seen.add(canonical), result.push(path);
|
|
3045
3087
|
} catch {
|
|
3046
|
-
continue;
|
|
3047
3088
|
}
|
|
3048
|
-
|
|
3049
|
-
record && addOpenCodeRecord(record, grouped, seenIds, seenFingerprints, projectAliases);
|
|
3050
|
-
}
|
|
3051
|
-
return sqliteRows.length === 0 && files.length === 0 ? emptyResult(dates) : finalize(grouped);
|
|
3089
|
+
return result;
|
|
3052
3090
|
}
|
|
3053
|
-
|
|
3054
|
-
|
|
3055
|
-
|
|
3056
|
-
|
|
3057
|
-
|
|
3091
|
+
function isOpenCodeDatabaseFilename(name) {
|
|
3092
|
+
return /^opencode(?:-[A-Za-z0-9._-]+)?\.db$/.test(name);
|
|
3093
|
+
}
|
|
3094
|
+
async function detectOpenCodeSqliteRuntime() {
|
|
3095
|
+
return sqliteRuntimePromise ??= (async () => {
|
|
3096
|
+
if (await loadNodeSqlite()) return "node";
|
|
3058
3097
|
try {
|
|
3059
|
-
|
|
3060
|
-
JSON.parse(await readFile10(filePath, "utf-8")),
|
|
3061
|
-
basename9(filePath, ".json")
|
|
3062
|
-
);
|
|
3063
|
-
record && result.add(dateKey(record.timestamp));
|
|
3098
|
+
return await runExternalSqlite(["-version"]), "external";
|
|
3064
3099
|
} catch {
|
|
3100
|
+
return "unavailable";
|
|
3065
3101
|
}
|
|
3066
|
-
|
|
3102
|
+
})(), sqliteRuntimePromise;
|
|
3067
3103
|
}
|
|
3068
|
-
function parseOpenCodeSqliteRows(rows) {
|
|
3104
|
+
function parseOpenCodeSqliteRows(rows, options = {}) {
|
|
3069
3105
|
return rows.flatMap((row) => {
|
|
3070
3106
|
if (!row.data) return [];
|
|
3071
3107
|
let message;
|
|
@@ -3074,83 +3110,193 @@ function parseOpenCodeSqliteRows(rows) {
|
|
|
3074
3110
|
} catch {
|
|
3075
3111
|
return [];
|
|
3076
3112
|
}
|
|
3077
|
-
message.
|
|
3078
|
-
let record = parseOpenCodeMessage(
|
|
3079
|
-
|
|
3113
|
+
if (!message || typeof message != "object" || Array.isArray(message)) return [];
|
|
3114
|
+
let record = parseOpenCodeMessage(
|
|
3115
|
+
message,
|
|
3116
|
+
row.id,
|
|
3117
|
+
row.session_id,
|
|
3118
|
+
options.assistantGuaranteed === !0
|
|
3119
|
+
);
|
|
3120
|
+
return record ? (record.sessionId = cleanString(row.session_id) || record.sessionId, record.projectRoot = normalizeOpenCodeProjectRoot(row.workspace_root) || record.projectRoot, [record]) : [];
|
|
3080
3121
|
});
|
|
3081
3122
|
}
|
|
3082
|
-
|
|
3083
|
-
let
|
|
3084
|
-
|
|
3085
|
-
|
|
3086
|
-
|
|
3087
|
-
|
|
3088
|
-
|
|
3089
|
-
|
|
3090
|
-
|
|
3091
|
-
|
|
3092
|
-
|
|
3093
|
-
|
|
3094
|
-
|
|
3095
|
-
|
|
3123
|
+
function deduplicateOpenCodeRecords(records) {
|
|
3124
|
+
let entries = [], idIndices = /* @__PURE__ */ new Map(), fingerprintIndices = /* @__PURE__ */ new Map();
|
|
3125
|
+
for (let rawRecord of records) {
|
|
3126
|
+
let record = {
|
|
3127
|
+
...rawRecord,
|
|
3128
|
+
tokens: { ...rawRecord.tokens }
|
|
3129
|
+
};
|
|
3130
|
+
if (record.id) {
|
|
3131
|
+
let existingIndex = idIndices.get(record.id);
|
|
3132
|
+
if (existingIndex !== void 0) {
|
|
3133
|
+
mergeDuplicateProject(entries[existingIndex], record.projectRoot), addFingerprintIndex(fingerprintIndices, record.fingerprint, existingIndex);
|
|
3134
|
+
continue;
|
|
3135
|
+
}
|
|
3136
|
+
}
|
|
3137
|
+
let duplicateIndex = (fingerprintIndices.get(record.fingerprint) ?? []).find((index2) => {
|
|
3138
|
+
let existingId = entries[index2].record.id;
|
|
3139
|
+
return !existingId || !record.id || existingId === record.id;
|
|
3140
|
+
});
|
|
3141
|
+
if (duplicateIndex !== void 0) {
|
|
3142
|
+
let entry = entries[duplicateIndex];
|
|
3143
|
+
record.id && !entry.record.id && (entry.record.id = record.id, idIndices.set(record.id, duplicateIndex)), mergeDuplicateProject(entry, record.projectRoot);
|
|
3144
|
+
continue;
|
|
3145
|
+
}
|
|
3146
|
+
let index = entries.length;
|
|
3147
|
+
entries.push({ record, hasProjectConflict: !1 }), record.id && idIndices.set(record.id, index), addFingerprintIndex(fingerprintIndices, record.fingerprint, index);
|
|
3148
|
+
}
|
|
3149
|
+
return entries.map((entry) => entry.record);
|
|
3150
|
+
}
|
|
3151
|
+
async function loadOpenCodeRecords(options) {
|
|
3152
|
+
let sources = await resolveOpenCodeSources(options), sqliteRecords = [];
|
|
3153
|
+
for (let dbPath of sources.dbPaths) {
|
|
3154
|
+
let { v2Rows, v1Rows } = await queryOpenCodeDatabase(dbPath);
|
|
3155
|
+
sqliteRecords.push(...deduplicateOpenCodeRecords([
|
|
3156
|
+
...parseOpenCodeSqliteRows(v2Rows, { assistantGuaranteed: !0 }),
|
|
3157
|
+
...parseOpenCodeSqliteRows(v1Rows)
|
|
3158
|
+
]));
|
|
3159
|
+
}
|
|
3160
|
+
let files = await walkFiles(sources.legacyDir, ".json"), legacyRecords = [];
|
|
3161
|
+
for (let filePath of files)
|
|
3162
|
+
try {
|
|
3163
|
+
let message = JSON.parse(await readFile10(filePath, "utf-8")), record = parseOpenCodeMessage(
|
|
3164
|
+
message,
|
|
3165
|
+
basename9(filePath, ".json"),
|
|
3166
|
+
message.sessionID ?? basename9(dirname5(filePath)),
|
|
3167
|
+
!1
|
|
3168
|
+
);
|
|
3169
|
+
record && legacyRecords.push(record);
|
|
3170
|
+
} catch {
|
|
3171
|
+
}
|
|
3172
|
+
return {
|
|
3173
|
+
records: deduplicateOpenCodeSources([...sqliteRecords, ...legacyRecords]),
|
|
3174
|
+
sourceCount: sources.dbPaths.length + files.length
|
|
3175
|
+
};
|
|
3176
|
+
}
|
|
3177
|
+
async function queryOpenCodeDatabase(dbPath) {
|
|
3178
|
+
let v2Rows = await queryFirstSupported(dbPath, [
|
|
3179
|
+
`SELECT sm.id, sm.session_id, sm.data, NULLIF(s.directory, '') AS workspace_root
|
|
3180
|
+
FROM session_message sm
|
|
3181
|
+
LEFT JOIN session s ON s.id = sm.session_id
|
|
3182
|
+
WHERE sm.type = 'assistant'
|
|
3183
|
+
AND CASE WHEN json_valid(sm.data)
|
|
3184
|
+
THEN json_extract(sm.data, '$.tokens') IS NOT NULL ELSE 0 END
|
|
3185
|
+
ORDER BY sm.id, sm.session_id`,
|
|
3186
|
+
`SELECT sm.id, sm.session_id, sm.data, NULL AS workspace_root
|
|
3187
|
+
FROM session_message sm
|
|
3188
|
+
WHERE sm.type = 'assistant'
|
|
3189
|
+
AND CASE WHEN json_valid(sm.data)
|
|
3190
|
+
THEN json_extract(sm.data, '$.tokens') IS NOT NULL ELSE 0 END
|
|
3191
|
+
ORDER BY sm.id, sm.session_id`
|
|
3192
|
+
]), v1Rows = await queryFirstSupported(dbPath, [
|
|
3193
|
+
`SELECT m.id, m.session_id, m.data, NULLIF(s.directory, '') AS workspace_root
|
|
3194
|
+
FROM message m
|
|
3195
|
+
LEFT JOIN session s ON s.id = m.session_id
|
|
3196
|
+
WHERE CASE WHEN json_valid(m.data) THEN
|
|
3197
|
+
json_extract(m.data, '$.role') = 'assistant'
|
|
3198
|
+
AND json_extract(m.data, '$.tokens') IS NOT NULL ELSE 0 END
|
|
3199
|
+
ORDER BY m.id, m.session_id`,
|
|
3200
|
+
`SELECT m.id, m.session_id, m.data, NULL AS workspace_root
|
|
3201
|
+
FROM message m
|
|
3202
|
+
WHERE CASE WHEN json_valid(m.data) THEN
|
|
3203
|
+
json_extract(m.data, '$.role') = 'assistant'
|
|
3204
|
+
AND json_extract(m.data, '$.tokens') IS NOT NULL ELSE 0 END
|
|
3205
|
+
ORDER BY m.id, m.session_id`
|
|
3206
|
+
]);
|
|
3207
|
+
return { v2Rows, v1Rows };
|
|
3208
|
+
}
|
|
3209
|
+
async function queryFirstSupported(dbPath, queries) {
|
|
3210
|
+
for (let query of queries)
|
|
3096
3211
|
try {
|
|
3097
|
-
|
|
3098
|
-
if (Array.isArray(rows)) return rows.filter(isSqliteRow);
|
|
3212
|
+
return await runSqliteQuery(dbPath, query);
|
|
3099
3213
|
} catch {
|
|
3100
3214
|
}
|
|
3101
3215
|
return [];
|
|
3102
3216
|
}
|
|
3103
|
-
function
|
|
3104
|
-
|
|
3217
|
+
async function runSqliteQuery(dbPath, query) {
|
|
3218
|
+
let nodeSqlite = await loadNodeSqlite();
|
|
3219
|
+
if (nodeSqlite) {
|
|
3220
|
+
let db = new nodeSqlite.DatabaseSync(dbPath, { readOnly: !0 });
|
|
3221
|
+
try {
|
|
3222
|
+
return db.prepare(query).all().filter(isSqliteRow);
|
|
3223
|
+
} finally {
|
|
3224
|
+
db.close();
|
|
3225
|
+
}
|
|
3226
|
+
}
|
|
3227
|
+
let stdout = await runExternalSqlite(["-readonly", "-json", dbPath, query]), rows = JSON.parse(stdout || "[]");
|
|
3228
|
+
return Array.isArray(rows) ? rows.filter(isSqliteRow) : [];
|
|
3229
|
+
}
|
|
3230
|
+
async function loadNodeSqlite() {
|
|
3231
|
+
return nodeSqliteModulePromise ??= (async () => {
|
|
3232
|
+
try {
|
|
3233
|
+
let module = await import("node:sqlite");
|
|
3234
|
+
return typeof module.DatabaseSync == "function" ? module : null;
|
|
3235
|
+
} catch {
|
|
3236
|
+
return null;
|
|
3237
|
+
}
|
|
3238
|
+
})(), nodeSqliteModulePromise;
|
|
3239
|
+
}
|
|
3240
|
+
function runExternalSqlite(args) {
|
|
3241
|
+
return new Promise((resolve6, reject) => {
|
|
3105
3242
|
execFile(
|
|
3106
3243
|
"sqlite3",
|
|
3107
3244
|
args,
|
|
3108
|
-
{ encoding: "utf8", maxBuffer:
|
|
3109
|
-
(error, stdout) => error ? reject(error) :
|
|
3245
|
+
{ encoding: "utf8", maxBuffer: 256 * 1024 * 1024 },
|
|
3246
|
+
(error, stdout) => error ? reject(error) : resolve6(stdout)
|
|
3110
3247
|
);
|
|
3111
3248
|
});
|
|
3112
3249
|
}
|
|
3113
|
-
function parseOpenCodeMessage(message, fallbackId) {
|
|
3114
|
-
if (message.role !== "assistant" || !message.tokens) return;
|
|
3250
|
+
function parseOpenCodeMessage(message, fallbackId, fallbackSessionId, assistantGuaranteed = !1) {
|
|
3251
|
+
if (message.role != null && message.role !== "assistant" || !assistantGuaranteed && message.role !== "assistant" || !message.tokens) return;
|
|
3115
3252
|
let timestamp = parseTs(message.time?.created);
|
|
3116
3253
|
if (!timestamp) return;
|
|
3117
|
-
let model = message.modelID
|
|
3254
|
+
let model = cleanString(message.modelID) || cleanString(message.model?.id);
|
|
3255
|
+
if (!model) return;
|
|
3256
|
+
let rawProvider = cleanString(message.providerID) || cleanString(message.model?.providerID), provider = canonicalizeOpenCodeProvider(rawProvider) || inferProviderFromModel(model, "opencode"), tokens = {
|
|
3118
3257
|
input: clamp3(message.tokens.input),
|
|
3119
3258
|
cached: clamp3(message.tokens.cache?.read),
|
|
3120
3259
|
cacheWrite: clamp3(message.tokens.cache?.write),
|
|
3121
3260
|
output: clamp3(message.tokens.output),
|
|
3122
3261
|
reasoning: clamp3(message.tokens.reasoning)
|
|
3123
|
-
};
|
|
3124
|
-
if (Object.values(tokens).every((value) => value === 0)) return;
|
|
3125
|
-
let
|
|
3262
|
+
}, completed = parseTs(message.time?.completed)?.getTime() ?? "", costUSD = clampCost(message.cost);
|
|
3263
|
+
if (Object.values(tokens).every((value) => value === 0) && costUSD === 0) return;
|
|
3264
|
+
let agent = (cleanString(message.mode) || cleanString(message.agent))?.toLowerCase(), projectRoot = normalizeOpenCodeProjectRoot(
|
|
3265
|
+
typeof message.path == "string" ? message.path : message.path?.root
|
|
3266
|
+
), id = cleanString(message.id), sessionId = cleanString(message.sessionID) || cleanString(fallbackSessionId);
|
|
3126
3267
|
return {
|
|
3127
|
-
id
|
|
3268
|
+
id,
|
|
3269
|
+
fallbackId,
|
|
3270
|
+
sessionId,
|
|
3128
3271
|
timestamp,
|
|
3129
3272
|
model,
|
|
3130
3273
|
provider,
|
|
3131
3274
|
projectRoot,
|
|
3132
3275
|
tokens,
|
|
3133
|
-
|
|
3276
|
+
costUSD,
|
|
3277
|
+
agent,
|
|
3278
|
+
fingerprint: JSON.stringify([
|
|
3134
3279
|
timestamp.getTime(),
|
|
3280
|
+
completed,
|
|
3135
3281
|
model,
|
|
3136
3282
|
provider,
|
|
3137
3283
|
tokens.input,
|
|
3138
3284
|
tokens.cached,
|
|
3139
3285
|
tokens.cacheWrite,
|
|
3140
3286
|
tokens.output,
|
|
3141
|
-
tokens.reasoning
|
|
3142
|
-
|
|
3287
|
+
tokens.reasoning,
|
|
3288
|
+
costUSD,
|
|
3289
|
+
agent ?? ""
|
|
3290
|
+
])
|
|
3143
3291
|
};
|
|
3144
3292
|
}
|
|
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));
|
|
3293
|
+
function addOpenCodeRecord(record, grouped, sessionsByBreakdown, aliases2) {
|
|
3294
|
+
let usageDate = dateKey(record.timestamp), dayMap = grouped.get(usageDate);
|
|
3149
3295
|
if (!dayMap) return;
|
|
3150
|
-
let fields = record.projectRoot ? resolveProjectFields(record.projectRoot, aliases2) : { project: "unknown", projectDisplay: "unknown" }
|
|
3296
|
+
let fields = record.projectRoot ? resolveProjectFields(record.projectRoot, aliases2) : { project: "unknown", projectDisplay: "unknown" }, breakdownKey = `${record.provider}|${record.model}|${fields.project}`;
|
|
3151
3297
|
accumulate(
|
|
3152
3298
|
dayMap,
|
|
3153
|
-
|
|
3299
|
+
breakdownKey,
|
|
3154
3300
|
{
|
|
3155
3301
|
provider: record.provider,
|
|
3156
3302
|
product: "opencode",
|
|
@@ -3167,6 +3313,67 @@ function addOpenCodeRecord(record, grouped, seenIds, seenFingerprints, aliases2)
|
|
|
3167
3313
|
},
|
|
3168
3314
|
record.tokens
|
|
3169
3315
|
);
|
|
3316
|
+
let breakdown = dayMap.get(breakdownKey);
|
|
3317
|
+
if (record.costUSD > 0 && (breakdown.costUSD = (breakdown.costUSD ?? 0) + record.costUSD), record.sessionId) {
|
|
3318
|
+
let sessionKey = `${usageDate}\0${breakdownKey}`, sessions = sessionsByBreakdown.get(sessionKey) ?? /* @__PURE__ */ new Set();
|
|
3319
|
+
sessions.add(record.sessionId), sessionsByBreakdown.set(sessionKey, sessions);
|
|
3320
|
+
}
|
|
3321
|
+
}
|
|
3322
|
+
function mergeDuplicateProject(entry, incomingRoot) {
|
|
3323
|
+
if (entry.hasProjectConflict || !incomingRoot) return;
|
|
3324
|
+
let existingRoot = entry.record.projectRoot;
|
|
3325
|
+
existingRoot ? existingRoot !== incomingRoot && (entry.hasProjectConflict = !0, entry.record.projectRoot = void 0) : entry.record.projectRoot = incomingRoot;
|
|
3326
|
+
}
|
|
3327
|
+
function addFingerprintIndex(map, fingerprint, index) {
|
|
3328
|
+
let indices = map.get(fingerprint) ?? [];
|
|
3329
|
+
indices.includes(index) || indices.push(index), map.set(fingerprint, indices);
|
|
3330
|
+
}
|
|
3331
|
+
function deduplicateOpenCodeSources(records) {
|
|
3332
|
+
let seen = /* @__PURE__ */ new Set();
|
|
3333
|
+
return records.filter((record) => {
|
|
3334
|
+
let key = record.id || record.fallbackId;
|
|
3335
|
+
return !key || seen.add(key);
|
|
3336
|
+
});
|
|
3337
|
+
}
|
|
3338
|
+
function canonicalizeOpenCodeProvider(raw) {
|
|
3339
|
+
if (!raw) return;
|
|
3340
|
+
let normalized = raw.trim().replace(/\/+$/, "").toLowerCase().replaceAll("-", "_");
|
|
3341
|
+
if (!normalized || normalized === "unknown" || normalized.startsWith("<") && normalized.endsWith(">"))
|
|
3342
|
+
return;
|
|
3343
|
+
let first = normalized.split("/")[0].split(".")[0];
|
|
3344
|
+
return {
|
|
3345
|
+
x_ai: "xai",
|
|
3346
|
+
z_ai: "zai",
|
|
3347
|
+
moonshotai: "moonshot",
|
|
3348
|
+
meta: "meta_llama",
|
|
3349
|
+
azure: "azure_ai",
|
|
3350
|
+
vertex: "anthropic",
|
|
3351
|
+
vertex_ai: "anthropic",
|
|
3352
|
+
together: "together_ai",
|
|
3353
|
+
fireworks: "fireworks_ai",
|
|
3354
|
+
gemini: "google",
|
|
3355
|
+
openai_codex: "openai",
|
|
3356
|
+
minimaxai: "minimax",
|
|
3357
|
+
minimax_ai: "minimax",
|
|
3358
|
+
mistral: "mistralai"
|
|
3359
|
+
}[first] ?? first;
|
|
3360
|
+
}
|
|
3361
|
+
function expandConfiguredPath(rawPath, home) {
|
|
3362
|
+
let value = rawPath.trim();
|
|
3363
|
+
if (value)
|
|
3364
|
+
return value === "~" ? home : value.startsWith("~/") || value.startsWith("~\\") ? join13(home, value.slice(2)) : isAbsolute(value) ? value : resolve2(value);
|
|
3365
|
+
}
|
|
3366
|
+
function normalizeOpenCodeProjectRoot(raw) {
|
|
3367
|
+
let trimmed = cleanString(raw);
|
|
3368
|
+
if (!trimmed) return;
|
|
3369
|
+
let preserveUncPrefix = trimmed.startsWith("\\\\") || trimmed.startsWith("//"), normalized = trimmed.replaceAll("\\", "/");
|
|
3370
|
+
preserveUncPrefix ? normalized = `//${normalized.replace(/^\/+/, "").replace(/\/{2,}/g, "/")}` : normalized = normalized.replace(/\/{2,}/g, "/");
|
|
3371
|
+
let minimumLength = preserveUncPrefix ? 2 : 1;
|
|
3372
|
+
return normalized.length > minimumLength && (normalized = normalized.replace(/\/+$/, "")), normalized || void 0;
|
|
3373
|
+
}
|
|
3374
|
+
function cleanString(value) {
|
|
3375
|
+
if (typeof value == "string")
|
|
3376
|
+
return value.trim() || void 0;
|
|
3170
3377
|
}
|
|
3171
3378
|
function isSqliteRow(value) {
|
|
3172
3379
|
return typeof value == "object" && value !== null && !Array.isArray(value);
|
|
@@ -3174,10 +3381,13 @@ function isSqliteRow(value) {
|
|
|
3174
3381
|
function clamp3(value) {
|
|
3175
3382
|
return Math.max(Number.isFinite(value) ? value : 0, 0);
|
|
3176
3383
|
}
|
|
3384
|
+
function clampCost(value) {
|
|
3385
|
+
return Number.isFinite(value) && value > 0 ? value : 0;
|
|
3386
|
+
}
|
|
3177
3387
|
|
|
3178
3388
|
// src/scanners/pi.ts
|
|
3179
3389
|
import { readFile as readFile11 } from "node:fs/promises";
|
|
3180
|
-
import { join as join14, basename as basename10, dirname as
|
|
3390
|
+
import { join as join14, basename as basename10, dirname as dirname6 } from "node:path";
|
|
3181
3391
|
import { homedir as homedir13 } from "node:os";
|
|
3182
3392
|
async function scanPiDates(targetDates, baseDir, projectAliases) {
|
|
3183
3393
|
let dates = new Set(targetDates), sessionDirs = baseDir ? [baseDir] : getSessionDirs(), files = [...new Set((await Promise.all(sessionDirs.map((dir) => walkFiles(dir, ".jsonl")))).flat())];
|
|
@@ -3190,7 +3400,7 @@ async function scanPiDates(targetDates, baseDir, projectAliases) {
|
|
|
3190
3400
|
} catch {
|
|
3191
3401
|
continue;
|
|
3192
3402
|
}
|
|
3193
|
-
let parentDir =
|
|
3403
|
+
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
3404
|
for (let line of content.split(`
|
|
3195
3405
|
`)) {
|
|
3196
3406
|
if (!line.trim()) continue;
|
|
@@ -3256,18 +3466,18 @@ function extractProjectFromEncoded(encoded) {
|
|
|
3256
3466
|
// src/scanners/trae.ts
|
|
3257
3467
|
import { readFile as readFile12 } from "node:fs/promises";
|
|
3258
3468
|
import { homedir as homedir14 } from "node:os";
|
|
3259
|
-
import { join as join15, resolve as
|
|
3469
|
+
import { join as join15, resolve as resolve3 } from "node:path";
|
|
3260
3470
|
function resolveTraeNativeCacheDir(home = homedir14()) {
|
|
3261
3471
|
let explicit = process.env.AIUSAGE_TRAE_CACHE_DIR?.trim();
|
|
3262
|
-
return explicit ?
|
|
3472
|
+
return explicit ? resolve3(explicit) : join15(home, ".aiusage", "trae-cache", "sessions");
|
|
3263
3473
|
}
|
|
3264
3474
|
function resolveTokscaleTraeCacheDir(home = homedir14()) {
|
|
3265
3475
|
let configDir = process.env.TOKSCALE_CONFIG_DIR?.trim();
|
|
3266
|
-
return configDir ? join15(
|
|
3476
|
+
return configDir ? join15(resolve3(configDir), "trae-cache", "sessions") : join15(home, ".config", "tokscale", "trae-cache", "sessions");
|
|
3267
3477
|
}
|
|
3268
3478
|
function resolveTraeIntlCacheDir(home = homedir14()) {
|
|
3269
3479
|
let explicit = process.env.AIUSAGE_TRAE_INTL_CACHE_DIR?.trim();
|
|
3270
|
-
return explicit ?
|
|
3480
|
+
return explicit ? resolve3(explicit) : join15(home, ".aiusage", "trae-cache", "intl", "sessions");
|
|
3271
3481
|
}
|
|
3272
3482
|
async function scanTraeDates(targetDates, options = {}) {
|
|
3273
3483
|
let dates = new Set(targetDates);
|
|
@@ -3499,7 +3709,13 @@ async function scanDates(targetDates, options = {}) {
|
|
|
3499
3709
|
{ products: ["kimi-code"], scan: () => scanKimiDates(uniqueDates, void 0, options.projectAliases) },
|
|
3500
3710
|
{ products: ["amp"], scan: () => scanAmpDates(uniqueDates, void 0, options.projectAliases) },
|
|
3501
3711
|
{ products: ["droid"], scan: () => scanDroidDates(uniqueDates, void 0, options.projectAliases) },
|
|
3502
|
-
{
|
|
3712
|
+
{
|
|
3713
|
+
products: ["opencode"],
|
|
3714
|
+
scan: () => scanOpencodeDates(uniqueDates, {
|
|
3715
|
+
projectAliases: options.projectAliases,
|
|
3716
|
+
dbPaths: options.opencodeDbPaths
|
|
3717
|
+
})
|
|
3718
|
+
},
|
|
3503
3719
|
{ products: ["pi"], scan: () => scanPiDates(uniqueDates, void 0, options.projectAliases) },
|
|
3504
3720
|
{
|
|
3505
3721
|
products: ["trae-cn", "trae-intl", "trae"],
|
|
@@ -3680,12 +3896,13 @@ function parseCsv(content) {
|
|
|
3680
3896
|
}
|
|
3681
3897
|
|
|
3682
3898
|
// src/report.ts
|
|
3683
|
-
import { readdir as
|
|
3899
|
+
import { readdir as readdir6, readFile as readFile14 } from "node:fs/promises";
|
|
3684
3900
|
import { homedir as homedir15 } from "node:os";
|
|
3685
|
-
import { basename as basename11, dirname as
|
|
3901
|
+
import { basename as basename11, dirname as dirname7, join as join16 } from "node:path";
|
|
3686
3902
|
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, {
|
|
3903
|
+
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
3904
|
projectAliases: options.projectAliases,
|
|
3905
|
+
opencodeDbPaths: options.opencodeDbPaths,
|
|
3689
3906
|
tools: options.tools
|
|
3690
3907
|
});
|
|
3691
3908
|
for (let result of results) {
|
|
@@ -3755,9 +3972,9 @@ function buildPresetDates(range) {
|
|
|
3755
3972
|
}
|
|
3756
3973
|
return result;
|
|
3757
3974
|
}
|
|
3758
|
-
async function discoverAllDates(tools) {
|
|
3975
|
+
async function discoverAllDates(tools, opencodeDbPaths) {
|
|
3759
3976
|
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) => {
|
|
3977
|
+
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
3978
|
found.forEach((date) => dates.add(date));
|
|
3762
3979
|
})), 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
3980
|
let explicitCopilotOtel = process.env.COPILOT_OTEL_FILE_EXPORTER_PATH?.trim();
|
|
@@ -3869,7 +4086,7 @@ async function addFileModifiedDate(filePath, dates) {
|
|
|
3869
4086
|
async function walkForFiles(dir, ext, result) {
|
|
3870
4087
|
let entries;
|
|
3871
4088
|
try {
|
|
3872
|
-
entries = await
|
|
4089
|
+
entries = await readdir6(dir, { withFileTypes: !0 });
|
|
3873
4090
|
} catch {
|
|
3874
4091
|
return;
|
|
3875
4092
|
}
|
|
@@ -3948,7 +4165,7 @@ async function discoverCopilotVscodeDates(dates) {
|
|
|
3948
4165
|
}
|
|
3949
4166
|
}
|
|
3950
4167
|
function isChatSessionFile2(filePath) {
|
|
3951
|
-
return basename11(
|
|
4168
|
+
return basename11(dirname7(filePath)) === "chatSessions";
|
|
3952
4169
|
}
|
|
3953
4170
|
async function discoverAntigravityDates(dates) {
|
|
3954
4171
|
let home = homedir15(), brainFiles = [], browserFiles = [];
|
|
@@ -3988,7 +4205,7 @@ async function discoverClaudeDates(dates) {
|
|
|
3988
4205
|
for (let baseDir of baseDirs) {
|
|
3989
4206
|
let projectDirs;
|
|
3990
4207
|
try {
|
|
3991
|
-
projectDirs = await
|
|
4208
|
+
projectDirs = await readdir6(baseDir);
|
|
3992
4209
|
} catch {
|
|
3993
4210
|
continue;
|
|
3994
4211
|
}
|
|
@@ -4041,7 +4258,7 @@ async function discoverCodexDates(dates) {
|
|
|
4041
4258
|
async function collectCodexSessionFiles(baseDir) {
|
|
4042
4259
|
let paths = [];
|
|
4043
4260
|
try {
|
|
4044
|
-
let archivedFiles = await
|
|
4261
|
+
let archivedFiles = await readdir6(join16(baseDir, "archived_sessions"));
|
|
4045
4262
|
for (let file of archivedFiles)
|
|
4046
4263
|
file.endsWith(".jsonl") && paths.push(join16(baseDir, "archived_sessions", file));
|
|
4047
4264
|
} catch {
|
|
@@ -4049,7 +4266,7 @@ async function collectCodexSessionFiles(baseDir) {
|
|
|
4049
4266
|
return await walkForCodexJsonl(join16(baseDir, "sessions"), paths), paths;
|
|
4050
4267
|
}
|
|
4051
4268
|
async function walkForClaudeJsonl(dir, result) {
|
|
4052
|
-
let entries = await
|
|
4269
|
+
let entries = await readdir6(dir, { withFileTypes: !0 });
|
|
4053
4270
|
for (let entry of entries) {
|
|
4054
4271
|
let fullPath = join16(dir, entry.name);
|
|
4055
4272
|
entry.isDirectory() ? await walkForClaudeJsonl(fullPath, result) : entry.name.endsWith(".jsonl") && result.push(fullPath);
|
|
@@ -4058,7 +4275,7 @@ async function walkForClaudeJsonl(dir, result) {
|
|
|
4058
4275
|
async function walkForCodexJsonl(dir, result) {
|
|
4059
4276
|
let entries;
|
|
4060
4277
|
try {
|
|
4061
|
-
entries = await
|
|
4278
|
+
entries = await readdir6(dir, { withFileTypes: !0 });
|
|
4062
4279
|
} catch {
|
|
4063
4280
|
return;
|
|
4064
4281
|
}
|
|
@@ -4120,7 +4337,7 @@ function toBreakdownTotals(breakdown, warnings, pricingCatalog) {
|
|
|
4120
4337
|
};
|
|
4121
4338
|
}
|
|
4122
4339
|
function calculateBreakdownCost(breakdown, warnings, pricingCatalog) {
|
|
4123
|
-
let effectivePricingVersion = pricingCatalog?.version ?? PRICING_VERSION, sourceCostMatchesCatalog = breakdown.product === "trae-intl" || breakdown.pricingVersion == null || breakdown.pricingVersion === effectivePricingVersion;
|
|
4340
|
+
let effectivePricingVersion = pricingCatalog?.version ?? PRICING_VERSION, sourceCostMatchesCatalog = breakdown.product === "trae-intl" || breakdown.product === "opencode" || breakdown.pricingVersion == null || breakdown.pricingVersion === effectivePricingVersion;
|
|
4124
4341
|
if (breakdown.costUSD != null && breakdown.costUSD > 0 && sourceCostMatchesCatalog)
|
|
4125
4342
|
return breakdown.costUSD;
|
|
4126
4343
|
let result = calculateCost(
|
|
@@ -4353,7 +4570,7 @@ function fmtDateShort(dateStr) {
|
|
|
4353
4570
|
}
|
|
4354
4571
|
|
|
4355
4572
|
// src/activity.ts
|
|
4356
|
-
import { open, readdir as
|
|
4573
|
+
import { open, readdir as readdir7 } from "node:fs/promises";
|
|
4357
4574
|
import { createInterface as createInterface3 } from "node:readline";
|
|
4358
4575
|
import { homedir as homedir16 } from "node:os";
|
|
4359
4576
|
import { basename as basename12, join as join17 } from "node:path";
|
|
@@ -4608,7 +4825,7 @@ async function scanClaudeActivity(targetDates, options) {
|
|
|
4608
4825
|
for (let baseDir of getClaudeProjectDirs2(options.claudeProjectsDirs)) {
|
|
4609
4826
|
let projectDirs;
|
|
4610
4827
|
try {
|
|
4611
|
-
projectDirs = await
|
|
4828
|
+
projectDirs = await readdir7(baseDir, { withFileTypes: !0 });
|
|
4612
4829
|
} catch {
|
|
4613
4830
|
continue;
|
|
4614
4831
|
}
|
|
@@ -4752,7 +4969,7 @@ function acceptsDate(acc, usageDate) {
|
|
|
4752
4969
|
async function collectCodexSessionFiles2(baseDir) {
|
|
4753
4970
|
let paths = [];
|
|
4754
4971
|
try {
|
|
4755
|
-
let files = await
|
|
4972
|
+
let files = await readdir7(join17(baseDir, "archived_sessions"));
|
|
4756
4973
|
for (let file of files)
|
|
4757
4974
|
file.endsWith(".jsonl") && paths.push(join17(baseDir, "archived_sessions", file));
|
|
4758
4975
|
} catch {
|
|
@@ -4773,7 +4990,7 @@ function getClaudeProjectDirs2(configured) {
|
|
|
4773
4990
|
async function walkJsonl(dir, result) {
|
|
4774
4991
|
let entries;
|
|
4775
4992
|
try {
|
|
4776
|
-
entries = await
|
|
4993
|
+
entries = await readdir7(dir, { withFileTypes: !0 });
|
|
4777
4994
|
} catch {
|
|
4778
4995
|
return;
|
|
4779
4996
|
}
|
|
@@ -4955,6 +5172,7 @@ function migrateConfig(config) {
|
|
|
4955
5172
|
projectAliases: config.projectAliases,
|
|
4956
5173
|
privacy: config.privacy,
|
|
4957
5174
|
pricing: config.pricing,
|
|
5175
|
+
scanner: config.scanner,
|
|
4958
5176
|
lang: config.lang,
|
|
4959
5177
|
emoji: config.emoji,
|
|
4960
5178
|
targets: [target]
|
|
@@ -5026,6 +5244,12 @@ function setConfigValue(config, keyPath, values) {
|
|
|
5026
5244
|
...next.pricing ?? {},
|
|
5027
5245
|
cacheTtlHours: parsePositiveInt(requireSingleValue(keyPath, values), keyPath)
|
|
5028
5246
|
}, next;
|
|
5247
|
+
if (keyPath === "scanner.opencodeDbPaths") {
|
|
5248
|
+
let paths = [...new Set(values.map((value) => value.trim()).filter(Boolean))];
|
|
5249
|
+
if (paths.length === 0)
|
|
5250
|
+
throw new Error("scanner.opencodeDbPaths \u81F3\u5C11\u9700\u8981\u4E00\u4E2A opencode*.db \u8DEF\u5F84");
|
|
5251
|
+
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);
|
|
5252
|
+
}
|
|
5029
5253
|
if (keyPath === "project.alias") {
|
|
5030
5254
|
if (values.length < 2)
|
|
5031
5255
|
throw new Error("project.alias \u9700\u8981\u4E24\u4E2A\u53C2\u6570\uFF1A\u539F\u59CB\u8DEF\u5F84/\u540D\u79F0 \u4E0E \u522B\u540D");
|
|
@@ -5070,13 +5294,13 @@ import { hostname as hostname2 } from "node:os";
|
|
|
5070
5294
|
|
|
5071
5295
|
// src/version.ts
|
|
5072
5296
|
import { readFileSync } from "node:fs";
|
|
5073
|
-
import { resolve as
|
|
5297
|
+
import { resolve as resolve4, dirname as dirname8 } from "node:path";
|
|
5074
5298
|
import { fileURLToPath } from "node:url";
|
|
5075
5299
|
var cached;
|
|
5076
5300
|
function getVersion() {
|
|
5077
5301
|
if (cached !== void 0) return cached;
|
|
5078
5302
|
try {
|
|
5079
|
-
let pkg =
|
|
5303
|
+
let pkg = resolve4(dirname8(fileURLToPath(import.meta.url)), "..", "package.json");
|
|
5080
5304
|
cached = JSON.parse(readFileSync(pkg, "utf-8")).version;
|
|
5081
5305
|
} catch {
|
|
5082
5306
|
cached = "unknown";
|
|
@@ -5149,11 +5373,11 @@ async function requestJson(url, init) {
|
|
|
5149
5373
|
}
|
|
5150
5374
|
|
|
5151
5375
|
// src/schedule.ts
|
|
5152
|
-
import { mkdir as mkdir2, readFile as readFile16, stat as
|
|
5376
|
+
import { mkdir as mkdir2, readFile as readFile16, stat as stat4, unlink, writeFile as writeFile2 } from "node:fs/promises";
|
|
5153
5377
|
import { execFile as execFile2 } from "node:child_process";
|
|
5154
5378
|
import { promisify } from "node:util";
|
|
5155
5379
|
import { homedir as homedir18, platform, tmpdir as tmpdir2 } from "node:os";
|
|
5156
|
-
import { join as join19, resolve as
|
|
5380
|
+
import { join as join19, resolve as resolve5 } from "node:path";
|
|
5157
5381
|
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
5382
|
function parseInterval(value) {
|
|
5159
5383
|
let match = value.match(/^(\d+)(m|h|d)$/);
|
|
@@ -5189,7 +5413,7 @@ async function getScheduleStatus() {
|
|
|
5189
5413
|
return platform() === "darwin" ? getLaunchdStatus() : getCronStatus();
|
|
5190
5414
|
}
|
|
5191
5415
|
function resolveCommandPaths() {
|
|
5192
|
-
let scriptPath =
|
|
5416
|
+
let scriptPath = resolve5(process.argv[1]);
|
|
5193
5417
|
if (scriptPath.includes("_npx") || scriptPath.includes("/npx-"))
|
|
5194
5418
|
throw new Error(
|
|
5195
5419
|
`\u68C0\u6D4B\u5230\u901A\u8FC7 npx \u8FD0\u884C\uFF0C\u5B9A\u65F6\u4EFB\u52A1\u9700\u8981\u5168\u5C40\u5B89\u88C5\u3002
|
|
@@ -5248,7 +5472,7 @@ async function disableLaunchd() {
|
|
|
5248
5472
|
}
|
|
5249
5473
|
async function getLaunchdStatus() {
|
|
5250
5474
|
try {
|
|
5251
|
-
await
|
|
5475
|
+
await stat4(PLIST_PATH);
|
|
5252
5476
|
} catch {
|
|
5253
5477
|
return { enabled: !1 };
|
|
5254
5478
|
}
|
|
@@ -5358,7 +5582,7 @@ function escapeXml(value) {
|
|
|
5358
5582
|
}
|
|
5359
5583
|
|
|
5360
5584
|
// src/doctor.ts
|
|
5361
|
-
import { readdir as
|
|
5585
|
+
import { readdir as readdir8, stat as stat5 } from "node:fs/promises";
|
|
5362
5586
|
import { homedir as homedir19 } from "node:os";
|
|
5363
5587
|
import { join as join20 } from "node:path";
|
|
5364
5588
|
var msgs = {
|
|
@@ -5381,6 +5605,8 @@ var msgs = {
|
|
|
5381
5605
|
notInstalled: "Not installed",
|
|
5382
5606
|
installedNoData: "Installed, no usage data yet",
|
|
5383
5607
|
hasData: (n) => `${n} session${n > 1 ? "s" : ""} found`,
|
|
5608
|
+
openCodeData: (dbs, legacy) => `${dbs} database(s), ${legacy} legacy message(s) found`,
|
|
5609
|
+
openCodeSqliteUnavailable: "Database found, but this Node version requires the system sqlite3 executable",
|
|
5384
5610
|
schedule: "Schedule",
|
|
5385
5611
|
scheduleEvery: "every",
|
|
5386
5612
|
scheduleEnabled: "Enabled",
|
|
@@ -5405,6 +5631,8 @@ var msgs = {
|
|
|
5405
5631
|
notInstalled: "\u672A\u5B89\u88C5",
|
|
5406
5632
|
installedNoData: "\u5DF2\u5B89\u88C5\uFF0C\u6682\u65E0\u4F7F\u7528\u6570\u636E",
|
|
5407
5633
|
hasData: (n) => `\u53D1\u73B0 ${n} \u4E2A\u4F1A\u8BDD`,
|
|
5634
|
+
openCodeData: (dbs, legacy) => `\u53D1\u73B0 ${dbs} \u4E2A\u6570\u636E\u5E93\u3001${legacy} \u6761\u65E7\u7248\u6D88\u606F`,
|
|
5635
|
+
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
5636
|
schedule: "\u5B9A\u65F6\u540C\u6B65",
|
|
5409
5637
|
scheduleEvery: "\u6BCF",
|
|
5410
5638
|
scheduleEnabled: "\u5DF2\u542F\u7528",
|
|
@@ -5416,7 +5644,7 @@ async function countFiles(dir, exts, cap = 1e3) {
|
|
|
5416
5644
|
for (; queue.length > 0 && count < cap; ) {
|
|
5417
5645
|
let current = queue.pop(), entries;
|
|
5418
5646
|
try {
|
|
5419
|
-
entries = await
|
|
5647
|
+
entries = await readdir8(current, { withFileTypes: !0 });
|
|
5420
5648
|
} catch {
|
|
5421
5649
|
continue;
|
|
5422
5650
|
}
|
|
@@ -5431,7 +5659,7 @@ async function countFiles(dir, exts, cap = 1e3) {
|
|
|
5431
5659
|
async function runDoctor(lang = "zh") {
|
|
5432
5660
|
let s = msgs[lang], checks = [], config = await readConfig(), g1 = s.groupConfig, configPath = getConfigPath();
|
|
5433
5661
|
try {
|
|
5434
|
-
await
|
|
5662
|
+
await stat5(configPath), checks.push({ group: g1, name: s.config, status: "ok", message: configPath });
|
|
5435
5663
|
} catch {
|
|
5436
5664
|
checks.push({ group: g1, name: s.config, status: "fail", message: s.configMissing });
|
|
5437
5665
|
}
|
|
@@ -5471,7 +5699,6 @@ async function runDoctor(lang = "zh") {
|
|
|
5471
5699
|
{ dirs: [join20(home, ".kimi", "sessions")], label: "Kimi CLI (legacy)", exts: [".jsonl"] },
|
|
5472
5700
|
{ dirs: [join20(home, ".local", "share", "amp", "threads")], label: "Amp", exts: [".json"] },
|
|
5473
5701
|
{ dirs: [join20(home, ".factory", "sessions")], label: "Droid", exts: [".settings.json"] },
|
|
5474
|
-
{ dirs: [join20(home, ".local", "share", "opencode")], label: "OpenCode", exts: [".db", ".json"] },
|
|
5475
5702
|
{ dirs: [join20(home, ".pi", "agent", "sessions"), join20(home, ".omp", "agent", "sessions")], label: "Pi / OMP", exts: [".jsonl"] },
|
|
5476
5703
|
{ dirs: [resolveTraeNativeCacheDir(home), resolveTokscaleTraeCacheDir(home)], label: "Trae", exts: [".json"] }
|
|
5477
5704
|
];
|
|
@@ -5479,7 +5706,7 @@ async function runDoctor(lang = "zh") {
|
|
|
5479
5706
|
let installed = !1, n = 0;
|
|
5480
5707
|
for (let dir of tool.dirs)
|
|
5481
5708
|
try {
|
|
5482
|
-
await
|
|
5709
|
+
await stat5(dir), installed = !0, n += await countFiles(dir, tool.exts);
|
|
5483
5710
|
} catch {
|
|
5484
5711
|
}
|
|
5485
5712
|
if (!installed) {
|
|
@@ -5488,6 +5715,25 @@ async function runDoctor(lang = "zh") {
|
|
|
5488
5715
|
}
|
|
5489
5716
|
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
5717
|
}
|
|
5718
|
+
let openCodeSources = await resolveOpenCodeSources({
|
|
5719
|
+
dbPaths: config.scanner?.opencodeDbPaths
|
|
5720
|
+
}), openCodeLegacyCount = await countFiles(openCodeSources.legacyDir, [".json"]), openCodeInstalled = openCodeSources.dbPaths.length > 0 || openCodeLegacyCount > 0;
|
|
5721
|
+
if (!openCodeInstalled)
|
|
5722
|
+
try {
|
|
5723
|
+
await stat5(openCodeSources.dataDir), openCodeInstalled = !0;
|
|
5724
|
+
} catch {
|
|
5725
|
+
}
|
|
5726
|
+
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({
|
|
5727
|
+
group: g3,
|
|
5728
|
+
name: "OpenCode",
|
|
5729
|
+
status: "warn",
|
|
5730
|
+
message: s.openCodeSqliteUnavailable
|
|
5731
|
+
}) : checks.push({
|
|
5732
|
+
group: g3,
|
|
5733
|
+
name: "OpenCode",
|
|
5734
|
+
status: "ok",
|
|
5735
|
+
message: s.openCodeData(openCodeSources.dbPaths.length, openCodeLegacyCount)
|
|
5736
|
+
}) : checks.push({ group: g3, name: "OpenCode", status: "warn", message: s.notInstalled });
|
|
5491
5737
|
let g4 = s.groupSchedule, schedule = await getScheduleStatus();
|
|
5492
5738
|
return schedule.enabled ? checks.push({
|
|
5493
5739
|
group: g4,
|
|
@@ -5498,7 +5744,7 @@ async function runDoctor(lang = "zh") {
|
|
|
5498
5744
|
}
|
|
5499
5745
|
|
|
5500
5746
|
// src/project.ts
|
|
5501
|
-
import { open as open2, readdir as
|
|
5747
|
+
import { open as open2, readdir as readdir9, readFile as readFile17 } from "node:fs/promises";
|
|
5502
5748
|
import { basename as basename14, join as join21 } from "node:path";
|
|
5503
5749
|
import { homedir as homedir20 } from "node:os";
|
|
5504
5750
|
async function discoverProjects(projectAliases) {
|
|
@@ -5548,7 +5794,7 @@ async function discoverClaudeProjects() {
|
|
|
5548
5794
|
for (let baseDir of getClaudeDirs()) {
|
|
5549
5795
|
let entries;
|
|
5550
5796
|
try {
|
|
5551
|
-
entries = await
|
|
5797
|
+
entries = await readdir9(baseDir, { withFileTypes: !0 });
|
|
5552
5798
|
} catch {
|
|
5553
5799
|
continue;
|
|
5554
5800
|
}
|
|
@@ -5593,7 +5839,7 @@ async function walkFiles2(dir, ext) {
|
|
|
5593
5839
|
async function walk2(d) {
|
|
5594
5840
|
let entries;
|
|
5595
5841
|
try {
|
|
5596
|
-
entries = await
|
|
5842
|
+
entries = await readdir9(d, { withFileTypes: !0 });
|
|
5597
5843
|
} catch {
|
|
5598
5844
|
return;
|
|
5599
5845
|
}
|
|
@@ -5635,7 +5881,7 @@ async function extractCwdFromFirstJsonl(dir) {
|
|
|
5635
5881
|
async function findFirstJsonl(dir) {
|
|
5636
5882
|
let entries;
|
|
5637
5883
|
try {
|
|
5638
|
-
entries = await
|
|
5884
|
+
entries = await readdir9(dir, { withFileTypes: !0 });
|
|
5639
5885
|
} catch {
|
|
5640
5886
|
return;
|
|
5641
5887
|
}
|
|
@@ -5644,7 +5890,7 @@ async function findFirstJsonl(dir) {
|
|
|
5644
5890
|
for (let entry of entries)
|
|
5645
5891
|
if (!(!entry.isDirectory() || entry.name.startsWith(".")))
|
|
5646
5892
|
try {
|
|
5647
|
-
let sub = (await
|
|
5893
|
+
let sub = (await readdir9(join21(dir, entry.name))).find((f) => f.endsWith(".jsonl"));
|
|
5648
5894
|
if (sub) return join21(dir, entry.name, sub);
|
|
5649
5895
|
} catch {
|
|
5650
5896
|
continue;
|
|
@@ -5724,7 +5970,7 @@ async function discoverCopilotVscodeProjects() {
|
|
|
5724
5970
|
async function discoverAntigravityProjects() {
|
|
5725
5971
|
let dir = join21(homedir20(), ".gemini", "antigravity", "knowledge"), entries;
|
|
5726
5972
|
try {
|
|
5727
|
-
entries = await
|
|
5973
|
+
entries = await readdir9(dir, { withFileTypes: !0 });
|
|
5728
5974
|
} catch {
|
|
5729
5975
|
return [];
|
|
5730
5976
|
}
|
|
@@ -5960,7 +6206,7 @@ function assertPricingCatalog(value) {
|
|
|
5960
6206
|
import { execFile as execFile3 } from "node:child_process";
|
|
5961
6207
|
import { createHash as createHash2 } from "node:crypto";
|
|
5962
6208
|
import { existsSync as existsSync2 } from "node:fs";
|
|
5963
|
-
import { mkdir as mkdir4, open as open3, readdir as
|
|
6209
|
+
import { mkdir as mkdir4, open as open3, readdir as readdir10, rename, stat as stat6, writeFile as writeFile4 } from "node:fs/promises";
|
|
5964
6210
|
import { createServer } from "node:net";
|
|
5965
6211
|
import { homedir as homedir22 } from "node:os";
|
|
5966
6212
|
import { join as join23 } from "node:path";
|
|
@@ -6197,12 +6443,12 @@ var CdpClient = class _CdpClient {
|
|
|
6197
6443
|
pending = /* @__PURE__ */ new Map();
|
|
6198
6444
|
static async connect(url, timeoutMs) {
|
|
6199
6445
|
let socket = new WebSocket(url);
|
|
6200
|
-
return await new Promise((
|
|
6446
|
+
return await new Promise((resolve6, reject) => {
|
|
6201
6447
|
let timer = setTimeout(() => {
|
|
6202
6448
|
socket.close(), reject(new Error("\u8FDE\u63A5 Trae CN \u672C\u5730\u63A5\u53E3\u8D85\u65F6"));
|
|
6203
6449
|
}, timeoutMs);
|
|
6204
6450
|
socket.once("open", () => {
|
|
6205
|
-
clearTimeout(timer),
|
|
6451
|
+
clearTimeout(timer), resolve6();
|
|
6206
6452
|
}), socket.once("error", (error) => {
|
|
6207
6453
|
clearTimeout(timer), reject(error);
|
|
6208
6454
|
});
|
|
@@ -6210,11 +6456,11 @@ var CdpClient = class _CdpClient {
|
|
|
6210
6456
|
}
|
|
6211
6457
|
call(method, params, timeoutMs) {
|
|
6212
6458
|
let id = ++this.sequence;
|
|
6213
|
-
return new Promise((
|
|
6459
|
+
return new Promise((resolve6, reject) => {
|
|
6214
6460
|
let timer = setTimeout(() => {
|
|
6215
6461
|
this.pending.delete(id), reject(new Error(`Trae CN \u672C\u5730\u8C03\u7528\u8D85\u65F6: ${method}`));
|
|
6216
6462
|
}, timeoutMs);
|
|
6217
|
-
this.pending.set(id, { resolve:
|
|
6463
|
+
this.pending.set(id, { resolve: resolve6, reject, timer }), this.socket.send(JSON.stringify({ id, method, params }));
|
|
6218
6464
|
});
|
|
6219
6465
|
}
|
|
6220
6466
|
close() {
|
|
@@ -6271,7 +6517,7 @@ async function findTraeUserIds(userDataDir) {
|
|
|
6271
6517
|
async function findCompletionLogs(dir) {
|
|
6272
6518
|
let entries;
|
|
6273
6519
|
try {
|
|
6274
|
-
entries = await
|
|
6520
|
+
entries = await readdir10(dir, { withFileTypes: !0 });
|
|
6275
6521
|
} catch {
|
|
6276
6522
|
return [];
|
|
6277
6523
|
}
|
|
@@ -6281,7 +6527,7 @@ async function findCompletionLogs(dir) {
|
|
|
6281
6527
|
if (entry.isDirectory()) files.push(...await findCompletionLogs(path));
|
|
6282
6528
|
else if (entry.name === "completion.log" && path.includes("trae.ai-code-completion"))
|
|
6283
6529
|
try {
|
|
6284
|
-
files.push({ path, mtimeMs: (await
|
|
6530
|
+
files.push({ path, mtimeMs: (await stat6(path)).mtimeMs });
|
|
6285
6531
|
} catch {
|
|
6286
6532
|
}
|
|
6287
6533
|
}
|
|
@@ -6340,17 +6586,17 @@ async function isTraeRunning() {
|
|
|
6340
6586
|
}
|
|
6341
6587
|
}
|
|
6342
6588
|
async function isPortAvailable(port) {
|
|
6343
|
-
return new Promise((
|
|
6589
|
+
return new Promise((resolve6) => {
|
|
6344
6590
|
let server = createServer();
|
|
6345
|
-
server.once("error", () =>
|
|
6591
|
+
server.once("error", () => resolve6(!1)), server.listen(port, "127.0.0.1", () => server.close(() => resolve6(!0)));
|
|
6346
6592
|
});
|
|
6347
6593
|
}
|
|
6348
6594
|
async function findFreePort() {
|
|
6349
|
-
return new Promise((
|
|
6595
|
+
return new Promise((resolve6, reject) => {
|
|
6350
6596
|
let server = createServer();
|
|
6351
6597
|
server.once("error", reject), server.listen(0, "127.0.0.1", () => {
|
|
6352
6598
|
let address = server.address(), port = typeof address == "object" && address ? address.port : 0;
|
|
6353
|
-
server.close((error) => error ? reject(error) :
|
|
6599
|
+
server.close((error) => error ? reject(error) : resolve6(port));
|
|
6354
6600
|
});
|
|
6355
6601
|
});
|
|
6356
6602
|
}
|
|
@@ -6383,7 +6629,7 @@ function stringValue4(value) {
|
|
|
6383
6629
|
return typeof value == "string" ? value.trim() : "";
|
|
6384
6630
|
}
|
|
6385
6631
|
function delay(ms) {
|
|
6386
|
-
return new Promise((
|
|
6632
|
+
return new Promise((resolve6) => setTimeout(resolve6, ms));
|
|
6387
6633
|
}
|
|
6388
6634
|
|
|
6389
6635
|
// src/trae-intl-sync.ts
|
|
@@ -6391,13 +6637,13 @@ import { createDecipheriv, createHash as createHash3, timingSafeEqual } from "no
|
|
|
6391
6637
|
import { existsSync as existsSync3 } from "node:fs";
|
|
6392
6638
|
import { chmod, mkdir as mkdir5, open as open4, readFile as readFile20, rename as rename2, unlink as unlink2 } from "node:fs/promises";
|
|
6393
6639
|
import { homedir as homedir23 } from "node:os";
|
|
6394
|
-
import { dirname as
|
|
6640
|
+
import { dirname as dirname9, join as join24 } from "node:path";
|
|
6395
6641
|
var DEFAULT_HOST = "https://api-sg-central.trae.ai", CLIENT_IDS = {
|
|
6396
6642
|
ide: "ono9krqynydwx5",
|
|
6397
6643
|
solo: "en1oxy7wnw8j9n"
|
|
6398
6644
|
}, 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
6645
|
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(
|
|
6646
|
+
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
6647
|
try {
|
|
6402
6648
|
return await performTraeIntlSync(options, sinceDays, cacheDir, fetchImpl, now);
|
|
6403
6649
|
} finally {
|
|
@@ -6657,10 +6903,10 @@ async function requestJson2(url, init, fetchImpl, timeoutMs) {
|
|
|
6657
6903
|
}
|
|
6658
6904
|
}
|
|
6659
6905
|
async function loadCredentials(variant, cacheDir) {
|
|
6660
|
-
return readCredentialFile(join24(
|
|
6906
|
+
return readCredentialFile(join24(dirname9(cacheDir), `credentials-${variant}.json`), variant);
|
|
6661
6907
|
}
|
|
6662
6908
|
async function loadTokscaleCredentials(variant) {
|
|
6663
|
-
let root =
|
|
6909
|
+
let root = dirname9(resolveTokscaleTraeCacheDir());
|
|
6664
6910
|
return readCredentialFile(join24(root, `credentials-${variant}.json`), variant);
|
|
6665
6911
|
}
|
|
6666
6912
|
async function readCredentialFile(path, fallbackVariant) {
|
|
@@ -6683,7 +6929,7 @@ async function readCredentialFile(path, fallbackVariant) {
|
|
|
6683
6929
|
}
|
|
6684
6930
|
}
|
|
6685
6931
|
async function saveCredentials(credentials, cacheDir) {
|
|
6686
|
-
let path = join24(
|
|
6932
|
+
let path = join24(dirname9(cacheDir), `credentials-${credentials.variant}.json`);
|
|
6687
6933
|
await writePrivateJson(path, credentials);
|
|
6688
6934
|
}
|
|
6689
6935
|
async function readSessionArray(path) {
|
|
@@ -6695,7 +6941,7 @@ async function readSessionArray(path) {
|
|
|
6695
6941
|
}
|
|
6696
6942
|
}
|
|
6697
6943
|
async function writePrivateJson(path, value) {
|
|
6698
|
-
let dir =
|
|
6944
|
+
let dir = dirname9(path);
|
|
6699
6945
|
await mkdir5(dir, { recursive: !0, mode: 448 }), await chmod(dir, 448).catch(() => {
|
|
6700
6946
|
});
|
|
6701
6947
|
let tempPath = join24(dir, `.${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}.tmp`), handle = await open4(tempPath, "w", 384);
|
|
@@ -6769,7 +7015,7 @@ function sanitizeError(error) {
|
|
|
6769
7015
|
return sanitizeResponse(parts.join(": "));
|
|
6770
7016
|
}
|
|
6771
7017
|
function delay2(ms) {
|
|
6772
|
-
return new Promise((
|
|
7018
|
+
return new Promise((resolve6) => setTimeout(resolve6, ms));
|
|
6773
7019
|
}
|
|
6774
7020
|
|
|
6775
7021
|
// src/cli.ts
|
|
@@ -6884,7 +7130,7 @@ await (async () => {
|
|
|
6884
7130
|
async function runScan(flags, positionals = []) {
|
|
6885
7131
|
let config = await readConfig(), zh2 = config.lang === "zh";
|
|
6886
7132
|
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 });
|
|
7133
|
+
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
7134
|
if (isJson) {
|
|
6889
7135
|
console.log(JSON.stringify(results.length === 1 ? results[0] : results, null, 2));
|
|
6890
7136
|
return;
|
|
@@ -6930,6 +7176,7 @@ async function runReport(flags, positionals = []) {
|
|
|
6930
7176
|
target: pricingTarget
|
|
6931
7177
|
}), report = await buildLocalReport(range, {
|
|
6932
7178
|
projectAliases: config.projectAliases,
|
|
7179
|
+
opencodeDbPaths: config.scanner?.opencodeDbPaths,
|
|
6933
7180
|
dates,
|
|
6934
7181
|
tools,
|
|
6935
7182
|
pricingCatalog: pricing.catalog,
|
|
@@ -6993,9 +7240,9 @@ async function runEnroll(flags) {
|
|
|
6993
7240
|
}
|
|
6994
7241
|
function prompt(question) {
|
|
6995
7242
|
let rl = createInterface4({ input: process.stdin, output: process.stdout });
|
|
6996
|
-
return new Promise((
|
|
7243
|
+
return new Promise((resolve6) => {
|
|
6997
7244
|
rl.question(question, (answer) => {
|
|
6998
|
-
rl.close(),
|
|
7245
|
+
rl.close(), resolve6(answer.trim());
|
|
6999
7246
|
});
|
|
7000
7247
|
});
|
|
7001
7248
|
}
|
|
@@ -7011,7 +7258,10 @@ async function runSync(flags, positionals = []) {
|
|
|
7011
7258
|
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
7259
|
console.log(`\u626B\u63CF ${targetDates.length} \u5929 (${targetDates[0]} ~ ${targetDates[targetDates.length - 1]}) ...`);
|
|
7013
7260
|
let [results, activityReport] = await Promise.all([
|
|
7014
|
-
scanDates(targetDates, {
|
|
7261
|
+
scanDates(targetDates, {
|
|
7262
|
+
projectAliases: config.projectAliases,
|
|
7263
|
+
opencodeDbPaths: config.scanner?.opencodeDbPaths
|
|
7264
|
+
}),
|
|
7015
7265
|
buildActivityReport("all", { dates: targetDates, projectAliases: config.projectAliases })
|
|
7016
7266
|
]), visibility = config.privacy?.projectVisibility, resultsByDate = new Map(results.map((result) => [result.usageDate, result])), activityByDate = buildActivityPayloadByDate(activityReport.items, visibility), allDays = targetDates.map((usageDate) => {
|
|
7017
7267
|
let breakdowns = applyPrivacy(resultsByDate.get(usageDate)?.breakdowns ?? [], visibility), activity = activityByDate.get(usageDate);
|
package/package.json
CHANGED
package/pricing-catalog.json
CHANGED