@aiusage/cli 1.7.3 → 1.7.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +41 -8
- package/README.zh-CN.md +21 -1
- package/dist/cli.js +1957 -630
- package/package.json +4 -1
package/dist/cli.js
CHANGED
|
@@ -16,7 +16,7 @@ import { join as join2 } from "node:path";
|
|
|
16
16
|
import { homedir } from "node:os";
|
|
17
17
|
|
|
18
18
|
// src/scanners/utils.ts
|
|
19
|
-
import { readdir } from "node:fs/promises";
|
|
19
|
+
import { readdir, stat } from "node:fs/promises";
|
|
20
20
|
import { join } from "node:path";
|
|
21
21
|
var MIN_VALID_MS = Date.UTC(2015, 0, 1);
|
|
22
22
|
function parseTs(value) {
|
|
@@ -32,12 +32,23 @@ function parseTs(value) {
|
|
|
32
32
|
function dateKey(date) {
|
|
33
33
|
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
|
|
34
34
|
}
|
|
35
|
+
async function fileModifiedTs(filePath) {
|
|
36
|
+
try {
|
|
37
|
+
return parseTs((await stat(filePath)).mtimeMs);
|
|
38
|
+
} catch {
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
function inferProviderFromModel(model, fallback) {
|
|
43
|
+
let value = model.trim().toLowerCase();
|
|
44
|
+
return /^(claude|opus|sonnet|haiku)(?:[-.]|$)/.test(value) ? "anthropic" : /^(gpt|chatgpt|codex|o[134])(?:[-.]|$)/.test(value) ? "openai" : /^gemini(?:[-.]|$)/.test(value) ? "google" : /^qwen(?:[-.]|$)/.test(value) ? "alibaba" : /^deepseek(?:[-.]|$)/.test(value) ? "deepseek" : /^(glm|codegeex)(?:[-.]|$)/.test(value) ? "zhipu" : /^(kimi|moonshot)(?:[-/.]|$)/.test(value) ? "moonshot" : /^grok(?:[-.]|$)/.test(value) ? "xai" : fallback;
|
|
45
|
+
}
|
|
35
46
|
function projectFromPath(raw, aliases2) {
|
|
36
|
-
let parts = raw.split(
|
|
47
|
+
let parts = raw.split(/[\\/]+/).filter(Boolean), name = parts[parts.length - 1] || "unknown";
|
|
37
48
|
return aliases2?.[raw] ?? aliases2?.[name] ?? name;
|
|
38
49
|
}
|
|
39
50
|
function resolveProjectFields(rawPath, aliases2) {
|
|
40
|
-
let parts = rawPath.split(
|
|
51
|
+
let parts = rawPath.split(/[\\/]+/).filter(Boolean), display = parts[parts.length - 1] || "unknown", alias = aliases2?.[rawPath] ?? aliases2?.[display];
|
|
41
52
|
return {
|
|
42
53
|
project: rawPath || "unknown",
|
|
43
54
|
projectDisplay: display,
|
|
@@ -55,6 +66,7 @@ async function walk(dir, ext, out) {
|
|
|
55
66
|
} catch {
|
|
56
67
|
return;
|
|
57
68
|
}
|
|
69
|
+
entries.sort((a, b) => a.name.localeCompare(b.name));
|
|
58
70
|
for (let e of entries) {
|
|
59
71
|
let full = join(dir, e.name);
|
|
60
72
|
e.isDirectory() ? await walk(full, ext, out) : e.name.endsWith(ext) && out.push(full);
|
|
@@ -167,11 +179,12 @@ function upsertSessionDate(sessionDates, sessionId, timestamp) {
|
|
|
167
179
|
}
|
|
168
180
|
|
|
169
181
|
// src/scanners/claude.ts
|
|
170
|
-
import {
|
|
182
|
+
import { createReadStream } from "node:fs";
|
|
183
|
+
import { readdir as readdir3 } from "node:fs/promises";
|
|
171
184
|
import { join as join3 } from "node:path";
|
|
172
185
|
import { homedir as homedir2 } from "node:os";
|
|
173
186
|
import { createInterface } from "node:readline";
|
|
174
|
-
var FILE_CONCURRENCY = 16, MAX_LINE_BYTES = 64 * 1024 * 1024
|
|
187
|
+
var FILE_CONCURRENCY = 16, MAX_LINE_BYTES = 64 * 1024 * 1024;
|
|
175
188
|
function getClaudeProjectDirs(claudeDir) {
|
|
176
189
|
if (claudeDir) return [claudeDir];
|
|
177
190
|
let envVar = process.env.CLAUDE_CONFIG_DIR?.trim();
|
|
@@ -186,7 +199,7 @@ function getClaudeProjectDirs(claudeDir) {
|
|
|
186
199
|
async function scanClaudeDates(targetDates, claudeDir, projectAliases) {
|
|
187
200
|
let targetDateSet = new Set(targetDates), groupedByDate = /* @__PURE__ */ new Map();
|
|
188
201
|
for (let targetDate of targetDateSet) groupedByDate.set(targetDate, /* @__PURE__ */ new Map());
|
|
189
|
-
let baseDirs = getClaudeProjectDirs(claudeDir), processedHashes = /* @__PURE__ */ new
|
|
202
|
+
let baseDirs = getClaudeProjectDirs(claudeDir), processedHashes = /* @__PURE__ */ new Map(), sessionSets = /* @__PURE__ */ new Map(), fileJobs = [];
|
|
190
203
|
for (let baseDir of baseDirs) {
|
|
191
204
|
let projectDirs;
|
|
192
205
|
try {
|
|
@@ -205,20 +218,9 @@ async function scanClaudeDates(targetDates, claudeDir, projectAliases) {
|
|
|
205
218
|
fileJobs.push({ filePath, projectFields: fields });
|
|
206
219
|
}
|
|
207
220
|
}
|
|
208
|
-
await runWithConcurrency(fileJobs, FILE_CONCURRENCY, async (job) => {
|
|
221
|
+
fileJobs.sort((a, b) => a.filePath.localeCompare(b.filePath)), await runWithConcurrency(fileJobs, FILE_CONCURRENCY, async (job) => {
|
|
209
222
|
await processJsonlFile(job.filePath, job.projectFields, targetDateSet, projectAliases, groupedByDate, processedHashes, sessionSets);
|
|
210
223
|
});
|
|
211
|
-
let missingDates = [...targetDateSet].filter((d) => groupedByDate.get(d)?.size === 0);
|
|
212
|
-
if (missingDates.length > 0) {
|
|
213
|
-
let remaining = new Set(missingDates);
|
|
214
|
-
for (let baseDir of baseDirs) {
|
|
215
|
-
if (remaining.size === 0) break;
|
|
216
|
-
let statsCachePath = join3(baseDir, "..", "stats-cache.json");
|
|
217
|
-
await fillFromStatsCache(statsCachePath, remaining, groupedByDate);
|
|
218
|
-
for (let d of remaining)
|
|
219
|
-
groupedByDate.get(d).size > 0 && remaining.delete(d);
|
|
220
|
-
}
|
|
221
|
-
}
|
|
222
224
|
for (let [usageDate, grouped] of groupedByDate.entries())
|
|
223
225
|
for (let [key, breakdown] of grouped.entries()) {
|
|
224
226
|
let sessionSetKey = `${usageDate}|${key}`;
|
|
@@ -229,15 +231,10 @@ async function scanClaudeDates(targetDates, claudeDir, projectAliases) {
|
|
|
229
231
|
);
|
|
230
232
|
}
|
|
231
233
|
async function processJsonlFile(filePath, fallbackFields, targetDateSet, projectAliases, groupedByDate, processedHashes, sessionSets) {
|
|
232
|
-
let fallbackSessionId = filePath.replace(/^.*[\\/]/, "").replace(/\.jsonl$/, ""),
|
|
233
|
-
try {
|
|
234
|
-
fh = await open(filePath, "r");
|
|
235
|
-
} catch {
|
|
236
|
-
return;
|
|
237
|
-
}
|
|
234
|
+
let fallbackSessionId = filePath.replace(/^.*[\\/]/, "").replace(/\.jsonl$/, ""), input = createReadStream(filePath, { encoding: "utf-8" });
|
|
238
235
|
try {
|
|
239
236
|
let rl = createInterface({
|
|
240
|
-
input
|
|
237
|
+
input,
|
|
241
238
|
crlfDelay: 1 / 0
|
|
242
239
|
});
|
|
243
240
|
for await (let line of rl) {
|
|
@@ -256,86 +253,76 @@ async function processJsonlFile(filePath, fallbackFields, targetDateSet, project
|
|
|
256
253
|
if (!message?.usage) continue;
|
|
257
254
|
let rawModel = message.model ?? "unknown";
|
|
258
255
|
if (rawModel === "<synthetic>") continue;
|
|
259
|
-
let messageId = message.id, requestId = record.requestId;
|
|
260
|
-
if (messageId && requestId) {
|
|
261
|
-
let hash = `${messageId}:${requestId}`;
|
|
262
|
-
if (processedHashes.has(hash)) continue;
|
|
263
|
-
processedHashes.add(hash);
|
|
264
|
-
}
|
|
265
|
-
let usage = message.usage, model = normalizeModelName(rawModel);
|
|
256
|
+
let messageId = message.id, requestId = record.requestId, hash = messageId ? requestId ? `${messageId}:${requestId}` : `message:${messageId}` : void 0, usage = message.usage, model = normalizeModelName(rawModel);
|
|
266
257
|
usage.speed === "fast" && (model = `${model}-fast`);
|
|
267
|
-
let recordFields = record.cwd ? resolveProject(record.cwd, projectAliases) : fallbackFields, sessionId = record.sessionId ?? fallbackSessionId, costUSD = record.costUSD ?? 0, cacheCreation = usage.cache_creation, cache5m = cacheCreation?.ephemeral_5m_input_tokens ?? 0, cache1h = cacheCreation?.ephemeral_1h_input_tokens ?? 0;
|
|
258
|
+
let provider = resolveClaudeProvider(record, rawModel), recordFields = record.cwd ? resolveProject(record.cwd, projectAliases) : fallbackFields, sessionId = record.sessionId ?? fallbackSessionId, costUSD = record.costUSD ?? 0, cacheCreation = usage.cache_creation, cache5m = cacheCreation?.ephemeral_5m_input_tokens ?? 0, cache1h = cacheCreation?.ephemeral_1h_input_tokens ?? 0;
|
|
268
259
|
cache5m === 0 && cache1h === 0 && (usage.cache_creation_input_tokens ?? 0) > 0 && (cache5m = usage.cache_creation_input_tokens);
|
|
269
260
|
let grouped = groupedByDate.get(usageDate);
|
|
270
261
|
if (!grouped) continue;
|
|
271
|
-
let
|
|
262
|
+
let snapshot = {
|
|
263
|
+
input: clampToken(usage.input_tokens),
|
|
264
|
+
cached: clampToken(usage.cache_read_input_tokens),
|
|
265
|
+
cacheWrite: clampToken(usage.cache_creation_input_tokens) || clampToken(cache5m) + clampToken(cache1h),
|
|
266
|
+
cache5m: clampToken(cache5m),
|
|
267
|
+
cache1h: clampToken(cache1h),
|
|
268
|
+
output: clampToken(usage.output_tokens),
|
|
269
|
+
costUSD: clampToken(costUSD)
|
|
270
|
+
}, cacheWriteTokens = snapshot.cacheWrite, seen = hash ? processedHashes.get(hash) : void 0;
|
|
271
|
+
if (seen) {
|
|
272
|
+
mergeClaudeDuplicate(seen, snapshot);
|
|
273
|
+
continue;
|
|
274
|
+
}
|
|
275
|
+
let key = `${provider}|${model}|${recordFields.project}`, sessionSetKey = `${usageDate}|${key}`;
|
|
272
276
|
sessionSets.has(sessionSetKey) || sessionSets.set(sessionSetKey, /* @__PURE__ */ new Set()), sessionSets.get(sessionSetKey).add(sessionId);
|
|
273
277
|
let existing = grouped.get(key);
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
project: recordFields.project,
|
|
280
|
-
projectDisplay: recordFields.projectDisplay,
|
|
281
|
-
projectAlias: recordFields.projectAlias,
|
|
282
|
-
eventCount: 1,
|
|
283
|
-
inputTokens: usage.input_tokens ?? 0,
|
|
284
|
-
cachedInputTokens: usage.cache_read_input_tokens ?? 0,
|
|
285
|
-
cacheWriteTokens,
|
|
286
|
-
cacheWrite5mTokens: cache5m,
|
|
287
|
-
cacheWrite1hTokens: cache1h,
|
|
288
|
-
outputTokens: usage.output_tokens ?? 0,
|
|
289
|
-
reasoningOutputTokens: 0,
|
|
290
|
-
costUSD
|
|
291
|
-
});
|
|
292
|
-
}
|
|
293
|
-
} finally {
|
|
294
|
-
await fh.close();
|
|
295
|
-
}
|
|
296
|
-
}
|
|
297
|
-
async function fillFromStatsCache(statsCachePath, missingDates, groupedByDate) {
|
|
298
|
-
let raw;
|
|
299
|
-
try {
|
|
300
|
-
raw = await readFile2(statsCachePath, "utf-8");
|
|
301
|
-
} catch {
|
|
302
|
-
return;
|
|
303
|
-
}
|
|
304
|
-
let cache;
|
|
305
|
-
try {
|
|
306
|
-
cache = JSON.parse(raw);
|
|
307
|
-
} catch {
|
|
308
|
-
return;
|
|
309
|
-
}
|
|
310
|
-
let inputRatios = {};
|
|
311
|
-
for (let [model, usage] of Object.entries(cache.modelUsage ?? {})) {
|
|
312
|
-
let inp = usage.inputTokens ?? 0, out = usage.outputTokens ?? 0, total = inp + out;
|
|
313
|
-
total > 0 && (inputRatios[model] = inp / total);
|
|
314
|
-
}
|
|
315
|
-
for (let entry of cache.dailyModelTokens ?? []) {
|
|
316
|
-
let { date, tokensByModel } = entry;
|
|
317
|
-
if (!missingDates.has(date)) continue;
|
|
318
|
-
let grouped = groupedByDate.get(date);
|
|
319
|
-
if (grouped)
|
|
320
|
-
for (let [rawModel, totalTokens] of Object.entries(tokensByModel)) {
|
|
321
|
-
if (!totalTokens) continue;
|
|
322
|
-
let model = normalizeModelName(rawModel), ratio = inputRatios[rawModel] ?? inputRatios[model] ?? STATS_CACHE_DEFAULT_INPUT_RATIO, inputTokens = Math.round(totalTokens * ratio), outputTokens = totalTokens - inputTokens, key = `${model}|unknown`, existing = grouped.get(key);
|
|
323
|
-
existing ? (existing.eventCount += 1, existing.inputTokens += inputTokens, existing.outputTokens += outputTokens) : grouped.set(key, {
|
|
324
|
-
provider: "anthropic",
|
|
278
|
+
if (existing)
|
|
279
|
+
existing.eventCount += 1, existing.inputTokens += snapshot.input, existing.cachedInputTokens += snapshot.cached, existing.cacheWriteTokens += cacheWriteTokens, existing.cacheWrite5mTokens = (existing.cacheWrite5mTokens ?? 0) + snapshot.cache5m, existing.cacheWrite1hTokens = (existing.cacheWrite1hTokens ?? 0) + snapshot.cache1h, existing.outputTokens += snapshot.output, existing.costUSD = (existing.costUSD ?? 0) + snapshot.costUSD, hash && processedHashes.set(hash, { breakdown: existing, snapshot });
|
|
280
|
+
else {
|
|
281
|
+
let breakdown = {
|
|
282
|
+
provider,
|
|
325
283
|
product: "claude-code",
|
|
326
284
|
channel: "cli",
|
|
327
285
|
model,
|
|
328
|
-
project:
|
|
286
|
+
project: recordFields.project,
|
|
287
|
+
projectDisplay: recordFields.projectDisplay,
|
|
288
|
+
projectAlias: recordFields.projectAlias,
|
|
329
289
|
eventCount: 1,
|
|
330
|
-
inputTokens,
|
|
331
|
-
cachedInputTokens:
|
|
332
|
-
cacheWriteTokens
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
290
|
+
inputTokens: snapshot.input,
|
|
291
|
+
cachedInputTokens: snapshot.cached,
|
|
292
|
+
cacheWriteTokens,
|
|
293
|
+
cacheWrite5mTokens: snapshot.cache5m,
|
|
294
|
+
cacheWrite1hTokens: snapshot.cache1h,
|
|
295
|
+
outputTokens: snapshot.output,
|
|
296
|
+
reasoningOutputTokens: 0,
|
|
297
|
+
costUSD: snapshot.costUSD
|
|
298
|
+
};
|
|
299
|
+
grouped.set(key, breakdown), hash && processedHashes.set(hash, { breakdown, snapshot });
|
|
336
300
|
}
|
|
301
|
+
}
|
|
302
|
+
} catch {
|
|
303
|
+
} finally {
|
|
304
|
+
input.destroy();
|
|
337
305
|
}
|
|
338
306
|
}
|
|
307
|
+
function mergeClaudeDuplicate(seen, incoming) {
|
|
308
|
+
let incomingHasNewerCacheWrite = incoming.cacheWrite > seen.snapshot.cacheWrite, merged = {
|
|
309
|
+
input: Math.max(seen.snapshot.input, incoming.input),
|
|
310
|
+
cached: Math.max(seen.snapshot.cached, incoming.cached),
|
|
311
|
+
cacheWrite: Math.max(seen.snapshot.cacheWrite, incoming.cacheWrite),
|
|
312
|
+
cache5m: incomingHasNewerCacheWrite ? incoming.cache5m : seen.snapshot.cache5m,
|
|
313
|
+
cache1h: incomingHasNewerCacheWrite ? incoming.cache1h : seen.snapshot.cache1h,
|
|
314
|
+
output: Math.max(seen.snapshot.output, incoming.output),
|
|
315
|
+
costUSD: Math.max(seen.snapshot.costUSD, incoming.costUSD)
|
|
316
|
+
}, breakdown = seen.breakdown;
|
|
317
|
+
breakdown.inputTokens += merged.input - seen.snapshot.input, breakdown.cachedInputTokens += merged.cached - seen.snapshot.cached, breakdown.cacheWrite5mTokens = (breakdown.cacheWrite5mTokens ?? 0) + merged.cache5m - seen.snapshot.cache5m, breakdown.cacheWrite1hTokens = (breakdown.cacheWrite1hTokens ?? 0) + merged.cache1h - seen.snapshot.cache1h, breakdown.cacheWriteTokens += merged.cacheWrite - seen.snapshot.cacheWrite, breakdown.outputTokens += merged.output - seen.snapshot.output, breakdown.costUSD = (breakdown.costUSD ?? 0) + merged.costUSD - seen.snapshot.costUSD, seen.snapshot = merged;
|
|
318
|
+
}
|
|
319
|
+
function clampToken(value) {
|
|
320
|
+
return Math.max(Number.isFinite(value) ? value : 0, 0);
|
|
321
|
+
}
|
|
322
|
+
function resolveClaudeProvider(record, model) {
|
|
323
|
+
let explicit = (record.message?.providerId ?? record.message?.provider_id ?? record.message?.provider ?? record.providerId ?? record.provider_id ?? record.provider)?.trim().toLowerCase(), inferred = model.trim().toLowerCase().match(/^([a-z0-9_-]+)\//)?.[1] ?? inferProviderFromModel(model, "unknown");
|
|
324
|
+
return explicit && explicit !== "anthropic" ? explicit : inferred !== "unknown" ? inferred : explicit ?? "unknown";
|
|
325
|
+
}
|
|
339
326
|
function parseTimestamp(value) {
|
|
340
327
|
if (!value) return null;
|
|
341
328
|
try {
|
|
@@ -366,8 +353,9 @@ async function walkForJsonl(dir, result) {
|
|
|
366
353
|
}
|
|
367
354
|
|
|
368
355
|
// src/scanners/codex.ts
|
|
369
|
-
import {
|
|
370
|
-
import {
|
|
356
|
+
import { createReadStream as createReadStream2 } from "node:fs";
|
|
357
|
+
import { readdir as readdir4, readFile as readFile2 } from "node:fs/promises";
|
|
358
|
+
import { basename, join as join4 } from "node:path";
|
|
371
359
|
import { homedir as homedir3 } from "node:os";
|
|
372
360
|
import { createInterface as createInterface2 } from "node:readline";
|
|
373
361
|
|
|
@@ -1443,25 +1431,32 @@ async function scanCodexDates(targetDates, codexDir, projectAliases) {
|
|
|
1443
1431
|
let baseDir = codexDir ?? join4(homedir3(), ".codex"), serviceTier = await detectCodexServiceTier(baseDir), sessionFiles = await collectSessionFiles(baseDir);
|
|
1444
1432
|
if (sessionFiles.length === 0)
|
|
1445
1433
|
return new Map([...targetDateSet].map((targetDate) => [targetDate, []]));
|
|
1434
|
+
let eventsByFile = Array.from({ length: sessionFiles.length }, () => []);
|
|
1435
|
+
await runWithConcurrency(sessionFiles, FILE_CONCURRENCY2, async (filePath, index) => {
|
|
1436
|
+
eventsByFile[index] = await processCodexFile(filePath, projectAliases, serviceTier);
|
|
1437
|
+
});
|
|
1446
1438
|
let globalSeenSigs = /* @__PURE__ */ new Set();
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1439
|
+
for (let events of eventsByFile)
|
|
1440
|
+
for (let event of events)
|
|
1441
|
+
globalSeenSigs.has(event.signature) || (globalSeenSigs.add(event.signature), targetDateSet.has(event.usageDate) && mergeCodexEvent(groupedByDate, event));
|
|
1442
|
+
return new Map(
|
|
1450
1443
|
[...groupedByDate.entries()].map(([usageDate, grouped]) => [usageDate, [...grouped.values()]])
|
|
1451
1444
|
);
|
|
1452
1445
|
}
|
|
1453
|
-
async function processCodexFile(filePath,
|
|
1454
|
-
let
|
|
1455
|
-
try {
|
|
1456
|
-
fh = await open2(filePath, "r");
|
|
1457
|
-
} catch {
|
|
1458
|
-
return;
|
|
1459
|
-
}
|
|
1446
|
+
async function processCodexFile(filePath, projectAliases, serviceTier) {
|
|
1447
|
+
let events = [], input = createReadStream2(filePath, { encoding: "utf-8" });
|
|
1460
1448
|
try {
|
|
1461
1449
|
let rl = createInterface2({
|
|
1462
|
-
input
|
|
1450
|
+
input,
|
|
1463
1451
|
crlfDelay: 1 / 0
|
|
1464
|
-
}),
|
|
1452
|
+
}), fileSessionId = basename(filePath, ".jsonl"), fallbackTs = await fileModifiedTs(filePath), state = {
|
|
1453
|
+
currentModel: "unknown",
|
|
1454
|
+
projectFields: { project: "unknown", projectDisplay: "unknown" },
|
|
1455
|
+
hasSessionWorkspace: !1,
|
|
1456
|
+
waitingForChildTurn: !1,
|
|
1457
|
+
taskStartedTurnIds: /* @__PURE__ */ new Set(),
|
|
1458
|
+
childIsUserFork: !1
|
|
1459
|
+
};
|
|
1465
1460
|
for await (let line of rl) {
|
|
1466
1461
|
if (!line || Buffer.byteLength(line) > MAX_LINE_BYTES2) continue;
|
|
1467
1462
|
let record;
|
|
@@ -1470,78 +1465,216 @@ async function processCodexFile(filePath, targetDateSet, projectAliases, grouped
|
|
|
1470
1465
|
} catch {
|
|
1471
1466
|
continue;
|
|
1472
1467
|
}
|
|
1468
|
+
let payload = record.payload;
|
|
1469
|
+
if (!payload) continue;
|
|
1470
|
+
let payloadModel = extractCodexModel(payload), isTokenCount = record.type === "event_msg" && payload.type === "token_count";
|
|
1471
|
+
if (state.waitingForChildTurn)
|
|
1472
|
+
if (record.type === "turn_context" && childTurnStartsOwnSession(state, payload.turn_id))
|
|
1473
|
+
state.waitingForChildTurn = !1, state.forkedChildReplaySessionId = void 0, state.taskStartedTurnIds.clear(), state.childIsUserFork = !1, state.sessionIdFromMeta = state.forkedChildSessionId ?? state.sessionIdFromMeta;
|
|
1474
|
+
else {
|
|
1475
|
+
record.type === "event_msg" && payload.type === "task_started" && childTaskStartsOwnSession(state, payload.turn_id, payload.started_at) && payload.turn_id && state.taskStartedTurnIds.add(payload.turn_id), record.type === "session_meta" && payload.id && payload.id !== state.forkedChildSessionId && (state.forkedChildReplaySessionId = payload.id), isTokenCount && rememberInheritedBaseline(state, payload.info);
|
|
1476
|
+
continue;
|
|
1477
|
+
}
|
|
1478
|
+
if (record.type === "session_meta") {
|
|
1479
|
+
let sessionId = payload.id?.trim();
|
|
1480
|
+
sessionId && (state.sessionIdFromMeta = sessionId);
|
|
1481
|
+
let forkParent = payload.forked_from_id?.trim() ?? forkParentFromSource(payload.source);
|
|
1482
|
+
if (forkParent) {
|
|
1483
|
+
let repeatedActiveChild = !state.waitingForChildTurn && !!sessionId && state.forkedChildSessionId === sessionId;
|
|
1484
|
+
state.sessionForkedFromId = forkParent, state.forkedChildSessionId = sessionId, repeatedActiveChild || (state.waitingForChildTurn = !0, state.forkedChildReplaySessionId = void 0, state.inheritedBaseline = void 0, state.inheritedReportedTotal = void 0, state.taskStartedTurnIds.clear(), state.childIsUserFork = payload.thread_source === "user");
|
|
1485
|
+
}
|
|
1486
|
+
payload.cwd && (state.projectFields = resolveProjectFields(payload.cwd, projectAliases), state.hasSessionWorkspace = !0);
|
|
1487
|
+
continue;
|
|
1488
|
+
}
|
|
1473
1489
|
if (record.type === "turn_context") {
|
|
1474
|
-
|
|
1475
|
-
rawModel !== "<synthetic>" && (currentModel = applyCodexServiceTier(normalizeModelName(rawModel), serviceTier)), record.payload?.cwd && (currentProjectFields = resolveProjectFields(record.payload.cwd, projectAliases));
|
|
1490
|
+
payloadModel && payloadModel !== "<synthetic>" && (state.currentModel = applyCodexServiceTier(normalizeModelName(payloadModel), serviceTier)), payload.cwd && !state.hasSessionWorkspace && (state.projectFields = resolveProjectFields(payload.cwd, projectAliases));
|
|
1476
1491
|
continue;
|
|
1477
1492
|
}
|
|
1478
|
-
if (
|
|
1479
|
-
let info =
|
|
1480
|
-
if (!info?.total_token_usage) continue;
|
|
1481
|
-
|
|
1493
|
+
if (!isTokenCount) continue;
|
|
1494
|
+
let info = payload.info;
|
|
1495
|
+
if (!info?.total_token_usage && !info?.last_token_usage) continue;
|
|
1496
|
+
payloadModel && payloadModel !== "<synthetic>" && (state.currentModel = applyCodexServiceTier(normalizeModelName(payloadModel), serviceTier));
|
|
1497
|
+
let ts = parseTimestamp2(record.timestamp) ?? fallbackTs;
|
|
1482
1498
|
if (!ts) continue;
|
|
1483
|
-
let usageDate = toDateKey2(ts);
|
|
1484
|
-
if (
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
if (
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
}
|
|
1496
|
-
previousTotal = total;
|
|
1497
|
-
let nonCachedInput = Math.max(0, (last.input_tokens ?? 0) - (last.cached_input_tokens ?? 0)), cachedInput = last.cached_input_tokens ?? 0, output = last.output_tokens ?? 0, eventCost = calculateCost("openai", "codex", currentModel, {
|
|
1499
|
+
let usageDate = toDateKey2(ts), total = info.total_token_usage ? totalsFromUsage(info.total_token_usage) : void 0, last = info.last_token_usage ? totalsFromUsage(info.last_token_usage) : void 0;
|
|
1500
|
+
if (shouldSkipInheritedSnapshot(state, info.total_token_usage, total)) continue;
|
|
1501
|
+
state.inheritedBaseline = void 0, state.inheritedReportedTotal = void 0;
|
|
1502
|
+
let parsed = resolveCodexIncrement(total, last, state.previousTotals);
|
|
1503
|
+
if (!parsed) continue;
|
|
1504
|
+
if (!parsed.tokens) {
|
|
1505
|
+
state.previousTotals = parsed.nextTotals;
|
|
1506
|
+
continue;
|
|
1507
|
+
}
|
|
1508
|
+
let { tokens, nextTotals } = parsed, cachedInput = Math.min(tokens.cached, tokens.input), nonCachedInput = Math.max(tokens.input - cachedInput, 0), output = tokens.output, reasoning = tokens.reasoning;
|
|
1509
|
+
if (nonCachedInput + cachedInput + output + reasoning === 0) continue;
|
|
1510
|
+
state.previousTotals = nextTotals;
|
|
1511
|
+
let dedupScope = state.sessionForkedFromId ?? state.sessionIdFromMeta ?? fileSessionId, signature = total ? `codex|${dedupScope}|${state.currentModel}|${total.input}|${total.cached}|${total.output}|${total.reasoning}` : `codex|${dedupScope}|${state.currentModel}|${ts.getTime()}|${tokens.input}|${tokens.cached}|${tokens.output}|${tokens.reasoning}`, eventCost = calculateCost("openai", "codex", state.currentModel, {
|
|
1498
1512
|
inputTokens: nonCachedInput,
|
|
1499
1513
|
cachedInputTokens: cachedInput,
|
|
1500
1514
|
cacheWriteTokens: 0,
|
|
1501
1515
|
outputTokens: output
|
|
1502
|
-
}), exactEventCost = eventCost.costStatus === "exact" ? eventCost.estimatedCostUsd : void 0
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
projectAlias: currentProjectFields.projectAlias,
|
|
1516
|
-
eventCount: 1,
|
|
1517
|
-
inputTokens: nonCachedInput,
|
|
1518
|
-
cachedInputTokens: cachedInput,
|
|
1519
|
-
cacheWriteTokens: 0,
|
|
1520
|
-
outputTokens: output,
|
|
1521
|
-
reasoningOutputTokens: last.reasoning_output_tokens ?? 0
|
|
1522
|
-
};
|
|
1523
|
-
exactEventCost !== void 0 && (breakdown.costUSD = exactEventCost, breakdown.pricingVersion = eventCost.pricingVersion), grouped.set(key, breakdown);
|
|
1524
|
-
}
|
|
1516
|
+
}), exactEventCost = eventCost.costStatus === "exact" ? eventCost.estimatedCostUsd : void 0;
|
|
1517
|
+
events.push({
|
|
1518
|
+
usageDate,
|
|
1519
|
+
signature,
|
|
1520
|
+
model: state.currentModel,
|
|
1521
|
+
projectFields: { ...state.projectFields },
|
|
1522
|
+
inputTokens: nonCachedInput,
|
|
1523
|
+
cachedInputTokens: cachedInput,
|
|
1524
|
+
outputTokens: output,
|
|
1525
|
+
reasoningOutputTokens: reasoning,
|
|
1526
|
+
costUSD: exactEventCost,
|
|
1527
|
+
pricingVersion: exactEventCost !== void 0 ? eventCost.pricingVersion : void 0
|
|
1528
|
+
});
|
|
1525
1529
|
}
|
|
1530
|
+
} catch {
|
|
1526
1531
|
} finally {
|
|
1527
|
-
|
|
1532
|
+
input.destroy();
|
|
1528
1533
|
}
|
|
1534
|
+
return events;
|
|
1529
1535
|
}
|
|
1530
|
-
|
|
1531
|
-
let
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1536
|
+
function mergeCodexEvent(groupedByDate, event) {
|
|
1537
|
+
let grouped = groupedByDate.get(event.usageDate);
|
|
1538
|
+
if (!grouped) return;
|
|
1539
|
+
let key = `${event.model}|${event.projectFields.project}`, existing = grouped.get(key);
|
|
1540
|
+
if (existing) {
|
|
1541
|
+
existing.eventCount += 1, existing.inputTokens += event.inputTokens, existing.cachedInputTokens += event.cachedInputTokens, existing.outputTokens += event.outputTokens, existing.reasoningOutputTokens += event.reasoningOutputTokens, event.costUSD !== void 0 && (existing.costUSD = (existing.costUSD ?? 0) + event.costUSD, existing.pricingVersion = event.pricingVersion);
|
|
1542
|
+
return;
|
|
1537
1543
|
}
|
|
1538
|
-
let
|
|
1539
|
-
|
|
1544
|
+
let breakdown = {
|
|
1545
|
+
provider: "openai",
|
|
1546
|
+
product: "codex",
|
|
1547
|
+
channel: "cli",
|
|
1548
|
+
model: event.model,
|
|
1549
|
+
project: event.projectFields.project,
|
|
1550
|
+
projectDisplay: event.projectFields.projectDisplay,
|
|
1551
|
+
projectAlias: event.projectFields.projectAlias,
|
|
1552
|
+
eventCount: 1,
|
|
1553
|
+
inputTokens: event.inputTokens,
|
|
1554
|
+
cachedInputTokens: event.cachedInputTokens,
|
|
1555
|
+
cacheWriteTokens: 0,
|
|
1556
|
+
outputTokens: event.outputTokens,
|
|
1557
|
+
reasoningOutputTokens: event.reasoningOutputTokens
|
|
1558
|
+
};
|
|
1559
|
+
event.costUSD !== void 0 && (breakdown.costUSD = event.costUSD, breakdown.pricingVersion = event.pricingVersion), grouped.set(key, breakdown);
|
|
1560
|
+
}
|
|
1561
|
+
function forkParentFromSource(source) {
|
|
1562
|
+
if (!source || typeof source != "object" || Array.isArray(source)) return;
|
|
1563
|
+
let subagent = source.subagent;
|
|
1564
|
+
if (!subagent || typeof subagent != "object" || Array.isArray(subagent)) return;
|
|
1565
|
+
let spawn = subagent.thread_spawn;
|
|
1566
|
+
if (!spawn || typeof spawn != "object" || Array.isArray(spawn)) return;
|
|
1567
|
+
let parent = spawn.parent_thread_id;
|
|
1568
|
+
return typeof parent == "string" && parent.trim() ? parent.trim() : void 0;
|
|
1569
|
+
}
|
|
1570
|
+
function clampToken2(value) {
|
|
1571
|
+
return Math.max(Number.isFinite(value) ? value : 0, 0);
|
|
1572
|
+
}
|
|
1573
|
+
function extractCodexModel(payload) {
|
|
1574
|
+
return payload.model ?? payload.model_name ?? payload.model_info?.slug ?? payload.info?.model ?? payload.info?.model_name;
|
|
1575
|
+
}
|
|
1576
|
+
function totalsFromUsage(usage) {
|
|
1577
|
+
return {
|
|
1578
|
+
input: clampToken2(usage.input_tokens),
|
|
1579
|
+
cached: Math.max(
|
|
1580
|
+
clampToken2(usage.cached_input_tokens),
|
|
1581
|
+
clampToken2(usage.cache_read_input_tokens)
|
|
1582
|
+
),
|
|
1583
|
+
output: clampToken2(usage.output_tokens),
|
|
1584
|
+
reasoning: clampToken2(usage.reasoning_output_tokens)
|
|
1585
|
+
};
|
|
1586
|
+
}
|
|
1587
|
+
function totalsEqual(a, b) {
|
|
1588
|
+
return a.input === b.input && a.cached === b.cached && a.output === b.output && a.reasoning === b.reasoning;
|
|
1589
|
+
}
|
|
1590
|
+
function totalsDelta(current, previous) {
|
|
1591
|
+
if (!(current.input < previous.input || current.cached < previous.cached || current.output < previous.output || current.reasoning < previous.reasoning))
|
|
1592
|
+
return {
|
|
1593
|
+
input: current.input - previous.input,
|
|
1594
|
+
cached: current.cached - previous.cached,
|
|
1595
|
+
output: current.output - previous.output,
|
|
1596
|
+
reasoning: current.reasoning - previous.reasoning
|
|
1597
|
+
};
|
|
1598
|
+
}
|
|
1599
|
+
function totalsAdd(a, b) {
|
|
1600
|
+
return {
|
|
1601
|
+
input: a.input + b.input,
|
|
1602
|
+
cached: a.cached + b.cached,
|
|
1603
|
+
output: a.output + b.output,
|
|
1604
|
+
reasoning: a.reasoning + b.reasoning
|
|
1605
|
+
};
|
|
1606
|
+
}
|
|
1607
|
+
function totalsSum(value) {
|
|
1608
|
+
return value.input + value.cached + value.output + value.reasoning;
|
|
1609
|
+
}
|
|
1610
|
+
function looksLikeStaleRegression(current, previous, last) {
|
|
1611
|
+
let previousSum = totalsSum(previous), currentSum = totalsSum(current), lastSum = totalsSum(last);
|
|
1612
|
+
return previousSum <= 0 || currentSum <= 0 || lastSum <= 0 ? !1 : currentSum * 100 >= previousSum * 98 || currentSum + lastSum * 2 >= previousSum;
|
|
1613
|
+
}
|
|
1614
|
+
function resolveCodexIncrement(total, last, previous) {
|
|
1615
|
+
if (total && last && previous)
|
|
1616
|
+
return totalsEqual(total, previous) || !totalsDelta(total, previous) && looksLikeStaleRegression(total, previous, last) ? void 0 : { tokens: last, nextTotals: total };
|
|
1617
|
+
if (total && last) return { tokens: last, nextTotals: total };
|
|
1618
|
+
if (total && previous) {
|
|
1619
|
+
if (totalsEqual(total, previous)) return;
|
|
1620
|
+
let delta = totalsDelta(total, previous);
|
|
1621
|
+
return delta ? { tokens: delta, nextTotals: total } : { nextTotals: total };
|
|
1622
|
+
}
|
|
1623
|
+
if (total) return { tokens: total, nextTotals: total };
|
|
1624
|
+
if (last && previous) return { tokens: last, nextTotals: totalsAdd(previous, last) };
|
|
1625
|
+
if (last) return { tokens: last };
|
|
1626
|
+
}
|
|
1627
|
+
function rememberInheritedBaseline(state, info) {
|
|
1628
|
+
let usage = info?.total_token_usage;
|
|
1629
|
+
if (!usage) return;
|
|
1630
|
+
let totals = totalsFromUsage(usage);
|
|
1631
|
+
state.previousTotals = totals, state.inheritedBaseline = totals, state.inheritedReportedTotal = reportedTotalTokens(usage);
|
|
1632
|
+
}
|
|
1633
|
+
function shouldSkipInheritedSnapshot(state, usage, totals) {
|
|
1634
|
+
let reported = usage ? reportedTotalTokens(usage) : void 0;
|
|
1635
|
+
if (reported != null && state.inheritedReportedTotal != null && reported <= state.inheritedReportedTotal) return !0;
|
|
1636
|
+
let baseline = state.inheritedBaseline;
|
|
1637
|
+
return !!(totals && baseline && totals.input <= baseline.input && totals.cached <= baseline.cached && totals.output <= baseline.output && totals.reasoning <= baseline.reasoning);
|
|
1638
|
+
}
|
|
1639
|
+
function reportedTotalTokens(usage) {
|
|
1640
|
+
return typeof usage.total_tokens == "number" && usage.total_tokens >= 0 ? usage.total_tokens : void 0;
|
|
1641
|
+
}
|
|
1642
|
+
function childTurnStartsOwnSession(state, turnId) {
|
|
1643
|
+
if (!state.forkedChildReplaySessionId) return !0;
|
|
1644
|
+
let childId = state.forkedChildSessionId;
|
|
1645
|
+
if (!childId) return !0;
|
|
1646
|
+
let childKey = uuidV7OrderKey(childId);
|
|
1647
|
+
if (!turnId || !childKey) return !0;
|
|
1648
|
+
let turnKey = uuidV7OrderKey(turnId);
|
|
1649
|
+
if (!turnKey) return state.childIsUserFork || state.taskStartedTurnIds.has(turnId);
|
|
1650
|
+
let turnMs = turnKey.slice(0, 12), childMs = childKey.slice(0, 12);
|
|
1651
|
+
return turnMs > childMs ? !0 : turnMs < childMs ? !1 : state.childIsUserFork || state.taskStartedTurnIds.has(turnId);
|
|
1652
|
+
}
|
|
1653
|
+
function childTaskStartsOwnSession(state, turnId, startedAt) {
|
|
1654
|
+
let childId = state.forkedChildSessionId;
|
|
1655
|
+
if (!turnId || !childId) return !1;
|
|
1656
|
+
let childKey = uuidV7OrderKey(childId);
|
|
1657
|
+
if (!childKey) return !0;
|
|
1658
|
+
let turnKey = uuidV7OrderKey(turnId);
|
|
1659
|
+
if (turnKey) return turnKey.slice(0, 12) >= childKey.slice(0, 12);
|
|
1660
|
+
let childStartedMs = Number.parseInt(childKey.slice(0, 12), 16);
|
|
1661
|
+
return Number.isFinite(startedAt) && startedAt >= Math.floor(childStartedMs / 1e3);
|
|
1662
|
+
}
|
|
1663
|
+
function uuidV7OrderKey(id) {
|
|
1664
|
+
let parts = id.split("-");
|
|
1665
|
+
if (!(parts.length !== 5 || parts[0]?.length !== 8 || parts[1]?.length !== 4 || parts[2]?.length !== 4 || parts[3]?.length !== 4 || parts[4]?.length !== 12 || !parts[2]?.startsWith("7") || !parts.every((part) => /^[0-9a-f]+$/i.test(part))))
|
|
1666
|
+
return parts.join("").toLowerCase();
|
|
1667
|
+
}
|
|
1668
|
+
async function collectSessionFiles(baseDir) {
|
|
1669
|
+
let activePaths = [], sessionsDir = join4(baseDir, "sessions");
|
|
1670
|
+
await walkDir(sessionsDir, activePaths), activePaths.sort();
|
|
1671
|
+
let archivedPaths = [];
|
|
1672
|
+
return await walkDir(join4(baseDir, "archived_sessions"), archivedPaths), archivedPaths.sort(), [...activePaths, ...archivedPaths];
|
|
1540
1673
|
}
|
|
1541
1674
|
async function detectCodexServiceTier(baseDir) {
|
|
1542
1675
|
let config = "";
|
|
1543
1676
|
try {
|
|
1544
|
-
config = await
|
|
1677
|
+
config = await readFile2(join4(baseDir, "config.toml"), "utf-8");
|
|
1545
1678
|
} catch {
|
|
1546
1679
|
return null;
|
|
1547
1680
|
}
|
|
@@ -1580,30 +1713,33 @@ function toDateKey2(date) {
|
|
|
1580
1713
|
}
|
|
1581
1714
|
|
|
1582
1715
|
// src/scanners/copilot.ts
|
|
1583
|
-
import { readFile as
|
|
1716
|
+
import { readFile as readFile3 } from "node:fs/promises";
|
|
1584
1717
|
import { join as join5 } from "node:path";
|
|
1585
1718
|
import { homedir as homedir4 } from "node:os";
|
|
1586
1719
|
async function scanCopilotDates(targetDates, baseDir, projectAliases) {
|
|
1587
|
-
let dates = new Set(targetDates),
|
|
1588
|
-
if (files.length === 0) return emptyResult(dates);
|
|
1589
|
-
let grouped = initDateMap(dates);
|
|
1720
|
+
let dates = new Set(targetDates), dirs = baseDir ? [baseDir] : [join5(homedir4(), ".copilot", "session-state"), join5(homedir4(), ".copilot", "otel")], files = [...new Set((await Promise.all(dirs.map((dir) => walkFiles(dir, ".jsonl")))).flat())], explicitOtel = baseDir ? void 0 : process.env.COPILOT_OTEL_FILE_EXPORTER_PATH?.trim();
|
|
1721
|
+
if (explicitOtel && files.push(explicitOtel), files.length === 0) return emptyResult(dates);
|
|
1722
|
+
let grouped = initDateMap(dates), seenOtel = /* @__PURE__ */ new Set();
|
|
1590
1723
|
for (let filePath of files) {
|
|
1591
1724
|
let content;
|
|
1592
1725
|
try {
|
|
1593
|
-
content = await
|
|
1726
|
+
content = await readFile3(filePath, "utf-8");
|
|
1594
1727
|
} catch {
|
|
1595
1728
|
continue;
|
|
1596
1729
|
}
|
|
1597
|
-
let sessionProjectFields = { project: "unknown", projectDisplay: "unknown" },
|
|
1598
|
-
`
|
|
1599
|
-
|
|
1730
|
+
let sessionProjectFields = { project: "unknown", projectDisplay: "unknown" }, records = [];
|
|
1731
|
+
for (let line of content.split(`
|
|
1732
|
+
`)) {
|
|
1600
1733
|
if (!line.trim()) continue;
|
|
1601
|
-
let
|
|
1734
|
+
let parsed;
|
|
1602
1735
|
try {
|
|
1603
|
-
|
|
1736
|
+
parsed = JSON.parse(line);
|
|
1604
1737
|
} catch {
|
|
1605
1738
|
continue;
|
|
1606
1739
|
}
|
|
1740
|
+
if (!isObject(parsed)) continue;
|
|
1741
|
+
records.push(parsed);
|
|
1742
|
+
let obj = parsed;
|
|
1607
1743
|
if (obj.type === "session.start" || obj.type === "session.resume") {
|
|
1608
1744
|
let ctx = obj.data?.context, raw = ctx?.gitRoot ?? ctx?.cwd;
|
|
1609
1745
|
raw && (sessionProjectFields = resolveProjectFields(raw, projectAliases));
|
|
@@ -1618,7 +1754,7 @@ async function scanCopilotDates(targetDates, baseDir, projectAliases) {
|
|
|
1618
1754
|
for (let [model, entry] of Object.entries(metrics)) {
|
|
1619
1755
|
let usage = entry.usage;
|
|
1620
1756
|
if (!usage) continue;
|
|
1621
|
-
let rawInput = usage.inputTokens
|
|
1757
|
+
let rawInput = clamp(usage.inputTokens), cacheRead = clamp(usage.cacheReadTokens), cacheWrite = clamp(usage.cacheWriteTokens), output = clamp(usage.outputTokens), reasoning = clamp(usage.reasoningTokens), input = Math.max(rawInput - Math.min(cacheRead, rawInput), 0);
|
|
1622
1758
|
accumulate(
|
|
1623
1759
|
dayMap,
|
|
1624
1760
|
`${model}|${sessionProjectFields.project}`,
|
|
@@ -1636,26 +1772,162 @@ async function scanCopilotDates(targetDates, baseDir, projectAliases) {
|
|
|
1636
1772
|
outputTokens: 0,
|
|
1637
1773
|
reasoningOutputTokens: 0
|
|
1638
1774
|
},
|
|
1639
|
-
{ input, cached: cacheRead, cacheWrite
|
|
1775
|
+
{ input, cached: cacheRead, cacheWrite, output, reasoning }
|
|
1640
1776
|
);
|
|
1641
1777
|
}
|
|
1642
1778
|
}
|
|
1779
|
+
let fallbackTs = await fileModifiedTs(filePath);
|
|
1780
|
+
if (fallbackTs)
|
|
1781
|
+
for (let candidate of selectOtelCandidates(records, fallbackTs)) {
|
|
1782
|
+
if (seenOtel.has(candidate.dedupKey)) continue;
|
|
1783
|
+
seenOtel.add(candidate.dedupKey);
|
|
1784
|
+
let dayMap = grouped.get(dateKey(candidate.timestamp));
|
|
1785
|
+
dayMap && accumulate(
|
|
1786
|
+
dayMap,
|
|
1787
|
+
`${candidate.provider}|${candidate.model}|unknown`,
|
|
1788
|
+
{
|
|
1789
|
+
provider: candidate.provider,
|
|
1790
|
+
product: "copilot-cli",
|
|
1791
|
+
channel: "cli",
|
|
1792
|
+
model: candidate.model,
|
|
1793
|
+
project: "unknown",
|
|
1794
|
+
projectDisplay: "unknown",
|
|
1795
|
+
inputTokens: 0,
|
|
1796
|
+
cachedInputTokens: 0,
|
|
1797
|
+
cacheWriteTokens: 0,
|
|
1798
|
+
outputTokens: 0,
|
|
1799
|
+
reasoningOutputTokens: 0
|
|
1800
|
+
},
|
|
1801
|
+
candidate.tokens
|
|
1802
|
+
);
|
|
1803
|
+
}
|
|
1643
1804
|
}
|
|
1644
1805
|
return finalize(grouped);
|
|
1645
1806
|
}
|
|
1807
|
+
function selectOtelCandidates(records, fallbackTs) {
|
|
1808
|
+
let candidates = records.flatMap((record, index) => {
|
|
1809
|
+
let candidate = otelCandidate(record, index, fallbackTs);
|
|
1810
|
+
return candidate ? [candidate] : [];
|
|
1811
|
+
}), traces = (source) => new Set(candidates.filter((c) => c.source === source).flatMap((c) => c.traceId ? [c.traceId] : [])), responses = (source) => new Set(candidates.filter((c) => c.source === source).flatMap((c) => c.responseId ? [c.responseId] : [])), chatTraces = traces("chat"), inferenceTraces = traces("inference"), agentTraces = traces("agent-turn"), chatResponses = responses("chat"), inferenceResponses = responses("inference"), agentResponses = responses("agent-turn");
|
|
1812
|
+
return candidates.filter((candidate) => candidate.source === "chat" ? !0 : candidate.source === "inference" ? !(candidate.traceId && chatTraces.has(candidate.traceId)) && !(candidate.responseId && chatResponses.has(candidate.responseId)) : candidate.source === "agent-turn" ? !(candidate.traceId && (chatTraces.has(candidate.traceId) || inferenceTraces.has(candidate.traceId))) && !(candidate.responseId && (chatResponses.has(candidate.responseId) || inferenceResponses.has(candidate.responseId))) : !(candidate.traceId && (chatTraces.has(candidate.traceId) || inferenceTraces.has(candidate.traceId) || agentTraces.has(candidate.traceId))) && !(candidate.responseId && (chatResponses.has(candidate.responseId) || inferenceResponses.has(candidate.responseId) || agentResponses.has(candidate.responseId))));
|
|
1813
|
+
}
|
|
1814
|
+
function otelCandidate(record, index, fallbackTs) {
|
|
1815
|
+
let attributes = isObject(record.attributes) ? record.attributes : void 0;
|
|
1816
|
+
if (!attributes) return;
|
|
1817
|
+
let source = otelSource(record, attributes);
|
|
1818
|
+
if (!source) return;
|
|
1819
|
+
let rawInput = attrNumber(attributes, ["gen_ai.usage.input_tokens"]), cached2 = attrNumber(attributes, [
|
|
1820
|
+
"gen_ai.usage.cache_read.input_tokens",
|
|
1821
|
+
"gen_ai.usage.cache_read_input_tokens"
|
|
1822
|
+
]), cacheWrite = attrNumber(attributes, [
|
|
1823
|
+
"gen_ai.usage.cache_write.input_tokens",
|
|
1824
|
+
"gen_ai.usage.cache_creation.input_tokens",
|
|
1825
|
+
"gen_ai.usage.cache_write_input_tokens",
|
|
1826
|
+
"gen_ai.usage.cache_creation_input_tokens"
|
|
1827
|
+
]), output = attrNumber(attributes, ["gen_ai.usage.output_tokens"]), reasoning = attrNumber(attributes, [
|
|
1828
|
+
"gen_ai.usage.reasoning.output_tokens",
|
|
1829
|
+
"gen_ai.usage.reasoning_tokens"
|
|
1830
|
+
]), input = Math.max(rawInput - Math.min(cached2, rawInput), 0);
|
|
1831
|
+
if (input + cached2 + cacheWrite + output + reasoning === 0) return;
|
|
1832
|
+
let traceId = stringAttr(record, ["traceId"]) ?? (isObject(record.spanContext) ? stringAttr(record.spanContext, ["traceId"]) : void 0), spanId = stringAttr(record, ["spanId"]) ?? (isObject(record.spanContext) ? stringAttr(record.spanContext, ["spanId"]) : void 0), responseId = stringAttr(attributes, ["gen_ai.response.id"]), sessionId = stringAttr(attributes, [
|
|
1833
|
+
"gen_ai.conversation.id",
|
|
1834
|
+
"session.id",
|
|
1835
|
+
"github.copilot.session_id",
|
|
1836
|
+
"github.copilot.interaction_id",
|
|
1837
|
+
"copilot_chat.session.id"
|
|
1838
|
+
]) ?? traceId ?? "unknown-session", model = stringAttr(attributes, [
|
|
1839
|
+
"gen_ai.response.model",
|
|
1840
|
+
"gen_ai.request.model",
|
|
1841
|
+
"gen_ai.system",
|
|
1842
|
+
"copilot_chat.model"
|
|
1843
|
+
]) ?? "unknown", provider = inferProviderFromModel(model, "github-copilot"), timestamp = otelRecordTimestamp(record) ?? fallbackTs, dedupKey = responseId ? `copilot:${source}:response:${responseId}` : traceId && spanId ? `copilot:${source}:${traceId}:${spanId}` : `copilot:${source}:${sessionId}:${timestamp.getTime()}:${index}`;
|
|
1844
|
+
return {
|
|
1845
|
+
source,
|
|
1846
|
+
traceId,
|
|
1847
|
+
responseId,
|
|
1848
|
+
model,
|
|
1849
|
+
provider,
|
|
1850
|
+
timestamp,
|
|
1851
|
+
dedupKey,
|
|
1852
|
+
tokens: { input, cached: cached2, cacheWrite, output, reasoning }
|
|
1853
|
+
};
|
|
1854
|
+
}
|
|
1855
|
+
function otelSource(record, attributes) {
|
|
1856
|
+
let name = typeof record.name == "string" ? record.name : "", body = typeof record.body == "string" ? record.body : typeof record._body == "string" ? record._body : "", eventName = typeof attributes["event.name"] == "string" ? attributes["event.name"] : "", operation = typeof attributes["gen_ai.operation.name"] == "string" ? attributes["gen_ai.operation.name"] : "", span = record.type === "span" || record.type == null && !!name && (record.spanId != null || record.traceId != null || record.startTime != null || record.endTime != null);
|
|
1857
|
+
if (span && (operation === "chat" || name.startsWith("chat "))) return "chat";
|
|
1858
|
+
if (!span && (eventName === "gen_ai.client.inference.operation.details" || body.startsWith("GenAI inference:"))) return "inference";
|
|
1859
|
+
if (!span && (eventName === "copilot_chat.agent.turn" || body.startsWith("copilot_chat.agent.turn"))) return "agent-turn";
|
|
1860
|
+
if (span && (operation === "invoke_agent" || name.startsWith("invoke_agent"))) return "summary";
|
|
1861
|
+
}
|
|
1862
|
+
function otelTimestamp(value) {
|
|
1863
|
+
if (Array.isArray(value) && value.length >= 1) {
|
|
1864
|
+
let seconds = Number(value[0]), nanos = Number(value[1] ?? 0);
|
|
1865
|
+
if (Number.isFinite(seconds) && Number.isFinite(nanos)) return parseTs(seconds * 1e3 + nanos / 1e6);
|
|
1866
|
+
}
|
|
1867
|
+
return typeof value == "number" || typeof value == "string" ? otelScalarTimestamp(value) : null;
|
|
1868
|
+
}
|
|
1869
|
+
function otelRecordTimestamp(record) {
|
|
1870
|
+
let start = otelTimestamp(record.startTime);
|
|
1871
|
+
if (start) return start;
|
|
1872
|
+
let end = otelTimestamp(record.endTime);
|
|
1873
|
+
if (end) {
|
|
1874
|
+
let duration = otelDurationMs(record.duration);
|
|
1875
|
+
return duration ? new Date(end.getTime() - duration) : end;
|
|
1876
|
+
}
|
|
1877
|
+
return otelTimestamp(record.hrTime) ?? otelTimestamp(record._hrTime) ?? otelTimestamp(record.time) ?? otelTimestamp(record.timestamp) ?? otelTimestamp(record.observedTimestamp) ?? otelTimestamp(record.timeUnixNano);
|
|
1878
|
+
}
|
|
1879
|
+
function otelScalarTimestamp(value) {
|
|
1880
|
+
if (typeof value == "string" && !/^\d+(?:\.\d+)?$/.test(value)) return parseTs(value);
|
|
1881
|
+
let raw = Number(value);
|
|
1882
|
+
if (!Number.isFinite(raw) || raw <= 0) return null;
|
|
1883
|
+
let abs = Math.abs(raw), millis = abs >= 1e17 ? raw / 1e6 : abs >= 1e14 ? raw / 1e3 : raw;
|
|
1884
|
+
return parseTs(millis);
|
|
1885
|
+
}
|
|
1886
|
+
function otelDurationMs(value) {
|
|
1887
|
+
if (Array.isArray(value) && value.length > 0) {
|
|
1888
|
+
let seconds = Number(value[0]), nanos = Number(value[1] ?? 0);
|
|
1889
|
+
if (Number.isFinite(seconds) && Number.isFinite(nanos)) return seconds * 1e3 + nanos / 1e6;
|
|
1890
|
+
}
|
|
1891
|
+
let raw = typeof value == "number" ? value : typeof value == "string" ? Number(value) : NaN;
|
|
1892
|
+
return !Number.isFinite(raw) || raw <= 0 ? null : raw >= 1e6 ? raw / 1e6 : raw;
|
|
1893
|
+
}
|
|
1894
|
+
function attrNumber(attributes, keys) {
|
|
1895
|
+
for (let key of keys) {
|
|
1896
|
+
let raw = attributes[key], value = typeof raw == "number" ? raw : typeof raw == "string" ? Number(raw) : NaN;
|
|
1897
|
+
if (Number.isFinite(value) && value > 0) return value;
|
|
1898
|
+
}
|
|
1899
|
+
return 0;
|
|
1900
|
+
}
|
|
1901
|
+
function stringAttr(value, keys) {
|
|
1902
|
+
for (let key of keys) {
|
|
1903
|
+
let raw = value[key];
|
|
1904
|
+
if (typeof raw == "string" && raw.trim()) return raw.trim();
|
|
1905
|
+
}
|
|
1906
|
+
}
|
|
1907
|
+
function isObject(value) {
|
|
1908
|
+
return typeof value == "object" && value !== null && !Array.isArray(value);
|
|
1909
|
+
}
|
|
1910
|
+
function clamp(value) {
|
|
1911
|
+
return Math.max(Number.isFinite(value) ? value : 0, 0);
|
|
1912
|
+
}
|
|
1646
1913
|
|
|
1647
1914
|
// src/scanners/copilot-vscode.ts
|
|
1648
|
-
import { readFile as
|
|
1649
|
-
import { basename as
|
|
1915
|
+
import { readFile as readFile4 } from "node:fs/promises";
|
|
1916
|
+
import { basename as basename3, dirname, join as join6 } from "node:path";
|
|
1650
1917
|
import { homedir as homedir5 } from "node:os";
|
|
1651
1918
|
async function scanCopilotVscodeDates(targetDates, baseDir, projectAliases, workspaceStorageDir) {
|
|
1652
|
-
let dates = new Set(targetDates), dir = baseDir ?? join6(homedir5(), "Library", "Application Support", "Code", "logs"), workspaceDir = workspaceStorageDir ?? join6(homedir5(), "Library", "Application Support", "Code", "User", "workspaceStorage"),
|
|
1653
|
-
|
|
1919
|
+
let dates = new Set(targetDates), dir = baseDir ?? join6(homedir5(), "Library", "Application Support", "Code", "logs"), workspaceDir = workspaceStorageDir ?? join6(homedir5(), "Library", "Application Support", "Code", "User", "workspaceStorage"), [allLogs, allJson, allJsonl] = await Promise.all([
|
|
1920
|
+
walkFiles(dir, ".log"),
|
|
1921
|
+
walkFiles(workspaceDir, ".json"),
|
|
1922
|
+
walkFiles(workspaceDir, ".jsonl")
|
|
1923
|
+
]), logFiles = allLogs.filter((filePath) => basename3(filePath) === "GitHub Copilot Chat.log"), sessionFiles = allJson.filter(isChatSessionFile), crdtSessionFiles = allJsonl.filter(isChatSessionFile);
|
|
1924
|
+
if (logFiles.length === 0 && sessionFiles.length === 0 && crdtSessionFiles.length === 0)
|
|
1925
|
+
return emptyResult(dates);
|
|
1654
1926
|
let grouped = initDateMap(dates), seenEvents = /* @__PURE__ */ new Set();
|
|
1655
1927
|
for (let filePath of logFiles) {
|
|
1656
1928
|
let content;
|
|
1657
1929
|
try {
|
|
1658
|
-
content = await
|
|
1930
|
+
content = await readFile4(filePath, "utf-8");
|
|
1659
1931
|
} catch {
|
|
1660
1932
|
continue;
|
|
1661
1933
|
}
|
|
@@ -1691,6 +1963,8 @@ async function scanCopilotVscodeDates(targetDates, baseDir, projectAliases, work
|
|
|
1691
1963
|
}
|
|
1692
1964
|
for (let filePath of sessionFiles)
|
|
1693
1965
|
await collectWorkspaceSessionEvents(filePath, grouped, seenEvents, projectAliases);
|
|
1966
|
+
for (let filePath of crdtSessionFiles)
|
|
1967
|
+
await collectWorkspaceJsonlEvents(filePath, grouped, seenEvents, projectAliases);
|
|
1694
1968
|
return finalize(grouped);
|
|
1695
1969
|
}
|
|
1696
1970
|
function extractSuccessEvent(line) {
|
|
@@ -1720,7 +1994,7 @@ function extractFileUriPath(line) {
|
|
|
1720
1994
|
async function collectWorkspaceSessionEvents(filePath, grouped, seenEvents, projectAliases) {
|
|
1721
1995
|
let content;
|
|
1722
1996
|
try {
|
|
1723
|
-
content = await
|
|
1997
|
+
content = await readFile4(filePath, "utf-8");
|
|
1724
1998
|
} catch {
|
|
1725
1999
|
return;
|
|
1726
2000
|
}
|
|
@@ -1759,16 +2033,82 @@ async function collectWorkspaceSessionEvents(filePath, grouped, seenEvents, proj
|
|
|
1759
2033
|
));
|
|
1760
2034
|
}
|
|
1761
2035
|
}
|
|
2036
|
+
async function collectWorkspaceJsonlEvents(filePath, grouped, seenEvents, projectAliases) {
|
|
2037
|
+
let content;
|
|
2038
|
+
try {
|
|
2039
|
+
content = await readFile4(filePath, "utf-8");
|
|
2040
|
+
} catch {
|
|
2041
|
+
return;
|
|
2042
|
+
}
|
|
2043
|
+
let workspacePath = await readWorkspaceFolderPath(filePath), project = workspacePath ? projectFromPath(workspacePath, projectAliases) : "unknown", sessionId = basename3(filePath, ".jsonl");
|
|
2044
|
+
for (let line of content.split(`
|
|
2045
|
+
`)) {
|
|
2046
|
+
if (!line.trim()) continue;
|
|
2047
|
+
let record;
|
|
2048
|
+
try {
|
|
2049
|
+
record = JSON.parse(line);
|
|
2050
|
+
} catch {
|
|
2051
|
+
continue;
|
|
2052
|
+
}
|
|
2053
|
+
let requests = [];
|
|
2054
|
+
if (record.kind === 0 && isRecord(record.v)) {
|
|
2055
|
+
let value = record.v.requests;
|
|
2056
|
+
Array.isArray(value) && (requests = value.filter(isRecord));
|
|
2057
|
+
} else record.kind === 2 && record.k?.[0] === "requests" && Array.isArray(record.v) && (requests = record.v.filter(isRecord));
|
|
2058
|
+
for (let request of requests)
|
|
2059
|
+
addTokenizedWorkspaceRequest(request, sessionId, project, grouped, seenEvents);
|
|
2060
|
+
}
|
|
2061
|
+
}
|
|
2062
|
+
function addTokenizedWorkspaceRequest(request, sessionId, project, grouped, seenEvents) {
|
|
2063
|
+
let metadata = request.result?.metadata, resolvedModel = metadata?.resolvedModel?.trim(), rawModelId = request.modelId?.trim();
|
|
2064
|
+
if (!resolvedModel && !rawModelId?.startsWith("copilot/")) return;
|
|
2065
|
+
let input = clampToken3(request.promptTokens ?? metadata?.promptTokens), output = clampToken3(request.completionTokens ?? metadata?.outputTokens);
|
|
2066
|
+
if (input === 0 && output === 0) return;
|
|
2067
|
+
let timestamp = parseTs(request.timestamp);
|
|
2068
|
+
if (!timestamp) return;
|
|
2069
|
+
let dayMap = grouped.get(dateKey(timestamp));
|
|
2070
|
+
if (!dayMap) return;
|
|
2071
|
+
let model = normalizeTokenizedWorkspaceModel(resolvedModel || rawModelId) || "auto", reasoning = (metadata?.toolCallRounds ?? []).reduce(
|
|
2072
|
+
(sum, round) => sum + clampToken3(round.thinking?.tokens),
|
|
2073
|
+
0
|
|
2074
|
+
), dedupeKey = `copilot-vscode|${sessionId}|${timestamp.getTime()}`;
|
|
2075
|
+
if (seenEvents.has(dedupeKey)) return;
|
|
2076
|
+
seenEvents.add(dedupeKey);
|
|
2077
|
+
let provider = inferProviderFromModel(model, "github-copilot");
|
|
2078
|
+
accumulate(
|
|
2079
|
+
dayMap,
|
|
2080
|
+
`${provider}|${model}|${project}`,
|
|
2081
|
+
{
|
|
2082
|
+
provider,
|
|
2083
|
+
product: "copilot-vscode",
|
|
2084
|
+
channel: "ide",
|
|
2085
|
+
model,
|
|
2086
|
+
project,
|
|
2087
|
+
inputTokens: 0,
|
|
2088
|
+
cachedInputTokens: 0,
|
|
2089
|
+
cacheWriteTokens: 0,
|
|
2090
|
+
outputTokens: 0,
|
|
2091
|
+
reasoningOutputTokens: 0
|
|
2092
|
+
},
|
|
2093
|
+
{ input, cached: 0, cacheWrite: 0, output, reasoning }
|
|
2094
|
+
);
|
|
2095
|
+
}
|
|
2096
|
+
function isRecord(value) {
|
|
2097
|
+
return !!value && typeof value == "object" && !Array.isArray(value);
|
|
2098
|
+
}
|
|
2099
|
+
function clampToken3(value) {
|
|
2100
|
+
return Math.max(Number.isFinite(value) ? value : 0, 0);
|
|
2101
|
+
}
|
|
1762
2102
|
async function readWorkspaceFolderPath(sessionFilePath) {
|
|
1763
2103
|
let workspaceJsonPath = join6(dirname(sessionFilePath), "..", "workspace.json"), content;
|
|
1764
2104
|
try {
|
|
1765
|
-
content = await
|
|
2105
|
+
content = await readFile4(workspaceJsonPath, "utf-8");
|
|
1766
2106
|
} catch {
|
|
1767
2107
|
return null;
|
|
1768
2108
|
}
|
|
1769
2109
|
try {
|
|
1770
|
-
let
|
|
1771
|
-
return raw
|
|
2110
|
+
let workspace = JSON.parse(content), raw = workspace.folder ?? workspace.workspace;
|
|
2111
|
+
return raw ? decodeURIComponent(raw.replace(/^file:\/\//, "")) : null;
|
|
1772
2112
|
} catch {
|
|
1773
2113
|
return null;
|
|
1774
2114
|
}
|
|
@@ -1776,6 +2116,13 @@ async function readWorkspaceFolderPath(sessionFilePath) {
|
|
|
1776
2116
|
function normalizeWorkspaceModel(raw) {
|
|
1777
2117
|
return raw ? raw.replace(/^copilot\//, "").trim() : "";
|
|
1778
2118
|
}
|
|
2119
|
+
function isChatSessionFile(filePath) {
|
|
2120
|
+
return basename3(dirname(filePath)) === "chatSessions";
|
|
2121
|
+
}
|
|
2122
|
+
function normalizeTokenizedWorkspaceModel(raw) {
|
|
2123
|
+
let normalized = normalizeModelName(normalizeWorkspaceModel(raw));
|
|
2124
|
+
return /^claude[-.]/i.test(normalized) ? normalized.replace(/\./g, "-") : normalized;
|
|
2125
|
+
}
|
|
1779
2126
|
|
|
1780
2127
|
// src/scanners/cursor.ts
|
|
1781
2128
|
import { existsSync } from "node:fs";
|
|
@@ -1937,69 +2284,175 @@ async function scanCursorDates(targetDates) {
|
|
|
1937
2284
|
}
|
|
1938
2285
|
|
|
1939
2286
|
// src/scanners/gemini.ts
|
|
1940
|
-
import { readFile as
|
|
1941
|
-
import { basename as
|
|
2287
|
+
import { readFile as readFile5 } from "node:fs/promises";
|
|
2288
|
+
import { basename as basename4, extname, join as join8, relative, sep } from "node:path";
|
|
1942
2289
|
import { homedir as homedir7 } from "node:os";
|
|
1943
2290
|
async function scanGeminiDates(targetDates, baseDir, projectAliases) {
|
|
1944
|
-
let dates = new Set(targetDates), dir = baseDir ?? join8(homedir7(), ".gemini", "tmp"),
|
|
2291
|
+
let dates = new Set(targetDates), dir = baseDir ?? join8(homedir7(), ".gemini", "tmp"), [jsonFiles, jsonlFiles] = await Promise.all([
|
|
2292
|
+
walkFiles(dir, ".json"),
|
|
2293
|
+
walkFiles(dir, ".jsonl")
|
|
2294
|
+
]), files = [.../* @__PURE__ */ new Set([...jsonFiles, ...jsonlFiles])];
|
|
1945
2295
|
if (files.length === 0) return emptyResult(dates);
|
|
1946
|
-
let grouped = initDateMap(dates), tokenBackedDates = /* @__PURE__ */ new Set();
|
|
2296
|
+
let grouped = initDateMap(dates), tokenBackedDates = /* @__PURE__ */ new Set(), seen = /* @__PURE__ */ new Set();
|
|
1947
2297
|
for (let filePath of files) {
|
|
1948
|
-
if (
|
|
2298
|
+
if (basename4(filePath) === "logs.json") continue;
|
|
1949
2299
|
let content;
|
|
1950
2300
|
try {
|
|
1951
|
-
content = await
|
|
1952
|
-
} catch {
|
|
1953
|
-
continue;
|
|
1954
|
-
}
|
|
1955
|
-
let session;
|
|
1956
|
-
try {
|
|
1957
|
-
session = JSON.parse(content);
|
|
2301
|
+
content = await readFile5(filePath, "utf-8");
|
|
1958
2302
|
} catch {
|
|
1959
2303
|
continue;
|
|
1960
2304
|
}
|
|
1961
|
-
let
|
|
1962
|
-
|
|
1963
|
-
|
|
1964
|
-
|
|
1965
|
-
|
|
1966
|
-
|
|
1967
|
-
|
|
1968
|
-
|
|
2305
|
+
let fallbackTs = await fileModifiedTs(filePath);
|
|
2306
|
+
if (!fallbackTs) continue;
|
|
2307
|
+
let events = extname(filePath) === ".jsonl" ? parseGeminiJsonl(content, basename4(filePath, ".jsonl"), fallbackTs) : parseGeminiJson(content, basename4(filePath, ".json"), fallbackTs), fields = projectFieldsFromFile(filePath, dir, projectAliases);
|
|
2308
|
+
for (let event of events) {
|
|
2309
|
+
if (event.dedupKey) {
|
|
2310
|
+
if (seen.has(event.dedupKey)) continue;
|
|
2311
|
+
seen.add(event.dedupKey);
|
|
2312
|
+
}
|
|
2313
|
+
let dk = dateKey(event.timestamp), dayMap = grouped.get(dk);
|
|
2314
|
+
if (!dayMap) continue;
|
|
2315
|
+
tokenBackedDates.add(dk);
|
|
2316
|
+
let model = normalizeModelName(event.model || "unknown");
|
|
2317
|
+
accumulate(
|
|
1969
2318
|
dayMap,
|
|
1970
|
-
`${model}
|
|
2319
|
+
`${model}|${fields.project}`,
|
|
1971
2320
|
{
|
|
1972
2321
|
provider: "google",
|
|
1973
2322
|
product: "gemini-cli",
|
|
1974
2323
|
channel: "cli",
|
|
1975
2324
|
model,
|
|
1976
|
-
project:
|
|
1977
|
-
projectDisplay:
|
|
2325
|
+
project: fields.project,
|
|
2326
|
+
projectDisplay: fields.projectDisplay,
|
|
2327
|
+
projectAlias: fields.projectAlias,
|
|
1978
2328
|
inputTokens: 0,
|
|
1979
2329
|
cachedInputTokens: 0,
|
|
1980
2330
|
cacheWriteTokens: 0,
|
|
1981
2331
|
outputTokens: 0,
|
|
1982
2332
|
reasoningOutputTokens: 0
|
|
1983
2333
|
},
|
|
1984
|
-
tokens
|
|
1985
|
-
)
|
|
2334
|
+
event.tokens
|
|
2335
|
+
);
|
|
1986
2336
|
}
|
|
1987
2337
|
}
|
|
1988
|
-
let
|
|
1989
|
-
for (let filePath of logFiles)
|
|
2338
|
+
for (let filePath of jsonFiles.filter((file) => basename4(file) === "logs.json"))
|
|
1990
2339
|
await collectGeminiLogEvents(filePath, grouped, tokenBackedDates);
|
|
1991
2340
|
return finalize(grouped);
|
|
1992
2341
|
}
|
|
1993
|
-
|
|
1994
|
-
let
|
|
2342
|
+
function parseGeminiJson(content, fallbackId, fallbackTs) {
|
|
2343
|
+
let value;
|
|
1995
2344
|
try {
|
|
1996
|
-
|
|
2345
|
+
value = JSON.parse(content);
|
|
1997
2346
|
} catch {
|
|
1998
|
-
return;
|
|
2347
|
+
return [];
|
|
1999
2348
|
}
|
|
2349
|
+
return isObject2(value) ? parseGeminiValue(value, fallbackId, fallbackTs) : [];
|
|
2350
|
+
}
|
|
2351
|
+
function parseGeminiJsonl(content, fallbackId, fallbackTs) {
|
|
2352
|
+
let sessionId = fallbackId, currentModel, keyed = /* @__PURE__ */ new Map(), anonymous = [], add = (event) => {
|
|
2353
|
+
event.dedupKey ? keyed.set(event.dedupKey, event) : anonymous.push(event);
|
|
2354
|
+
};
|
|
2355
|
+
for (let line of content.split(`
|
|
2356
|
+
`)) {
|
|
2357
|
+
if (!line.trim()) continue;
|
|
2358
|
+
let value;
|
|
2359
|
+
try {
|
|
2360
|
+
let parsed = JSON.parse(line);
|
|
2361
|
+
if (!isObject2(parsed)) continue;
|
|
2362
|
+
value = parsed;
|
|
2363
|
+
} catch {
|
|
2364
|
+
continue;
|
|
2365
|
+
}
|
|
2366
|
+
if (sessionId = stringValue(value.session_id) ?? stringValue(value.sessionId) ?? sessionId, currentModel = stringValue(value.model) ?? currentModel, value.type === "init") continue;
|
|
2367
|
+
let set = isObject2(value.$set) ? value.$set : void 0;
|
|
2368
|
+
if (set) {
|
|
2369
|
+
currentModel = stringValue(set.model) ?? currentModel;
|
|
2370
|
+
for (let message of arrayValue(set.messages)) {
|
|
2371
|
+
let event = parseGeminiMessage(message, currentModel, sessionId, fallbackTs, !0);
|
|
2372
|
+
event && add(event);
|
|
2373
|
+
}
|
|
2374
|
+
}
|
|
2375
|
+
for (let message of arrayValue(value.messages)) {
|
|
2376
|
+
let event = parseGeminiMessage(message, currentModel, sessionId, fallbackTs, !0);
|
|
2377
|
+
event && add(event);
|
|
2378
|
+
}
|
|
2379
|
+
let direct = parseDirectGeminiEvent(value, currentModel, sessionId, fallbackTs);
|
|
2380
|
+
if (direct) {
|
|
2381
|
+
currentModel = direct.model, add(direct);
|
|
2382
|
+
continue;
|
|
2383
|
+
}
|
|
2384
|
+
let stats = isObject2(value.stats) ? value.stats : isObject2(value.result) && isObject2(value.result.stats) ? value.result.stats : void 0;
|
|
2385
|
+
if (stats)
|
|
2386
|
+
for (let event of parseGeminiStats(stats, currentModel, sessionId, timestampFrom(value) ?? fallbackTs)) add(event);
|
|
2387
|
+
}
|
|
2388
|
+
return [...keyed.values(), ...anonymous];
|
|
2389
|
+
}
|
|
2390
|
+
function parseGeminiValue(value, fallbackId, fallbackTs) {
|
|
2391
|
+
let data = isObject2(value.data) ? value.data : void 0, sessionId = stringValue(value.sessionId) ?? stringValue(value.session_id) ?? fallbackId, fallbackModel = stringValue(value.model) ?? stringValue(data?.model), sessionTs = timestampFrom(value) ?? timestampFrom(data) ?? parseTs(value.startTime) ?? fallbackTs, messages = [
|
|
2392
|
+
...arrayValue(value.messages),
|
|
2393
|
+
...arrayValue(value.history),
|
|
2394
|
+
...arrayValue(data?.messages),
|
|
2395
|
+
...arrayValue(data?.history)
|
|
2396
|
+
], keyed = /* @__PURE__ */ new Map(), anonymous = [];
|
|
2397
|
+
for (let message of messages) {
|
|
2398
|
+
let event = parseGeminiMessage(message, fallbackModel, sessionId, sessionTs, !1);
|
|
2399
|
+
event && (event.dedupKey ? keyed.set(event.dedupKey, event) : anonymous.push(event));
|
|
2400
|
+
}
|
|
2401
|
+
if (keyed.size + anonymous.length > 0) return [...keyed.values(), ...anonymous];
|
|
2402
|
+
let direct = parseDirectGeminiEvent(value, fallbackModel, sessionId, sessionTs);
|
|
2403
|
+
if (direct) return [direct];
|
|
2404
|
+
let stats = isObject2(value.stats) ? value.stats : isObject2(value.result) && isObject2(value.result.stats) ? value.result.stats : void 0;
|
|
2405
|
+
return stats ? parseGeminiStats(stats, fallbackModel, sessionId, sessionTs) : [];
|
|
2406
|
+
}
|
|
2407
|
+
function parseGeminiMessage(message, fallbackModel, sessionId, fallbackTs, usageMetadataIsInclusive) {
|
|
2408
|
+
let source = (isObject2(message.message) ? message.message : void 0) ?? message, usageMetadata = isObject2(source.usageMetadata) ? source.usageMetadata : isObject2(source.usage) ? source.usage : void 0, tokens = isObject2(source.tokens) ? source.tokens : void 0, tokenValues = usageMetadata ? extractTokenValues(usageMetadata, usageMetadataIsInclusive || hasUsageMetadataKeys(usageMetadata)) : tokens ? extractTokenValues(tokens, !1) : void 0;
|
|
2409
|
+
if (!tokenValues || tokenTotal(tokenValues) === 0) return;
|
|
2410
|
+
let model = stringValue(source.model) ?? stringValue(message.model) ?? fallbackModel ?? "unknown", timestamp = timestampFrom(message) ?? timestampFrom(source) ?? fallbackTs, id = stringValue(message.id) ?? stringValue(source.id) ?? stringValue(message.messageId);
|
|
2411
|
+
return {
|
|
2412
|
+
model,
|
|
2413
|
+
timestamp,
|
|
2414
|
+
tokens: tokenValues,
|
|
2415
|
+
dedupKey: id ? `gemini:${sessionId}:${id}` : void 0
|
|
2416
|
+
};
|
|
2417
|
+
}
|
|
2418
|
+
function parseDirectGeminiEvent(value, modelHint, sessionId, fallbackTs) {
|
|
2419
|
+
let tokens = isObject2(value.tokens) ? value.tokens : void 0;
|
|
2420
|
+
if (!tokens || value.type !== "gemini" && !value.model && !modelHint) return;
|
|
2421
|
+
let tokenValues = extractTokenValues(
|
|
2422
|
+
tokens,
|
|
2423
|
+
hasAny(tokens, ["prompt", "prompt_tokens", "input_tokens", "promptTokenCount"])
|
|
2424
|
+
);
|
|
2425
|
+
if (tokenTotal(tokenValues) === 0) return;
|
|
2426
|
+
let id = stringValue(value.id);
|
|
2427
|
+
return {
|
|
2428
|
+
model: stringValue(value.model) ?? modelHint ?? "unknown",
|
|
2429
|
+
timestamp: timestampFrom(value) ?? fallbackTs,
|
|
2430
|
+
tokens: tokenValues,
|
|
2431
|
+
dedupKey: id ? `gemini:${sessionId}:${id}` : void 0
|
|
2432
|
+
};
|
|
2433
|
+
}
|
|
2434
|
+
function parseGeminiStats(stats, modelHint, sessionId, timestamp) {
|
|
2435
|
+
let models = isObject2(stats.models) ? stats.models : void 0;
|
|
2436
|
+
return (models ? Object.entries(models) : [[modelHint ?? "unknown", stats]]).flatMap(([model, raw], index) => {
|
|
2437
|
+
if (!isObject2(raw)) return [];
|
|
2438
|
+
let wrapped = isObject2(raw.tokens), source = wrapped ? raw.tokens : raw, inclusive = hasAny(source, ["prompt", "prompt_tokens", "input_tokens"]) || wrapped, tokens = extractTokenValues(source, inclusive);
|
|
2439
|
+
return tokenTotal(tokens) === 0 ? [] : [{ model, timestamp, tokens, dedupKey: `gemini:${sessionId}:stats:${model}:${index}:${timestamp.getTime()}` }];
|
|
2440
|
+
});
|
|
2441
|
+
}
|
|
2442
|
+
function extractTokenValues(value, inputIncludesCache) {
|
|
2443
|
+
let rawInput = firstNumber(value, ["input", "prompt", "input_tokens", "prompt_tokens", "promptTokenCount"]), cached2 = firstNumber(value, ["cached", "cached_tokens", "cachedContentTokenCount"]), output = firstNumber(value, ["output", "candidates", "output_tokens", "completion_tokens", "candidates_tokens", "candidatesTokenCount"]), reasoning = firstNumber(value, ["thoughts", "reasoning", "thoughts_tokens", "reasoning_tokens", "thoughtsTokenCount"]), tool = firstNumber(value, ["tool", "tool_tokens"]), total = optionalNumber(value, ["total", "total_tokens", "totalTokenCount"]), input = rawInput;
|
|
2444
|
+
if (inputIncludesCache)
|
|
2445
|
+
input = Math.max(rawInput - Math.min(rawInput, cached2), 0);
|
|
2446
|
+
else if (total != null && cached2 > 0) {
|
|
2447
|
+
let inclusiveTotal = rawInput + output + reasoning + tool;
|
|
2448
|
+
total === inclusiveTotal && (input = Math.max(rawInput - Math.min(rawInput, cached2), 0));
|
|
2449
|
+
}
|
|
2450
|
+
return { input: input + tool, cached: cached2, cacheWrite: 0, output, reasoning };
|
|
2451
|
+
}
|
|
2452
|
+
async function collectGeminiLogEvents(filePath, grouped, tokenBackedDates) {
|
|
2000
2453
|
let rows;
|
|
2001
2454
|
try {
|
|
2002
|
-
rows = JSON.parse(
|
|
2455
|
+
rows = JSON.parse(await readFile5(filePath, "utf-8"));
|
|
2003
2456
|
} catch {
|
|
2004
2457
|
return;
|
|
2005
2458
|
}
|
|
@@ -2020,6 +2473,7 @@ async function collectGeminiLogEvents(filePath, grouped, tokenBackedDates) {
|
|
|
2020
2473
|
channel: "cli",
|
|
2021
2474
|
model: "unknown",
|
|
2022
2475
|
project: "unknown",
|
|
2476
|
+
projectDisplay: "unknown",
|
|
2023
2477
|
inputTokens: 0,
|
|
2024
2478
|
cachedInputTokens: 0,
|
|
2025
2479
|
cacheWriteTokens: 0,
|
|
@@ -2030,31 +2484,53 @@ async function collectGeminiLogEvents(filePath, grouped, tokenBackedDates) {
|
|
|
2030
2484
|
);
|
|
2031
2485
|
}
|
|
2032
2486
|
}
|
|
2033
|
-
function
|
|
2034
|
-
|
|
2035
|
-
|
|
2036
|
-
|
|
2037
|
-
|
|
2038
|
-
|
|
2039
|
-
|
|
2040
|
-
|
|
2041
|
-
|
|
2487
|
+
function projectFieldsFromFile(filePath, baseDir, aliases2) {
|
|
2488
|
+
let first = relative(baseDir, filePath).split(sep).filter(Boolean)[0];
|
|
2489
|
+
return first && first !== basename4(filePath) ? resolveProjectFields(first, aliases2) : { project: "unknown", projectDisplay: "unknown" };
|
|
2490
|
+
}
|
|
2491
|
+
function timestampFrom(value) {
|
|
2492
|
+
return value ? parseTs(value.timestamp ?? value.createTime ?? value.created_at ?? value.lastUpdated) : null;
|
|
2493
|
+
}
|
|
2494
|
+
function firstNumber(value, keys) {
|
|
2495
|
+
return Math.max(optionalNumber(value, keys) ?? 0, 0);
|
|
2496
|
+
}
|
|
2497
|
+
function optionalNumber(value, keys) {
|
|
2498
|
+
for (let key of keys) {
|
|
2499
|
+
let raw = value[key], parsed = typeof raw == "number" ? raw : typeof raw == "string" ? Number(raw) : NaN;
|
|
2500
|
+
if (Number.isFinite(parsed)) return parsed;
|
|
2042
2501
|
}
|
|
2043
|
-
|
|
2502
|
+
}
|
|
2503
|
+
function hasUsageMetadataKeys(value) {
|
|
2504
|
+
return hasAny(value, ["promptTokenCount", "candidatesTokenCount", "cachedContentTokenCount"]);
|
|
2505
|
+
}
|
|
2506
|
+
function hasAny(value, keys) {
|
|
2507
|
+
return keys.some((key) => value[key] != null);
|
|
2508
|
+
}
|
|
2509
|
+
function tokenTotal(tokens) {
|
|
2510
|
+
return tokens.input + tokens.cached + tokens.cacheWrite + tokens.output + tokens.reasoning;
|
|
2511
|
+
}
|
|
2512
|
+
function isObject2(value) {
|
|
2513
|
+
return typeof value == "object" && value !== null && !Array.isArray(value);
|
|
2514
|
+
}
|
|
2515
|
+
function arrayValue(value) {
|
|
2516
|
+
return Array.isArray(value) ? value.filter(isObject2) : [];
|
|
2517
|
+
}
|
|
2518
|
+
function stringValue(value) {
|
|
2519
|
+
return typeof value == "string" && value.trim() ? value.trim() : void 0;
|
|
2044
2520
|
}
|
|
2045
2521
|
|
|
2046
2522
|
// src/scanners/qwen.ts
|
|
2047
|
-
import { readFile as
|
|
2048
|
-
import { join as join9, basename as
|
|
2523
|
+
import { readFile as readFile6 } from "node:fs/promises";
|
|
2524
|
+
import { join as join9, basename as basename5, dirname as dirname2 } from "node:path";
|
|
2049
2525
|
import { homedir as homedir8 } from "node:os";
|
|
2050
2526
|
async function scanQwenDates(targetDates, baseDir, projectAliases) {
|
|
2051
|
-
let dates = new Set(targetDates),
|
|
2527
|
+
let dates = new Set(targetDates), dirs = baseDir ? [baseDir] : [join9(homedir8(), ".qwen", "projects"), join9(homedir8(), ".qwen", "tmp")], files = [...new Set((await Promise.all(dirs.map((dir) => walkFiles(dir, ".jsonl")))).flat())];
|
|
2052
2528
|
if (files.length === 0) return emptyResult(dates);
|
|
2053
2529
|
let grouped = initDateMap(dates), seen = /* @__PURE__ */ new Set();
|
|
2054
2530
|
for (let filePath of files) {
|
|
2055
|
-
let chatsDir = dirname2(filePath), projectDir = dirname2(chatsDir), projectId =
|
|
2531
|
+
let chatsDir = dirname2(filePath), projectDir = dirname2(chatsDir), projectId = basename5(projectDir), pathSessionId = basename5(filePath, ".jsonl"), fallbackTs = await fileModifiedTs(filePath), assistantIndex = 0, content;
|
|
2056
2532
|
try {
|
|
2057
|
-
content = await
|
|
2533
|
+
content = await readFile6(filePath, "utf-8");
|
|
2058
2534
|
} catch {
|
|
2059
2535
|
continue;
|
|
2060
2536
|
}
|
|
@@ -2068,18 +2544,17 @@ async function scanQwenDates(targetDates, baseDir, projectAliases) {
|
|
|
2068
2544
|
continue;
|
|
2069
2545
|
}
|
|
2070
2546
|
if (obj.type !== "assistant") continue;
|
|
2071
|
-
let
|
|
2547
|
+
let u = obj.usageMetadata;
|
|
2548
|
+
if (!u) continue;
|
|
2549
|
+
let messageKey = obj.uuid ?? `${obj.sessionId ?? pathSessionId}:${assistantIndex}`;
|
|
2550
|
+
if (assistantIndex += 1, seen.has(messageKey)) continue;
|
|
2551
|
+
seen.add(messageKey);
|
|
2552
|
+
let ts = parseTs(obj.timestamp) ?? fallbackTs;
|
|
2072
2553
|
if (!ts) continue;
|
|
2073
2554
|
let dk = dateKey(ts), dayMap = grouped.get(dk);
|
|
2074
2555
|
if (!dayMap) continue;
|
|
2075
|
-
|
|
2076
|
-
|
|
2077
|
-
seen.add(obj.uuid);
|
|
2078
|
-
}
|
|
2079
|
-
let u = obj.usageMetadata;
|
|
2080
|
-
if (!u) continue;
|
|
2081
|
-
let model = obj.model ?? "unknown", fields = obj.cwd ? resolveProjectFields(obj.cwd, projectAliases) : resolveProjectFields(projectId, projectAliases), cached2 = u.cachedContentTokenCount ?? 0, input = Math.max((u.promptTokenCount ?? 0) - cached2, 0), thoughts = u.thoughtsTokenCount ?? 0, output = Math.max((u.candidatesTokenCount ?? 0) - thoughts, 0);
|
|
2082
|
-
accumulate(
|
|
2556
|
+
let model = obj.model ?? "unknown", fields = obj.cwd ? resolveProjectFields(obj.cwd, projectAliases) : resolveProjectFields(projectId, projectAliases), cached2 = Math.max(u.cachedContentTokenCount ?? 0, 0), prompt2 = Math.max(u.promptTokenCount ?? 0, 0), input = Math.max(prompt2 - Math.min(cached2, prompt2), 0), thoughts = Math.max(u.thoughtsTokenCount ?? 0, 0), output = Math.max(u.candidatesTokenCount ?? 0, 0);
|
|
2557
|
+
input + cached2 + output + thoughts !== 0 && accumulate(
|
|
2083
2558
|
dayMap,
|
|
2084
2559
|
`${model}|${fields.project}`,
|
|
2085
2560
|
{
|
|
@@ -2104,8 +2579,8 @@ async function scanQwenDates(targetDates, baseDir, projectAliases) {
|
|
|
2104
2579
|
}
|
|
2105
2580
|
|
|
2106
2581
|
// src/scanners/kimi.ts
|
|
2107
|
-
import { readFile as
|
|
2108
|
-
import { join as join10, basename as
|
|
2582
|
+
import { readFile as readFile7, stat as stat2 } from "node:fs/promises";
|
|
2583
|
+
import { join as join10, basename as basename6, dirname as dirname3 } from "node:path";
|
|
2109
2584
|
import { homedir as homedir9 } from "node:os";
|
|
2110
2585
|
var DEFAULT_MODEL = "kimi-for-coding";
|
|
2111
2586
|
function resolveKimiCodeHome(home = homedir9()) {
|
|
@@ -2123,7 +2598,7 @@ async function scanKimiDates(targetDates, legacyBaseDir, projectAliases, kimiCod
|
|
|
2123
2598
|
codeHome ? loadKimiCodeSessionIndex(codeHome) : Promise.resolve(/* @__PURE__ */ new Map())
|
|
2124
2599
|
]), grouped = initDateMap(dates), sessionSets = /* @__PURE__ */ new Map(), codeProjectCache = /* @__PURE__ */ new Map();
|
|
2125
2600
|
for (let filePath of legacyFiles) {
|
|
2126
|
-
let sessionDir = dirname3(filePath), workspaceHash =
|
|
2601
|
+
let sessionDir = dirname3(filePath), workspaceHash = basename6(dirname3(sessionDir)), sessionId = basename6(sessionDir), rawProject = legacyWorkspaceMap.get(workspaceHash) ?? workspaceHash, projectFields = resolveProjectFields(rawProject, projectAliases), usages = await parseLegacyFile(filePath, legacyModel);
|
|
2127
2602
|
for (let usage of usages)
|
|
2128
2603
|
addUsage(grouped, sessionSets, dates, usage, projectFields, sessionId);
|
|
2129
2604
|
}
|
|
@@ -2148,7 +2623,7 @@ async function scanKimiDates(targetDates, legacyBaseDir, projectAliases, kimiCod
|
|
|
2148
2623
|
return result;
|
|
2149
2624
|
}
|
|
2150
2625
|
async function findWireFiles(sessionsDir) {
|
|
2151
|
-
return (await walkFiles(sessionsDir, ".jsonl")).filter((filePath) =>
|
|
2626
|
+
return (await walkFiles(sessionsDir, ".jsonl")).filter((filePath) => basename6(filePath) === "wire.jsonl");
|
|
2152
2627
|
}
|
|
2153
2628
|
async function parseLegacyFile(filePath, fallbackModel) {
|
|
2154
2629
|
let content = await safeRead(filePath);
|
|
@@ -2272,17 +2747,17 @@ function totalUsage(usage) {
|
|
|
2272
2747
|
}
|
|
2273
2748
|
function getKimiCodePathInfo(filePath) {
|
|
2274
2749
|
let agentDir = dirname3(filePath), agentsDir = dirname3(agentDir);
|
|
2275
|
-
if (
|
|
2750
|
+
if (basename6(agentsDir) !== "agents") return null;
|
|
2276
2751
|
let sessionDir = dirname3(agentsDir);
|
|
2277
2752
|
return {
|
|
2278
2753
|
sessionDir,
|
|
2279
|
-
sessionId:
|
|
2280
|
-
workspaceKey:
|
|
2754
|
+
sessionId: basename6(sessionDir),
|
|
2755
|
+
workspaceKey: basename6(dirname3(sessionDir))
|
|
2281
2756
|
};
|
|
2282
2757
|
}
|
|
2283
2758
|
async function resolveKimiCodeProjectPath(pathInfo, sessionIndex) {
|
|
2284
2759
|
try {
|
|
2285
|
-
let raw = await
|
|
2760
|
+
let raw = await readFile7(join10(pathInfo.sessionDir, "state.json"), "utf-8"), state = JSON.parse(raw);
|
|
2286
2761
|
if (state.workDir?.trim()) return state.workDir;
|
|
2287
2762
|
} catch {
|
|
2288
2763
|
}
|
|
@@ -2309,7 +2784,7 @@ async function loadKimiCodeSessionIndex(kimiCodeHome) {
|
|
|
2309
2784
|
async function loadLegacyWorkspaceMap(kimiHome) {
|
|
2310
2785
|
let map = /* @__PURE__ */ new Map();
|
|
2311
2786
|
try {
|
|
2312
|
-
let raw = await
|
|
2787
|
+
let raw = await readFile7(join10(kimiHome, "kimi.json"), "utf-8"), config = JSON.parse(raw);
|
|
2313
2788
|
for (let [hash, info] of Object.entries(config.workspaces ?? {}))
|
|
2314
2789
|
info.path?.trim() && map.set(hash, info.path);
|
|
2315
2790
|
} catch {
|
|
@@ -2319,7 +2794,7 @@ async function loadLegacyWorkspaceMap(kimiHome) {
|
|
|
2319
2794
|
async function loadLegacyModel(kimiHome) {
|
|
2320
2795
|
for (let name of ["config.json", "kimi.json"])
|
|
2321
2796
|
try {
|
|
2322
|
-
let raw = await
|
|
2797
|
+
let raw = await readFile7(join10(kimiHome, name), "utf-8"), config = JSON.parse(raw);
|
|
2323
2798
|
if (config.model?.trim()) return normalizeModel2(config.model);
|
|
2324
2799
|
} catch {
|
|
2325
2800
|
continue;
|
|
@@ -2328,22 +2803,22 @@ async function loadLegacyModel(kimiHome) {
|
|
|
2328
2803
|
}
|
|
2329
2804
|
async function safeRead(filePath) {
|
|
2330
2805
|
try {
|
|
2331
|
-
return await
|
|
2806
|
+
return await readFile7(filePath, "utf-8");
|
|
2332
2807
|
} catch {
|
|
2333
2808
|
return null;
|
|
2334
2809
|
}
|
|
2335
2810
|
}
|
|
2336
2811
|
async function fileModifiedDate(filePath) {
|
|
2337
2812
|
try {
|
|
2338
|
-
return (await
|
|
2813
|
+
return (await stat2(filePath)).mtime;
|
|
2339
2814
|
} catch {
|
|
2340
2815
|
return null;
|
|
2341
2816
|
}
|
|
2342
2817
|
}
|
|
2343
2818
|
|
|
2344
2819
|
// src/scanners/amp.ts
|
|
2345
|
-
import { readFile as
|
|
2346
|
-
import { join as join11 } from "node:path";
|
|
2820
|
+
import { readFile as readFile8 } from "node:fs/promises";
|
|
2821
|
+
import { basename as basename7, join as join11 } from "node:path";
|
|
2347
2822
|
import { homedir as homedir10 } from "node:os";
|
|
2348
2823
|
function resolveAmpDir(baseDir) {
|
|
2349
2824
|
if (baseDir) return baseDir;
|
|
@@ -2353,134 +2828,153 @@ function resolveAmpDir(baseDir) {
|
|
|
2353
2828
|
return xdgDataHome ? join11(xdgDataHome, "amp", "threads") : join11(homedir10(), ".local", "share", "amp", "threads");
|
|
2354
2829
|
}
|
|
2355
2830
|
async function scanAmpDates(targetDates, baseDir, _projectAliases) {
|
|
2356
|
-
let dates = new Set(targetDates),
|
|
2357
|
-
|
|
2358
|
-
|
|
2359
|
-
|
|
2360
|
-
if (threadFiles.length === 0) return emptyResult(dates);
|
|
2831
|
+
let dates = new Set(targetDates), files = (await walkFiles(resolveAmpDir(baseDir), ".json")).filter(
|
|
2832
|
+
(file) => basename7(file).startsWith("T-")
|
|
2833
|
+
);
|
|
2834
|
+
if (files.length === 0) return emptyResult(dates);
|
|
2361
2835
|
let grouped = initDateMap(dates);
|
|
2362
|
-
for (let filePath of
|
|
2363
|
-
let raw;
|
|
2364
|
-
try {
|
|
2365
|
-
raw = await readFile9(filePath, "utf-8");
|
|
2366
|
-
} catch {
|
|
2367
|
-
continue;
|
|
2368
|
-
}
|
|
2836
|
+
for (let filePath of files) {
|
|
2369
2837
|
let thread;
|
|
2370
2838
|
try {
|
|
2371
|
-
thread = JSON.parse(
|
|
2839
|
+
thread = JSON.parse(await readFile8(filePath, "utf-8"));
|
|
2372
2840
|
} catch {
|
|
2373
2841
|
continue;
|
|
2374
2842
|
}
|
|
2375
|
-
let
|
|
2376
|
-
|
|
2843
|
+
let fileTs = await fileModifiedTs(filePath), threadTs = parseTs(thread.created) ?? fileTs;
|
|
2844
|
+
if (!threadTs) continue;
|
|
2845
|
+
let ledger = buildLedgerRecords(thread.usageLedger?.events ?? [], threadTs), messages = buildMessageRecords(thread.messages, threadTs), records = reconcileAmpRecords(ledger, messages);
|
|
2846
|
+
for (let record of records) {
|
|
2847
|
+
let dayMap = grouped.get(dateKey(record.timestamp));
|
|
2848
|
+
if (!dayMap) continue;
|
|
2849
|
+
let { input, cached: cached2, cacheWrite, output, reasoning } = record.tokens;
|
|
2850
|
+
if (input + cached2 + cacheWrite + output + reasoning === 0) continue;
|
|
2851
|
+
let provider = inferProviderFromModel(record.model, "anthropic");
|
|
2852
|
+
accumulate(
|
|
2853
|
+
dayMap,
|
|
2854
|
+
`${provider}|${record.model}|unknown`,
|
|
2855
|
+
{
|
|
2856
|
+
provider,
|
|
2857
|
+
product: "amp",
|
|
2858
|
+
channel: "cli",
|
|
2859
|
+
model: record.model,
|
|
2860
|
+
project: "unknown",
|
|
2861
|
+
projectDisplay: "unknown",
|
|
2862
|
+
inputTokens: 0,
|
|
2863
|
+
cachedInputTokens: 0,
|
|
2864
|
+
cacheWriteTokens: 0,
|
|
2865
|
+
outputTokens: 0,
|
|
2866
|
+
reasoningOutputTokens: 0
|
|
2867
|
+
},
|
|
2868
|
+
record.tokens
|
|
2869
|
+
);
|
|
2870
|
+
}
|
|
2377
2871
|
}
|
|
2378
2872
|
return finalize(grouped);
|
|
2379
2873
|
}
|
|
2380
|
-
function
|
|
2381
|
-
|
|
2382
|
-
|
|
2383
|
-
|
|
2384
|
-
|
|
2874
|
+
function buildLedgerRecords(events, fallbackTs) {
|
|
2875
|
+
return events.map((event) => {
|
|
2876
|
+
let explicitTs = parseTs(event.timestamp);
|
|
2877
|
+
return {
|
|
2878
|
+
model: event.model ?? "unknown",
|
|
2879
|
+
timestamp: explicitTs ?? fallbackTs,
|
|
2880
|
+
hasExplicitTimestamp: !!explicitTs,
|
|
2881
|
+
ledgerToMessageId: normalizeId(event.toMessageId),
|
|
2882
|
+
tokens: {
|
|
2883
|
+
input: clamp2(event.tokens?.input),
|
|
2884
|
+
output: clamp2(event.tokens?.output),
|
|
2885
|
+
cached: clamp2(event.tokens?.cacheReadInputTokens),
|
|
2886
|
+
cacheWrite: clamp2(event.tokens?.cacheCreationInputTokens),
|
|
2887
|
+
reasoning: 0
|
|
2888
|
+
}
|
|
2889
|
+
};
|
|
2890
|
+
});
|
|
2891
|
+
}
|
|
2892
|
+
function buildMessageRecords(messages, fallbackTs) {
|
|
2893
|
+
return messages ? (Array.isArray(messages) ? messages.map((message, index) => [String(index), message]) : Object.entries(messages)).flatMap(([key, message], index) => {
|
|
2894
|
+
if (message.role && message.role !== "assistant") return [];
|
|
2895
|
+
let usage = message.usage;
|
|
2896
|
+
if (!usage) return [];
|
|
2897
|
+
let numericId = typeof message.messageId == "number" ? message.messageId : void 0, timestamp = parseTs(message.timestamp) ?? new Date(fallbackTs.getTime() + Math.max(numericId ?? index, 0) * 1e3);
|
|
2898
|
+
return [{
|
|
2899
|
+
model: usage.model ?? message.model ?? "unknown",
|
|
2900
|
+
timestamp,
|
|
2901
|
+
hasExplicitTimestamp: !!parseTs(message.timestamp),
|
|
2902
|
+
messageId: normalizeId(message.messageId ?? key),
|
|
2903
|
+
tokens: {
|
|
2904
|
+
input: clamp2(usage.inputTokens),
|
|
2905
|
+
output: clamp2(usage.outputTokens),
|
|
2906
|
+
cached: clamp2(usage.cacheReadInputTokens),
|
|
2907
|
+
cacheWrite: clamp2(usage.cacheCreationInputTokens),
|
|
2908
|
+
reasoning: 0
|
|
2909
|
+
}
|
|
2910
|
+
}];
|
|
2911
|
+
}) : [];
|
|
2912
|
+
}
|
|
2913
|
+
function reconcileAmpRecords(ledger, messages) {
|
|
2914
|
+
if (ledger.length === 0) return messages.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime());
|
|
2915
|
+
let consumed = /* @__PURE__ */ new Set(), merged = [...ledger], unmatched = [];
|
|
2916
|
+
for (let message of messages) {
|
|
2917
|
+
let index = findLedgerMatch(merged, consumed, message);
|
|
2918
|
+
if (index < 0) {
|
|
2919
|
+
unmatched.push(message);
|
|
2920
|
+
continue;
|
|
2385
2921
|
}
|
|
2386
|
-
|
|
2922
|
+
consumed.add(index);
|
|
2923
|
+
let item = merged[index];
|
|
2924
|
+
merged[index] = {
|
|
2925
|
+
...item,
|
|
2926
|
+
model: item.model === "unknown" ? message.model : item.model,
|
|
2927
|
+
timestamp: item.hasExplicitTimestamp ? item.timestamp : message.timestamp,
|
|
2928
|
+
messageId: message.messageId,
|
|
2929
|
+
tokens: {
|
|
2930
|
+
input: item.tokens.input || message.tokens.input,
|
|
2931
|
+
output: item.tokens.output || message.tokens.output,
|
|
2932
|
+
cached: item.tokens.cached || message.tokens.cached,
|
|
2933
|
+
cacheWrite: item.tokens.cacheWrite || message.tokens.cacheWrite,
|
|
2934
|
+
reasoning: 0
|
|
2935
|
+
}
|
|
2936
|
+
};
|
|
2387
2937
|
}
|
|
2938
|
+
return [...merged, ...unmatched].sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime());
|
|
2388
2939
|
}
|
|
2389
|
-
function
|
|
2390
|
-
|
|
2391
|
-
let
|
|
2392
|
-
|
|
2393
|
-
let dk = dateKey(ts), dayMap = grouped.get(dk);
|
|
2394
|
-
if (!dayMap) continue;
|
|
2395
|
-
let model = event.model ?? "unknown", input = event.tokens?.input ?? 0, output = event.tokens?.output ?? 0, cached2 = 0;
|
|
2396
|
-
event.toMessageId && (cached2 = getMessageByKey(thread.messages, event.toMessageId)?.usage?.cacheReadInputTokens ?? 0), accumulate(
|
|
2397
|
-
dayMap,
|
|
2398
|
-
`${model}|unknown`,
|
|
2399
|
-
{
|
|
2400
|
-
provider: "sourcegraph",
|
|
2401
|
-
product: "amp",
|
|
2402
|
-
channel: "cli",
|
|
2403
|
-
model,
|
|
2404
|
-
project: "unknown",
|
|
2405
|
-
projectDisplay: "unknown",
|
|
2406
|
-
inputTokens: 0,
|
|
2407
|
-
cachedInputTokens: 0,
|
|
2408
|
-
cacheWriteTokens: 0,
|
|
2409
|
-
outputTokens: 0,
|
|
2410
|
-
reasoningOutputTokens: 0
|
|
2411
|
-
},
|
|
2412
|
-
{ input, cached: cached2, cacheWrite: 0, output, reasoning: 0 }
|
|
2940
|
+
function findLedgerMatch(ledger, consumed, message) {
|
|
2941
|
+
if (message.messageId) {
|
|
2942
|
+
let byId = ledger.findIndex(
|
|
2943
|
+
(record, index) => !consumed.has(index) && record.ledgerToMessageId === message.messageId
|
|
2413
2944
|
);
|
|
2945
|
+
if (byId >= 0) return byId;
|
|
2414
2946
|
}
|
|
2947
|
+
return ledger.findIndex(
|
|
2948
|
+
(record, index) => !consumed.has(index) && record.model === message.model && tokenFingerprint(record.tokens) === tokenFingerprint(message.tokens)
|
|
2949
|
+
);
|
|
2415
2950
|
}
|
|
2416
|
-
function
|
|
2417
|
-
|
|
2418
|
-
|
|
2419
|
-
|
|
2420
|
-
|
|
2421
|
-
|
|
2422
|
-
|
|
2423
|
-
|
|
2424
|
-
|
|
2425
|
-
let dk = dateKey(ts), dayMap = grouped.get(dk);
|
|
2426
|
-
if (!dayMap) continue;
|
|
2427
|
-
let model = msg.model ?? "unknown", input = usage.inputTokens ?? 0, output = usage.outputTokens ?? 0, cached2 = usage.cacheReadInputTokens ?? 0;
|
|
2428
|
-
accumulate(
|
|
2429
|
-
dayMap,
|
|
2430
|
-
`${model}|unknown`,
|
|
2431
|
-
{
|
|
2432
|
-
provider: "sourcegraph",
|
|
2433
|
-
product: "amp",
|
|
2434
|
-
channel: "cli",
|
|
2435
|
-
model,
|
|
2436
|
-
project: "unknown",
|
|
2437
|
-
projectDisplay: "unknown",
|
|
2438
|
-
inputTokens: 0,
|
|
2439
|
-
cachedInputTokens: 0,
|
|
2440
|
-
cacheWriteTokens: 0,
|
|
2441
|
-
outputTokens: 0,
|
|
2442
|
-
reasoningOutputTokens: 0
|
|
2443
|
-
},
|
|
2444
|
-
{ input, cached: cached2, cacheWrite: 0, output, reasoning: 0 }
|
|
2445
|
-
);
|
|
2446
|
-
}
|
|
2951
|
+
function tokenFingerprint(tokens) {
|
|
2952
|
+
return [tokens.input, tokens.cached, tokens.cacheWrite, tokens.output, tokens.reasoning].join(":");
|
|
2953
|
+
}
|
|
2954
|
+
function normalizeId(value) {
|
|
2955
|
+
if (!(value == null || value === ""))
|
|
2956
|
+
return String(value);
|
|
2957
|
+
}
|
|
2958
|
+
function clamp2(value) {
|
|
2959
|
+
return Math.max(Number.isFinite(value) ? value : 0, 0);
|
|
2447
2960
|
}
|
|
2448
2961
|
|
|
2449
2962
|
// src/scanners/droid.ts
|
|
2450
|
-
import { readFile as
|
|
2451
|
-
import { join as join12, dirname as dirname4, basename as
|
|
2963
|
+
import { readFile as readFile9 } from "node:fs/promises";
|
|
2964
|
+
import { join as join12, dirname as dirname4, basename as basename8 } from "node:path";
|
|
2452
2965
|
import { homedir as homedir11 } from "node:os";
|
|
2453
2966
|
function extractProjectFromSlug(dirPath) {
|
|
2454
|
-
let parts =
|
|
2967
|
+
let parts = basename8(dirPath).split("-").filter(Boolean);
|
|
2455
2968
|
return parts[parts.length - 1] || "unknown";
|
|
2456
2969
|
}
|
|
2457
2970
|
async function scanDroidDates(targetDates, baseDir, projectAliases) {
|
|
2458
|
-
let dates = new Set(targetDates), dir = baseDir ?? join12(homedir11(), ".factory", "sessions"), files = await walkFiles(dir, ".
|
|
2971
|
+
let dates = new Set(targetDates), dir = baseDir ?? join12(homedir11(), ".factory", "sessions"), files = await walkFiles(dir, ".settings.json");
|
|
2459
2972
|
if (files.length === 0) return emptyResult(dates);
|
|
2460
2973
|
let grouped = initDateMap(dates);
|
|
2461
|
-
for (let
|
|
2462
|
-
let
|
|
2463
|
-
try {
|
|
2464
|
-
content = await readFile10(jsonlPath, "utf-8");
|
|
2465
|
-
} catch {
|
|
2466
|
-
continue;
|
|
2467
|
-
}
|
|
2468
|
-
let firstLine = content.split(`
|
|
2469
|
-
`).find((l) => l.trim());
|
|
2470
|
-
if (!firstLine) continue;
|
|
2471
|
-
let firstObj;
|
|
2472
|
-
try {
|
|
2473
|
-
firstObj = JSON.parse(firstLine);
|
|
2474
|
-
} catch {
|
|
2475
|
-
continue;
|
|
2476
|
-
}
|
|
2477
|
-
let ts = parseTs(firstObj.timestamp);
|
|
2478
|
-
if (!ts) continue;
|
|
2479
|
-
let dk = dateKey(ts), dayMap = grouped.get(dk);
|
|
2480
|
-
if (!dayMap) continue;
|
|
2481
|
-
let sessionDir = dirname4(jsonlPath), jsonlName = basename6(jsonlPath, ".jsonl"), settingsPath = join12(sessionDir, `${jsonlName}.settings.json`), settingsRaw;
|
|
2974
|
+
for (let settingsPath of files) {
|
|
2975
|
+
let settingsRaw;
|
|
2482
2976
|
try {
|
|
2483
|
-
settingsRaw = await
|
|
2977
|
+
settingsRaw = await readFile9(settingsPath, "utf-8");
|
|
2484
2978
|
} catch {
|
|
2485
2979
|
continue;
|
|
2486
2980
|
}
|
|
@@ -2492,12 +2986,18 @@ async function scanDroidDates(targetDates, baseDir, projectAliases) {
|
|
|
2492
2986
|
}
|
|
2493
2987
|
let usage = settings.tokenUsage;
|
|
2494
2988
|
if (!usage) continue;
|
|
2495
|
-
let
|
|
2989
|
+
let input = Math.max(usage.inputTokens ?? 0, 0), cacheRead = Math.max(usage.cacheReadTokens ?? 0, 0), cacheWrite = Math.max(usage.cacheCreationTokens ?? 0, 0), output = Math.max(usage.outputTokens ?? 0, 0), thinking = Math.max(usage.thinkingTokens ?? 0, 0);
|
|
2990
|
+
if (input + cacheRead + cacheWrite + output + thinking === 0) continue;
|
|
2991
|
+
let sessionDir = dirname4(settingsPath), transcriptPath = settingsPath.replace(/\.settings\.json$/, ".jsonl"), transcriptModel = settings.model ? void 0 : await extractModelFromTranscript(transcriptPath), model = normalizeDroidModel(settings.model ?? transcriptModel ?? `${settings.providerLock ?? "droid"}-unknown`), provider = settings.providerLock?.trim().toLowerCase() || inferProviderFromModel(model, "droid"), ts = parseTs(settings.providerLockTimestamp) ?? await fileModifiedTs(settingsPath);
|
|
2992
|
+
if (!ts) continue;
|
|
2993
|
+
let dk = dateKey(ts), dayMap = grouped.get(dk);
|
|
2994
|
+
if (!dayMap) continue;
|
|
2995
|
+
let rawProject = extractProjectFromSlug(sessionDir), alias = projectAliases?.[rawProject], project = alias ?? rawProject;
|
|
2496
2996
|
accumulate(
|
|
2497
2997
|
dayMap,
|
|
2498
2998
|
`${model}|${project}`,
|
|
2499
2999
|
{
|
|
2500
|
-
provider
|
|
3000
|
+
provider,
|
|
2501
3001
|
product: "droid",
|
|
2502
3002
|
channel: "cli",
|
|
2503
3003
|
model,
|
|
@@ -2510,80 +3010,187 @@ async function scanDroidDates(targetDates, baseDir, projectAliases) {
|
|
|
2510
3010
|
outputTokens: 0,
|
|
2511
3011
|
reasoningOutputTokens: 0
|
|
2512
3012
|
},
|
|
2513
|
-
{ input, cached: cacheRead, cacheWrite
|
|
3013
|
+
{ input, cached: cacheRead, cacheWrite, output, reasoning: thinking }
|
|
2514
3014
|
);
|
|
2515
3015
|
}
|
|
2516
3016
|
return finalize(grouped);
|
|
2517
3017
|
}
|
|
3018
|
+
function normalizeDroidModel(model) {
|
|
3019
|
+
return model.replace(/^custom:/i, "").replace(/\[[^\]]*\]/g, "").replace(/\./g, "-").replace(/[\s_]+/g, "-").replace(/-+/g, "-").replace(/-+$/, "").toLowerCase();
|
|
3020
|
+
}
|
|
3021
|
+
async function extractModelFromTranscript(filePath) {
|
|
3022
|
+
let content;
|
|
3023
|
+
try {
|
|
3024
|
+
content = await readFile9(filePath, "utf-8");
|
|
3025
|
+
} catch {
|
|
3026
|
+
return;
|
|
3027
|
+
}
|
|
3028
|
+
return content.match(/Model:\s*([^\\\["\n]+)/i)?.[1]?.trim() || void 0;
|
|
3029
|
+
}
|
|
2518
3030
|
|
|
2519
3031
|
// src/scanners/opencode.ts
|
|
2520
|
-
import {
|
|
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";
|
|
2521
3035
|
import { homedir as homedir12 } from "node:os";
|
|
2522
3036
|
async function scanOpencodeDates(targetDates, baseDir, projectAliases) {
|
|
2523
|
-
let dates = new Set(targetDates),
|
|
2524
|
-
|
|
2525
|
-
|
|
3037
|
+
let dates = new Set(targetDates), dataDir = baseDir ?? join13(homedir12(), ".local", "share", "opencode"), legacyDir = baseDir ?? join13(dataDir, "storage", "message"), dbPath = join13(dataDir, "opencode.db"), grouped = initDateMap(dates), seenIds = /* @__PURE__ */ new Set(), seenFingerprints = /* @__PURE__ */ new Set(), sqliteRows = await queryOpenCodeSqlite(dbPath), sqliteRecords = parseOpenCodeSqliteRows(sqliteRows);
|
|
3038
|
+
for (let record of sqliteRecords)
|
|
3039
|
+
addOpenCodeRecord(record, grouped, seenIds, seenFingerprints, projectAliases);
|
|
3040
|
+
let files = await walkFiles(legacyDir, ".json");
|
|
2526
3041
|
for (let filePath of files) {
|
|
2527
|
-
let
|
|
3042
|
+
let message;
|
|
2528
3043
|
try {
|
|
2529
|
-
|
|
3044
|
+
message = JSON.parse(await readFile10(filePath, "utf-8"));
|
|
2530
3045
|
} catch {
|
|
2531
3046
|
continue;
|
|
2532
3047
|
}
|
|
2533
|
-
let
|
|
3048
|
+
let record = parseOpenCodeMessage(message, basename9(filePath, ".json"));
|
|
3049
|
+
record && addOpenCodeRecord(record, grouped, seenIds, seenFingerprints, projectAliases);
|
|
3050
|
+
}
|
|
3051
|
+
return sqliteRows.length === 0 && files.length === 0 ? emptyResult(dates) : finalize(grouped);
|
|
3052
|
+
}
|
|
3053
|
+
async function discoverOpenCodeUsageDates(baseDir) {
|
|
3054
|
+
let dataDir = baseDir ?? join13(homedir12(), ".local", "share", "opencode"), legacyDir = baseDir ?? join13(dataDir, "storage", "message"), result = /* @__PURE__ */ new Set();
|
|
3055
|
+
for (let record of parseOpenCodeSqliteRows(await queryOpenCodeSqlite(join13(dataDir, "opencode.db"))))
|
|
3056
|
+
result.add(dateKey(record.timestamp));
|
|
3057
|
+
for (let filePath of await walkFiles(legacyDir, ".json"))
|
|
2534
3058
|
try {
|
|
2535
|
-
|
|
3059
|
+
let record = parseOpenCodeMessage(
|
|
3060
|
+
JSON.parse(await readFile10(filePath, "utf-8")),
|
|
3061
|
+
basename9(filePath, ".json")
|
|
3062
|
+
);
|
|
3063
|
+
record && result.add(dateKey(record.timestamp));
|
|
2536
3064
|
} catch {
|
|
2537
|
-
continue;
|
|
2538
3065
|
}
|
|
2539
|
-
|
|
2540
|
-
|
|
2541
|
-
|
|
2542
|
-
|
|
2543
|
-
|
|
2544
|
-
|
|
2545
|
-
|
|
2546
|
-
|
|
2547
|
-
|
|
2548
|
-
|
|
2549
|
-
|
|
2550
|
-
|
|
2551
|
-
|
|
2552
|
-
|
|
2553
|
-
|
|
2554
|
-
|
|
2555
|
-
|
|
2556
|
-
|
|
2557
|
-
|
|
2558
|
-
|
|
2559
|
-
|
|
2560
|
-
|
|
2561
|
-
|
|
2562
|
-
|
|
2563
|
-
|
|
2564
|
-
|
|
2565
|
-
|
|
3066
|
+
return result;
|
|
3067
|
+
}
|
|
3068
|
+
function parseOpenCodeSqliteRows(rows) {
|
|
3069
|
+
return rows.flatMap((row) => {
|
|
3070
|
+
if (!row.data) return [];
|
|
3071
|
+
let message;
|
|
3072
|
+
try {
|
|
3073
|
+
message = JSON.parse(row.data);
|
|
3074
|
+
} catch {
|
|
3075
|
+
return [];
|
|
3076
|
+
}
|
|
3077
|
+
message.sessionID ??= row.session_id;
|
|
3078
|
+
let record = parseOpenCodeMessage(message, row.id);
|
|
3079
|
+
return record ? (record.projectRoot = row.workspace_root || record.projectRoot, [record]) : [];
|
|
3080
|
+
});
|
|
3081
|
+
}
|
|
3082
|
+
async function queryOpenCodeSqlite(dbPath) {
|
|
3083
|
+
let modern = `
|
|
3084
|
+
SELECT m.id, m.session_id, m.data, NULLIF(s.directory, '') AS workspace_root
|
|
3085
|
+
FROM message m
|
|
3086
|
+
LEFT JOIN session s ON s.id = m.session_id
|
|
3087
|
+
WHERE json_extract(m.data, '$.role') = 'assistant'
|
|
3088
|
+
AND json_extract(m.data, '$.tokens') IS NOT NULL
|
|
3089
|
+
ORDER BY m.id, m.session_id`, legacy = `
|
|
3090
|
+
SELECT m.id, m.session_id, m.data, NULL AS workspace_root
|
|
3091
|
+
FROM message m
|
|
3092
|
+
WHERE json_extract(m.data, '$.role') = 'assistant'
|
|
3093
|
+
AND json_extract(m.data, '$.tokens') IS NOT NULL
|
|
3094
|
+
ORDER BY m.id, m.session_id`;
|
|
3095
|
+
for (let query of [modern, legacy])
|
|
3096
|
+
try {
|
|
3097
|
+
let stdout = await runSqlite(["-readonly", "-json", dbPath, query]), rows = JSON.parse(stdout || "[]");
|
|
3098
|
+
if (Array.isArray(rows)) return rows.filter(isSqliteRow);
|
|
3099
|
+
} catch {
|
|
3100
|
+
}
|
|
3101
|
+
return [];
|
|
3102
|
+
}
|
|
3103
|
+
function runSqlite(args) {
|
|
3104
|
+
return new Promise((resolve5, reject) => {
|
|
3105
|
+
execFile(
|
|
3106
|
+
"sqlite3",
|
|
3107
|
+
args,
|
|
3108
|
+
{ encoding: "utf8", maxBuffer: 64 * 1024 * 1024 },
|
|
3109
|
+
(error, stdout) => error ? reject(error) : resolve5(stdout)
|
|
2566
3110
|
);
|
|
2567
|
-
}
|
|
2568
|
-
|
|
3111
|
+
});
|
|
3112
|
+
}
|
|
3113
|
+
function parseOpenCodeMessage(message, fallbackId) {
|
|
3114
|
+
if (message.role !== "assistant" || !message.tokens) return;
|
|
3115
|
+
let timestamp = parseTs(message.time?.created);
|
|
3116
|
+
if (!timestamp) return;
|
|
3117
|
+
let model = message.modelID ?? "unknown", provider = message.providerID?.trim().toLowerCase() || inferProviderFromModel(model, "opencode"), tokens = {
|
|
3118
|
+
input: clamp3(message.tokens.input),
|
|
3119
|
+
cached: clamp3(message.tokens.cache?.read),
|
|
3120
|
+
cacheWrite: clamp3(message.tokens.cache?.write),
|
|
3121
|
+
output: clamp3(message.tokens.output),
|
|
3122
|
+
reasoning: clamp3(message.tokens.reasoning)
|
|
3123
|
+
};
|
|
3124
|
+
if (Object.values(tokens).every((value) => value === 0)) return;
|
|
3125
|
+
let projectRoot = typeof message.path == "string" ? message.path : message.path?.root;
|
|
3126
|
+
return {
|
|
3127
|
+
id: message.id ?? fallbackId,
|
|
3128
|
+
timestamp,
|
|
3129
|
+
model,
|
|
3130
|
+
provider,
|
|
3131
|
+
projectRoot,
|
|
3132
|
+
tokens,
|
|
3133
|
+
fingerprint: [
|
|
3134
|
+
timestamp.getTime(),
|
|
3135
|
+
model,
|
|
3136
|
+
provider,
|
|
3137
|
+
tokens.input,
|
|
3138
|
+
tokens.cached,
|
|
3139
|
+
tokens.cacheWrite,
|
|
3140
|
+
tokens.output,
|
|
3141
|
+
tokens.reasoning
|
|
3142
|
+
].join("|")
|
|
3143
|
+
};
|
|
3144
|
+
}
|
|
3145
|
+
function addOpenCodeRecord(record, grouped, seenIds, seenFingerprints, aliases2) {
|
|
3146
|
+
if (record.id && seenIds.has(record.id) || seenFingerprints.has(record.fingerprint)) return;
|
|
3147
|
+
record.id && seenIds.add(record.id), seenFingerprints.add(record.fingerprint);
|
|
3148
|
+
let dayMap = grouped.get(dateKey(record.timestamp));
|
|
3149
|
+
if (!dayMap) return;
|
|
3150
|
+
let fields = record.projectRoot ? resolveProjectFields(record.projectRoot, aliases2) : { project: "unknown", projectDisplay: "unknown" };
|
|
3151
|
+
accumulate(
|
|
3152
|
+
dayMap,
|
|
3153
|
+
`${record.provider}|${record.model}|${fields.project}`,
|
|
3154
|
+
{
|
|
3155
|
+
provider: record.provider,
|
|
3156
|
+
product: "opencode",
|
|
3157
|
+
channel: "cli",
|
|
3158
|
+
model: record.model,
|
|
3159
|
+
project: fields.project,
|
|
3160
|
+
projectDisplay: fields.projectDisplay,
|
|
3161
|
+
projectAlias: fields.projectAlias,
|
|
3162
|
+
inputTokens: 0,
|
|
3163
|
+
cachedInputTokens: 0,
|
|
3164
|
+
cacheWriteTokens: 0,
|
|
3165
|
+
outputTokens: 0,
|
|
3166
|
+
reasoningOutputTokens: 0
|
|
3167
|
+
},
|
|
3168
|
+
record.tokens
|
|
3169
|
+
);
|
|
3170
|
+
}
|
|
3171
|
+
function isSqliteRow(value) {
|
|
3172
|
+
return typeof value == "object" && value !== null && !Array.isArray(value);
|
|
3173
|
+
}
|
|
3174
|
+
function clamp3(value) {
|
|
3175
|
+
return Math.max(Number.isFinite(value) ? value : 0, 0);
|
|
2569
3176
|
}
|
|
2570
3177
|
|
|
2571
3178
|
// src/scanners/pi.ts
|
|
2572
|
-
import { readFile as
|
|
2573
|
-
import { join as
|
|
3179
|
+
import { readFile as readFile11 } from "node:fs/promises";
|
|
3180
|
+
import { join as join14, basename as basename10, dirname as dirname5 } from "node:path";
|
|
2574
3181
|
import { homedir as homedir13 } from "node:os";
|
|
2575
3182
|
async function scanPiDates(targetDates, baseDir, projectAliases) {
|
|
2576
|
-
let dates = new Set(targetDates),
|
|
3183
|
+
let dates = new Set(targetDates), sessionDirs = baseDir ? [baseDir] : getSessionDirs(), files = [...new Set((await Promise.all(sessionDirs.map((dir) => walkFiles(dir, ".jsonl")))).flat())];
|
|
2577
3184
|
if (files.length === 0) return emptyResult(dates);
|
|
2578
3185
|
let grouped = initDateMap(dates), seen = /* @__PURE__ */ new Set();
|
|
2579
3186
|
for (let filePath of files) {
|
|
2580
3187
|
let content;
|
|
2581
3188
|
try {
|
|
2582
|
-
content = await
|
|
3189
|
+
content = await readFile11(filePath, "utf-8");
|
|
2583
3190
|
} catch {
|
|
2584
3191
|
continue;
|
|
2585
3192
|
}
|
|
2586
|
-
let parentDir = dirname5(filePath), encodedCwd =
|
|
3193
|
+
let parentDir = dirname5(filePath), encodedCwd = basename10(parentDir), sessionProjectFields = { project: extractProjectFromEncoded(encodedCwd), projectDisplay: extractProjectFromEncoded(encodedCwd) }, sessionId = basename10(filePath, ".jsonl"), messageIndex = 0, fallbackTs = await fileModifiedTs(filePath);
|
|
2587
3194
|
for (let line of content.split(`
|
|
2588
3195
|
`)) {
|
|
2589
3196
|
if (!line.trim()) continue;
|
|
@@ -2594,7 +3201,11 @@ async function scanPiDates(targetDates, baseDir, projectAliases) {
|
|
|
2594
3201
|
continue;
|
|
2595
3202
|
}
|
|
2596
3203
|
if (obj.type === "session" && obj.cwd) {
|
|
2597
|
-
sessionProjectFields = resolveProjectFields(obj.cwd, projectAliases);
|
|
3204
|
+
sessionId = obj.id ?? sessionId, sessionProjectFields = resolveProjectFields(obj.cwd, projectAliases);
|
|
3205
|
+
continue;
|
|
3206
|
+
}
|
|
3207
|
+
if (obj.type === "session") {
|
|
3208
|
+
sessionId = obj.id ?? sessionId;
|
|
2598
3209
|
continue;
|
|
2599
3210
|
}
|
|
2600
3211
|
if (obj.type !== "message") continue;
|
|
@@ -2602,20 +3213,19 @@ async function scanPiDates(targetDates, baseDir, projectAliases) {
|
|
|
2602
3213
|
if (!msg || msg.role !== "assistant") continue;
|
|
2603
3214
|
let usage = msg.usage;
|
|
2604
3215
|
if (!usage || usage.input == null && usage.output == null) continue;
|
|
2605
|
-
let ts = parseTs(obj.timestamp);
|
|
3216
|
+
let ts = parseTs(obj.timestamp) ?? fallbackTs;
|
|
2606
3217
|
if (!ts) continue;
|
|
2607
3218
|
let dk = dateKey(ts), dayMap = grouped.get(dk);
|
|
2608
3219
|
if (!dayMap) continue;
|
|
2609
|
-
|
|
2610
|
-
|
|
2611
|
-
|
|
2612
|
-
|
|
2613
|
-
|
|
2614
|
-
accumulate(
|
|
3220
|
+
let messageKey = `${sessionId}:${obj.id ?? messageIndex}`;
|
|
3221
|
+
if (messageIndex += 1, seen.has(messageKey)) continue;
|
|
3222
|
+
seen.add(messageKey);
|
|
3223
|
+
let model = msg.model ?? "unknown", provider = msg.provider?.trim() || inferProviderFromModel(model, "inflection"), input = Math.max(usage.input ?? 0, 0), cached2 = Math.max(usage.cacheRead ?? 0, 0), cacheWrite = Math.max(usage.cacheWrite ?? 0, 0), output = Math.max(usage.output ?? 0, 0);
|
|
3224
|
+
input + cached2 + cacheWrite + output !== 0 && accumulate(
|
|
2615
3225
|
dayMap,
|
|
2616
3226
|
`${model}|${sessionProjectFields.project}`,
|
|
2617
3227
|
{
|
|
2618
|
-
provider
|
|
3228
|
+
provider,
|
|
2619
3229
|
product: "pi",
|
|
2620
3230
|
channel: "cli",
|
|
2621
3231
|
model,
|
|
@@ -2628,19 +3238,193 @@ async function scanPiDates(targetDates, baseDir, projectAliases) {
|
|
|
2628
3238
|
outputTokens: 0,
|
|
2629
3239
|
reasoningOutputTokens: 0
|
|
2630
3240
|
},
|
|
2631
|
-
{ input, cached: cached2, cacheWrite
|
|
3241
|
+
{ input, cached: cached2, cacheWrite, output, reasoning: 0 }
|
|
2632
3242
|
);
|
|
2633
3243
|
}
|
|
2634
3244
|
}
|
|
2635
|
-
return finalize(grouped);
|
|
3245
|
+
return finalize(grouped);
|
|
3246
|
+
}
|
|
3247
|
+
function getSessionDirs() {
|
|
3248
|
+
let envDir = process.env.PI_CODING_AGENT_DIR;
|
|
3249
|
+
return [envDir ? join14(envDir, "sessions") : join14(homedir13(), ".pi", "agent", "sessions"), join14(homedir13(), ".omp", "agent", "sessions")];
|
|
3250
|
+
}
|
|
3251
|
+
function extractProjectFromEncoded(encoded) {
|
|
3252
|
+
let parts = encoded.split("-").filter(Boolean);
|
|
3253
|
+
return parts.length > 0 ? parts[parts.length - 1] : "unknown";
|
|
3254
|
+
}
|
|
3255
|
+
|
|
3256
|
+
// src/scanners/trae.ts
|
|
3257
|
+
import { readFile as readFile12 } from "node:fs/promises";
|
|
3258
|
+
import { homedir as homedir14 } from "node:os";
|
|
3259
|
+
import { join as join15, resolve as resolve2 } from "node:path";
|
|
3260
|
+
function resolveTraeNativeCacheDir(home = homedir14()) {
|
|
3261
|
+
let explicit = process.env.AIUSAGE_TRAE_CACHE_DIR?.trim();
|
|
3262
|
+
return explicit ? resolve2(explicit) : join15(home, ".aiusage", "trae-cache", "sessions");
|
|
3263
|
+
}
|
|
3264
|
+
function resolveTokscaleTraeCacheDir(home = homedir14()) {
|
|
3265
|
+
let configDir = process.env.TOKSCALE_CONFIG_DIR?.trim();
|
|
3266
|
+
return configDir ? join15(resolve2(configDir), "trae-cache", "sessions") : join15(home, ".config", "tokscale", "trae-cache", "sessions");
|
|
3267
|
+
}
|
|
3268
|
+
async function scanTraeDates(targetDates, options = {}) {
|
|
3269
|
+
let dates = new Set(targetDates);
|
|
3270
|
+
if (dates.size === 0) return /* @__PURE__ */ new Map();
|
|
3271
|
+
let nativeDir = options.nativeCacheDir ?? resolveTraeNativeCacheDir(), tokscaleDir = options.tokscaleCacheDir ?? resolveTokscaleTraeCacheDir(), cacheSources = [.../* @__PURE__ */ new Set([
|
|
3272
|
+
`${nativeDir}\0native`,
|
|
3273
|
+
`${tokscaleDir}\0tokscale`
|
|
3274
|
+
])], files = (await Promise.all(cacheSources.map(async (source) => {
|
|
3275
|
+
let [dir, kind] = source.split("\0");
|
|
3276
|
+
return (await walkFiles(dir, ".json")).map((filePath) => ({ filePath, kind }));
|
|
3277
|
+
}))).flat();
|
|
3278
|
+
if (files.length === 0) return emptyResult(dates);
|
|
3279
|
+
let grouped = initDateMap(dates), seenEvents = /* @__PURE__ */ new Set(), sessionSets = /* @__PURE__ */ new Map();
|
|
3280
|
+
for (let { filePath, kind } of files) {
|
|
3281
|
+
let value = await readJson2(filePath);
|
|
3282
|
+
if (value == null) continue;
|
|
3283
|
+
let events = kind === "native" ? parseNativeCache(value) : parseTokscaleCache(value);
|
|
3284
|
+
for (let event of events) {
|
|
3285
|
+
if (seenEvents.has(event.dedupKey)) continue;
|
|
3286
|
+
seenEvents.add(event.dedupKey);
|
|
3287
|
+
let usageDate = dateKey(event.timestamp);
|
|
3288
|
+
if (!dates.has(usageDate)) continue;
|
|
3289
|
+
let day = grouped.get(usageDate);
|
|
3290
|
+
if (!day) continue;
|
|
3291
|
+
let projectFields = resolveProjectFields(event.project, options.projectAliases), breakdownKey = `${event.provider}|${event.model}|${projectFields.project}`;
|
|
3292
|
+
if (accumulate(
|
|
3293
|
+
day,
|
|
3294
|
+
breakdownKey,
|
|
3295
|
+
{
|
|
3296
|
+
provider: event.provider,
|
|
3297
|
+
product: "trae",
|
|
3298
|
+
channel: "ide",
|
|
3299
|
+
model: event.model,
|
|
3300
|
+
project: projectFields.project,
|
|
3301
|
+
projectDisplay: projectFields.projectDisplay,
|
|
3302
|
+
projectAlias: projectFields.projectAlias,
|
|
3303
|
+
sessionCount: 0,
|
|
3304
|
+
inputTokens: 0,
|
|
3305
|
+
cachedInputTokens: 0,
|
|
3306
|
+
cacheWriteTokens: 0,
|
|
3307
|
+
outputTokens: 0,
|
|
3308
|
+
reasoningOutputTokens: 0
|
|
3309
|
+
},
|
|
3310
|
+
event
|
|
3311
|
+
), event.costUSD && event.costUSD > 0) {
|
|
3312
|
+
let breakdown = day.get(breakdownKey);
|
|
3313
|
+
breakdown && (breakdown.costUSD = (breakdown.costUSD ?? 0) + event.costUSD);
|
|
3314
|
+
}
|
|
3315
|
+
let sessionKey = `${usageDate}|${breakdownKey}`, sessions = sessionSets.get(sessionKey);
|
|
3316
|
+
sessions || (sessions = /* @__PURE__ */ new Set(), sessionSets.set(sessionKey, sessions)), sessions.add(event.sessionId);
|
|
3317
|
+
}
|
|
3318
|
+
}
|
|
3319
|
+
let result = finalize(grouped);
|
|
3320
|
+
for (let [usageDate, breakdowns] of result)
|
|
3321
|
+
for (let breakdown of breakdowns) {
|
|
3322
|
+
let key = `${usageDate}|${breakdown.provider}|${breakdown.model}|${breakdown.project}`;
|
|
3323
|
+
breakdown.sessionCount = sessionSets.get(key)?.size ?? 0;
|
|
3324
|
+
}
|
|
3325
|
+
return result;
|
|
3326
|
+
}
|
|
3327
|
+
function parseNativeCache(value) {
|
|
3328
|
+
if (!isRecord2(value) || value.schemaVersion !== 1 || value.source !== "trae-cn-local-rpc") return [];
|
|
3329
|
+
let sessionId = stringValue2(value.sessionId), project = stringValue2(value.project) || "unknown";
|
|
3330
|
+
if (!sessionId || !Array.isArray(value.events)) return [];
|
|
3331
|
+
let events = [];
|
|
3332
|
+
for (let raw of value.events) {
|
|
3333
|
+
if (!isRecord2(raw)) continue;
|
|
3334
|
+
let messageId = stringValue2(raw.messageId), timestamp = parseTs(raw.timestamp);
|
|
3335
|
+
if (!messageId || !timestamp) continue;
|
|
3336
|
+
let model = normalizeTraeModel(stringValue2(raw.model)), tokens = {
|
|
3337
|
+
input: tokenValue(raw.inputTokens),
|
|
3338
|
+
cached: tokenValue(raw.cachedInputTokens),
|
|
3339
|
+
cacheWrite: tokenValue(raw.cacheWriteTokens),
|
|
3340
|
+
output: tokenValue(raw.outputTokens),
|
|
3341
|
+
reasoning: tokenValue(raw.reasoningOutputTokens)
|
|
3342
|
+
};
|
|
3343
|
+
tokenTotal2(tokens) !== 0 && events.push({
|
|
3344
|
+
dedupKey: `trae-cn:${messageId}`,
|
|
3345
|
+
sessionId,
|
|
3346
|
+
timestamp,
|
|
3347
|
+
provider: inferProviderFromModel(model, "trae"),
|
|
3348
|
+
model,
|
|
3349
|
+
project,
|
|
3350
|
+
...tokens
|
|
3351
|
+
});
|
|
3352
|
+
}
|
|
3353
|
+
return events;
|
|
3354
|
+
}
|
|
3355
|
+
function parseTokscaleCache(value) {
|
|
3356
|
+
if (!Array.isArray(value)) return [];
|
|
3357
|
+
let events = [];
|
|
3358
|
+
for (let raw of value) {
|
|
3359
|
+
if (!isRecord2(raw)) continue;
|
|
3360
|
+
let session = raw, sessionId = stringValue2(session.session_id), timestamp = parseTs(session.usage_time);
|
|
3361
|
+
if (!sessionId || !timestamp || !session.usage_time || session.usage_time <= 0) continue;
|
|
3362
|
+
let rawModel = stringValue2(session.model_name), mode = stringValue2(session.mode), model = rawModel ? normalizeTraeModel(rawModel) : mode ? `trae-${mode.toLowerCase()}` : "trae-unknown", extra = session.extra_info ?? {}, tokens = {
|
|
3363
|
+
input: tokenValue(extra.input_token),
|
|
3364
|
+
cached: tokenValue(extra.cache_read_token),
|
|
3365
|
+
cacheWrite: tokenValue(extra.cache_write_token),
|
|
3366
|
+
output: tokenValue(extra.output_token),
|
|
3367
|
+
reasoning: 0
|
|
3368
|
+
};
|
|
3369
|
+
tokenTotal2(tokens) !== 0 && events.push({
|
|
3370
|
+
dedupKey: `trae-intl:${sessionId}:${session.usage_time}`,
|
|
3371
|
+
sessionId,
|
|
3372
|
+
timestamp,
|
|
3373
|
+
provider: inferProviderFromModel(model, "trae"),
|
|
3374
|
+
model,
|
|
3375
|
+
project: "unknown",
|
|
3376
|
+
...tokens,
|
|
3377
|
+
costUSD: positiveNumber(session.dollar_float)
|
|
3378
|
+
});
|
|
3379
|
+
}
|
|
3380
|
+
return events;
|
|
2636
3381
|
}
|
|
2637
|
-
function
|
|
2638
|
-
let
|
|
2639
|
-
return
|
|
3382
|
+
function normalizeTraeModel(name) {
|
|
3383
|
+
let value = name?.trim() ?? "";
|
|
3384
|
+
return {
|
|
3385
|
+
"GPT-5.4": "gpt-5.4",
|
|
3386
|
+
"GPT-5.3-Codex": "gpt-5.3-codex",
|
|
3387
|
+
"GPT-5.3 Codex": "gpt-5.3-codex",
|
|
3388
|
+
"GPT-5.3": "gpt-5.3",
|
|
3389
|
+
"GPT-5.2-Codex": "gpt-5.2-codex",
|
|
3390
|
+
"GPT-5.2 Codex": "gpt-5.2-codex",
|
|
3391
|
+
"GPT-5.2": "gpt-5.2",
|
|
3392
|
+
"GPT-5.1-Codex": "gpt-5.1-codex",
|
|
3393
|
+
"GPT-5.1 Codex": "gpt-5.1-codex",
|
|
3394
|
+
"GPT-5.1": "gpt-5.1",
|
|
3395
|
+
"Gemini 3.1 Pro": "gemini-3.1-pro",
|
|
3396
|
+
"Gemini 3.1": "gemini-3.1",
|
|
3397
|
+
"GLM 5.1": "glm-5.1",
|
|
3398
|
+
"GLM-5.1": "glm-5.1",
|
|
3399
|
+
"Claude Sonnet 4.6": "claude-sonnet-4.6",
|
|
3400
|
+
"Claude-Sonnet-4.6": "claude-sonnet-4.6",
|
|
3401
|
+
"Claude Sonnet 4.5": "claude-sonnet-4.5",
|
|
3402
|
+
"Claude-Sonnet-4.5": "claude-sonnet-4.5"
|
|
3403
|
+
}[value] ?? (value || "trae-unknown");
|
|
3404
|
+
}
|
|
3405
|
+
async function readJson2(filePath) {
|
|
3406
|
+
try {
|
|
3407
|
+
return JSON.parse(await readFile12(filePath, "utf8"));
|
|
3408
|
+
} catch {
|
|
3409
|
+
return null;
|
|
3410
|
+
}
|
|
2640
3411
|
}
|
|
2641
|
-
function
|
|
2642
|
-
let
|
|
2643
|
-
return
|
|
3412
|
+
function tokenValue(value) {
|
|
3413
|
+
let number = typeof value == "number" ? value : Number(value);
|
|
3414
|
+
return Number.isFinite(number) && number > 0 ? Math.floor(number) : 0;
|
|
3415
|
+
}
|
|
3416
|
+
function positiveNumber(value) {
|
|
3417
|
+
let number = typeof value == "number" ? value : Number(value);
|
|
3418
|
+
return Number.isFinite(number) && number > 0 ? number : void 0;
|
|
3419
|
+
}
|
|
3420
|
+
function tokenTotal2(tokens) {
|
|
3421
|
+
return tokens.input + tokens.cached + tokens.cacheWrite + tokens.output + tokens.reasoning;
|
|
3422
|
+
}
|
|
3423
|
+
function stringValue2(value) {
|
|
3424
|
+
return typeof value == "string" ? value.trim() : "";
|
|
3425
|
+
}
|
|
3426
|
+
function isRecord2(value) {
|
|
3427
|
+
return value != null && typeof value == "object" && !Array.isArray(value);
|
|
2644
3428
|
}
|
|
2645
3429
|
|
|
2646
3430
|
// src/scan.ts
|
|
@@ -2668,7 +3452,8 @@ async function scanDates(targetDates, options = {}) {
|
|
|
2668
3452
|
scanAmpDates(uniqueDates, void 0, options.projectAliases),
|
|
2669
3453
|
scanDroidDates(uniqueDates, void 0, options.projectAliases),
|
|
2670
3454
|
scanOpencodeDates(uniqueDates, void 0, options.projectAliases),
|
|
2671
|
-
scanPiDates(uniqueDates, void 0, options.projectAliases)
|
|
3455
|
+
scanPiDates(uniqueDates, void 0, options.projectAliases),
|
|
3456
|
+
scanTraeDates(uniqueDates, { projectAliases: options.projectAliases })
|
|
2672
3457
|
], results = await Promise.all(scanners);
|
|
2673
3458
|
return uniqueDates.map((usageDate) => {
|
|
2674
3459
|
let breakdowns = results.flatMap((m) => m.get(usageDate) ?? []), totals = breakdowns.reduce(
|
|
@@ -2844,9 +3629,9 @@ function parseCsv(content) {
|
|
|
2844
3629
|
}
|
|
2845
3630
|
|
|
2846
3631
|
// src/report.ts
|
|
2847
|
-
import { readdir as
|
|
2848
|
-
import { homedir as
|
|
2849
|
-
import { basename as
|
|
3632
|
+
import { readdir as readdir5, readFile as readFile14 } from "node:fs/promises";
|
|
3633
|
+
import { homedir as homedir15 } from "node:os";
|
|
3634
|
+
import { basename as basename11, dirname as dirname6, join as join16 } from "node:path";
|
|
2850
3635
|
async function buildLocalReport(range, options = {}) {
|
|
2851
3636
|
let requestedDates = options.dates ? options.dates : range === "all" ? await discoverAllDates() : range === "today" ? [dateKey(getTodayLocalDate())] : buildPresetDates(range), daily = [], totals = createEmptyTotals2(), bySource = /* @__PURE__ */ new Map(), byModel = /* @__PURE__ */ new Map(), pricingWarnings = /* @__PURE__ */ new Set(), daysWithData = 0, results = await scanDates(requestedDates, { projectAliases: options.projectAliases });
|
|
2852
3637
|
for (let result of results) {
|
|
@@ -2914,43 +3699,62 @@ function buildPresetDates(range) {
|
|
|
2914
3699
|
return result;
|
|
2915
3700
|
}
|
|
2916
3701
|
async function discoverAllDates() {
|
|
2917
|
-
let dates = /* @__PURE__ */ new Set(), home =
|
|
2918
|
-
|
|
3702
|
+
let dates = /* @__PURE__ */ new Set(), home = homedir15();
|
|
3703
|
+
await Promise.all([
|
|
2919
3704
|
discoverClaudeDates(dates),
|
|
2920
3705
|
discoverCodexDates(dates),
|
|
2921
3706
|
discoverGeminiDates(dates),
|
|
2922
3707
|
discoverCopilotVscodeDates(dates),
|
|
2923
3708
|
discoverAntigravityDates(dates),
|
|
2924
|
-
discoverGenericJsonlDates(
|
|
2925
|
-
discoverGenericJsonlDates(
|
|
2926
|
-
discoverGenericJsonlDates(
|
|
2927
|
-
discoverGenericJsonlDates(
|
|
2928
|
-
|
|
2929
|
-
discoverGenericJsonlDates(
|
|
2930
|
-
discoverGenericJsonDates(
|
|
2931
|
-
|
|
2932
|
-
|
|
3709
|
+
discoverGenericJsonlDates(join16(home, ".copilot", "session-state"), dates),
|
|
3710
|
+
discoverGenericJsonlDates(join16(home, ".copilot", "otel"), dates),
|
|
3711
|
+
discoverGenericJsonlDates(join16(home, ".qwen", "tmp"), dates),
|
|
3712
|
+
discoverGenericJsonlDates(join16(home, ".qwen", "projects"), dates),
|
|
3713
|
+
discoverGenericJsonlDates(join16(home, ".kimi", "sessions"), dates),
|
|
3714
|
+
discoverGenericJsonlDates(join16(resolveKimiCodeHome(home), "sessions"), dates),
|
|
3715
|
+
discoverGenericJsonDates(join16(home, ".local", "share", "amp", "threads"), dates),
|
|
3716
|
+
discoverGenericJsonDates(join16(home, ".factory", "sessions"), dates),
|
|
3717
|
+
discoverOpenCodeUsageDates().then((found) => found.forEach((date) => dates.add(date))),
|
|
3718
|
+
discoverGenericJsonlDates(join16(home, ".pi", "agent", "sessions"), dates),
|
|
3719
|
+
discoverGenericJsonlDates(join16(home, ".omp", "agent", "sessions"), dates)
|
|
3720
|
+
]);
|
|
3721
|
+
let explicitCopilotOtel = process.env.COPILOT_OTEL_FILE_EXPORTER_PATH?.trim();
|
|
3722
|
+
return explicitCopilotOtel && await discoverJsonlFileDates(explicitCopilotOtel, dates), [...dates].sort();
|
|
2933
3723
|
}
|
|
2934
3724
|
async function discoverGenericJsonlDates(baseDir, dates) {
|
|
2935
3725
|
let files = [];
|
|
2936
3726
|
await walkForFiles(baseDir, ".jsonl", files);
|
|
2937
3727
|
for (let filePath of files) {
|
|
2938
3728
|
let content = await safeReadUtf8(filePath);
|
|
2939
|
-
if (content)
|
|
2940
|
-
|
|
3729
|
+
if (!content) continue;
|
|
3730
|
+
let foundDate = !1;
|
|
3731
|
+
for (let line of content.split(`
|
|
2941
3732
|
`)) {
|
|
2942
|
-
|
|
2943
|
-
|
|
2944
|
-
|
|
2945
|
-
|
|
2946
|
-
|
|
2947
|
-
|
|
2948
|
-
}
|
|
2949
|
-
let ts = parseTs(record.timestamp ?? record.time ?? record.created_at);
|
|
2950
|
-
ts && dates.add(dateKey(ts));
|
|
3733
|
+
if (!line.trim()) continue;
|
|
3734
|
+
let record;
|
|
3735
|
+
try {
|
|
3736
|
+
record = JSON.parse(line);
|
|
3737
|
+
} catch {
|
|
3738
|
+
continue;
|
|
2951
3739
|
}
|
|
3740
|
+
foundDate = collectRecordDates(record, dates) || foundDate;
|
|
3741
|
+
}
|
|
3742
|
+
foundDate || await addFileModifiedDate(filePath, dates);
|
|
2952
3743
|
}
|
|
2953
3744
|
}
|
|
3745
|
+
async function discoverJsonlFileDates(filePath, dates) {
|
|
3746
|
+
let content = await safeReadUtf8(filePath);
|
|
3747
|
+
if (!content) return;
|
|
3748
|
+
let foundDate = !1;
|
|
3749
|
+
for (let line of content.split(`
|
|
3750
|
+
`))
|
|
3751
|
+
if (line.trim())
|
|
3752
|
+
try {
|
|
3753
|
+
foundDate = collectRecordDates(JSON.parse(line), dates) || foundDate;
|
|
3754
|
+
} catch {
|
|
3755
|
+
}
|
|
3756
|
+
foundDate || await addFileModifiedDate(filePath, dates);
|
|
3757
|
+
}
|
|
2954
3758
|
async function discoverGenericJsonDates(baseDir, dates) {
|
|
2955
3759
|
let files = [];
|
|
2956
3760
|
await walkForFiles(baseDir, ".json", files);
|
|
@@ -2963,78 +3767,84 @@ async function discoverGenericJsonDates(baseDir, dates) {
|
|
|
2963
3767
|
} catch {
|
|
2964
3768
|
continue;
|
|
2965
3769
|
}
|
|
2966
|
-
|
|
2967
|
-
|
|
2968
|
-
|
|
2969
|
-
|
|
2970
|
-
|
|
2971
|
-
|
|
2972
|
-
|
|
2973
|
-
|
|
3770
|
+
(Array.isArray(data) ? data.reduce((found, row) => collectRecordDates(row, dates) || found, !1) : collectRecordDates(data, dates)) || await addFileModifiedDate(filePath, dates);
|
|
3771
|
+
}
|
|
3772
|
+
}
|
|
3773
|
+
function collectRecordDates(record, dates) {
|
|
3774
|
+
if (!record || typeof record != "object") return !1;
|
|
3775
|
+
let found = !1, candidates = [
|
|
3776
|
+
record.timestamp,
|
|
3777
|
+
record.time,
|
|
3778
|
+
record.created_at,
|
|
3779
|
+
record.createTime,
|
|
3780
|
+
record.startTime,
|
|
3781
|
+
record.lastUpdated,
|
|
3782
|
+
record.created,
|
|
3783
|
+
record.providerLockTimestamp,
|
|
3784
|
+
record.endTime,
|
|
3785
|
+
record.hrTime,
|
|
3786
|
+
record._hrTime,
|
|
3787
|
+
record.observedTimestamp,
|
|
3788
|
+
record.timeUnixNano,
|
|
3789
|
+
record.time?.created
|
|
3790
|
+
];
|
|
3791
|
+
for (let value of candidates) {
|
|
3792
|
+
let ts = parseStructuredTs(value);
|
|
3793
|
+
ts && (dates.add(dateKey(ts)), found = !0);
|
|
3794
|
+
}
|
|
3795
|
+
let nestedRows = [
|
|
3796
|
+
...Array.isArray(record.messages) ? record.messages : [],
|
|
3797
|
+
...Array.isArray(record.history) ? record.history : [],
|
|
3798
|
+
...Array.isArray(record.data?.messages) ? record.data.messages : [],
|
|
3799
|
+
...Array.isArray(record.data?.history) ? record.data.history : [],
|
|
3800
|
+
...Array.isArray(record.$set?.messages) ? record.$set.messages : [],
|
|
3801
|
+
...Array.isArray(record.usageLedger?.events) ? record.usageLedger.events : []
|
|
3802
|
+
];
|
|
3803
|
+
for (let row of nestedRows) found = collectRecordDates(row, dates) || found;
|
|
3804
|
+
return found;
|
|
3805
|
+
}
|
|
3806
|
+
function parseStructuredTs(value) {
|
|
3807
|
+
if (Array.isArray(value) && value.length > 0) {
|
|
3808
|
+
let seconds = Number(value[0]), nanos = Number(value[1] ?? 0);
|
|
3809
|
+
if (Number.isFinite(seconds) && Number.isFinite(nanos))
|
|
3810
|
+
return parseTs(seconds * 1e3 + nanos / 1e6);
|
|
2974
3811
|
}
|
|
3812
|
+
if (typeof value == "number" || typeof value == "string" && /^\d+(?:\.\d+)?$/.test(value)) {
|
|
3813
|
+
let raw = Number(value);
|
|
3814
|
+
if (!Number.isFinite(raw) || raw <= 0) return null;
|
|
3815
|
+
let abs = Math.abs(raw), millis = abs >= 1e17 ? raw / 1e6 : abs >= 1e14 ? raw / 1e3 : raw;
|
|
3816
|
+
return parseTs(millis);
|
|
3817
|
+
}
|
|
3818
|
+
return parseTs(value);
|
|
3819
|
+
}
|
|
3820
|
+
async function addFileModifiedDate(filePath, dates) {
|
|
3821
|
+
let timestamp = await fileModifiedTs(filePath);
|
|
3822
|
+
timestamp && dates.add(dateKey(timestamp));
|
|
2975
3823
|
}
|
|
2976
3824
|
async function walkForFiles(dir, ext, result) {
|
|
2977
3825
|
let entries;
|
|
2978
3826
|
try {
|
|
2979
|
-
entries = await
|
|
3827
|
+
entries = await readdir5(dir, { withFileTypes: !0 });
|
|
2980
3828
|
} catch {
|
|
2981
3829
|
return;
|
|
2982
3830
|
}
|
|
2983
3831
|
for (let entry of entries) {
|
|
2984
|
-
let fullPath =
|
|
3832
|
+
let fullPath = join16(dir, entry.name);
|
|
2985
3833
|
entry.isDirectory() ? await walkForFiles(fullPath, ext, result) : entry.name.endsWith(ext) && result.push(fullPath);
|
|
2986
3834
|
}
|
|
2987
3835
|
}
|
|
2988
3836
|
async function discoverGeminiDates(dates) {
|
|
2989
|
-
let baseDir =
|
|
2990
|
-
await
|
|
2991
|
-
|
|
2992
|
-
|
|
2993
|
-
|
|
2994
|
-
let session;
|
|
2995
|
-
try {
|
|
2996
|
-
session = JSON.parse(content);
|
|
2997
|
-
} catch {
|
|
2998
|
-
continue;
|
|
2999
|
-
}
|
|
3000
|
-
if (Array.isArray(session)) {
|
|
3001
|
-
for (let row of session) {
|
|
3002
|
-
let ts = parseTs(row.timestamp);
|
|
3003
|
-
ts && dates.add(dateKey(ts));
|
|
3004
|
-
}
|
|
3005
|
-
continue;
|
|
3006
|
-
}
|
|
3007
|
-
let topLevelTs = parseTs(session.timestamp ?? session.createTime ?? session.startTime ?? session.data?.createTime);
|
|
3008
|
-
topLevelTs && dates.add(dateKey(topLevelTs));
|
|
3009
|
-
let messages = [
|
|
3010
|
-
...session.messages ?? [],
|
|
3011
|
-
...session.history ?? [],
|
|
3012
|
-
...session.data?.messages ?? [],
|
|
3013
|
-
...session.data?.history ?? []
|
|
3014
|
-
];
|
|
3015
|
-
for (let msg of messages) {
|
|
3016
|
-
let ts = parseTs(msg.timestamp ?? msg.createTime);
|
|
3017
|
-
ts && dates.add(dateKey(ts));
|
|
3018
|
-
}
|
|
3019
|
-
}
|
|
3020
|
-
}
|
|
3021
|
-
async function walkForGeminiJsonl(dir, result) {
|
|
3022
|
-
let entries;
|
|
3023
|
-
try {
|
|
3024
|
-
entries = await readdir6(dir, { withFileTypes: !0 });
|
|
3025
|
-
} catch {
|
|
3026
|
-
return;
|
|
3027
|
-
}
|
|
3028
|
-
for (let entry of entries) {
|
|
3029
|
-
let fullPath = join14(dir, entry.name);
|
|
3030
|
-
entry.isDirectory() ? await walkForGeminiJsonl(fullPath, result) : entry.name.endsWith(".json") && result.push(fullPath);
|
|
3031
|
-
}
|
|
3837
|
+
let baseDir = join16(homedir15(), ".gemini", "tmp");
|
|
3838
|
+
await Promise.all([
|
|
3839
|
+
discoverGenericJsonDates(baseDir, dates),
|
|
3840
|
+
discoverGenericJsonlDates(baseDir, dates)
|
|
3841
|
+
]);
|
|
3032
3842
|
}
|
|
3033
3843
|
async function discoverCopilotVscodeDates(dates) {
|
|
3034
|
-
let home =
|
|
3035
|
-
await walkForFiles(
|
|
3844
|
+
let home = homedir15(), logFiles = [];
|
|
3845
|
+
await walkForFiles(join16(home, "Library", "Application Support", "Code", "logs"), ".log", logFiles);
|
|
3036
3846
|
for (let filePath of logFiles) {
|
|
3037
|
-
if (
|
|
3847
|
+
if (basename11(filePath) !== "GitHub Copilot Chat.log") continue;
|
|
3038
3848
|
let content = await safeReadUtf8(filePath);
|
|
3039
3849
|
if (content)
|
|
3040
3850
|
for (let line of content.split(`
|
|
@@ -3045,9 +3855,9 @@ async function discoverCopilotVscodeDates(dates) {
|
|
|
3045
3855
|
}
|
|
3046
3856
|
}
|
|
3047
3857
|
let sessionFiles = [];
|
|
3048
|
-
await walkForFiles(
|
|
3858
|
+
await walkForFiles(join16(home, "Library", "Application Support", "Code", "User", "workspaceStorage"), ".json", sessionFiles);
|
|
3049
3859
|
for (let filePath of sessionFiles) {
|
|
3050
|
-
if (!filePath
|
|
3860
|
+
if (!isChatSessionFile2(filePath)) continue;
|
|
3051
3861
|
let content = await safeReadUtf8(filePath);
|
|
3052
3862
|
if (!content) continue;
|
|
3053
3863
|
let session;
|
|
@@ -3062,12 +3872,44 @@ async function discoverCopilotVscodeDates(dates) {
|
|
|
3062
3872
|
ts && dates.add(dateKey(ts));
|
|
3063
3873
|
}
|
|
3064
3874
|
}
|
|
3875
|
+
let crdtFiles = [];
|
|
3876
|
+
await walkForFiles(
|
|
3877
|
+
join16(home, "Library", "Application Support", "Code", "User", "workspaceStorage"),
|
|
3878
|
+
".jsonl",
|
|
3879
|
+
crdtFiles
|
|
3880
|
+
);
|
|
3881
|
+
for (let filePath of crdtFiles) {
|
|
3882
|
+
if (!isChatSessionFile2(filePath)) continue;
|
|
3883
|
+
let content = await safeReadUtf8(filePath);
|
|
3884
|
+
if (content)
|
|
3885
|
+
for (let line of content.split(`
|
|
3886
|
+
`)) {
|
|
3887
|
+
if (!line.trim()) continue;
|
|
3888
|
+
let record;
|
|
3889
|
+
try {
|
|
3890
|
+
record = JSON.parse(line);
|
|
3891
|
+
} catch {
|
|
3892
|
+
continue;
|
|
3893
|
+
}
|
|
3894
|
+
let root = record.v && typeof record.v == "object" && !Array.isArray(record.v) ? record.v : void 0, requests = record.kind === 0 && Array.isArray(root?.requests) ? root.requests : record.kind === 2 && record.k?.[0] === "requests" && Array.isArray(record.v) ? record.v : [];
|
|
3895
|
+
for (let value of requests) {
|
|
3896
|
+
if (!value || typeof value != "object" || Array.isArray(value)) continue;
|
|
3897
|
+
let request = value, metadata = request.result?.metadata, isCopilot = !!metadata?.resolvedModel || request.modelId?.startsWith("copilot/"), hasTokens = (request.promptTokens ?? metadata?.promptTokens ?? 0) > 0 || (request.completionTokens ?? metadata?.outputTokens ?? 0) > 0;
|
|
3898
|
+
if (!isCopilot || !hasTokens) continue;
|
|
3899
|
+
let ts = parseTs(request.timestamp);
|
|
3900
|
+
ts && dates.add(dateKey(ts));
|
|
3901
|
+
}
|
|
3902
|
+
}
|
|
3903
|
+
}
|
|
3904
|
+
}
|
|
3905
|
+
function isChatSessionFile2(filePath) {
|
|
3906
|
+
return basename11(dirname6(filePath)) === "chatSessions";
|
|
3065
3907
|
}
|
|
3066
3908
|
async function discoverAntigravityDates(dates) {
|
|
3067
|
-
let home =
|
|
3068
|
-
await walkForFiles(
|
|
3909
|
+
let home = homedir15(), brainFiles = [], browserFiles = [];
|
|
3910
|
+
await walkForFiles(join16(home, ".gemini", "antigravity", "brain"), ".json", brainFiles), await walkForFiles(join16(home, ".gemini", "antigravity", "browser_recordings"), ".json", browserFiles);
|
|
3069
3911
|
for (let filePath of brainFiles) {
|
|
3070
|
-
if (
|
|
3912
|
+
if (basename11(filePath) !== "task.md.metadata.json") continue;
|
|
3071
3913
|
let content = await safeReadUtf8(filePath);
|
|
3072
3914
|
if (!content) continue;
|
|
3073
3915
|
let data;
|
|
@@ -3080,7 +3922,7 @@ async function discoverAntigravityDates(dates) {
|
|
|
3080
3922
|
ts && dates.add(dateKey(ts));
|
|
3081
3923
|
}
|
|
3082
3924
|
for (let filePath of browserFiles) {
|
|
3083
|
-
if (
|
|
3925
|
+
if (basename11(filePath) !== "metadata.json") continue;
|
|
3084
3926
|
let content = await safeReadUtf8(filePath);
|
|
3085
3927
|
if (!content) continue;
|
|
3086
3928
|
let data;
|
|
@@ -3094,21 +3936,21 @@ async function discoverAntigravityDates(dates) {
|
|
|
3094
3936
|
}
|
|
3095
3937
|
}
|
|
3096
3938
|
async function discoverClaudeDates(dates) {
|
|
3097
|
-
let home =
|
|
3098
|
-
|
|
3099
|
-
|
|
3939
|
+
let home = homedir15(), baseDirs = [
|
|
3940
|
+
join16(home, ".config", "claude", "projects"),
|
|
3941
|
+
join16(home, ".claude", "projects")
|
|
3100
3942
|
];
|
|
3101
3943
|
for (let baseDir of baseDirs) {
|
|
3102
3944
|
let projectDirs;
|
|
3103
3945
|
try {
|
|
3104
|
-
projectDirs = await
|
|
3946
|
+
projectDirs = await readdir5(baseDir);
|
|
3105
3947
|
} catch {
|
|
3106
3948
|
continue;
|
|
3107
3949
|
}
|
|
3108
3950
|
for (let projectDir of projectDirs) {
|
|
3109
3951
|
let jsonlFiles = [];
|
|
3110
3952
|
try {
|
|
3111
|
-
await walkForClaudeJsonl(
|
|
3953
|
+
await walkForClaudeJsonl(join16(baseDir, projectDir), jsonlFiles);
|
|
3112
3954
|
} catch {
|
|
3113
3955
|
continue;
|
|
3114
3956
|
}
|
|
@@ -3132,7 +3974,7 @@ async function discoverClaudeDates(dates) {
|
|
|
3132
3974
|
}
|
|
3133
3975
|
}
|
|
3134
3976
|
async function discoverCodexDates(dates) {
|
|
3135
|
-
let baseDir =
|
|
3977
|
+
let baseDir = join16(homedir15(), ".codex"), files = await collectCodexSessionFiles(baseDir);
|
|
3136
3978
|
for (let filePath of files) {
|
|
3137
3979
|
let content = await safeReadUtf8(filePath);
|
|
3138
3980
|
if (content)
|
|
@@ -3154,29 +3996,29 @@ async function discoverCodexDates(dates) {
|
|
|
3154
3996
|
async function collectCodexSessionFiles(baseDir) {
|
|
3155
3997
|
let paths = [];
|
|
3156
3998
|
try {
|
|
3157
|
-
let archivedFiles = await
|
|
3999
|
+
let archivedFiles = await readdir5(join16(baseDir, "archived_sessions"));
|
|
3158
4000
|
for (let file of archivedFiles)
|
|
3159
|
-
file.endsWith(".jsonl") && paths.push(
|
|
4001
|
+
file.endsWith(".jsonl") && paths.push(join16(baseDir, "archived_sessions", file));
|
|
3160
4002
|
} catch {
|
|
3161
4003
|
}
|
|
3162
|
-
return await walkForCodexJsonl(
|
|
4004
|
+
return await walkForCodexJsonl(join16(baseDir, "sessions"), paths), paths;
|
|
3163
4005
|
}
|
|
3164
4006
|
async function walkForClaudeJsonl(dir, result) {
|
|
3165
|
-
let entries = await
|
|
4007
|
+
let entries = await readdir5(dir, { withFileTypes: !0 });
|
|
3166
4008
|
for (let entry of entries) {
|
|
3167
|
-
let fullPath =
|
|
4009
|
+
let fullPath = join16(dir, entry.name);
|
|
3168
4010
|
entry.isDirectory() ? await walkForClaudeJsonl(fullPath, result) : entry.name.endsWith(".jsonl") && result.push(fullPath);
|
|
3169
4011
|
}
|
|
3170
4012
|
}
|
|
3171
4013
|
async function walkForCodexJsonl(dir, result) {
|
|
3172
4014
|
let entries;
|
|
3173
4015
|
try {
|
|
3174
|
-
entries = await
|
|
4016
|
+
entries = await readdir5(dir, { withFileTypes: !0 });
|
|
3175
4017
|
} catch {
|
|
3176
4018
|
return;
|
|
3177
4019
|
}
|
|
3178
4020
|
for (let entry of entries) {
|
|
3179
|
-
let fullPath =
|
|
4021
|
+
let fullPath = join16(dir, entry.name);
|
|
3180
4022
|
entry.isDirectory() ? await walkForCodexJsonl(fullPath, result) : entry.name.startsWith("rollout-") && entry.name.endsWith(".jsonl") && result.push(fullPath);
|
|
3181
4023
|
}
|
|
3182
4024
|
}
|
|
@@ -3466,10 +4308,10 @@ function fmtDateShort(dateStr) {
|
|
|
3466
4308
|
}
|
|
3467
4309
|
|
|
3468
4310
|
// src/activity.ts
|
|
3469
|
-
import { open
|
|
4311
|
+
import { open, readdir as readdir6 } from "node:fs/promises";
|
|
3470
4312
|
import { createInterface as createInterface3 } from "node:readline";
|
|
3471
|
-
import { homedir as
|
|
3472
|
-
import { basename as
|
|
4313
|
+
import { homedir as homedir16 } from "node:os";
|
|
4314
|
+
import { basename as basename12, join as join17 } from "node:path";
|
|
3473
4315
|
var FILE_CONCURRENCY3 = 16, MAX_LINE_BYTES3 = 64 * 1024 * 1024;
|
|
3474
4316
|
async function buildActivityReport(range, options = {}) {
|
|
3475
4317
|
let targetDates = options.dates ? new Set(options.dates) : void 0, [codex, claude] = await Promise.all([
|
|
@@ -3566,7 +4408,7 @@ function renderActivityReport(report, opts) {
|
|
|
3566
4408
|
`);
|
|
3567
4409
|
}
|
|
3568
4410
|
async function scanCodexActivity(targetDates, options) {
|
|
3569
|
-
let baseDir = options.codexDir ??
|
|
4411
|
+
let baseDir = options.codexDir ?? join17(homedir16(), ".codex"), acc = createAccumulator(targetDates, options.projectAliases), files = await collectCodexSessionFiles2(baseDir);
|
|
3570
4412
|
return acc.stats.filesScanned = files.length, await runWithConcurrency(files, FILE_CONCURRENCY3, async (filePath) => {
|
|
3571
4413
|
await processCodexFile2(filePath, acc);
|
|
3572
4414
|
}), finalizeActivity(acc);
|
|
@@ -3574,11 +4416,11 @@ async function scanCodexActivity(targetDates, options) {
|
|
|
3574
4416
|
async function processCodexFile2(filePath, acc) {
|
|
3575
4417
|
let fh;
|
|
3576
4418
|
try {
|
|
3577
|
-
fh = await
|
|
4419
|
+
fh = await open(filePath, "r");
|
|
3578
4420
|
} catch {
|
|
3579
4421
|
return;
|
|
3580
4422
|
}
|
|
3581
|
-
let sessionId =
|
|
4423
|
+
let sessionId = basename12(filePath).replace(/\.jsonl$/, ""), projectFields = { project: "unknown", projectDisplay: "unknown" };
|
|
3582
4424
|
try {
|
|
3583
4425
|
let rl = createInterface3({
|
|
3584
4426
|
input: fh.createReadStream({ encoding: "utf-8" }),
|
|
@@ -3593,12 +4435,12 @@ async function processCodexFile2(filePath, acc) {
|
|
|
3593
4435
|
continue;
|
|
3594
4436
|
}
|
|
3595
4437
|
if (record.type === "session_meta") {
|
|
3596
|
-
let id =
|
|
4438
|
+
let id = stringValue3(record.payload?.id);
|
|
3597
4439
|
id && (sessionId = id), acc.stats.sessions.add(`codex:${sessionId}`);
|
|
3598
4440
|
continue;
|
|
3599
4441
|
}
|
|
3600
4442
|
if (record.type === "turn_context") {
|
|
3601
|
-
let cwd =
|
|
4443
|
+
let cwd = stringValue3(record.payload?.cwd);
|
|
3602
4444
|
cwd && (projectFields = resolveProjectFields(cwd, acc.projectAliases));
|
|
3603
4445
|
continue;
|
|
3604
4446
|
}
|
|
@@ -3642,7 +4484,7 @@ function handleCodexResponseItem(item, usageDate, projectFields, sessionId, file
|
|
|
3642
4484
|
projectFields,
|
|
3643
4485
|
sessionId,
|
|
3644
4486
|
kind,
|
|
3645
|
-
name: kind === "agent_call" ?
|
|
4487
|
+
name: kind === "agent_call" ? stringValue3(args.agent_type) ?? name : name,
|
|
3646
4488
|
confidence: "exact",
|
|
3647
4489
|
dedupeKey: baseKey
|
|
3648
4490
|
});
|
|
@@ -3696,14 +4538,14 @@ function handleCodexEvent(record, usageDate, projectFields, sessionId, filePath,
|
|
|
3696
4538
|
projectFields,
|
|
3697
4539
|
sessionId,
|
|
3698
4540
|
timestamp: record.timestamp ?? "",
|
|
3699
|
-
content:
|
|
4541
|
+
content: stringValue3(record.payload?.message),
|
|
3700
4542
|
fallbackKey: `${filePath}:${usageDate}:${sessionId}:event_user_message:${record.timestamp ?? ""}`
|
|
3701
4543
|
});
|
|
3702
4544
|
return;
|
|
3703
4545
|
}
|
|
3704
4546
|
let kind = payloadType === "task_started" || payloadType === "task_complete" ? "task" : payloadType === "context_compacted" ? "compaction" : payloadType === "thread_rolled_back" ? "rollback" : payloadType === "turn_aborted" ? "interruption" : payloadType === "mcp_tool_call_end" ? "mcp_tool_call" : void 0;
|
|
3705
4547
|
if (!kind) return;
|
|
3706
|
-
let callId =
|
|
4548
|
+
let callId = stringValue3(record.payload?.call_id);
|
|
3707
4549
|
addActivity(acc, {
|
|
3708
4550
|
usageDate,
|
|
3709
4551
|
provider: "openai",
|
|
@@ -3721,13 +4563,13 @@ async function scanClaudeActivity(targetDates, options) {
|
|
|
3721
4563
|
for (let baseDir of getClaudeProjectDirs2(options.claudeProjectsDirs)) {
|
|
3722
4564
|
let projectDirs;
|
|
3723
4565
|
try {
|
|
3724
|
-
projectDirs = await
|
|
4566
|
+
projectDirs = await readdir6(baseDir, { withFileTypes: !0 });
|
|
3725
4567
|
} catch {
|
|
3726
4568
|
continue;
|
|
3727
4569
|
}
|
|
3728
4570
|
for (let entry of projectDirs) {
|
|
3729
4571
|
if (!entry.isDirectory()) continue;
|
|
3730
|
-
let projectPath =
|
|
4572
|
+
let projectPath = join17(baseDir, entry.name), jsonlFiles = [];
|
|
3731
4573
|
await walkJsonl(projectPath, jsonlFiles);
|
|
3732
4574
|
let fields = resolveClaudeProject(projectPath, acc.projectAliases);
|
|
3733
4575
|
for (let filePath of jsonlFiles) fileJobs.push({ filePath, projectFields: fields });
|
|
@@ -3740,11 +4582,11 @@ async function scanClaudeActivity(targetDates, options) {
|
|
|
3740
4582
|
async function processClaudeFile(filePath, fallbackFields, acc) {
|
|
3741
4583
|
let fh;
|
|
3742
4584
|
try {
|
|
3743
|
-
fh = await
|
|
4585
|
+
fh = await open(filePath, "r");
|
|
3744
4586
|
} catch {
|
|
3745
4587
|
return;
|
|
3746
4588
|
}
|
|
3747
|
-
let fallbackSessionId =
|
|
4589
|
+
let fallbackSessionId = basename12(filePath).replace(/\.jsonl$/, "");
|
|
3748
4590
|
try {
|
|
3749
4591
|
let rl = createInterface3({
|
|
3750
4592
|
input: fh.createReadStream({ encoding: "utf-8" }),
|
|
@@ -3865,38 +4707,38 @@ function acceptsDate(acc, usageDate) {
|
|
|
3865
4707
|
async function collectCodexSessionFiles2(baseDir) {
|
|
3866
4708
|
let paths = [];
|
|
3867
4709
|
try {
|
|
3868
|
-
let files = await
|
|
4710
|
+
let files = await readdir6(join17(baseDir, "archived_sessions"));
|
|
3869
4711
|
for (let file of files)
|
|
3870
|
-
file.endsWith(".jsonl") && paths.push(
|
|
4712
|
+
file.endsWith(".jsonl") && paths.push(join17(baseDir, "archived_sessions", file));
|
|
3871
4713
|
} catch {
|
|
3872
4714
|
}
|
|
3873
|
-
return await walkJsonl(
|
|
4715
|
+
return await walkJsonl(join17(baseDir, "sessions"), paths), paths;
|
|
3874
4716
|
}
|
|
3875
4717
|
function getClaudeProjectDirs2(configured) {
|
|
3876
4718
|
if (configured?.length) return configured;
|
|
3877
4719
|
let envVar = process.env.CLAUDE_CONFIG_DIR?.trim();
|
|
3878
4720
|
if (envVar)
|
|
3879
|
-
return envVar.split(",").map((p) => p.trim()).filter(Boolean).map((p) =>
|
|
3880
|
-
let home =
|
|
4721
|
+
return envVar.split(",").map((p) => p.trim()).filter(Boolean).map((p) => join17(p, "projects"));
|
|
4722
|
+
let home = homedir16();
|
|
3881
4723
|
return [
|
|
3882
|
-
|
|
3883
|
-
|
|
4724
|
+
join17(home, ".config", "claude", "projects"),
|
|
4725
|
+
join17(home, ".claude", "projects")
|
|
3884
4726
|
];
|
|
3885
4727
|
}
|
|
3886
4728
|
async function walkJsonl(dir, result) {
|
|
3887
4729
|
let entries;
|
|
3888
4730
|
try {
|
|
3889
|
-
entries = await
|
|
4731
|
+
entries = await readdir6(dir, { withFileTypes: !0 });
|
|
3890
4732
|
} catch {
|
|
3891
4733
|
return;
|
|
3892
4734
|
}
|
|
3893
4735
|
for (let entry of entries) {
|
|
3894
|
-
let fullPath =
|
|
4736
|
+
let fullPath = join17(dir, entry.name);
|
|
3895
4737
|
entry.isDirectory() ? await walkJsonl(fullPath, result) : entry.name.endsWith(".jsonl") && result.push(fullPath);
|
|
3896
4738
|
}
|
|
3897
4739
|
}
|
|
3898
4740
|
function resolveClaudeProject(projectPath, aliases2) {
|
|
3899
|
-
let rawName =
|
|
4741
|
+
let rawName = basename12(projectPath), display = rawName.split("-").filter(Boolean).at(-1) || rawName || "unknown", alias = aliases2?.[projectPath] ?? aliases2?.[display];
|
|
3900
4742
|
return {
|
|
3901
4743
|
project: projectPath,
|
|
3902
4744
|
projectDisplay: display,
|
|
@@ -3907,22 +4749,22 @@ function classifyClaudeTool(name) {
|
|
|
3907
4749
|
return name === "Skill" ? "skill_call" : name === "Agent" ? "agent_call" : name === "WebSearch" || name === "WebFetch" ? "web_search" : name === "ToolSearch" ? "tool_search" : name === "TaskCreate" || name === "TaskUpdate" || name === "TaskList" || name === "TaskStop" ? "task" : "tool_call";
|
|
3908
4750
|
}
|
|
3909
4751
|
function getClaudeMetricName(toolName, input) {
|
|
3910
|
-
return toolName === "Skill" ?
|
|
4752
|
+
return toolName === "Skill" ? stringValue3(input?.skill) ?? "unknown" : toolName === "Agent" ? stringValue3(input?.description) ?? stringValue3(input?.subagent_type) ?? "unknown" : toolName;
|
|
3911
4753
|
}
|
|
3912
4754
|
function isClaudeUserMessage(record) {
|
|
3913
4755
|
if (record.type !== "user" || record.message?.role !== "user" || record.isMeta || record.toolUseResult || record.sourceToolAssistantUUID || record.sourceToolUseID) return !1;
|
|
3914
4756
|
let content = record.message.content;
|
|
3915
|
-
return typeof content == "string" ? content.trim().length > 0 : !Array.isArray(content) || content.length === 0 || content.some((block) => block?.type === "tool_result") ? !1 : content.some((block) => block?.type === "text" &&
|
|
4757
|
+
return typeof content == "string" ? content.trim().length > 0 : !Array.isArray(content) || content.length === 0 || content.some((block) => block?.type === "tool_result") ? !1 : content.some((block) => block?.type === "text" && stringValue3(block.text));
|
|
3916
4758
|
}
|
|
3917
4759
|
function hasCodexUserMessageContent(content) {
|
|
3918
4760
|
return typeof content == "string" ? content.trim().length > 0 : !Array.isArray(content) || content.length === 0 ? !1 : content.some((block) => block?.type === "input_text" || block?.type === "text");
|
|
3919
4761
|
}
|
|
3920
4762
|
function extractCodexMessageText(content) {
|
|
3921
|
-
return typeof content == "string" ? content : Array.isArray(content) && content.map((block) =>
|
|
4763
|
+
return typeof content == "string" ? content : Array.isArray(content) && content.map((block) => stringValue3(block.text)).filter(Boolean).join(`
|
|
3922
4764
|
`) || void 0;
|
|
3923
4765
|
}
|
|
3924
4766
|
function extractClaudeMessageText(content) {
|
|
3925
|
-
return typeof content == "string" ? content : Array.isArray(content) && content.filter((block) => block?.type === "text").map((block) =>
|
|
4767
|
+
return typeof content == "string" ? content : Array.isArray(content) && content.filter((block) => block?.type === "text").map((block) => stringValue3(block.text)).filter(Boolean).join(`
|
|
3926
4768
|
`) || void 0;
|
|
3927
4769
|
}
|
|
3928
4770
|
function normalizeMessageText(value) {
|
|
@@ -3930,7 +4772,7 @@ function normalizeMessageText(value) {
|
|
|
3930
4772
|
}
|
|
3931
4773
|
function extractSkillProxyNames(rawArguments) {
|
|
3932
4774
|
if (!rawArguments) return [];
|
|
3933
|
-
let args = parseJsonObject(rawArguments), command2 =
|
|
4775
|
+
let args = parseJsonObject(rawArguments), command2 = stringValue3(args.cmd) ?? stringValue3(args.command) ?? "";
|
|
3934
4776
|
if (!command2.includes("SKILL.md")) return [];
|
|
3935
4777
|
let names = /* @__PURE__ */ new Set();
|
|
3936
4778
|
for (let match of command2.matchAll(/([^\s'"]*SKILL\.md)/g))
|
|
@@ -3950,7 +4792,7 @@ function skillNameFromPath(rawPath) {
|
|
|
3950
4792
|
let parts = rawPath.replace(/^[`'"]+|[`'"]+$/g, "").split("/").filter(Boolean), idx = parts.lastIndexOf("SKILL.md"), name = idx > 0 ? parts[idx - 1] : void 0;
|
|
3951
4793
|
return !name || name === "$d" || name === "s#" ? "unknown-skill" : name;
|
|
3952
4794
|
}
|
|
3953
|
-
function
|
|
4795
|
+
function stringValue3(value) {
|
|
3954
4796
|
return typeof value == "string" && value.length > 0 ? value : void 0;
|
|
3955
4797
|
}
|
|
3956
4798
|
function summarize(items, keyFn, labelFn, limit) {
|
|
@@ -4044,9 +4886,9 @@ function stripAnsi(s) {
|
|
|
4044
4886
|
|
|
4045
4887
|
// src/config.ts
|
|
4046
4888
|
import { mkdir, readFile as readFile15, writeFile } from "node:fs/promises";
|
|
4047
|
-
import { homedir as
|
|
4048
|
-
import { basename as
|
|
4049
|
-
var CONFIG_DIR =
|
|
4889
|
+
import { homedir as homedir17, hostname } from "node:os";
|
|
4890
|
+
import { basename as basename13, join as join18 } from "node:path";
|
|
4891
|
+
var CONFIG_DIR = join18(homedir17(), ".aiusage"), CONFIG_PATH = join18(CONFIG_DIR, "config.json");
|
|
4050
4892
|
function getConfigPath() {
|
|
4051
4893
|
return CONFIG_PATH;
|
|
4052
4894
|
}
|
|
@@ -4181,13 +5023,13 @@ import { hostname as hostname2 } from "node:os";
|
|
|
4181
5023
|
|
|
4182
5024
|
// src/version.ts
|
|
4183
5025
|
import { readFileSync } from "node:fs";
|
|
4184
|
-
import { resolve as
|
|
5026
|
+
import { resolve as resolve3, dirname as dirname7 } from "node:path";
|
|
4185
5027
|
import { fileURLToPath } from "node:url";
|
|
4186
5028
|
var cached;
|
|
4187
5029
|
function getVersion() {
|
|
4188
5030
|
if (cached !== void 0) return cached;
|
|
4189
5031
|
try {
|
|
4190
|
-
let pkg =
|
|
5032
|
+
let pkg = resolve3(dirname7(fileURLToPath(import.meta.url)), "..", "package.json");
|
|
4191
5033
|
cached = JSON.parse(readFileSync(pkg, "utf-8")).version;
|
|
4192
5034
|
} catch {
|
|
4193
5035
|
cached = "unknown";
|
|
@@ -4260,12 +5102,12 @@ async function requestJson(url, init) {
|
|
|
4260
5102
|
}
|
|
4261
5103
|
|
|
4262
5104
|
// src/schedule.ts
|
|
4263
|
-
import { mkdir as mkdir2, readFile as readFile16, stat as
|
|
4264
|
-
import { execFile } from "node:child_process";
|
|
5105
|
+
import { mkdir as mkdir2, readFile as readFile16, stat as stat3, unlink, writeFile as writeFile2 } from "node:fs/promises";
|
|
5106
|
+
import { execFile as execFile2 } from "node:child_process";
|
|
4265
5107
|
import { promisify } from "node:util";
|
|
4266
|
-
import { homedir as
|
|
4267
|
-
import { join as
|
|
4268
|
-
var execFileAsync = promisify(
|
|
5108
|
+
import { homedir as homedir18, platform, tmpdir as tmpdir2 } from "node:os";
|
|
5109
|
+
import { join as join19, resolve as resolve4 } from "node:path";
|
|
5110
|
+
var execFileAsync = promisify(execFile2), LABEL = "com.aiusage.sync", PLIST_PATH = join19(homedir18(), "Library", "LaunchAgents", `${LABEL}.plist`), LOG_PATH = join19(homedir18(), ".aiusage", "sync.log"), CRON_MARKER = "# aiusage-sync";
|
|
4269
5111
|
function parseInterval(value) {
|
|
4270
5112
|
let match = value.match(/^(\d+)(m|h|d)$/);
|
|
4271
5113
|
if (!match) throw new Error("--every \u683C\u5F0F\u9519\u8BEF\uFF0C\u793A\u4F8B: 30m, 1h, 2h, 1d");
|
|
@@ -4300,7 +5142,7 @@ async function getScheduleStatus() {
|
|
|
4300
5142
|
return platform() === "darwin" ? getLaunchdStatus() : getCronStatus();
|
|
4301
5143
|
}
|
|
4302
5144
|
function resolveCommandPaths() {
|
|
4303
|
-
let scriptPath =
|
|
5145
|
+
let scriptPath = resolve4(process.argv[1]);
|
|
4304
5146
|
if (scriptPath.includes("_npx") || scriptPath.includes("/npx-"))
|
|
4305
5147
|
throw new Error(
|
|
4306
5148
|
`\u68C0\u6D4B\u5230\u901A\u8FC7 npx \u8FD0\u884C\uFF0C\u5B9A\u65F6\u4EFB\u52A1\u9700\u8981\u5168\u5C40\u5B89\u88C5\u3002
|
|
@@ -4310,7 +5152,7 @@ function resolveCommandPaths() {
|
|
|
4310
5152
|
}
|
|
4311
5153
|
async function enableLaunchd(intervalSeconds) {
|
|
4312
5154
|
let { nodePath, scriptPath } = resolveCommandPaths();
|
|
4313
|
-
await mkdir2(
|
|
5155
|
+
await mkdir2(join19(homedir18(), ".aiusage"), { recursive: !0 });
|
|
4314
5156
|
let plist = [
|
|
4315
5157
|
'<?xml version="1.0" encoding="UTF-8"?>',
|
|
4316
5158
|
'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
|
|
@@ -4359,7 +5201,7 @@ async function disableLaunchd() {
|
|
|
4359
5201
|
}
|
|
4360
5202
|
async function getLaunchdStatus() {
|
|
4361
5203
|
try {
|
|
4362
|
-
await
|
|
5204
|
+
await stat3(PLIST_PATH);
|
|
4363
5205
|
} catch {
|
|
4364
5206
|
return { enabled: !1 };
|
|
4365
5207
|
}
|
|
@@ -4379,8 +5221,8 @@ async function getLaunchdStatus() {
|
|
|
4379
5221
|
}
|
|
4380
5222
|
}
|
|
4381
5223
|
async function enableCron(intervalSeconds) {
|
|
4382
|
-
let { nodePath, scriptPath } = resolveCommandPaths(), cronExpr = secondsToCron(intervalSeconds), logPath =
|
|
4383
|
-
await mkdir2(
|
|
5224
|
+
let { nodePath, scriptPath } = resolveCommandPaths(), cronExpr = secondsToCron(intervalSeconds), logPath = join19(homedir18(), ".aiusage", "sync.log"), cronLine = `${cronExpr} ${nodePath} ${scriptPath} sync --today >> ${logPath} 2>&1 ${CRON_MARKER}`;
|
|
5225
|
+
await mkdir2(join19(homedir18(), ".aiusage"), { recursive: !0 });
|
|
4384
5226
|
let existing = "";
|
|
4385
5227
|
try {
|
|
4386
5228
|
let { stdout } = await execFileAsync("crontab", ["-l"]);
|
|
@@ -4438,7 +5280,7 @@ async function getCronStatus() {
|
|
|
4438
5280
|
}
|
|
4439
5281
|
}
|
|
4440
5282
|
async function writeCrontab(content) {
|
|
4441
|
-
let tmpFile =
|
|
5283
|
+
let tmpFile = join19(tmpdir2(), `aiusage-cron-${Date.now()}`);
|
|
4442
5284
|
await writeFile2(tmpFile, content, "utf-8");
|
|
4443
5285
|
try {
|
|
4444
5286
|
await execFileAsync("crontab", [tmpFile]);
|
|
@@ -4469,9 +5311,9 @@ function escapeXml(value) {
|
|
|
4469
5311
|
}
|
|
4470
5312
|
|
|
4471
5313
|
// src/doctor.ts
|
|
4472
|
-
import { readdir as
|
|
4473
|
-
import { homedir as
|
|
4474
|
-
import { join as
|
|
5314
|
+
import { readdir as readdir7, stat as stat4 } from "node:fs/promises";
|
|
5315
|
+
import { homedir as homedir19 } from "node:os";
|
|
5316
|
+
import { join as join20 } from "node:path";
|
|
4475
5317
|
var msgs = {
|
|
4476
5318
|
en: {
|
|
4477
5319
|
groupConfig: "Configuration",
|
|
@@ -4527,13 +5369,13 @@ async function countFiles(dir, exts, cap = 1e3) {
|
|
|
4527
5369
|
for (; queue.length > 0 && count < cap; ) {
|
|
4528
5370
|
let current = queue.pop(), entries;
|
|
4529
5371
|
try {
|
|
4530
|
-
entries = await
|
|
5372
|
+
entries = await readdir7(current, { withFileTypes: !0 });
|
|
4531
5373
|
} catch {
|
|
4532
5374
|
continue;
|
|
4533
5375
|
}
|
|
4534
5376
|
for (let e of entries) {
|
|
4535
5377
|
if (count >= cap) break;
|
|
4536
|
-
let full =
|
|
5378
|
+
let full = join20(current, e.name);
|
|
4537
5379
|
e.isDirectory() ? queue.push(full) : exts.some((ext) => e.name.endsWith(ext)) && count++;
|
|
4538
5380
|
}
|
|
4539
5381
|
}
|
|
@@ -4542,7 +5384,7 @@ async function countFiles(dir, exts, cap = 1e3) {
|
|
|
4542
5384
|
async function runDoctor(lang = "zh") {
|
|
4543
5385
|
let s = msgs[lang], checks = [], config = await readConfig(), g1 = s.groupConfig, configPath = getConfigPath();
|
|
4544
5386
|
try {
|
|
4545
|
-
await
|
|
5387
|
+
await stat4(configPath), checks.push({ group: g1, name: s.config, status: "ok", message: configPath });
|
|
4546
5388
|
} catch {
|
|
4547
5389
|
checks.push({ group: g1, name: s.config, status: "fail", message: s.configMissing });
|
|
4548
5390
|
}
|
|
@@ -4562,30 +5404,41 @@ async function runDoctor(lang = "zh") {
|
|
|
4562
5404
|
}
|
|
4563
5405
|
target.lastSuccessfulUploadAt ? checks.push({ group: g2, name: `${prefix} ${s.lastSync}`, status: "ok", message: target.lastSuccessfulUploadAt }) : checks.push({ group: g2, name: `${prefix} ${s.lastSync}`, status: "warn", message: s.lastSyncNone });
|
|
4564
5406
|
}
|
|
4565
|
-
let g3 = s.groupTools, home =
|
|
4566
|
-
{
|
|
4567
|
-
{
|
|
4568
|
-
{
|
|
4569
|
-
{
|
|
4570
|
-
{
|
|
4571
|
-
|
|
4572
|
-
|
|
4573
|
-
|
|
4574
|
-
|
|
4575
|
-
|
|
4576
|
-
|
|
4577
|
-
|
|
4578
|
-
{
|
|
4579
|
-
{
|
|
5407
|
+
let g3 = s.groupTools, home = homedir19(), tools = [
|
|
5408
|
+
{ dirs: [join20(home, ".config", "claude", "projects"), join20(home, ".claude", "projects")], label: "Claude Code", exts: [".jsonl"] },
|
|
5409
|
+
{ dirs: [join20(home, ".codex")], label: "Codex CLI", exts: [".jsonl"] },
|
|
5410
|
+
{ dirs: [join20(home, "Library", "Application Support", "Cursor", "User", "globalStorage")], label: "Cursor", exts: [".vscdb"] },
|
|
5411
|
+
{ dirs: [join20(home, ".copilot", "session-state"), join20(home, ".copilot", "otel")], label: "Copilot CLI", exts: [".jsonl"] },
|
|
5412
|
+
{
|
|
5413
|
+
dirs: [
|
|
5414
|
+
join20(home, "Library", "Application Support", "Code", "logs"),
|
|
5415
|
+
join20(home, "Library", "Application Support", "Code", "User", "workspaceStorage")
|
|
5416
|
+
],
|
|
5417
|
+
label: "Copilot VS Code",
|
|
5418
|
+
exts: [".log", ".json", ".jsonl"]
|
|
5419
|
+
},
|
|
5420
|
+
{ dirs: [join20(home, ".gemini", "tmp")], label: "Gemini CLI", exts: [".json", ".jsonl"] },
|
|
5421
|
+
{ dirs: [join20(home, ".gemini", "antigravity")], label: "Antigravity", exts: [".json"] },
|
|
5422
|
+
{ dirs: [join20(home, ".qwen", "projects"), join20(home, ".qwen", "tmp")], label: "Qwen Code", exts: [".jsonl"] },
|
|
5423
|
+
{ dirs: [join20(resolveKimiCodeHome(home), "sessions")], label: "Kimi Code", exts: [".jsonl"] },
|
|
5424
|
+
{ dirs: [join20(home, ".kimi", "sessions")], label: "Kimi CLI (legacy)", exts: [".jsonl"] },
|
|
5425
|
+
{ dirs: [join20(home, ".local", "share", "amp", "threads")], label: "Amp", exts: [".json"] },
|
|
5426
|
+
{ dirs: [join20(home, ".factory", "sessions")], label: "Droid", exts: [".settings.json"] },
|
|
5427
|
+
{ dirs: [join20(home, ".local", "share", "opencode")], label: "OpenCode", exts: [".db", ".json"] },
|
|
5428
|
+
{ dirs: [join20(home, ".pi", "agent", "sessions"), join20(home, ".omp", "agent", "sessions")], label: "Pi / OMP", exts: [".jsonl"] },
|
|
5429
|
+
{ dirs: [resolveTraeNativeCacheDir(home), resolveTokscaleTraeCacheDir(home)], label: "Trae", exts: [".json"] }
|
|
4580
5430
|
];
|
|
4581
5431
|
for (let tool of tools) {
|
|
4582
|
-
|
|
4583
|
-
|
|
4584
|
-
|
|
5432
|
+
let installed = !1, n = 0;
|
|
5433
|
+
for (let dir of tool.dirs)
|
|
5434
|
+
try {
|
|
5435
|
+
await stat4(dir), installed = !0, n += await countFiles(dir, tool.exts);
|
|
5436
|
+
} catch {
|
|
5437
|
+
}
|
|
5438
|
+
if (!installed) {
|
|
4585
5439
|
checks.push({ group: g3, name: tool.label, status: "warn", message: s.notInstalled });
|
|
4586
5440
|
continue;
|
|
4587
5441
|
}
|
|
4588
|
-
let n = await countFiles(tool.dir, tool.exts);
|
|
4589
5442
|
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 });
|
|
4590
5443
|
}
|
|
4591
5444
|
let g4 = s.groupSchedule, schedule = await getScheduleStatus();
|
|
@@ -4598,9 +5451,9 @@ async function runDoctor(lang = "zh") {
|
|
|
4598
5451
|
}
|
|
4599
5452
|
|
|
4600
5453
|
// src/project.ts
|
|
4601
|
-
import { open as
|
|
4602
|
-
import { basename as
|
|
4603
|
-
import { homedir as
|
|
5454
|
+
import { open as open2, readdir as readdir8, readFile as readFile17 } from "node:fs/promises";
|
|
5455
|
+
import { basename as basename14, join as join21 } from "node:path";
|
|
5456
|
+
import { homedir as homedir20 } from "node:os";
|
|
4604
5457
|
async function discoverProjects(projectAliases) {
|
|
4605
5458
|
let projectMap = /* @__PURE__ */ new Map();
|
|
4606
5459
|
function add(name, source) {
|
|
@@ -4628,7 +5481,9 @@ async function discoverProjects(projectAliases) {
|
|
|
4628
5481
|
// 仅读取知识项元数据标题,不读取对话内容
|
|
4629
5482
|
discoverAntigravityProjects().then((names) => names.forEach((n) => add(n, "antigravity"))),
|
|
4630
5483
|
// Kimi CLI / Kimi Code: legacy workspace map + new session metadata.
|
|
4631
|
-
discoverKimiProjects().then((names) => names.forEach((n) => add(n, "kimi")))
|
|
5484
|
+
discoverKimiProjects().then((names) => names.forEach((n) => add(n, "kimi"))),
|
|
5485
|
+
// Trae CN: privacy-minimized cache written by `aiusage trae sync`.
|
|
5486
|
+
discoverTraeProjects().then((names) => names.forEach((n) => add(n, "trae")))
|
|
4632
5487
|
]);
|
|
4633
5488
|
let results = [];
|
|
4634
5489
|
for (let [name, sources] of projectMap) {
|
|
@@ -4646,20 +5501,20 @@ async function discoverClaudeProjects() {
|
|
|
4646
5501
|
for (let baseDir of getClaudeDirs()) {
|
|
4647
5502
|
let entries;
|
|
4648
5503
|
try {
|
|
4649
|
-
entries = await
|
|
5504
|
+
entries = await readdir8(baseDir, { withFileTypes: !0 });
|
|
4650
5505
|
} catch {
|
|
4651
5506
|
continue;
|
|
4652
5507
|
}
|
|
4653
5508
|
for (let entry of entries) {
|
|
4654
5509
|
if (!entry.isDirectory() || entry.name.startsWith(".")) continue;
|
|
4655
|
-
let projectDir =
|
|
5510
|
+
let projectDir = join21(baseDir, entry.name), name = await extractCwdFromFirstJsonl(projectDir);
|
|
4656
5511
|
name && name !== "unknown" && names.push(name);
|
|
4657
5512
|
}
|
|
4658
5513
|
}
|
|
4659
5514
|
return names;
|
|
4660
5515
|
}
|
|
4661
5516
|
async function discoverCodexProjects() {
|
|
4662
|
-
let sessionsDir =
|
|
5517
|
+
let sessionsDir = join21(homedir20(), ".codex", "sessions"), files = await walkJsonlFiles(sessionsDir), projects = /* @__PURE__ */ new Set();
|
|
4663
5518
|
for (let filePath of files) {
|
|
4664
5519
|
let name = await extractCwdFromSessionMeta(filePath);
|
|
4665
5520
|
name && name !== "unknown" && projects.add(name);
|
|
@@ -4669,7 +5524,7 @@ async function discoverCodexProjects() {
|
|
|
4669
5524
|
async function extractCwdFromSessionMeta(filePath) {
|
|
4670
5525
|
let fh;
|
|
4671
5526
|
try {
|
|
4672
|
-
fh = await
|
|
5527
|
+
fh = await open2(filePath, "r");
|
|
4673
5528
|
let buf = Buffer.alloc(4096), { bytesRead } = await fh.read(buf, 0, buf.length, 0);
|
|
4674
5529
|
if (bytesRead === 0) return;
|
|
4675
5530
|
let line = buf.subarray(0, bytesRead).toString("utf-8").split(`
|
|
@@ -4691,12 +5546,12 @@ async function walkFiles2(dir, ext) {
|
|
|
4691
5546
|
async function walk2(d) {
|
|
4692
5547
|
let entries;
|
|
4693
5548
|
try {
|
|
4694
|
-
entries = await
|
|
5549
|
+
entries = await readdir8(d, { withFileTypes: !0 });
|
|
4695
5550
|
} catch {
|
|
4696
5551
|
return;
|
|
4697
5552
|
}
|
|
4698
5553
|
for (let entry of entries) {
|
|
4699
|
-
let full =
|
|
5554
|
+
let full = join21(d, entry.name);
|
|
4700
5555
|
entry.isDirectory() ? await walk2(full) : entry.name.endsWith(ext) && result.push(full);
|
|
4701
5556
|
}
|
|
4702
5557
|
}
|
|
@@ -4707,7 +5562,7 @@ async function extractCwdFromFirstJsonl(dir) {
|
|
|
4707
5562
|
if (!jsonlPath) return;
|
|
4708
5563
|
let fh;
|
|
4709
5564
|
try {
|
|
4710
|
-
fh = await
|
|
5565
|
+
fh = await open2(jsonlPath, "r");
|
|
4711
5566
|
let buf = Buffer.alloc(32 * 1024), { bytesRead } = await fh.read(buf, 0, buf.length, 0);
|
|
4712
5567
|
if (bytesRead === 0) return;
|
|
4713
5568
|
let lines = buf.subarray(0, bytesRead).toString("utf-8").split(`
|
|
@@ -4733,27 +5588,27 @@ async function extractCwdFromFirstJsonl(dir) {
|
|
|
4733
5588
|
async function findFirstJsonl(dir) {
|
|
4734
5589
|
let entries;
|
|
4735
5590
|
try {
|
|
4736
|
-
entries = await
|
|
5591
|
+
entries = await readdir8(dir, { withFileTypes: !0 });
|
|
4737
5592
|
} catch {
|
|
4738
5593
|
return;
|
|
4739
5594
|
}
|
|
4740
5595
|
let topJsonl = entries.find((e) => e.isFile() && e.name.endsWith(".jsonl"));
|
|
4741
|
-
if (topJsonl) return
|
|
5596
|
+
if (topJsonl) return join21(dir, topJsonl.name);
|
|
4742
5597
|
for (let entry of entries)
|
|
4743
5598
|
if (!(!entry.isDirectory() || entry.name.startsWith(".")))
|
|
4744
5599
|
try {
|
|
4745
|
-
let sub = (await
|
|
4746
|
-
if (sub) return
|
|
5600
|
+
let sub = (await readdir8(join21(dir, entry.name))).find((f) => f.endsWith(".jsonl"));
|
|
5601
|
+
if (sub) return join21(dir, entry.name, sub);
|
|
4747
5602
|
} catch {
|
|
4748
5603
|
continue;
|
|
4749
5604
|
}
|
|
4750
5605
|
}
|
|
4751
5606
|
async function discoverCopilotProjects() {
|
|
4752
|
-
let dir =
|
|
5607
|
+
let dir = join21(homedir20(), ".copilot", "session-state"), files = await walkJsonlFiles(dir), projects = /* @__PURE__ */ new Set();
|
|
4753
5608
|
for (let filePath of files) {
|
|
4754
5609
|
let fh;
|
|
4755
5610
|
try {
|
|
4756
|
-
fh = await
|
|
5611
|
+
fh = await open2(filePath, "r");
|
|
4757
5612
|
let buf = Buffer.alloc(4096), { bytesRead } = await fh.read(buf, 0, buf.length, 0);
|
|
4758
5613
|
if (bytesRead === 0) continue;
|
|
4759
5614
|
let line = buf.subarray(0, bytesRead).toString("utf-8").split(`
|
|
@@ -4771,7 +5626,7 @@ async function discoverCopilotProjects() {
|
|
|
4771
5626
|
return [...projects];
|
|
4772
5627
|
}
|
|
4773
5628
|
async function discoverGeminiProjects() {
|
|
4774
|
-
let filePath =
|
|
5629
|
+
let filePath = join21(homedir20(), ".gemini", "projects.json");
|
|
4775
5630
|
try {
|
|
4776
5631
|
let raw = await readFile17(filePath, "utf-8"), projects = JSON.parse(raw)?.projects;
|
|
4777
5632
|
if (!projects || typeof projects != "object") return [];
|
|
@@ -4786,7 +5641,7 @@ async function discoverGeminiProjects() {
|
|
|
4786
5641
|
}
|
|
4787
5642
|
}
|
|
4788
5643
|
async function discoverCursorProjects() {
|
|
4789
|
-
let storagePath =
|
|
5644
|
+
let storagePath = join21(homedir20(), "Library", "Application Support", "Cursor", "User", "globalStorage", "storage.json");
|
|
4790
5645
|
try {
|
|
4791
5646
|
let raw = await readFile17(storagePath, "utf-8"), data = JSON.parse(raw), projects = /* @__PURE__ */ new Set(), workspaceUris = Object.keys(data.profileAssociations?.workspaces ?? {});
|
|
4792
5647
|
for (let uri of workspaceUris) {
|
|
@@ -4803,7 +5658,7 @@ async function discoverCursorProjects() {
|
|
|
4803
5658
|
}
|
|
4804
5659
|
}
|
|
4805
5660
|
async function discoverCopilotVscodeProjects() {
|
|
4806
|
-
let dir =
|
|
5661
|
+
let dir = join21(homedir20(), "Library", "Application Support", "Code", "logs"), files = (await walkFiles2(dir, ".log")).filter((filePath) => filePath.endsWith("GitHub Copilot Chat.log")), projects = /* @__PURE__ */ new Set();
|
|
4807
5662
|
for (let filePath of files) {
|
|
4808
5663
|
let content;
|
|
4809
5664
|
try {
|
|
@@ -4820,16 +5675,16 @@ async function discoverCopilotVscodeProjects() {
|
|
|
4820
5675
|
return [...projects];
|
|
4821
5676
|
}
|
|
4822
5677
|
async function discoverAntigravityProjects() {
|
|
4823
|
-
let dir =
|
|
5678
|
+
let dir = join21(homedir20(), ".gemini", "antigravity", "knowledge"), entries;
|
|
4824
5679
|
try {
|
|
4825
|
-
entries = await
|
|
5680
|
+
entries = await readdir8(dir, { withFileTypes: !0 });
|
|
4826
5681
|
} catch {
|
|
4827
5682
|
return [];
|
|
4828
5683
|
}
|
|
4829
5684
|
let projects = /* @__PURE__ */ new Set();
|
|
4830
5685
|
for (let entry of entries) {
|
|
4831
5686
|
if (!entry.isDirectory()) continue;
|
|
4832
|
-
let metadataPath =
|
|
5687
|
+
let metadataPath = join21(dir, entry.name, "metadata.json");
|
|
4833
5688
|
try {
|
|
4834
5689
|
let raw = await readFile17(metadataPath, "utf-8"), name = JSON.parse(raw).title?.trim() || entry.name.trim();
|
|
4835
5690
|
name && name !== "unknown" && projects.add(name);
|
|
@@ -4840,33 +5695,44 @@ async function discoverAntigravityProjects() {
|
|
|
4840
5695
|
return [...projects];
|
|
4841
5696
|
}
|
|
4842
5697
|
async function discoverKimiProjects() {
|
|
4843
|
-
let projects = /* @__PURE__ */ new Set(), home =
|
|
5698
|
+
let projects = /* @__PURE__ */ new Set(), home = homedir20();
|
|
4844
5699
|
try {
|
|
4845
|
-
let raw = await readFile17(
|
|
5700
|
+
let raw = await readFile17(join21(home, ".kimi", "kimi.json"), "utf-8"), data = JSON.parse(raw);
|
|
4846
5701
|
for (let workspace of Object.values(data.workspaces ?? {})) {
|
|
4847
|
-
let name =
|
|
5702
|
+
let name = basename14(workspace.path?.trim() ?? "");
|
|
4848
5703
|
name && name !== "unknown" && projects.add(name);
|
|
4849
5704
|
}
|
|
4850
5705
|
} catch {
|
|
4851
5706
|
}
|
|
4852
5707
|
let codeHome = resolveKimiCodeHome(home);
|
|
4853
5708
|
try {
|
|
4854
|
-
let raw = await readFile17(
|
|
5709
|
+
let raw = await readFile17(join21(codeHome, "session_index.jsonl"), "utf-8");
|
|
4855
5710
|
for (let line of raw.split(`
|
|
4856
5711
|
`))
|
|
4857
5712
|
if (line.trim())
|
|
4858
5713
|
try {
|
|
4859
|
-
let record = JSON.parse(line), name =
|
|
5714
|
+
let record = JSON.parse(line), name = basename14(record.workDir?.trim() ?? "");
|
|
4860
5715
|
name && name !== "unknown" && projects.add(name);
|
|
4861
5716
|
} catch {
|
|
4862
5717
|
continue;
|
|
4863
5718
|
}
|
|
4864
5719
|
} catch {
|
|
4865
5720
|
}
|
|
4866
|
-
let stateFiles = (await walkFiles2(
|
|
5721
|
+
let stateFiles = (await walkFiles2(join21(codeHome, "sessions"), ".json")).filter((filePath) => basename14(filePath) === "state.json");
|
|
4867
5722
|
for (let filePath of stateFiles)
|
|
4868
5723
|
try {
|
|
4869
|
-
let raw = await readFile17(filePath, "utf-8"), state = JSON.parse(raw), name =
|
|
5724
|
+
let raw = await readFile17(filePath, "utf-8"), state = JSON.parse(raw), name = basename14(state.workDir?.trim() ?? "");
|
|
5725
|
+
name && name !== "unknown" && projects.add(name);
|
|
5726
|
+
} catch {
|
|
5727
|
+
continue;
|
|
5728
|
+
}
|
|
5729
|
+
return [...projects];
|
|
5730
|
+
}
|
|
5731
|
+
async function discoverTraeProjects() {
|
|
5732
|
+
let projects = /* @__PURE__ */ new Set();
|
|
5733
|
+
for (let filePath of await walkFiles2(resolveTraeNativeCacheDir(), ".json"))
|
|
5734
|
+
try {
|
|
5735
|
+
let data = JSON.parse(await readFile17(filePath, "utf8")), name = basename14(data.project?.trim() ?? "");
|
|
4870
5736
|
name && name !== "unknown" && projects.add(name);
|
|
4871
5737
|
} catch {
|
|
4872
5738
|
continue;
|
|
@@ -4876,7 +5742,7 @@ async function discoverKimiProjects() {
|
|
|
4876
5742
|
function nameFromFileUri(raw) {
|
|
4877
5743
|
let path = pathFromFileUri(raw);
|
|
4878
5744
|
if (!path) return;
|
|
4879
|
-
let name =
|
|
5745
|
+
let name = basename14(path);
|
|
4880
5746
|
return name && name !== "unknown" ? name : void 0;
|
|
4881
5747
|
}
|
|
4882
5748
|
function pathFromFileUri(raw) {
|
|
@@ -4895,11 +5761,11 @@ function pathFromFileUri(raw) {
|
|
|
4895
5761
|
function getClaudeDirs() {
|
|
4896
5762
|
let envVar = process.env.CLAUDE_CONFIG_DIR?.trim();
|
|
4897
5763
|
if (envVar)
|
|
4898
|
-
return envVar.split(",").map((p) => p.trim()).filter(Boolean).map((p) =>
|
|
4899
|
-
let home =
|
|
5764
|
+
return envVar.split(",").map((p) => p.trim()).filter(Boolean).map((p) => join21(p, "projects"));
|
|
5765
|
+
let home = homedir20();
|
|
4900
5766
|
return [
|
|
4901
|
-
|
|
4902
|
-
|
|
5767
|
+
join21(home, ".config", "claude", "projects"),
|
|
5768
|
+
join21(home, ".claude", "projects")
|
|
4903
5769
|
];
|
|
4904
5770
|
}
|
|
4905
5771
|
|
|
@@ -4945,9 +5811,9 @@ function shortHash(p) {
|
|
|
4945
5811
|
|
|
4946
5812
|
// src/pricing.ts
|
|
4947
5813
|
import { mkdir as mkdir3, readFile as readFile18, writeFile as writeFile3 } from "node:fs/promises";
|
|
4948
|
-
import { homedir as
|
|
4949
|
-
import { join as
|
|
4950
|
-
var CACHE_DIR =
|
|
5814
|
+
import { homedir as homedir21 } from "node:os";
|
|
5815
|
+
import { join as join22 } from "node:path";
|
|
5816
|
+
var CACHE_DIR = join22(homedir21(), ".aiusage"), CACHE_PATH = join22(CACHE_DIR, "pricing-cache.json"), DEFAULT_CACHE_TTL_HOURS = 24, FETCH_TIMEOUT_MS = 5e3, NPM_CDN_URLS = [
|
|
4951
5817
|
"https://cdn.jsdelivr.net/npm/@aiusage/cli@latest/pricing-catalog.json",
|
|
4952
5818
|
"https://unpkg.com/@aiusage/cli@latest/pricing-catalog.json",
|
|
4953
5819
|
"https://cdn.jsdelivr.net/npm/@aiusage/pricing@latest/catalog.json",
|
|
@@ -5043,6 +5909,436 @@ function assertPricingCatalog(value) {
|
|
|
5043
5909
|
if (!catalog2.providers.openai?.codex?.models) throw new Error("invalid OpenAI pricing catalog");
|
|
5044
5910
|
}
|
|
5045
5911
|
|
|
5912
|
+
// src/trae-sync.ts
|
|
5913
|
+
import { execFile as execFile3 } from "node:child_process";
|
|
5914
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
5915
|
+
import { existsSync as existsSync2 } from "node:fs";
|
|
5916
|
+
import { mkdir as mkdir4, open as open3, readdir as readdir9, rename, stat as stat5, writeFile as writeFile4 } from "node:fs/promises";
|
|
5917
|
+
import { createServer } from "node:net";
|
|
5918
|
+
import { homedir as homedir22 } from "node:os";
|
|
5919
|
+
import { join as join23 } from "node:path";
|
|
5920
|
+
import { promisify as promisify2 } from "node:util";
|
|
5921
|
+
import WebSocket from "ws";
|
|
5922
|
+
var execFileAsync2 = promisify2(execFile3), DEFAULT_DEBUG_PORT = 9230, DEFAULT_APP_PATH = "/Applications/TRAE.app", JWT_PATTERN = /eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g;
|
|
5923
|
+
async function syncTraeCnUsage(options = {}) {
|
|
5924
|
+
let timeoutMs = clampTimeout(options.timeoutMs), userDataDir = options.userDataDir ?? resolveTraeCnUserDataDir(), cacheDir = options.cacheDir ?? resolveTraeNativeCacheDir(), appPath = options.appPath ?? DEFAULT_APP_PATH, port = normalizePort(options.port) ?? DEFAULT_DEBUG_PORT, target = await findWorkbenchTarget(port), launched = !1;
|
|
5925
|
+
try {
|
|
5926
|
+
if (!target) {
|
|
5927
|
+
if (options.launch === !1)
|
|
5928
|
+
throw new Error(`\u672A\u8FDE\u63A5\u5230 Trae CN \u672C\u5730\u8C03\u8BD5\u63A5\u53E3 (127.0.0.1:${port})`);
|
|
5929
|
+
if (process.platform !== "darwin")
|
|
5930
|
+
throw new Error("Trae CN \u81EA\u52A8\u540C\u6B65\u76EE\u524D\u4EC5\u652F\u6301 macOS\uFF1B\u5176\u4ED6\u7CFB\u7EDF\u53EF\u7528 --port \u8FDE\u63A5\u5DF2\u5F00\u542F\u8C03\u8BD5\u7AEF\u53E3\u7684 Trae");
|
|
5931
|
+
if (await isTraeRunning())
|
|
5932
|
+
throw new Error("\u68C0\u6D4B\u5230 Trae CN \u6B63\u5728\u8FD0\u884C\u4F46\u672A\u5F00\u653E\u672C\u5730\u8BFB\u53D6\u63A5\u53E3\u3002\u8BF7\u5148\u9000\u51FA Trae\uFF0C\u518D\u6267\u884C aiusage trae sync");
|
|
5933
|
+
if (!existsSync2(appPath)) throw new Error(`\u672A\u627E\u5230 Trae CN: ${appPath}`);
|
|
5934
|
+
options.port == null && !await isPortAvailable(port) && (port = await findFreePort()), await launchTrae(appPath, port), launched = !0, target = await waitForWorkbench(port, timeoutMs);
|
|
5935
|
+
}
|
|
5936
|
+
let userIds = await waitForTraeUserIds(userDataDir, timeoutMs);
|
|
5937
|
+
if (userIds.length === 0)
|
|
5938
|
+
throw new Error("\u672A\u80FD\u4ECE Trae CN \u672C\u5730\u65E5\u5FD7\u8BC6\u522B\u8D26\u53F7\uFF0C\u8BF7\u786E\u8BA4 Trae \u5DF2\u767B\u5F55\u540E\u91CD\u8BD5");
|
|
5939
|
+
let raw = await readTraeUsageWithRetry(port, target, userIds, timeoutMs), normalized = normalizeSyncResult(raw);
|
|
5940
|
+
if (normalized.sessions.length === 0 && (raw.errors?.length ?? 0) > 0)
|
|
5941
|
+
throw new Error(`Trae CN \u672C\u5730\u8BFB\u53D6\u5931\u8D25: ${sanitizeMessage(raw.errors?.[0]?.message)}`);
|
|
5942
|
+
await writeCache(normalized.sessions, cacheDir);
|
|
5943
|
+
let totals = normalized.sessions.flatMap((session) => session.events).reduce(
|
|
5944
|
+
(sum, event) => (sum.inputTokens += event.inputTokens, sum.cachedInputTokens += event.cachedInputTokens, sum.cacheWriteTokens += event.cacheWriteTokens, sum.outputTokens += event.outputTokens, sum.reasoningOutputTokens += event.reasoningOutputTokens, sum.totalTokens += event.inputTokens + event.cachedInputTokens + event.cacheWriteTokens + event.outputTokens + event.reasoningOutputTokens, sum),
|
|
5945
|
+
{
|
|
5946
|
+
inputTokens: 0,
|
|
5947
|
+
cachedInputTokens: 0,
|
|
5948
|
+
cacheWriteTokens: 0,
|
|
5949
|
+
outputTokens: 0,
|
|
5950
|
+
reasoningOutputTokens: 0,
|
|
5951
|
+
totalTokens: 0
|
|
5952
|
+
}
|
|
5953
|
+
);
|
|
5954
|
+
return {
|
|
5955
|
+
cacheDir,
|
|
5956
|
+
accounts: raw.accounts ?? userIds.length,
|
|
5957
|
+
sessions: normalized.sessions.length,
|
|
5958
|
+
events: normalized.sessions.reduce((sum, session) => sum + session.events.length, 0),
|
|
5959
|
+
totals,
|
|
5960
|
+
warnings: (raw.errors ?? []).map((error) => sanitizeMessage(error.message)).filter(Boolean)
|
|
5961
|
+
};
|
|
5962
|
+
} finally {
|
|
5963
|
+
launched && await quitTrae();
|
|
5964
|
+
}
|
|
5965
|
+
}
|
|
5966
|
+
function normalizeTraeCnUsage(raw) {
|
|
5967
|
+
let prompt2 = tokenValue2(raw.promptTokens), completion = tokenValue2(raw.completionTokens), cached2 = Math.min(tokenValue2(raw.cacheReadInputTokens), prompt2), cacheWrite = Math.min(tokenValue2(raw.cacheCreationInputTokens), Math.max(0, prompt2 - cached2)), reportedTotal = tokenValue2(raw.totalTokens), reportedReasoning = tokenValue2(raw.reasoningTokens), reasoning = reportedTotal > 0 && prompt2 + completion > 0 ? Math.max(0, reportedTotal - prompt2 - completion) : reportedReasoning, input = Math.max(0, prompt2 - cached2 - cacheWrite), output = completion;
|
|
5968
|
+
if (prompt2 + completion + reportedReasoning === 0 && reportedTotal > 0 && (input = reportedTotal, reasoning = 0), input + cached2 + cacheWrite + output + reasoning === 0) return null;
|
|
5969
|
+
let messageId = stringValue4(raw.messageId), timestamp = raw.timestamp;
|
|
5970
|
+
return !messageId || timestamp == null || timestamp === "" ? null : {
|
|
5971
|
+
messageId,
|
|
5972
|
+
timestamp,
|
|
5973
|
+
model: normalizeTraeModel(stringValue4(raw.model)),
|
|
5974
|
+
inputTokens: input,
|
|
5975
|
+
cachedInputTokens: cached2,
|
|
5976
|
+
cacheWriteTokens: cacheWrite,
|
|
5977
|
+
outputTokens: output,
|
|
5978
|
+
reasoningOutputTokens: reasoning
|
|
5979
|
+
};
|
|
5980
|
+
}
|
|
5981
|
+
function normalizeSyncResult(raw) {
|
|
5982
|
+
let syncedAt = (/* @__PURE__ */ new Date()).toISOString(), sessions = [], seenMessages = /* @__PURE__ */ new Set();
|
|
5983
|
+
for (let rawSession of raw.sessions ?? []) {
|
|
5984
|
+
let sessionId = stringValue4(rawSession.sessionId);
|
|
5985
|
+
if (!sessionId) continue;
|
|
5986
|
+
let events = [];
|
|
5987
|
+
for (let rawEvent of rawSession.events ?? []) {
|
|
5988
|
+
let event = normalizeTraeCnUsage(rawEvent);
|
|
5989
|
+
!event || seenMessages.has(event.messageId) || (seenMessages.add(event.messageId), events.push(event));
|
|
5990
|
+
}
|
|
5991
|
+
events.length !== 0 && sessions.push({
|
|
5992
|
+
schemaVersion: 1,
|
|
5993
|
+
source: "trae-cn-local-rpc",
|
|
5994
|
+
syncedAt,
|
|
5995
|
+
sessionId,
|
|
5996
|
+
project: stringValue4(rawSession.project) || "unknown",
|
|
5997
|
+
events
|
|
5998
|
+
});
|
|
5999
|
+
}
|
|
6000
|
+
return { sessions };
|
|
6001
|
+
}
|
|
6002
|
+
async function readTraeUsage(webSocketDebuggerUrl, userIds, timeoutMs) {
|
|
6003
|
+
if (!webSocketDebuggerUrl) throw new Error("Trae CN \u8C03\u8BD5\u76EE\u6807\u7F3A\u5C11 WebSocket \u5730\u5740");
|
|
6004
|
+
let client = await CdpClient.connect(webSocketDebuggerUrl, timeoutMs);
|
|
6005
|
+
try {
|
|
6006
|
+
let result = await client.call("Runtime.evaluate", {
|
|
6007
|
+
expression: buildSyncExpression(userIds),
|
|
6008
|
+
awaitPromise: !0,
|
|
6009
|
+
returnByValue: !0
|
|
6010
|
+
}, timeoutMs), exception = result?.exceptionDetails?.exception?.description ?? result?.exceptionDetails?.text;
|
|
6011
|
+
if (exception) throw new Error(sanitizeMessage(exception));
|
|
6012
|
+
return result?.result?.value ?? {};
|
|
6013
|
+
} finally {
|
|
6014
|
+
client.close();
|
|
6015
|
+
}
|
|
6016
|
+
}
|
|
6017
|
+
async function readTraeUsageWithRetry(port, initialTarget, userIds, timeoutMs) {
|
|
6018
|
+
let deadline = Date.now() + timeoutMs, target = initialTarget, lastError;
|
|
6019
|
+
for (; Date.now() < deadline; )
|
|
6020
|
+
try {
|
|
6021
|
+
let remaining = Math.max(5e3, deadline - Date.now());
|
|
6022
|
+
return await readTraeUsage(target.webSocketDebuggerUrl, userIds, Math.min(6e4, remaining));
|
|
6023
|
+
} catch (error) {
|
|
6024
|
+
if (lastError = error instanceof Error ? error : new Error(String(error)), Date.now() + 1e3 >= deadline) break;
|
|
6025
|
+
await delay(1e3), target = await findWorkbenchTarget(port) ?? target;
|
|
6026
|
+
}
|
|
6027
|
+
throw lastError ?? new Error("Trae CN \u672C\u5730\u670D\u52A1\u672A\u5C31\u7EEA");
|
|
6028
|
+
}
|
|
6029
|
+
function buildSyncExpression(userIds) {
|
|
6030
|
+
return `(async()=>{
|
|
6031
|
+
const userIds=${JSON.stringify(userIds)};
|
|
6032
|
+
const connection=await vscode.ahaIpc.connect('ai-agent');
|
|
6033
|
+
let sequence=0;
|
|
6034
|
+
const rpc=(method,data,sessionId='')=>new Promise((resolve,reject)=>{
|
|
6035
|
+
const id='aiusage-trae-'+Date.now()+'-'+(++sequence);
|
|
6036
|
+
const timer=setTimeout(()=>{connection.off('message',handler);reject(new Error('Trae RPC timeout'))},15000);
|
|
6037
|
+
const handler=raw=>{
|
|
6038
|
+
let message;
|
|
6039
|
+
try{message=typeof raw==='string'?JSON.parse(raw):raw}catch{return}
|
|
6040
|
+
if(message.id!==id)return;
|
|
6041
|
+
clearTimeout(timer);
|
|
6042
|
+
connection.off('message',handler);
|
|
6043
|
+
const params=message.result&&message.result.params||{};
|
|
6044
|
+
let responseData=params.data;
|
|
6045
|
+
try{if(typeof responseData==='string')responseData=JSON.parse(responseData)}catch{}
|
|
6046
|
+
resolve({code:params.code,message:params.message,data:responseData||{}});
|
|
6047
|
+
};
|
|
6048
|
+
connection.on('message',handler);
|
|
6049
|
+
connection.send(JSON.stringify({jsonrpc:'2.0',id,method:'request',params:[{
|
|
6050
|
+
packet_type:'request',session_id:sessionId,channel_id:id,params:{
|
|
6051
|
+
service:'chat',method,data:JSON.stringify(data),common_params:{},
|
|
6052
|
+
user_info:{name:'',token:'',region:'',is_internal:false,user_id:'',scope:''},
|
|
6053
|
+
streamlined_common_params:{},client_info:{connect_session_id:''}
|
|
6054
|
+
}
|
|
6055
|
+
}]}));
|
|
6056
|
+
});
|
|
6057
|
+
const number=value=>{const parsed=Number(value);return Number.isFinite(parsed)&&parsed>0?Math.floor(parsed):0};
|
|
6058
|
+
const errors=[];
|
|
6059
|
+
const sessionMap=new Map();
|
|
6060
|
+
const loadSession=async(session,userId)=>{
|
|
6061
|
+
const sessionId=String(session.session_id||session.id||'');
|
|
6062
|
+
if(!sessionId)return null;
|
|
6063
|
+
const loaded={
|
|
6064
|
+
sessionId,
|
|
6065
|
+
project:typeof session.main_folder==='string'?session.main_folder:'unknown',
|
|
6066
|
+
events:[]
|
|
6067
|
+
};
|
|
6068
|
+
const seenMessages=new Set();
|
|
6069
|
+
let messageCursor='';
|
|
6070
|
+
const seenMessageCursors=new Set();
|
|
6071
|
+
for(let messagePage=0;messagePage<100;messagePage++){
|
|
6072
|
+
const messageRequest={user_id:userId,session_id:sessionId,page_size:100};
|
|
6073
|
+
if(messageCursor)messageRequest.next_page_token=messageCursor;
|
|
6074
|
+
const messageResponse=await rpc('get_messages',messageRequest,sessionId);
|
|
6075
|
+
if(messageResponse.code!==0){errors.push({code:messageResponse.code,message:messageResponse.message});break}
|
|
6076
|
+
const messageData=messageResponse.data||{};
|
|
6077
|
+
for(const message of Array.isArray(messageData.messages)?messageData.messages:[]){
|
|
6078
|
+
const usage=message.token_usage;
|
|
6079
|
+
if(!usage)continue;
|
|
6080
|
+
const messageId=String(message.message_id||message.id||'');
|
|
6081
|
+
if(!messageId||seenMessages.has(messageId))continue;
|
|
6082
|
+
const meta=message.model_smart_selection_meta||{};
|
|
6083
|
+
loaded.events.push({
|
|
6084
|
+
messageId,
|
|
6085
|
+
timestamp:message.created_at||message.timestamp||session.update_at||session.created_at,
|
|
6086
|
+
model:typeof meta.config_name==='string'&&meta.config_name?meta.config_name:
|
|
6087
|
+
(typeof meta.mode==='string'&&meta.mode?'trae-'+meta.mode.toLowerCase():'trae-unknown'),
|
|
6088
|
+
promptTokens:number(usage.prompt_tokens||usage.prompt_tokens_total),
|
|
6089
|
+
completionTokens:number(usage.completion_tokens||usage.completion_tokens_total),
|
|
6090
|
+
reasoningTokens:number(usage.reasoning_tokens),
|
|
6091
|
+
cacheReadInputTokens:number(usage.cache_read_input_tokens),
|
|
6092
|
+
cacheCreationInputTokens:number(usage.cache_creation_input_tokens),
|
|
6093
|
+
totalTokens:number(usage.total_tokens)
|
|
6094
|
+
});
|
|
6095
|
+
seenMessages.add(messageId);
|
|
6096
|
+
}
|
|
6097
|
+
const next=typeof messageData.next_page_token==='string'?messageData.next_page_token:'';
|
|
6098
|
+
if(!next||seenMessageCursors.has(next))break;
|
|
6099
|
+
seenMessageCursors.add(next);
|
|
6100
|
+
messageCursor=next;
|
|
6101
|
+
}
|
|
6102
|
+
return loaded;
|
|
6103
|
+
};
|
|
6104
|
+
try{
|
|
6105
|
+
for(const userId of userIds){
|
|
6106
|
+
let sessionCursor='';
|
|
6107
|
+
const seenSessionCursors=new Set();
|
|
6108
|
+
for(let sessionPage=0;sessionPage<100;sessionPage++){
|
|
6109
|
+
const sessionRequest={user_id:userId,page_size:100};
|
|
6110
|
+
if(sessionCursor)sessionRequest.next_page_token=sessionCursor;
|
|
6111
|
+
const sessionResponse=await rpc('get_lite_sessions',sessionRequest);
|
|
6112
|
+
if(sessionResponse.code!==0){errors.push({code:sessionResponse.code,message:sessionResponse.message});break}
|
|
6113
|
+
const data=sessionResponse.data||{};
|
|
6114
|
+
const sessions=Array.isArray(data.sessions)?data.sessions:[];
|
|
6115
|
+
for(let index=0;index<sessions.length;index+=6){
|
|
6116
|
+
const loaded=await Promise.all(sessions.slice(index,index+6).map(session=>loadSession(session,userId)));
|
|
6117
|
+
for(const session of loaded){
|
|
6118
|
+
if(!session)continue;
|
|
6119
|
+
const existing=sessionMap.get(session.sessionId);
|
|
6120
|
+
if(!existing){sessionMap.set(session.sessionId,session);continue}
|
|
6121
|
+
const seen=new Set(existing.events.map(event=>event.messageId));
|
|
6122
|
+
for(const event of session.events)if(!seen.has(event.messageId))existing.events.push(event);
|
|
6123
|
+
}
|
|
6124
|
+
}
|
|
6125
|
+
const next=typeof data.next_page_token==='string'?data.next_page_token:'';
|
|
6126
|
+
if(!next||seenSessionCursors.has(next))break;
|
|
6127
|
+
seenSessionCursors.add(next);
|
|
6128
|
+
sessionCursor=next;
|
|
6129
|
+
}
|
|
6130
|
+
}
|
|
6131
|
+
return {accounts:userIds.length,sessions:[...sessionMap.values()],errors};
|
|
6132
|
+
}finally{connection.disconnect()}
|
|
6133
|
+
})()`;
|
|
6134
|
+
}
|
|
6135
|
+
var CdpClient = class _CdpClient {
|
|
6136
|
+
constructor(socket) {
|
|
6137
|
+
this.socket = socket;
|
|
6138
|
+
socket.on("message", (raw) => {
|
|
6139
|
+
let message;
|
|
6140
|
+
try {
|
|
6141
|
+
message = JSON.parse(String(raw));
|
|
6142
|
+
} catch {
|
|
6143
|
+
return;
|
|
6144
|
+
}
|
|
6145
|
+
let entry = this.pending.get(message.id);
|
|
6146
|
+
entry && (clearTimeout(entry.timer), this.pending.delete(message.id), message.error ? entry.reject(new Error(sanitizeMessage(message.error.message))) : entry.resolve(message.result));
|
|
6147
|
+
}), socket.on("error", (error) => this.rejectAll(error)), socket.on("close", () => this.rejectAll(new Error("Trae CN \u672C\u5730\u8FDE\u63A5\u5DF2\u5173\u95ED")));
|
|
6148
|
+
}
|
|
6149
|
+
sequence = 0;
|
|
6150
|
+
pending = /* @__PURE__ */ new Map();
|
|
6151
|
+
static async connect(url, timeoutMs) {
|
|
6152
|
+
let socket = new WebSocket(url);
|
|
6153
|
+
return await new Promise((resolve5, reject) => {
|
|
6154
|
+
let timer = setTimeout(() => {
|
|
6155
|
+
socket.close(), reject(new Error("\u8FDE\u63A5 Trae CN \u672C\u5730\u63A5\u53E3\u8D85\u65F6"));
|
|
6156
|
+
}, timeoutMs);
|
|
6157
|
+
socket.once("open", () => {
|
|
6158
|
+
clearTimeout(timer), resolve5();
|
|
6159
|
+
}), socket.once("error", (error) => {
|
|
6160
|
+
clearTimeout(timer), reject(error);
|
|
6161
|
+
});
|
|
6162
|
+
}), new _CdpClient(socket);
|
|
6163
|
+
}
|
|
6164
|
+
call(method, params, timeoutMs) {
|
|
6165
|
+
let id = ++this.sequence;
|
|
6166
|
+
return new Promise((resolve5, reject) => {
|
|
6167
|
+
let timer = setTimeout(() => {
|
|
6168
|
+
this.pending.delete(id), reject(new Error(`Trae CN \u672C\u5730\u8C03\u7528\u8D85\u65F6: ${method}`));
|
|
6169
|
+
}, timeoutMs);
|
|
6170
|
+
this.pending.set(id, { resolve: resolve5, reject, timer }), this.socket.send(JSON.stringify({ id, method, params }));
|
|
6171
|
+
});
|
|
6172
|
+
}
|
|
6173
|
+
close() {
|
|
6174
|
+
this.socket.close();
|
|
6175
|
+
}
|
|
6176
|
+
rejectAll(error) {
|
|
6177
|
+
for (let entry of this.pending.values())
|
|
6178
|
+
clearTimeout(entry.timer), entry.reject(error);
|
|
6179
|
+
this.pending.clear();
|
|
6180
|
+
}
|
|
6181
|
+
};
|
|
6182
|
+
async function findWorkbenchTarget(port) {
|
|
6183
|
+
try {
|
|
6184
|
+
let response = await fetchWithTimeout(`http://127.0.0.1:${port}/json/list`, 1500);
|
|
6185
|
+
return response.ok ? (await response.json()).find((target) => target.type === "page" && target.url?.includes("workbench.html")) ?? null : null;
|
|
6186
|
+
} catch {
|
|
6187
|
+
return null;
|
|
6188
|
+
}
|
|
6189
|
+
}
|
|
6190
|
+
async function waitForWorkbench(port, timeoutMs) {
|
|
6191
|
+
let deadline = Date.now() + timeoutMs;
|
|
6192
|
+
for (; Date.now() < deadline; ) {
|
|
6193
|
+
let target = await findWorkbenchTarget(port);
|
|
6194
|
+
if (target) return target;
|
|
6195
|
+
await delay(500);
|
|
6196
|
+
}
|
|
6197
|
+
throw new Error("\u7B49\u5F85 Trae CN \u542F\u52A8\u8D85\u65F6");
|
|
6198
|
+
}
|
|
6199
|
+
async function waitForTraeUserIds(userDataDir, timeoutMs) {
|
|
6200
|
+
let deadline = Date.now() + timeoutMs;
|
|
6201
|
+
for (; Date.now() < deadline; ) {
|
|
6202
|
+
let ids = await findTraeUserIds(userDataDir);
|
|
6203
|
+
if (ids.length > 0) return ids;
|
|
6204
|
+
await delay(500);
|
|
6205
|
+
}
|
|
6206
|
+
return [];
|
|
6207
|
+
}
|
|
6208
|
+
async function findTraeUserIds(userDataDir) {
|
|
6209
|
+
let candidates = (await findCompletionLogs(join23(userDataDir, "logs"))).sort((a, b) => b.mtimeMs - a.mtimeMs).slice(0, 30), ids = /* @__PURE__ */ new Set(), legacyTokenPath = join23(homedir22(), ".trae-cn", "trae-jwt-token");
|
|
6210
|
+
if (existsSync2(legacyTokenPath))
|
|
6211
|
+
try {
|
|
6212
|
+
collectJwtUserIds(await readFileTail(legacyTokenPath), ids);
|
|
6213
|
+
} catch {
|
|
6214
|
+
}
|
|
6215
|
+
for (let candidate of candidates) {
|
|
6216
|
+
try {
|
|
6217
|
+
collectJwtUserIds(await readFileTail(candidate.path), ids);
|
|
6218
|
+
} catch {
|
|
6219
|
+
}
|
|
6220
|
+
if (ids.size >= 10) break;
|
|
6221
|
+
}
|
|
6222
|
+
return [...ids];
|
|
6223
|
+
}
|
|
6224
|
+
async function findCompletionLogs(dir) {
|
|
6225
|
+
let entries;
|
|
6226
|
+
try {
|
|
6227
|
+
entries = await readdir9(dir, { withFileTypes: !0 });
|
|
6228
|
+
} catch {
|
|
6229
|
+
return [];
|
|
6230
|
+
}
|
|
6231
|
+
let files = [];
|
|
6232
|
+
for (let entry of entries) {
|
|
6233
|
+
let path = join23(dir, entry.name);
|
|
6234
|
+
if (entry.isDirectory()) files.push(...await findCompletionLogs(path));
|
|
6235
|
+
else if (entry.name === "completion.log" && path.includes("trae.ai-code-completion"))
|
|
6236
|
+
try {
|
|
6237
|
+
files.push({ path, mtimeMs: (await stat5(path)).mtimeMs });
|
|
6238
|
+
} catch {
|
|
6239
|
+
}
|
|
6240
|
+
}
|
|
6241
|
+
return files;
|
|
6242
|
+
}
|
|
6243
|
+
async function readFileTail(path, maxBytes = 2 * 1024 * 1024) {
|
|
6244
|
+
let handle = await open3(path, "r");
|
|
6245
|
+
try {
|
|
6246
|
+
let size = (await handle.stat()).size, length = Math.min(size, maxBytes), buffer = Buffer.alloc(length);
|
|
6247
|
+
return await handle.read(buffer, 0, length, Math.max(0, size - length)), buffer.toString("utf8");
|
|
6248
|
+
} finally {
|
|
6249
|
+
await handle.close();
|
|
6250
|
+
}
|
|
6251
|
+
}
|
|
6252
|
+
function collectJwtUserIds(content, ids) {
|
|
6253
|
+
for (let token of content.match(JWT_PATTERN) ?? []) {
|
|
6254
|
+
let payloadPart = token.split(".")[1];
|
|
6255
|
+
if (payloadPart)
|
|
6256
|
+
try {
|
|
6257
|
+
let id = JSON.parse(Buffer.from(payloadPart, "base64url").toString("utf8")).data?.id;
|
|
6258
|
+
(typeof id == "string" || typeof id == "number") && String(id).trim() && ids.add(String(id));
|
|
6259
|
+
} catch {
|
|
6260
|
+
}
|
|
6261
|
+
}
|
|
6262
|
+
}
|
|
6263
|
+
async function writeCache(sessions, cacheDir) {
|
|
6264
|
+
await mkdir4(cacheDir, { recursive: !0, mode: 448 });
|
|
6265
|
+
for (let session of sessions) {
|
|
6266
|
+
let hash = createHash2("sha256").update(session.sessionId).digest("hex").slice(0, 32), destination = join23(cacheDir, `${hash}.json`), temporary = join23(cacheDir, `.${hash}.${process.pid}.tmp`);
|
|
6267
|
+
await writeFile4(temporary, `${JSON.stringify(session, null, 2)}
|
|
6268
|
+
`, { encoding: "utf8", mode: 384 }), await rename(temporary, destination);
|
|
6269
|
+
}
|
|
6270
|
+
}
|
|
6271
|
+
async function launchTrae(appPath, port) {
|
|
6272
|
+
await execFileAsync2("open", [
|
|
6273
|
+
"-g",
|
|
6274
|
+
"-j",
|
|
6275
|
+
"-na",
|
|
6276
|
+
appPath,
|
|
6277
|
+
"--args",
|
|
6278
|
+
`--remote-debugging-port=${port}`
|
|
6279
|
+
]);
|
|
6280
|
+
}
|
|
6281
|
+
async function quitTrae() {
|
|
6282
|
+
if (process.platform === "darwin")
|
|
6283
|
+
try {
|
|
6284
|
+
await execFileAsync2("osascript", ["-e", 'tell application id "cn.trae.app" to quit']);
|
|
6285
|
+
} catch {
|
|
6286
|
+
}
|
|
6287
|
+
}
|
|
6288
|
+
async function isTraeRunning() {
|
|
6289
|
+
try {
|
|
6290
|
+
return await execFileAsync2("pgrep", ["-x", "TRAE"]), !0;
|
|
6291
|
+
} catch {
|
|
6292
|
+
return !1;
|
|
6293
|
+
}
|
|
6294
|
+
}
|
|
6295
|
+
async function isPortAvailable(port) {
|
|
6296
|
+
return new Promise((resolve5) => {
|
|
6297
|
+
let server = createServer();
|
|
6298
|
+
server.once("error", () => resolve5(!1)), server.listen(port, "127.0.0.1", () => server.close(() => resolve5(!0)));
|
|
6299
|
+
});
|
|
6300
|
+
}
|
|
6301
|
+
async function findFreePort() {
|
|
6302
|
+
return new Promise((resolve5, reject) => {
|
|
6303
|
+
let server = createServer();
|
|
6304
|
+
server.once("error", reject), server.listen(0, "127.0.0.1", () => {
|
|
6305
|
+
let address = server.address(), port = typeof address == "object" && address ? address.port : 0;
|
|
6306
|
+
server.close((error) => error ? reject(error) : resolve5(port));
|
|
6307
|
+
});
|
|
6308
|
+
});
|
|
6309
|
+
}
|
|
6310
|
+
function resolveTraeCnUserDataDir() {
|
|
6311
|
+
return process.platform === "darwin" ? join23(homedir22(), "Library", "Application Support", "Trae CN") : process.platform === "win32" ? join23(process.env.APPDATA?.trim() || join23(homedir22(), "AppData", "Roaming"), "Trae CN") : join23(process.env.XDG_CONFIG_HOME?.trim() || join23(homedir22(), ".config"), "Trae CN");
|
|
6312
|
+
}
|
|
6313
|
+
async function fetchWithTimeout(url, timeoutMs) {
|
|
6314
|
+
let controller = new AbortController(), timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
6315
|
+
try {
|
|
6316
|
+
return await fetch(url, { signal: controller.signal });
|
|
6317
|
+
} finally {
|
|
6318
|
+
clearTimeout(timer);
|
|
6319
|
+
}
|
|
6320
|
+
}
|
|
6321
|
+
function normalizePort(value) {
|
|
6322
|
+
if (value != null)
|
|
6323
|
+
return Number.isInteger(value) && value > 0 && value <= 65535 ? value : void 0;
|
|
6324
|
+
}
|
|
6325
|
+
function clampTimeout(value) {
|
|
6326
|
+
return Number.isFinite(value) ? Math.min(18e4, Math.max(5e3, Math.floor(value))) : 12e4;
|
|
6327
|
+
}
|
|
6328
|
+
function sanitizeMessage(value) {
|
|
6329
|
+
return String(value ?? "").replace(/eyJ[A-Za-z0-9_.-]+/g, "<token>").replace(/[A-Za-z0-9_-]{24,}/g, "<id>").slice(0, 300);
|
|
6330
|
+
}
|
|
6331
|
+
function tokenValue2(value) {
|
|
6332
|
+
let number = typeof value == "number" ? value : Number(value);
|
|
6333
|
+
return Number.isFinite(number) && number > 0 ? Math.floor(number) : 0;
|
|
6334
|
+
}
|
|
6335
|
+
function stringValue4(value) {
|
|
6336
|
+
return typeof value == "string" ? value.trim() : "";
|
|
6337
|
+
}
|
|
6338
|
+
function delay(ms) {
|
|
6339
|
+
return new Promise((resolve5) => setTimeout(resolve5, ms));
|
|
6340
|
+
}
|
|
6341
|
+
|
|
5046
6342
|
// src/cli.ts
|
|
5047
6343
|
var argv = process.argv.slice(2), command = argv[0];
|
|
5048
6344
|
await (async () => {
|
|
@@ -5073,6 +6369,15 @@ await (async () => {
|
|
|
5073
6369
|
let parsed = parseArgs(argv.slice(1));
|
|
5074
6370
|
if (parsed.flags.help) return helpForSubcommand("sync");
|
|
5075
6371
|
await runSync(parsed.flags, parsed.positionals);
|
|
6372
|
+
} else if (command === "trae") {
|
|
6373
|
+
let sub = argv[1], parsed = parseArgs(argv.slice(2));
|
|
6374
|
+
if (sub === "--help" || sub === "-h" || parsed.flags.help) return helpForSubcommand("trae");
|
|
6375
|
+
if (sub === "sync")
|
|
6376
|
+
await runTraeSync(parsed.flags, parsed.positionals);
|
|
6377
|
+
else {
|
|
6378
|
+
let zh2 = (await readConfig()).lang === "zh";
|
|
6379
|
+
throw new Error(zh2 ? "\u7528\u6CD5: aiusage trae sync [--port 9230] [--no-launch] [--json]" : "Usage: aiusage trae sync [--port 9230] [--no-launch] [--json]");
|
|
6380
|
+
}
|
|
5076
6381
|
} else if (command === "init") {
|
|
5077
6382
|
let parsed = parseArgs(argv.slice(1));
|
|
5078
6383
|
if (parsed.flags.help) return helpForSubcommand("init");
|
|
@@ -5254,9 +6559,9 @@ async function runEnroll(flags) {
|
|
|
5254
6559
|
}
|
|
5255
6560
|
function prompt(question) {
|
|
5256
6561
|
let rl = createInterface4({ input: process.stdin, output: process.stdout });
|
|
5257
|
-
return new Promise((
|
|
6562
|
+
return new Promise((resolve5) => {
|
|
5258
6563
|
rl.question(question, (answer) => {
|
|
5259
|
-
rl.close(),
|
|
6564
|
+
rl.close(), resolve5(answer.trim());
|
|
5260
6565
|
});
|
|
5261
6566
|
});
|
|
5262
6567
|
}
|
|
@@ -5311,6 +6616,24 @@ async function runSync(flags, positionals = []) {
|
|
|
5311
6616
|
results: uploadResults
|
|
5312
6617
|
}, null, 2));
|
|
5313
6618
|
}
|
|
6619
|
+
async function runTraeSync(flags, positionals = []) {
|
|
6620
|
+
let zh2 = (await readConfig()).lang === "zh";
|
|
6621
|
+
assertNoPositionals("trae sync", positionals, zh2);
|
|
6622
|
+
let portFlag = resolveOptionalString(flags.port, void 0), port = portFlag ? parsePositiveInt2(portFlag, "--port") : void 0;
|
|
6623
|
+
if (port != null && port > 65535) throw new Error("--port \u5FC5\u987B\u5728 1 \u5230 65535 \u4E4B\u95F4");
|
|
6624
|
+
flags.json || console.log(zh2 ? "\u6B63\u5728\u901A\u8FC7 Trae CN \u5B98\u65B9\u672C\u5730\u63A5\u53E3\u540C\u6B65\u5386\u53F2\u7528\u91CF\u2026" : "Syncing Trae CN history through its official local interface\u2026");
|
|
6625
|
+
let result = await syncTraeCnUsage({
|
|
6626
|
+
port,
|
|
6627
|
+
appPath: resolveOptionalString(flags.app, void 0),
|
|
6628
|
+
launch: flags["no-launch"] !== !0
|
|
6629
|
+
});
|
|
6630
|
+
if (flags.json) {
|
|
6631
|
+
console.log(JSON.stringify(result, null, 2));
|
|
6632
|
+
return;
|
|
6633
|
+
}
|
|
6634
|
+
console.log(zh2 ? `\u5DF2\u540C\u6B65 ${result.sessions} \u4E2A\u4F1A\u8BDD\u3001${result.events} \u6761\u7528\u91CF\u8BB0\u5F55\uFF0C\u5171 ${fmt2(result.totals.totalTokens)} tokens\u3002` : `Synced ${result.sessions} sessions and ${result.events} usage records (${fmt2(result.totals.totalTokens)} tokens).`), console.log(`${zh2 ? "\u7F13\u5B58" : "Cache"}: ${result.cacheDir}`);
|
|
6635
|
+
for (let warning of result.warnings) console.warn(`${zh2 ? "\u8B66\u544A" : "Warning"}: ${warning}`);
|
|
6636
|
+
}
|
|
5314
6637
|
function buildActivityPayloadByDate(items, visibility) {
|
|
5315
6638
|
let map = /* @__PURE__ */ new Map(), sanitized = applyProjectPrivacy(items, visibility);
|
|
5316
6639
|
for (let item of sanitized) {
|
|
@@ -5513,6 +6836,7 @@ function printHelp(zh2 = !1) {
|
|
|
5513
6836
|
["report [--today] [--range 7d|1m|3m|all] [--detail] [--json]", "\u672C\u5730\u7528\u91CF\u62A5\u544A"],
|
|
5514
6837
|
["activity [--today] [--range 7d|1m|3m|all] [--detail] [--json]", "\u672C\u5730\u4EA4\u4E92\u6307\u6807"],
|
|
5515
6838
|
["sync [--today] [--range 7d|1m|3m]", "\u4E0A\u4F20\u7528\u91CF\u5230\u670D\u52A1\u7AEF"],
|
|
6839
|
+
["trae sync [--port 9230] [--no-launch]", "\u540C\u6B65 Trae CN \u672C\u5730\u5386\u53F2\u7528\u91CF"],
|
|
5516
6840
|
["scan/report/sync --from YYYY-MM-DD [--to YYYY-MM-DD]", "\u6307\u5B9A\u65E5\u671F\u8303\u56F4\uFF08--start/--end \u540C\u4E49\uFF09"],
|
|
5517
6841
|
["project [list|alias]", "\u9879\u76EE\u7BA1\u7406\u4E0E\u522B\u540D\u8BBE\u7F6E"],
|
|
5518
6842
|
["pricing [status|update] [--url URL]", "\u67E5\u770B/\u66F4\u65B0\u5B9A\u4EF7\u76EE\u5F55"],
|
|
@@ -5527,6 +6851,7 @@ function printHelp(zh2 = !1) {
|
|
|
5527
6851
|
["report [--today] [--range 7d|1m|3m|all] [--detail] [--json]", "Local usage report"],
|
|
5528
6852
|
["activity [--today] [--range 7d|1m|3m|all] [--detail] [--json]", "Local interaction metrics"],
|
|
5529
6853
|
["sync [--today] [--range 7d|1m|3m]", "Upload usage to server"],
|
|
6854
|
+
["trae sync [--port 9230] [--no-launch]", "Sync local Trae CN history"],
|
|
5530
6855
|
["scan/report/sync --from YYYY-MM-DD [--to YYYY-MM-DD]", "Date range (--start/--end aliases)"],
|
|
5531
6856
|
["project [list|alias]", "Project management & aliases"],
|
|
5532
6857
|
["pricing [status|update] [--url URL]", "Pricing catalog management"],
|
|
@@ -5550,6 +6875,7 @@ function printUsageHint(zh2 = !1) {
|
|
|
5550
6875
|
["report [--today] [--range 7d|1m|3m|all]", "\u672C\u5730\u7528\u91CF\u62A5\u544A"],
|
|
5551
6876
|
["activity [--range 7d|1m|3m|all]", "\u672C\u5730\u4EA4\u4E92\u6307\u6807"],
|
|
5552
6877
|
["sync [--today] [--range 7d|1m|3m]", "\u4E0A\u4F20\u7528\u91CF\u5230\u670D\u52A1\u7AEF"],
|
|
6878
|
+
["trae sync", "\u540C\u6B65 Trae CN \u672C\u5730\u5386\u53F2\u7528\u91CF"],
|
|
5553
6879
|
["project [list|alias]", "\u9879\u76EE\u7BA1\u7406\u4E0E\u522B\u540D\u8BBE\u7F6E"],
|
|
5554
6880
|
["pricing [status|update]", "\u67E5\u770B/\u66F4\u65B0\u5B9A\u4EF7\u76EE\u5F55"],
|
|
5555
6881
|
["schedule [on|off|status]", "\u5B9A\u65F6\u540C\u6B65\u7BA1\u7406"],
|
|
@@ -5560,6 +6886,7 @@ function printUsageHint(zh2 = !1) {
|
|
|
5560
6886
|
["report [--today] [--range 7d|1m|3m|all]", "Local usage report"],
|
|
5561
6887
|
["activity [--range 7d|1m|3m|all]", "Local interaction metrics"],
|
|
5562
6888
|
["sync [--today] [--range 7d|1m|3m]", "Upload usage to server"],
|
|
6889
|
+
["trae sync", "Sync local Trae CN history"],
|
|
5563
6890
|
["project [list|alias]", "Project management & aliases"],
|
|
5564
6891
|
["pricing [status|update]", "Pricing catalog management"],
|
|
5565
6892
|
["schedule [on|off|status]", "Scheduled sync management"],
|