@aiusage/cli 1.7.3 → 1.7.4
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 +25 -6
- package/dist/cli.js +1295 -618
- package/package.json +1 -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 [];
|
|
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));
|
|
1999
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
|
-
|
|
2361
|
-
let
|
|
2362
|
-
for (let filePath of threadFiles) {
|
|
2363
|
-
let raw;
|
|
2364
|
-
try {
|
|
2365
|
-
raw = await readFile9(filePath, "utf-8");
|
|
2366
|
-
} catch {
|
|
2367
|
-
continue;
|
|
2368
|
-
}
|
|
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);
|
|
2835
|
+
let grouped = initDateMap(dates);
|
|
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((resolve4, reject) => {
|
|
3105
|
+
execFile(
|
|
3106
|
+
"sqlite3",
|
|
3107
|
+
args,
|
|
3108
|
+
{ encoding: "utf8", maxBuffer: 64 * 1024 * 1024 },
|
|
3109
|
+
(error, stdout) => error ? reject(error) : resolve4(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,15 +3238,15 @@ 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
3245
|
return finalize(grouped);
|
|
2636
3246
|
}
|
|
2637
|
-
function
|
|
3247
|
+
function getSessionDirs() {
|
|
2638
3248
|
let envDir = process.env.PI_CODING_AGENT_DIR;
|
|
2639
|
-
return envDir ?
|
|
3249
|
+
return [envDir ? join14(envDir, "sessions") : join14(homedir13(), ".pi", "agent", "sessions"), join14(homedir13(), ".omp", "agent", "sessions")];
|
|
2640
3250
|
}
|
|
2641
3251
|
function extractProjectFromEncoded(encoded) {
|
|
2642
3252
|
let parts = encoded.split("-").filter(Boolean);
|
|
@@ -2777,7 +3387,7 @@ function chunkDateRange(startDate, endDate) {
|
|
|
2777
3387
|
}
|
|
2778
3388
|
|
|
2779
3389
|
// src/scanners/anthropic-csv.ts
|
|
2780
|
-
import { readFile as
|
|
3390
|
+
import { readFile as readFile12 } from "node:fs/promises";
|
|
2781
3391
|
async function scanAnthropicCsvDates(targetDates, csvFilePaths) {
|
|
2782
3392
|
if (!targetDates.length) return /* @__PURE__ */ new Map();
|
|
2783
3393
|
let targetDateSet = new Set(targetDates), grouped = new Map(
|
|
@@ -2786,7 +3396,7 @@ async function scanAnthropicCsvDates(targetDates, csvFilePaths) {
|
|
|
2786
3396
|
for (let filePath of csvFilePaths) {
|
|
2787
3397
|
let content;
|
|
2788
3398
|
try {
|
|
2789
|
-
content = await
|
|
3399
|
+
content = await readFile12(filePath, "utf-8");
|
|
2790
3400
|
} catch {
|
|
2791
3401
|
continue;
|
|
2792
3402
|
}
|
|
@@ -2844,9 +3454,9 @@ function parseCsv(content) {
|
|
|
2844
3454
|
}
|
|
2845
3455
|
|
|
2846
3456
|
// src/report.ts
|
|
2847
|
-
import { readdir as
|
|
3457
|
+
import { readdir as readdir5, readFile as readFile13 } from "node:fs/promises";
|
|
2848
3458
|
import { homedir as homedir14 } from "node:os";
|
|
2849
|
-
import { basename as
|
|
3459
|
+
import { basename as basename11, dirname as dirname6, join as join15 } from "node:path";
|
|
2850
3460
|
async function buildLocalReport(range, options = {}) {
|
|
2851
3461
|
let requestedDates = options.dates ? options.dates : range === "all" ? await discoverAllDates() : range === "today" ? [dateKey(getTodayLocalDate())] : buildPresetDates(range), daily = [], totals = createEmptyTotals2(), bySource = /* @__PURE__ */ new Map(), byModel = /* @__PURE__ */ new Map(), pricingWarnings = /* @__PURE__ */ new Set(), daysWithData = 0, results = await scanDates(requestedDates, { projectAliases: options.projectAliases });
|
|
2852
3462
|
for (let result of results) {
|
|
@@ -2915,42 +3525,61 @@ function buildPresetDates(range) {
|
|
|
2915
3525
|
}
|
|
2916
3526
|
async function discoverAllDates() {
|
|
2917
3527
|
let dates = /* @__PURE__ */ new Set(), home = homedir14();
|
|
2918
|
-
|
|
3528
|
+
await Promise.all([
|
|
2919
3529
|
discoverClaudeDates(dates),
|
|
2920
3530
|
discoverCodexDates(dates),
|
|
2921
3531
|
discoverGeminiDates(dates),
|
|
2922
3532
|
discoverCopilotVscodeDates(dates),
|
|
2923
3533
|
discoverAntigravityDates(dates),
|
|
2924
|
-
discoverGenericJsonlDates(
|
|
2925
|
-
discoverGenericJsonlDates(
|
|
2926
|
-
discoverGenericJsonlDates(
|
|
2927
|
-
discoverGenericJsonlDates(
|
|
2928
|
-
|
|
2929
|
-
discoverGenericJsonlDates(
|
|
2930
|
-
discoverGenericJsonDates(
|
|
2931
|
-
|
|
2932
|
-
|
|
3534
|
+
discoverGenericJsonlDates(join15(home, ".copilot", "session-state"), dates),
|
|
3535
|
+
discoverGenericJsonlDates(join15(home, ".copilot", "otel"), dates),
|
|
3536
|
+
discoverGenericJsonlDates(join15(home, ".qwen", "tmp"), dates),
|
|
3537
|
+
discoverGenericJsonlDates(join15(home, ".qwen", "projects"), dates),
|
|
3538
|
+
discoverGenericJsonlDates(join15(home, ".kimi", "sessions"), dates),
|
|
3539
|
+
discoverGenericJsonlDates(join15(resolveKimiCodeHome(home), "sessions"), dates),
|
|
3540
|
+
discoverGenericJsonDates(join15(home, ".local", "share", "amp", "threads"), dates),
|
|
3541
|
+
discoverGenericJsonDates(join15(home, ".factory", "sessions"), dates),
|
|
3542
|
+
discoverOpenCodeUsageDates().then((found) => found.forEach((date) => dates.add(date))),
|
|
3543
|
+
discoverGenericJsonlDates(join15(home, ".pi", "agent", "sessions"), dates),
|
|
3544
|
+
discoverGenericJsonlDates(join15(home, ".omp", "agent", "sessions"), dates)
|
|
3545
|
+
]);
|
|
3546
|
+
let explicitCopilotOtel = process.env.COPILOT_OTEL_FILE_EXPORTER_PATH?.trim();
|
|
3547
|
+
return explicitCopilotOtel && await discoverJsonlFileDates(explicitCopilotOtel, dates), [...dates].sort();
|
|
2933
3548
|
}
|
|
2934
3549
|
async function discoverGenericJsonlDates(baseDir, dates) {
|
|
2935
3550
|
let files = [];
|
|
2936
3551
|
await walkForFiles(baseDir, ".jsonl", files);
|
|
2937
3552
|
for (let filePath of files) {
|
|
2938
3553
|
let content = await safeReadUtf8(filePath);
|
|
2939
|
-
if (content)
|
|
2940
|
-
|
|
3554
|
+
if (!content) continue;
|
|
3555
|
+
let foundDate = !1;
|
|
3556
|
+
for (let line of content.split(`
|
|
2941
3557
|
`)) {
|
|
2942
|
-
|
|
2943
|
-
|
|
2944
|
-
|
|
2945
|
-
|
|
2946
|
-
|
|
2947
|
-
|
|
2948
|
-
}
|
|
2949
|
-
let ts = parseTs(record.timestamp ?? record.time ?? record.created_at);
|
|
2950
|
-
ts && dates.add(dateKey(ts));
|
|
3558
|
+
if (!line.trim()) continue;
|
|
3559
|
+
let record;
|
|
3560
|
+
try {
|
|
3561
|
+
record = JSON.parse(line);
|
|
3562
|
+
} catch {
|
|
3563
|
+
continue;
|
|
2951
3564
|
}
|
|
3565
|
+
foundDate = collectRecordDates(record, dates) || foundDate;
|
|
3566
|
+
}
|
|
3567
|
+
foundDate || await addFileModifiedDate(filePath, dates);
|
|
2952
3568
|
}
|
|
2953
3569
|
}
|
|
3570
|
+
async function discoverJsonlFileDates(filePath, dates) {
|
|
3571
|
+
let content = await safeReadUtf8(filePath);
|
|
3572
|
+
if (!content) return;
|
|
3573
|
+
let foundDate = !1;
|
|
3574
|
+
for (let line of content.split(`
|
|
3575
|
+
`))
|
|
3576
|
+
if (line.trim())
|
|
3577
|
+
try {
|
|
3578
|
+
foundDate = collectRecordDates(JSON.parse(line), dates) || foundDate;
|
|
3579
|
+
} catch {
|
|
3580
|
+
}
|
|
3581
|
+
foundDate || await addFileModifiedDate(filePath, dates);
|
|
3582
|
+
}
|
|
2954
3583
|
async function discoverGenericJsonDates(baseDir, dates) {
|
|
2955
3584
|
let files = [];
|
|
2956
3585
|
await walkForFiles(baseDir, ".json", files);
|
|
@@ -2963,78 +3592,84 @@ async function discoverGenericJsonDates(baseDir, dates) {
|
|
|
2963
3592
|
} catch {
|
|
2964
3593
|
continue;
|
|
2965
3594
|
}
|
|
2966
|
-
|
|
2967
|
-
|
|
2968
|
-
|
|
2969
|
-
|
|
2970
|
-
|
|
2971
|
-
|
|
2972
|
-
|
|
2973
|
-
|
|
3595
|
+
(Array.isArray(data) ? data.reduce((found, row) => collectRecordDates(row, dates) || found, !1) : collectRecordDates(data, dates)) || await addFileModifiedDate(filePath, dates);
|
|
3596
|
+
}
|
|
3597
|
+
}
|
|
3598
|
+
function collectRecordDates(record, dates) {
|
|
3599
|
+
if (!record || typeof record != "object") return !1;
|
|
3600
|
+
let found = !1, candidates = [
|
|
3601
|
+
record.timestamp,
|
|
3602
|
+
record.time,
|
|
3603
|
+
record.created_at,
|
|
3604
|
+
record.createTime,
|
|
3605
|
+
record.startTime,
|
|
3606
|
+
record.lastUpdated,
|
|
3607
|
+
record.created,
|
|
3608
|
+
record.providerLockTimestamp,
|
|
3609
|
+
record.endTime,
|
|
3610
|
+
record.hrTime,
|
|
3611
|
+
record._hrTime,
|
|
3612
|
+
record.observedTimestamp,
|
|
3613
|
+
record.timeUnixNano,
|
|
3614
|
+
record.time?.created
|
|
3615
|
+
];
|
|
3616
|
+
for (let value of candidates) {
|
|
3617
|
+
let ts = parseStructuredTs(value);
|
|
3618
|
+
ts && (dates.add(dateKey(ts)), found = !0);
|
|
3619
|
+
}
|
|
3620
|
+
let nestedRows = [
|
|
3621
|
+
...Array.isArray(record.messages) ? record.messages : [],
|
|
3622
|
+
...Array.isArray(record.history) ? record.history : [],
|
|
3623
|
+
...Array.isArray(record.data?.messages) ? record.data.messages : [],
|
|
3624
|
+
...Array.isArray(record.data?.history) ? record.data.history : [],
|
|
3625
|
+
...Array.isArray(record.$set?.messages) ? record.$set.messages : [],
|
|
3626
|
+
...Array.isArray(record.usageLedger?.events) ? record.usageLedger.events : []
|
|
3627
|
+
];
|
|
3628
|
+
for (let row of nestedRows) found = collectRecordDates(row, dates) || found;
|
|
3629
|
+
return found;
|
|
3630
|
+
}
|
|
3631
|
+
function parseStructuredTs(value) {
|
|
3632
|
+
if (Array.isArray(value) && value.length > 0) {
|
|
3633
|
+
let seconds = Number(value[0]), nanos = Number(value[1] ?? 0);
|
|
3634
|
+
if (Number.isFinite(seconds) && Number.isFinite(nanos))
|
|
3635
|
+
return parseTs(seconds * 1e3 + nanos / 1e6);
|
|
2974
3636
|
}
|
|
3637
|
+
if (typeof value == "number" || typeof value == "string" && /^\d+(?:\.\d+)?$/.test(value)) {
|
|
3638
|
+
let raw = Number(value);
|
|
3639
|
+
if (!Number.isFinite(raw) || raw <= 0) return null;
|
|
3640
|
+
let abs = Math.abs(raw), millis = abs >= 1e17 ? raw / 1e6 : abs >= 1e14 ? raw / 1e3 : raw;
|
|
3641
|
+
return parseTs(millis);
|
|
3642
|
+
}
|
|
3643
|
+
return parseTs(value);
|
|
3644
|
+
}
|
|
3645
|
+
async function addFileModifiedDate(filePath, dates) {
|
|
3646
|
+
let timestamp = await fileModifiedTs(filePath);
|
|
3647
|
+
timestamp && dates.add(dateKey(timestamp));
|
|
2975
3648
|
}
|
|
2976
3649
|
async function walkForFiles(dir, ext, result) {
|
|
2977
3650
|
let entries;
|
|
2978
3651
|
try {
|
|
2979
|
-
entries = await
|
|
3652
|
+
entries = await readdir5(dir, { withFileTypes: !0 });
|
|
2980
3653
|
} catch {
|
|
2981
3654
|
return;
|
|
2982
3655
|
}
|
|
2983
3656
|
for (let entry of entries) {
|
|
2984
|
-
let fullPath =
|
|
3657
|
+
let fullPath = join15(dir, entry.name);
|
|
2985
3658
|
entry.isDirectory() ? await walkForFiles(fullPath, ext, result) : entry.name.endsWith(ext) && result.push(fullPath);
|
|
2986
3659
|
}
|
|
2987
3660
|
}
|
|
2988
3661
|
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
|
-
}
|
|
3662
|
+
let baseDir = join15(homedir14(), ".gemini", "tmp");
|
|
3663
|
+
await Promise.all([
|
|
3664
|
+
discoverGenericJsonDates(baseDir, dates),
|
|
3665
|
+
discoverGenericJsonlDates(baseDir, dates)
|
|
3666
|
+
]);
|
|
3032
3667
|
}
|
|
3033
3668
|
async function discoverCopilotVscodeDates(dates) {
|
|
3034
3669
|
let home = homedir14(), logFiles = [];
|
|
3035
|
-
await walkForFiles(
|
|
3670
|
+
await walkForFiles(join15(home, "Library", "Application Support", "Code", "logs"), ".log", logFiles);
|
|
3036
3671
|
for (let filePath of logFiles) {
|
|
3037
|
-
if (
|
|
3672
|
+
if (basename11(filePath) !== "GitHub Copilot Chat.log") continue;
|
|
3038
3673
|
let content = await safeReadUtf8(filePath);
|
|
3039
3674
|
if (content)
|
|
3040
3675
|
for (let line of content.split(`
|
|
@@ -3045,9 +3680,9 @@ async function discoverCopilotVscodeDates(dates) {
|
|
|
3045
3680
|
}
|
|
3046
3681
|
}
|
|
3047
3682
|
let sessionFiles = [];
|
|
3048
|
-
await walkForFiles(
|
|
3683
|
+
await walkForFiles(join15(home, "Library", "Application Support", "Code", "User", "workspaceStorage"), ".json", sessionFiles);
|
|
3049
3684
|
for (let filePath of sessionFiles) {
|
|
3050
|
-
if (!filePath
|
|
3685
|
+
if (!isChatSessionFile2(filePath)) continue;
|
|
3051
3686
|
let content = await safeReadUtf8(filePath);
|
|
3052
3687
|
if (!content) continue;
|
|
3053
3688
|
let session;
|
|
@@ -3062,12 +3697,44 @@ async function discoverCopilotVscodeDates(dates) {
|
|
|
3062
3697
|
ts && dates.add(dateKey(ts));
|
|
3063
3698
|
}
|
|
3064
3699
|
}
|
|
3700
|
+
let crdtFiles = [];
|
|
3701
|
+
await walkForFiles(
|
|
3702
|
+
join15(home, "Library", "Application Support", "Code", "User", "workspaceStorage"),
|
|
3703
|
+
".jsonl",
|
|
3704
|
+
crdtFiles
|
|
3705
|
+
);
|
|
3706
|
+
for (let filePath of crdtFiles) {
|
|
3707
|
+
if (!isChatSessionFile2(filePath)) continue;
|
|
3708
|
+
let content = await safeReadUtf8(filePath);
|
|
3709
|
+
if (content)
|
|
3710
|
+
for (let line of content.split(`
|
|
3711
|
+
`)) {
|
|
3712
|
+
if (!line.trim()) continue;
|
|
3713
|
+
let record;
|
|
3714
|
+
try {
|
|
3715
|
+
record = JSON.parse(line);
|
|
3716
|
+
} catch {
|
|
3717
|
+
continue;
|
|
3718
|
+
}
|
|
3719
|
+
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 : [];
|
|
3720
|
+
for (let value of requests) {
|
|
3721
|
+
if (!value || typeof value != "object" || Array.isArray(value)) continue;
|
|
3722
|
+
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;
|
|
3723
|
+
if (!isCopilot || !hasTokens) continue;
|
|
3724
|
+
let ts = parseTs(request.timestamp);
|
|
3725
|
+
ts && dates.add(dateKey(ts));
|
|
3726
|
+
}
|
|
3727
|
+
}
|
|
3728
|
+
}
|
|
3729
|
+
}
|
|
3730
|
+
function isChatSessionFile2(filePath) {
|
|
3731
|
+
return basename11(dirname6(filePath)) === "chatSessions";
|
|
3065
3732
|
}
|
|
3066
3733
|
async function discoverAntigravityDates(dates) {
|
|
3067
3734
|
let home = homedir14(), brainFiles = [], browserFiles = [];
|
|
3068
|
-
await walkForFiles(
|
|
3735
|
+
await walkForFiles(join15(home, ".gemini", "antigravity", "brain"), ".json", brainFiles), await walkForFiles(join15(home, ".gemini", "antigravity", "browser_recordings"), ".json", browserFiles);
|
|
3069
3736
|
for (let filePath of brainFiles) {
|
|
3070
|
-
if (
|
|
3737
|
+
if (basename11(filePath) !== "task.md.metadata.json") continue;
|
|
3071
3738
|
let content = await safeReadUtf8(filePath);
|
|
3072
3739
|
if (!content) continue;
|
|
3073
3740
|
let data;
|
|
@@ -3080,7 +3747,7 @@ async function discoverAntigravityDates(dates) {
|
|
|
3080
3747
|
ts && dates.add(dateKey(ts));
|
|
3081
3748
|
}
|
|
3082
3749
|
for (let filePath of browserFiles) {
|
|
3083
|
-
if (
|
|
3750
|
+
if (basename11(filePath) !== "metadata.json") continue;
|
|
3084
3751
|
let content = await safeReadUtf8(filePath);
|
|
3085
3752
|
if (!content) continue;
|
|
3086
3753
|
let data;
|
|
@@ -3095,20 +3762,20 @@ async function discoverAntigravityDates(dates) {
|
|
|
3095
3762
|
}
|
|
3096
3763
|
async function discoverClaudeDates(dates) {
|
|
3097
3764
|
let home = homedir14(), baseDirs = [
|
|
3098
|
-
|
|
3099
|
-
|
|
3765
|
+
join15(home, ".config", "claude", "projects"),
|
|
3766
|
+
join15(home, ".claude", "projects")
|
|
3100
3767
|
];
|
|
3101
3768
|
for (let baseDir of baseDirs) {
|
|
3102
3769
|
let projectDirs;
|
|
3103
3770
|
try {
|
|
3104
|
-
projectDirs = await
|
|
3771
|
+
projectDirs = await readdir5(baseDir);
|
|
3105
3772
|
} catch {
|
|
3106
3773
|
continue;
|
|
3107
3774
|
}
|
|
3108
3775
|
for (let projectDir of projectDirs) {
|
|
3109
3776
|
let jsonlFiles = [];
|
|
3110
3777
|
try {
|
|
3111
|
-
await walkForClaudeJsonl(
|
|
3778
|
+
await walkForClaudeJsonl(join15(baseDir, projectDir), jsonlFiles);
|
|
3112
3779
|
} catch {
|
|
3113
3780
|
continue;
|
|
3114
3781
|
}
|
|
@@ -3132,7 +3799,7 @@ async function discoverClaudeDates(dates) {
|
|
|
3132
3799
|
}
|
|
3133
3800
|
}
|
|
3134
3801
|
async function discoverCodexDates(dates) {
|
|
3135
|
-
let baseDir =
|
|
3802
|
+
let baseDir = join15(homedir14(), ".codex"), files = await collectCodexSessionFiles(baseDir);
|
|
3136
3803
|
for (let filePath of files) {
|
|
3137
3804
|
let content = await safeReadUtf8(filePath);
|
|
3138
3805
|
if (content)
|
|
@@ -3154,35 +3821,35 @@ async function discoverCodexDates(dates) {
|
|
|
3154
3821
|
async function collectCodexSessionFiles(baseDir) {
|
|
3155
3822
|
let paths = [];
|
|
3156
3823
|
try {
|
|
3157
|
-
let archivedFiles = await
|
|
3824
|
+
let archivedFiles = await readdir5(join15(baseDir, "archived_sessions"));
|
|
3158
3825
|
for (let file of archivedFiles)
|
|
3159
|
-
file.endsWith(".jsonl") && paths.push(
|
|
3826
|
+
file.endsWith(".jsonl") && paths.push(join15(baseDir, "archived_sessions", file));
|
|
3160
3827
|
} catch {
|
|
3161
3828
|
}
|
|
3162
|
-
return await walkForCodexJsonl(
|
|
3829
|
+
return await walkForCodexJsonl(join15(baseDir, "sessions"), paths), paths;
|
|
3163
3830
|
}
|
|
3164
3831
|
async function walkForClaudeJsonl(dir, result) {
|
|
3165
|
-
let entries = await
|
|
3832
|
+
let entries = await readdir5(dir, { withFileTypes: !0 });
|
|
3166
3833
|
for (let entry of entries) {
|
|
3167
|
-
let fullPath =
|
|
3834
|
+
let fullPath = join15(dir, entry.name);
|
|
3168
3835
|
entry.isDirectory() ? await walkForClaudeJsonl(fullPath, result) : entry.name.endsWith(".jsonl") && result.push(fullPath);
|
|
3169
3836
|
}
|
|
3170
3837
|
}
|
|
3171
3838
|
async function walkForCodexJsonl(dir, result) {
|
|
3172
3839
|
let entries;
|
|
3173
3840
|
try {
|
|
3174
|
-
entries = await
|
|
3841
|
+
entries = await readdir5(dir, { withFileTypes: !0 });
|
|
3175
3842
|
} catch {
|
|
3176
3843
|
return;
|
|
3177
3844
|
}
|
|
3178
3845
|
for (let entry of entries) {
|
|
3179
|
-
let fullPath =
|
|
3846
|
+
let fullPath = join15(dir, entry.name);
|
|
3180
3847
|
entry.isDirectory() ? await walkForCodexJsonl(fullPath, result) : entry.name.startsWith("rollout-") && entry.name.endsWith(".jsonl") && result.push(fullPath);
|
|
3181
3848
|
}
|
|
3182
3849
|
}
|
|
3183
3850
|
async function safeReadUtf8(filePath) {
|
|
3184
3851
|
try {
|
|
3185
|
-
return await
|
|
3852
|
+
return await readFile13(filePath, "utf-8");
|
|
3186
3853
|
} catch {
|
|
3187
3854
|
return null;
|
|
3188
3855
|
}
|
|
@@ -3466,10 +4133,10 @@ function fmtDateShort(dateStr) {
|
|
|
3466
4133
|
}
|
|
3467
4134
|
|
|
3468
4135
|
// src/activity.ts
|
|
3469
|
-
import { open
|
|
4136
|
+
import { open, readdir as readdir6 } from "node:fs/promises";
|
|
3470
4137
|
import { createInterface as createInterface3 } from "node:readline";
|
|
3471
4138
|
import { homedir as homedir15 } from "node:os";
|
|
3472
|
-
import { basename as
|
|
4139
|
+
import { basename as basename12, join as join16 } from "node:path";
|
|
3473
4140
|
var FILE_CONCURRENCY3 = 16, MAX_LINE_BYTES3 = 64 * 1024 * 1024;
|
|
3474
4141
|
async function buildActivityReport(range, options = {}) {
|
|
3475
4142
|
let targetDates = options.dates ? new Set(options.dates) : void 0, [codex, claude] = await Promise.all([
|
|
@@ -3566,7 +4233,7 @@ function renderActivityReport(report, opts) {
|
|
|
3566
4233
|
`);
|
|
3567
4234
|
}
|
|
3568
4235
|
async function scanCodexActivity(targetDates, options) {
|
|
3569
|
-
let baseDir = options.codexDir ??
|
|
4236
|
+
let baseDir = options.codexDir ?? join16(homedir15(), ".codex"), acc = createAccumulator(targetDates, options.projectAliases), files = await collectCodexSessionFiles2(baseDir);
|
|
3570
4237
|
return acc.stats.filesScanned = files.length, await runWithConcurrency(files, FILE_CONCURRENCY3, async (filePath) => {
|
|
3571
4238
|
await processCodexFile2(filePath, acc);
|
|
3572
4239
|
}), finalizeActivity(acc);
|
|
@@ -3574,11 +4241,11 @@ async function scanCodexActivity(targetDates, options) {
|
|
|
3574
4241
|
async function processCodexFile2(filePath, acc) {
|
|
3575
4242
|
let fh;
|
|
3576
4243
|
try {
|
|
3577
|
-
fh = await
|
|
4244
|
+
fh = await open(filePath, "r");
|
|
3578
4245
|
} catch {
|
|
3579
4246
|
return;
|
|
3580
4247
|
}
|
|
3581
|
-
let sessionId =
|
|
4248
|
+
let sessionId = basename12(filePath).replace(/\.jsonl$/, ""), projectFields = { project: "unknown", projectDisplay: "unknown" };
|
|
3582
4249
|
try {
|
|
3583
4250
|
let rl = createInterface3({
|
|
3584
4251
|
input: fh.createReadStream({ encoding: "utf-8" }),
|
|
@@ -3593,12 +4260,12 @@ async function processCodexFile2(filePath, acc) {
|
|
|
3593
4260
|
continue;
|
|
3594
4261
|
}
|
|
3595
4262
|
if (record.type === "session_meta") {
|
|
3596
|
-
let id =
|
|
4263
|
+
let id = stringValue2(record.payload?.id);
|
|
3597
4264
|
id && (sessionId = id), acc.stats.sessions.add(`codex:${sessionId}`);
|
|
3598
4265
|
continue;
|
|
3599
4266
|
}
|
|
3600
4267
|
if (record.type === "turn_context") {
|
|
3601
|
-
let cwd =
|
|
4268
|
+
let cwd = stringValue2(record.payload?.cwd);
|
|
3602
4269
|
cwd && (projectFields = resolveProjectFields(cwd, acc.projectAliases));
|
|
3603
4270
|
continue;
|
|
3604
4271
|
}
|
|
@@ -3642,7 +4309,7 @@ function handleCodexResponseItem(item, usageDate, projectFields, sessionId, file
|
|
|
3642
4309
|
projectFields,
|
|
3643
4310
|
sessionId,
|
|
3644
4311
|
kind,
|
|
3645
|
-
name: kind === "agent_call" ?
|
|
4312
|
+
name: kind === "agent_call" ? stringValue2(args.agent_type) ?? name : name,
|
|
3646
4313
|
confidence: "exact",
|
|
3647
4314
|
dedupeKey: baseKey
|
|
3648
4315
|
});
|
|
@@ -3696,14 +4363,14 @@ function handleCodexEvent(record, usageDate, projectFields, sessionId, filePath,
|
|
|
3696
4363
|
projectFields,
|
|
3697
4364
|
sessionId,
|
|
3698
4365
|
timestamp: record.timestamp ?? "",
|
|
3699
|
-
content:
|
|
4366
|
+
content: stringValue2(record.payload?.message),
|
|
3700
4367
|
fallbackKey: `${filePath}:${usageDate}:${sessionId}:event_user_message:${record.timestamp ?? ""}`
|
|
3701
4368
|
});
|
|
3702
4369
|
return;
|
|
3703
4370
|
}
|
|
3704
4371
|
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
4372
|
if (!kind) return;
|
|
3706
|
-
let callId =
|
|
4373
|
+
let callId = stringValue2(record.payload?.call_id);
|
|
3707
4374
|
addActivity(acc, {
|
|
3708
4375
|
usageDate,
|
|
3709
4376
|
provider: "openai",
|
|
@@ -3721,13 +4388,13 @@ async function scanClaudeActivity(targetDates, options) {
|
|
|
3721
4388
|
for (let baseDir of getClaudeProjectDirs2(options.claudeProjectsDirs)) {
|
|
3722
4389
|
let projectDirs;
|
|
3723
4390
|
try {
|
|
3724
|
-
projectDirs = await
|
|
4391
|
+
projectDirs = await readdir6(baseDir, { withFileTypes: !0 });
|
|
3725
4392
|
} catch {
|
|
3726
4393
|
continue;
|
|
3727
4394
|
}
|
|
3728
4395
|
for (let entry of projectDirs) {
|
|
3729
4396
|
if (!entry.isDirectory()) continue;
|
|
3730
|
-
let projectPath =
|
|
4397
|
+
let projectPath = join16(baseDir, entry.name), jsonlFiles = [];
|
|
3731
4398
|
await walkJsonl(projectPath, jsonlFiles);
|
|
3732
4399
|
let fields = resolveClaudeProject(projectPath, acc.projectAliases);
|
|
3733
4400
|
for (let filePath of jsonlFiles) fileJobs.push({ filePath, projectFields: fields });
|
|
@@ -3740,11 +4407,11 @@ async function scanClaudeActivity(targetDates, options) {
|
|
|
3740
4407
|
async function processClaudeFile(filePath, fallbackFields, acc) {
|
|
3741
4408
|
let fh;
|
|
3742
4409
|
try {
|
|
3743
|
-
fh = await
|
|
4410
|
+
fh = await open(filePath, "r");
|
|
3744
4411
|
} catch {
|
|
3745
4412
|
return;
|
|
3746
4413
|
}
|
|
3747
|
-
let fallbackSessionId =
|
|
4414
|
+
let fallbackSessionId = basename12(filePath).replace(/\.jsonl$/, "");
|
|
3748
4415
|
try {
|
|
3749
4416
|
let rl = createInterface3({
|
|
3750
4417
|
input: fh.createReadStream({ encoding: "utf-8" }),
|
|
@@ -3865,38 +4532,38 @@ function acceptsDate(acc, usageDate) {
|
|
|
3865
4532
|
async function collectCodexSessionFiles2(baseDir) {
|
|
3866
4533
|
let paths = [];
|
|
3867
4534
|
try {
|
|
3868
|
-
let files = await
|
|
4535
|
+
let files = await readdir6(join16(baseDir, "archived_sessions"));
|
|
3869
4536
|
for (let file of files)
|
|
3870
|
-
file.endsWith(".jsonl") && paths.push(
|
|
4537
|
+
file.endsWith(".jsonl") && paths.push(join16(baseDir, "archived_sessions", file));
|
|
3871
4538
|
} catch {
|
|
3872
4539
|
}
|
|
3873
|
-
return await walkJsonl(
|
|
4540
|
+
return await walkJsonl(join16(baseDir, "sessions"), paths), paths;
|
|
3874
4541
|
}
|
|
3875
4542
|
function getClaudeProjectDirs2(configured) {
|
|
3876
4543
|
if (configured?.length) return configured;
|
|
3877
4544
|
let envVar = process.env.CLAUDE_CONFIG_DIR?.trim();
|
|
3878
4545
|
if (envVar)
|
|
3879
|
-
return envVar.split(",").map((p) => p.trim()).filter(Boolean).map((p) =>
|
|
4546
|
+
return envVar.split(",").map((p) => p.trim()).filter(Boolean).map((p) => join16(p, "projects"));
|
|
3880
4547
|
let home = homedir15();
|
|
3881
4548
|
return [
|
|
3882
|
-
|
|
3883
|
-
|
|
4549
|
+
join16(home, ".config", "claude", "projects"),
|
|
4550
|
+
join16(home, ".claude", "projects")
|
|
3884
4551
|
];
|
|
3885
4552
|
}
|
|
3886
4553
|
async function walkJsonl(dir, result) {
|
|
3887
4554
|
let entries;
|
|
3888
4555
|
try {
|
|
3889
|
-
entries = await
|
|
4556
|
+
entries = await readdir6(dir, { withFileTypes: !0 });
|
|
3890
4557
|
} catch {
|
|
3891
4558
|
return;
|
|
3892
4559
|
}
|
|
3893
4560
|
for (let entry of entries) {
|
|
3894
|
-
let fullPath =
|
|
4561
|
+
let fullPath = join16(dir, entry.name);
|
|
3895
4562
|
entry.isDirectory() ? await walkJsonl(fullPath, result) : entry.name.endsWith(".jsonl") && result.push(fullPath);
|
|
3896
4563
|
}
|
|
3897
4564
|
}
|
|
3898
4565
|
function resolveClaudeProject(projectPath, aliases2) {
|
|
3899
|
-
let rawName =
|
|
4566
|
+
let rawName = basename12(projectPath), display = rawName.split("-").filter(Boolean).at(-1) || rawName || "unknown", alias = aliases2?.[projectPath] ?? aliases2?.[display];
|
|
3900
4567
|
return {
|
|
3901
4568
|
project: projectPath,
|
|
3902
4569
|
projectDisplay: display,
|
|
@@ -3907,22 +4574,22 @@ function classifyClaudeTool(name) {
|
|
|
3907
4574
|
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
4575
|
}
|
|
3909
4576
|
function getClaudeMetricName(toolName, input) {
|
|
3910
|
-
return toolName === "Skill" ?
|
|
4577
|
+
return toolName === "Skill" ? stringValue2(input?.skill) ?? "unknown" : toolName === "Agent" ? stringValue2(input?.description) ?? stringValue2(input?.subagent_type) ?? "unknown" : toolName;
|
|
3911
4578
|
}
|
|
3912
4579
|
function isClaudeUserMessage(record) {
|
|
3913
4580
|
if (record.type !== "user" || record.message?.role !== "user" || record.isMeta || record.toolUseResult || record.sourceToolAssistantUUID || record.sourceToolUseID) return !1;
|
|
3914
4581
|
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" &&
|
|
4582
|
+
return typeof content == "string" ? content.trim().length > 0 : !Array.isArray(content) || content.length === 0 || content.some((block) => block?.type === "tool_result") ? !1 : content.some((block) => block?.type === "text" && stringValue2(block.text));
|
|
3916
4583
|
}
|
|
3917
4584
|
function hasCodexUserMessageContent(content) {
|
|
3918
4585
|
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
4586
|
}
|
|
3920
4587
|
function extractCodexMessageText(content) {
|
|
3921
|
-
return typeof content == "string" ? content : Array.isArray(content) && content.map((block) =>
|
|
4588
|
+
return typeof content == "string" ? content : Array.isArray(content) && content.map((block) => stringValue2(block.text)).filter(Boolean).join(`
|
|
3922
4589
|
`) || void 0;
|
|
3923
4590
|
}
|
|
3924
4591
|
function extractClaudeMessageText(content) {
|
|
3925
|
-
return typeof content == "string" ? content : Array.isArray(content) && content.filter((block) => block?.type === "text").map((block) =>
|
|
4592
|
+
return typeof content == "string" ? content : Array.isArray(content) && content.filter((block) => block?.type === "text").map((block) => stringValue2(block.text)).filter(Boolean).join(`
|
|
3926
4593
|
`) || void 0;
|
|
3927
4594
|
}
|
|
3928
4595
|
function normalizeMessageText(value) {
|
|
@@ -3930,7 +4597,7 @@ function normalizeMessageText(value) {
|
|
|
3930
4597
|
}
|
|
3931
4598
|
function extractSkillProxyNames(rawArguments) {
|
|
3932
4599
|
if (!rawArguments) return [];
|
|
3933
|
-
let args = parseJsonObject(rawArguments), command2 =
|
|
4600
|
+
let args = parseJsonObject(rawArguments), command2 = stringValue2(args.cmd) ?? stringValue2(args.command) ?? "";
|
|
3934
4601
|
if (!command2.includes("SKILL.md")) return [];
|
|
3935
4602
|
let names = /* @__PURE__ */ new Set();
|
|
3936
4603
|
for (let match of command2.matchAll(/([^\s'"]*SKILL\.md)/g))
|
|
@@ -3950,7 +4617,7 @@ function skillNameFromPath(rawPath) {
|
|
|
3950
4617
|
let parts = rawPath.replace(/^[`'"]+|[`'"]+$/g, "").split("/").filter(Boolean), idx = parts.lastIndexOf("SKILL.md"), name = idx > 0 ? parts[idx - 1] : void 0;
|
|
3951
4618
|
return !name || name === "$d" || name === "s#" ? "unknown-skill" : name;
|
|
3952
4619
|
}
|
|
3953
|
-
function
|
|
4620
|
+
function stringValue2(value) {
|
|
3954
4621
|
return typeof value == "string" && value.length > 0 ? value : void 0;
|
|
3955
4622
|
}
|
|
3956
4623
|
function summarize(items, keyFn, labelFn, limit) {
|
|
@@ -4043,10 +4710,10 @@ function stripAnsi(s) {
|
|
|
4043
4710
|
}
|
|
4044
4711
|
|
|
4045
4712
|
// src/config.ts
|
|
4046
|
-
import { mkdir, readFile as
|
|
4713
|
+
import { mkdir, readFile as readFile14, writeFile } from "node:fs/promises";
|
|
4047
4714
|
import { homedir as homedir16, hostname } from "node:os";
|
|
4048
|
-
import { basename as
|
|
4049
|
-
var CONFIG_DIR =
|
|
4715
|
+
import { basename as basename13, join as join17 } from "node:path";
|
|
4716
|
+
var CONFIG_DIR = join17(homedir16(), ".aiusage"), CONFIG_PATH = join17(CONFIG_DIR, "config.json");
|
|
4050
4717
|
function getConfigPath() {
|
|
4051
4718
|
return CONFIG_PATH;
|
|
4052
4719
|
}
|
|
@@ -4073,7 +4740,7 @@ function migrateConfig(config) {
|
|
|
4073
4740
|
}
|
|
4074
4741
|
async function readConfig() {
|
|
4075
4742
|
try {
|
|
4076
|
-
let raw = await
|
|
4743
|
+
let raw = await readFile14(CONFIG_PATH, "utf-8");
|
|
4077
4744
|
return migrateConfig(JSON.parse(raw));
|
|
4078
4745
|
} catch {
|
|
4079
4746
|
return {};
|
|
@@ -4181,13 +4848,13 @@ import { hostname as hostname2 } from "node:os";
|
|
|
4181
4848
|
|
|
4182
4849
|
// src/version.ts
|
|
4183
4850
|
import { readFileSync } from "node:fs";
|
|
4184
|
-
import { resolve as resolve2, dirname as
|
|
4851
|
+
import { resolve as resolve2, dirname as dirname7 } from "node:path";
|
|
4185
4852
|
import { fileURLToPath } from "node:url";
|
|
4186
4853
|
var cached;
|
|
4187
4854
|
function getVersion() {
|
|
4188
4855
|
if (cached !== void 0) return cached;
|
|
4189
4856
|
try {
|
|
4190
|
-
let pkg = resolve2(
|
|
4857
|
+
let pkg = resolve2(dirname7(fileURLToPath(import.meta.url)), "..", "package.json");
|
|
4191
4858
|
cached = JSON.parse(readFileSync(pkg, "utf-8")).version;
|
|
4192
4859
|
} catch {
|
|
4193
4860
|
cached = "unknown";
|
|
@@ -4260,12 +4927,12 @@ async function requestJson(url, init) {
|
|
|
4260
4927
|
}
|
|
4261
4928
|
|
|
4262
4929
|
// src/schedule.ts
|
|
4263
|
-
import { mkdir as mkdir2, readFile as
|
|
4264
|
-
import { execFile } from "node:child_process";
|
|
4930
|
+
import { mkdir as mkdir2, readFile as readFile15, stat as stat3, unlink, writeFile as writeFile2 } from "node:fs/promises";
|
|
4931
|
+
import { execFile as execFile2 } from "node:child_process";
|
|
4265
4932
|
import { promisify } from "node:util";
|
|
4266
4933
|
import { homedir as homedir17, platform, tmpdir as tmpdir2 } from "node:os";
|
|
4267
|
-
import { join as
|
|
4268
|
-
var execFileAsync = promisify(
|
|
4934
|
+
import { join as join18, resolve as resolve3 } from "node:path";
|
|
4935
|
+
var execFileAsync = promisify(execFile2), LABEL = "com.aiusage.sync", PLIST_PATH = join18(homedir17(), "Library", "LaunchAgents", `${LABEL}.plist`), LOG_PATH = join18(homedir17(), ".aiusage", "sync.log"), CRON_MARKER = "# aiusage-sync";
|
|
4269
4936
|
function parseInterval(value) {
|
|
4270
4937
|
let match = value.match(/^(\d+)(m|h|d)$/);
|
|
4271
4938
|
if (!match) throw new Error("--every \u683C\u5F0F\u9519\u8BEF\uFF0C\u793A\u4F8B: 30m, 1h, 2h, 1d");
|
|
@@ -4310,7 +4977,7 @@ function resolveCommandPaths() {
|
|
|
4310
4977
|
}
|
|
4311
4978
|
async function enableLaunchd(intervalSeconds) {
|
|
4312
4979
|
let { nodePath, scriptPath } = resolveCommandPaths();
|
|
4313
|
-
await mkdir2(
|
|
4980
|
+
await mkdir2(join18(homedir17(), ".aiusage"), { recursive: !0 });
|
|
4314
4981
|
let plist = [
|
|
4315
4982
|
'<?xml version="1.0" encoding="UTF-8"?>',
|
|
4316
4983
|
'<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
|
|
@@ -4359,12 +5026,12 @@ async function disableLaunchd() {
|
|
|
4359
5026
|
}
|
|
4360
5027
|
async function getLaunchdStatus() {
|
|
4361
5028
|
try {
|
|
4362
|
-
await
|
|
5029
|
+
await stat3(PLIST_PATH);
|
|
4363
5030
|
} catch {
|
|
4364
5031
|
return { enabled: !1 };
|
|
4365
5032
|
}
|
|
4366
5033
|
try {
|
|
4367
|
-
let content = await
|
|
5034
|
+
let content = await readFile15(PLIST_PATH, "utf-8"), match = content.match(/<key>StartInterval<\/key>\s*<integer>(\d+)<\/integer>/), interval = match ? parseInt(match[1], 10) : void 0, argMatches = [...content.matchAll(/<string>([^<]+)<\/string>/g)].map((m) => m[1]), command2 = argMatches.length > 0 ? argMatches.join(" ") : void 0, includeToday = content.includes("--today"), logPath = content.match(/<key>StandardOutPath<\/key>\s*<string>([^<]+)<\/string>/)?.[1];
|
|
4368
5035
|
return {
|
|
4369
5036
|
enabled: !0,
|
|
4370
5037
|
interval,
|
|
@@ -4379,8 +5046,8 @@ async function getLaunchdStatus() {
|
|
|
4379
5046
|
}
|
|
4380
5047
|
}
|
|
4381
5048
|
async function enableCron(intervalSeconds) {
|
|
4382
|
-
let { nodePath, scriptPath } = resolveCommandPaths(), cronExpr = secondsToCron(intervalSeconds), logPath =
|
|
4383
|
-
await mkdir2(
|
|
5049
|
+
let { nodePath, scriptPath } = resolveCommandPaths(), cronExpr = secondsToCron(intervalSeconds), logPath = join18(homedir17(), ".aiusage", "sync.log"), cronLine = `${cronExpr} ${nodePath} ${scriptPath} sync --today >> ${logPath} 2>&1 ${CRON_MARKER}`;
|
|
5050
|
+
await mkdir2(join18(homedir17(), ".aiusage"), { recursive: !0 });
|
|
4384
5051
|
let existing = "";
|
|
4385
5052
|
try {
|
|
4386
5053
|
let { stdout } = await execFileAsync("crontab", ["-l"]);
|
|
@@ -4438,7 +5105,7 @@ async function getCronStatus() {
|
|
|
4438
5105
|
}
|
|
4439
5106
|
}
|
|
4440
5107
|
async function writeCrontab(content) {
|
|
4441
|
-
let tmpFile =
|
|
5108
|
+
let tmpFile = join18(tmpdir2(), `aiusage-cron-${Date.now()}`);
|
|
4442
5109
|
await writeFile2(tmpFile, content, "utf-8");
|
|
4443
5110
|
try {
|
|
4444
5111
|
await execFileAsync("crontab", [tmpFile]);
|
|
@@ -4469,9 +5136,9 @@ function escapeXml(value) {
|
|
|
4469
5136
|
}
|
|
4470
5137
|
|
|
4471
5138
|
// src/doctor.ts
|
|
4472
|
-
import { readdir as
|
|
5139
|
+
import { readdir as readdir7, stat as stat4 } from "node:fs/promises";
|
|
4473
5140
|
import { homedir as homedir18 } from "node:os";
|
|
4474
|
-
import { join as
|
|
5141
|
+
import { join as join19 } from "node:path";
|
|
4475
5142
|
var msgs = {
|
|
4476
5143
|
en: {
|
|
4477
5144
|
groupConfig: "Configuration",
|
|
@@ -4527,13 +5194,13 @@ async function countFiles(dir, exts, cap = 1e3) {
|
|
|
4527
5194
|
for (; queue.length > 0 && count < cap; ) {
|
|
4528
5195
|
let current = queue.pop(), entries;
|
|
4529
5196
|
try {
|
|
4530
|
-
entries = await
|
|
5197
|
+
entries = await readdir7(current, { withFileTypes: !0 });
|
|
4531
5198
|
} catch {
|
|
4532
5199
|
continue;
|
|
4533
5200
|
}
|
|
4534
5201
|
for (let e of entries) {
|
|
4535
5202
|
if (count >= cap) break;
|
|
4536
|
-
let full =
|
|
5203
|
+
let full = join19(current, e.name);
|
|
4537
5204
|
e.isDirectory() ? queue.push(full) : exts.some((ext) => e.name.endsWith(ext)) && count++;
|
|
4538
5205
|
}
|
|
4539
5206
|
}
|
|
@@ -4542,7 +5209,7 @@ async function countFiles(dir, exts, cap = 1e3) {
|
|
|
4542
5209
|
async function runDoctor(lang = "zh") {
|
|
4543
5210
|
let s = msgs[lang], checks = [], config = await readConfig(), g1 = s.groupConfig, configPath = getConfigPath();
|
|
4544
5211
|
try {
|
|
4545
|
-
await
|
|
5212
|
+
await stat4(configPath), checks.push({ group: g1, name: s.config, status: "ok", message: configPath });
|
|
4546
5213
|
} catch {
|
|
4547
5214
|
checks.push({ group: g1, name: s.config, status: "fail", message: s.configMissing });
|
|
4548
5215
|
}
|
|
@@ -4563,29 +5230,39 @@ async function runDoctor(lang = "zh") {
|
|
|
4563
5230
|
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
5231
|
}
|
|
4565
5232
|
let g3 = s.groupTools, home = homedir18(), tools = [
|
|
4566
|
-
{
|
|
4567
|
-
{
|
|
4568
|
-
{
|
|
4569
|
-
{
|
|
4570
|
-
{
|
|
4571
|
-
|
|
4572
|
-
|
|
4573
|
-
|
|
4574
|
-
|
|
4575
|
-
|
|
4576
|
-
|
|
4577
|
-
|
|
4578
|
-
{
|
|
4579
|
-
{
|
|
5233
|
+
{ dirs: [join19(home, ".config", "claude", "projects"), join19(home, ".claude", "projects")], label: "Claude Code", exts: [".jsonl"] },
|
|
5234
|
+
{ dirs: [join19(home, ".codex")], label: "Codex CLI", exts: [".jsonl"] },
|
|
5235
|
+
{ dirs: [join19(home, "Library", "Application Support", "Cursor", "User", "globalStorage")], label: "Cursor", exts: [".vscdb"] },
|
|
5236
|
+
{ dirs: [join19(home, ".copilot", "session-state"), join19(home, ".copilot", "otel")], label: "Copilot CLI", exts: [".jsonl"] },
|
|
5237
|
+
{
|
|
5238
|
+
dirs: [
|
|
5239
|
+
join19(home, "Library", "Application Support", "Code", "logs"),
|
|
5240
|
+
join19(home, "Library", "Application Support", "Code", "User", "workspaceStorage")
|
|
5241
|
+
],
|
|
5242
|
+
label: "Copilot VS Code",
|
|
5243
|
+
exts: [".log", ".json", ".jsonl"]
|
|
5244
|
+
},
|
|
5245
|
+
{ dirs: [join19(home, ".gemini", "tmp")], label: "Gemini CLI", exts: [".json", ".jsonl"] },
|
|
5246
|
+
{ dirs: [join19(home, ".gemini", "antigravity")], label: "Antigravity", exts: [".json"] },
|
|
5247
|
+
{ dirs: [join19(home, ".qwen", "projects"), join19(home, ".qwen", "tmp")], label: "Qwen Code", exts: [".jsonl"] },
|
|
5248
|
+
{ dirs: [join19(resolveKimiCodeHome(home), "sessions")], label: "Kimi Code", exts: [".jsonl"] },
|
|
5249
|
+
{ dirs: [join19(home, ".kimi", "sessions")], label: "Kimi CLI (legacy)", exts: [".jsonl"] },
|
|
5250
|
+
{ dirs: [join19(home, ".local", "share", "amp", "threads")], label: "Amp", exts: [".json"] },
|
|
5251
|
+
{ dirs: [join19(home, ".factory", "sessions")], label: "Droid", exts: [".settings.json"] },
|
|
5252
|
+
{ dirs: [join19(home, ".local", "share", "opencode")], label: "OpenCode", exts: [".db", ".json"] },
|
|
5253
|
+
{ dirs: [join19(home, ".pi", "agent", "sessions"), join19(home, ".omp", "agent", "sessions")], label: "Pi / OMP", exts: [".jsonl"] }
|
|
4580
5254
|
];
|
|
4581
5255
|
for (let tool of tools) {
|
|
4582
|
-
|
|
4583
|
-
|
|
4584
|
-
|
|
5256
|
+
let installed = !1, n = 0;
|
|
5257
|
+
for (let dir of tool.dirs)
|
|
5258
|
+
try {
|
|
5259
|
+
await stat4(dir), installed = !0, n += await countFiles(dir, tool.exts);
|
|
5260
|
+
} catch {
|
|
5261
|
+
}
|
|
5262
|
+
if (!installed) {
|
|
4585
5263
|
checks.push({ group: g3, name: tool.label, status: "warn", message: s.notInstalled });
|
|
4586
5264
|
continue;
|
|
4587
5265
|
}
|
|
4588
|
-
let n = await countFiles(tool.dir, tool.exts);
|
|
4589
5266
|
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
5267
|
}
|
|
4591
5268
|
let g4 = s.groupSchedule, schedule = await getScheduleStatus();
|
|
@@ -4598,8 +5275,8 @@ async function runDoctor(lang = "zh") {
|
|
|
4598
5275
|
}
|
|
4599
5276
|
|
|
4600
5277
|
// src/project.ts
|
|
4601
|
-
import { open as
|
|
4602
|
-
import { basename as
|
|
5278
|
+
import { open as open2, readdir as readdir8, readFile as readFile16 } from "node:fs/promises";
|
|
5279
|
+
import { basename as basename14, join as join20 } from "node:path";
|
|
4603
5280
|
import { homedir as homedir19 } from "node:os";
|
|
4604
5281
|
async function discoverProjects(projectAliases) {
|
|
4605
5282
|
let projectMap = /* @__PURE__ */ new Map();
|
|
@@ -4646,20 +5323,20 @@ async function discoverClaudeProjects() {
|
|
|
4646
5323
|
for (let baseDir of getClaudeDirs()) {
|
|
4647
5324
|
let entries;
|
|
4648
5325
|
try {
|
|
4649
|
-
entries = await
|
|
5326
|
+
entries = await readdir8(baseDir, { withFileTypes: !0 });
|
|
4650
5327
|
} catch {
|
|
4651
5328
|
continue;
|
|
4652
5329
|
}
|
|
4653
5330
|
for (let entry of entries) {
|
|
4654
5331
|
if (!entry.isDirectory() || entry.name.startsWith(".")) continue;
|
|
4655
|
-
let projectDir =
|
|
5332
|
+
let projectDir = join20(baseDir, entry.name), name = await extractCwdFromFirstJsonl(projectDir);
|
|
4656
5333
|
name && name !== "unknown" && names.push(name);
|
|
4657
5334
|
}
|
|
4658
5335
|
}
|
|
4659
5336
|
return names;
|
|
4660
5337
|
}
|
|
4661
5338
|
async function discoverCodexProjects() {
|
|
4662
|
-
let sessionsDir =
|
|
5339
|
+
let sessionsDir = join20(homedir19(), ".codex", "sessions"), files = await walkJsonlFiles(sessionsDir), projects = /* @__PURE__ */ new Set();
|
|
4663
5340
|
for (let filePath of files) {
|
|
4664
5341
|
let name = await extractCwdFromSessionMeta(filePath);
|
|
4665
5342
|
name && name !== "unknown" && projects.add(name);
|
|
@@ -4669,7 +5346,7 @@ async function discoverCodexProjects() {
|
|
|
4669
5346
|
async function extractCwdFromSessionMeta(filePath) {
|
|
4670
5347
|
let fh;
|
|
4671
5348
|
try {
|
|
4672
|
-
fh = await
|
|
5349
|
+
fh = await open2(filePath, "r");
|
|
4673
5350
|
let buf = Buffer.alloc(4096), { bytesRead } = await fh.read(buf, 0, buf.length, 0);
|
|
4674
5351
|
if (bytesRead === 0) return;
|
|
4675
5352
|
let line = buf.subarray(0, bytesRead).toString("utf-8").split(`
|
|
@@ -4691,12 +5368,12 @@ async function walkFiles2(dir, ext) {
|
|
|
4691
5368
|
async function walk2(d) {
|
|
4692
5369
|
let entries;
|
|
4693
5370
|
try {
|
|
4694
|
-
entries = await
|
|
5371
|
+
entries = await readdir8(d, { withFileTypes: !0 });
|
|
4695
5372
|
} catch {
|
|
4696
5373
|
return;
|
|
4697
5374
|
}
|
|
4698
5375
|
for (let entry of entries) {
|
|
4699
|
-
let full =
|
|
5376
|
+
let full = join20(d, entry.name);
|
|
4700
5377
|
entry.isDirectory() ? await walk2(full) : entry.name.endsWith(ext) && result.push(full);
|
|
4701
5378
|
}
|
|
4702
5379
|
}
|
|
@@ -4707,7 +5384,7 @@ async function extractCwdFromFirstJsonl(dir) {
|
|
|
4707
5384
|
if (!jsonlPath) return;
|
|
4708
5385
|
let fh;
|
|
4709
5386
|
try {
|
|
4710
|
-
fh = await
|
|
5387
|
+
fh = await open2(jsonlPath, "r");
|
|
4711
5388
|
let buf = Buffer.alloc(32 * 1024), { bytesRead } = await fh.read(buf, 0, buf.length, 0);
|
|
4712
5389
|
if (bytesRead === 0) return;
|
|
4713
5390
|
let lines = buf.subarray(0, bytesRead).toString("utf-8").split(`
|
|
@@ -4733,27 +5410,27 @@ async function extractCwdFromFirstJsonl(dir) {
|
|
|
4733
5410
|
async function findFirstJsonl(dir) {
|
|
4734
5411
|
let entries;
|
|
4735
5412
|
try {
|
|
4736
|
-
entries = await
|
|
5413
|
+
entries = await readdir8(dir, { withFileTypes: !0 });
|
|
4737
5414
|
} catch {
|
|
4738
5415
|
return;
|
|
4739
5416
|
}
|
|
4740
5417
|
let topJsonl = entries.find((e) => e.isFile() && e.name.endsWith(".jsonl"));
|
|
4741
|
-
if (topJsonl) return
|
|
5418
|
+
if (topJsonl) return join20(dir, topJsonl.name);
|
|
4742
5419
|
for (let entry of entries)
|
|
4743
5420
|
if (!(!entry.isDirectory() || entry.name.startsWith(".")))
|
|
4744
5421
|
try {
|
|
4745
|
-
let sub = (await
|
|
4746
|
-
if (sub) return
|
|
5422
|
+
let sub = (await readdir8(join20(dir, entry.name))).find((f) => f.endsWith(".jsonl"));
|
|
5423
|
+
if (sub) return join20(dir, entry.name, sub);
|
|
4747
5424
|
} catch {
|
|
4748
5425
|
continue;
|
|
4749
5426
|
}
|
|
4750
5427
|
}
|
|
4751
5428
|
async function discoverCopilotProjects() {
|
|
4752
|
-
let dir =
|
|
5429
|
+
let dir = join20(homedir19(), ".copilot", "session-state"), files = await walkJsonlFiles(dir), projects = /* @__PURE__ */ new Set();
|
|
4753
5430
|
for (let filePath of files) {
|
|
4754
5431
|
let fh;
|
|
4755
5432
|
try {
|
|
4756
|
-
fh = await
|
|
5433
|
+
fh = await open2(filePath, "r");
|
|
4757
5434
|
let buf = Buffer.alloc(4096), { bytesRead } = await fh.read(buf, 0, buf.length, 0);
|
|
4758
5435
|
if (bytesRead === 0) continue;
|
|
4759
5436
|
let line = buf.subarray(0, bytesRead).toString("utf-8").split(`
|
|
@@ -4771,9 +5448,9 @@ async function discoverCopilotProjects() {
|
|
|
4771
5448
|
return [...projects];
|
|
4772
5449
|
}
|
|
4773
5450
|
async function discoverGeminiProjects() {
|
|
4774
|
-
let filePath =
|
|
5451
|
+
let filePath = join20(homedir19(), ".gemini", "projects.json");
|
|
4775
5452
|
try {
|
|
4776
|
-
let raw = await
|
|
5453
|
+
let raw = await readFile16(filePath, "utf-8"), projects = JSON.parse(raw)?.projects;
|
|
4777
5454
|
if (!projects || typeof projects != "object") return [];
|
|
4778
5455
|
let names = [];
|
|
4779
5456
|
for (let [path, _name] of Object.entries(projects)) {
|
|
@@ -4786,9 +5463,9 @@ async function discoverGeminiProjects() {
|
|
|
4786
5463
|
}
|
|
4787
5464
|
}
|
|
4788
5465
|
async function discoverCursorProjects() {
|
|
4789
|
-
let storagePath =
|
|
5466
|
+
let storagePath = join20(homedir19(), "Library", "Application Support", "Cursor", "User", "globalStorage", "storage.json");
|
|
4790
5467
|
try {
|
|
4791
|
-
let raw = await
|
|
5468
|
+
let raw = await readFile16(storagePath, "utf-8"), data = JSON.parse(raw), projects = /* @__PURE__ */ new Set(), workspaceUris = Object.keys(data.profileAssociations?.workspaces ?? {});
|
|
4792
5469
|
for (let uri of workspaceUris) {
|
|
4793
5470
|
let name = nameFromFileUri(uri);
|
|
4794
5471
|
name && projects.add(name);
|
|
@@ -4803,11 +5480,11 @@ async function discoverCursorProjects() {
|
|
|
4803
5480
|
}
|
|
4804
5481
|
}
|
|
4805
5482
|
async function discoverCopilotVscodeProjects() {
|
|
4806
|
-
let dir =
|
|
5483
|
+
let dir = join20(homedir19(), "Library", "Application Support", "Code", "logs"), files = (await walkFiles2(dir, ".log")).filter((filePath) => filePath.endsWith("GitHub Copilot Chat.log")), projects = /* @__PURE__ */ new Set();
|
|
4807
5484
|
for (let filePath of files) {
|
|
4808
5485
|
let content;
|
|
4809
5486
|
try {
|
|
4810
|
-
content = await
|
|
5487
|
+
content = await readFile16(filePath, "utf-8");
|
|
4811
5488
|
} catch {
|
|
4812
5489
|
continue;
|
|
4813
5490
|
}
|
|
@@ -4820,18 +5497,18 @@ async function discoverCopilotVscodeProjects() {
|
|
|
4820
5497
|
return [...projects];
|
|
4821
5498
|
}
|
|
4822
5499
|
async function discoverAntigravityProjects() {
|
|
4823
|
-
let dir =
|
|
5500
|
+
let dir = join20(homedir19(), ".gemini", "antigravity", "knowledge"), entries;
|
|
4824
5501
|
try {
|
|
4825
|
-
entries = await
|
|
5502
|
+
entries = await readdir8(dir, { withFileTypes: !0 });
|
|
4826
5503
|
} catch {
|
|
4827
5504
|
return [];
|
|
4828
5505
|
}
|
|
4829
5506
|
let projects = /* @__PURE__ */ new Set();
|
|
4830
5507
|
for (let entry of entries) {
|
|
4831
5508
|
if (!entry.isDirectory()) continue;
|
|
4832
|
-
let metadataPath =
|
|
5509
|
+
let metadataPath = join20(dir, entry.name, "metadata.json");
|
|
4833
5510
|
try {
|
|
4834
|
-
let raw = await
|
|
5511
|
+
let raw = await readFile16(metadataPath, "utf-8"), name = JSON.parse(raw).title?.trim() || entry.name.trim();
|
|
4835
5512
|
name && name !== "unknown" && projects.add(name);
|
|
4836
5513
|
} catch {
|
|
4837
5514
|
continue;
|
|
@@ -4842,31 +5519,31 @@ async function discoverAntigravityProjects() {
|
|
|
4842
5519
|
async function discoverKimiProjects() {
|
|
4843
5520
|
let projects = /* @__PURE__ */ new Set(), home = homedir19();
|
|
4844
5521
|
try {
|
|
4845
|
-
let raw = await
|
|
5522
|
+
let raw = await readFile16(join20(home, ".kimi", "kimi.json"), "utf-8"), data = JSON.parse(raw);
|
|
4846
5523
|
for (let workspace of Object.values(data.workspaces ?? {})) {
|
|
4847
|
-
let name =
|
|
5524
|
+
let name = basename14(workspace.path?.trim() ?? "");
|
|
4848
5525
|
name && name !== "unknown" && projects.add(name);
|
|
4849
5526
|
}
|
|
4850
5527
|
} catch {
|
|
4851
5528
|
}
|
|
4852
5529
|
let codeHome = resolveKimiCodeHome(home);
|
|
4853
5530
|
try {
|
|
4854
|
-
let raw = await
|
|
5531
|
+
let raw = await readFile16(join20(codeHome, "session_index.jsonl"), "utf-8");
|
|
4855
5532
|
for (let line of raw.split(`
|
|
4856
5533
|
`))
|
|
4857
5534
|
if (line.trim())
|
|
4858
5535
|
try {
|
|
4859
|
-
let record = JSON.parse(line), name =
|
|
5536
|
+
let record = JSON.parse(line), name = basename14(record.workDir?.trim() ?? "");
|
|
4860
5537
|
name && name !== "unknown" && projects.add(name);
|
|
4861
5538
|
} catch {
|
|
4862
5539
|
continue;
|
|
4863
5540
|
}
|
|
4864
5541
|
} catch {
|
|
4865
5542
|
}
|
|
4866
|
-
let stateFiles = (await walkFiles2(
|
|
5543
|
+
let stateFiles = (await walkFiles2(join20(codeHome, "sessions"), ".json")).filter((filePath) => basename14(filePath) === "state.json");
|
|
4867
5544
|
for (let filePath of stateFiles)
|
|
4868
5545
|
try {
|
|
4869
|
-
let raw = await
|
|
5546
|
+
let raw = await readFile16(filePath, "utf-8"), state = JSON.parse(raw), name = basename14(state.workDir?.trim() ?? "");
|
|
4870
5547
|
name && name !== "unknown" && projects.add(name);
|
|
4871
5548
|
} catch {
|
|
4872
5549
|
continue;
|
|
@@ -4876,7 +5553,7 @@ async function discoverKimiProjects() {
|
|
|
4876
5553
|
function nameFromFileUri(raw) {
|
|
4877
5554
|
let path = pathFromFileUri(raw);
|
|
4878
5555
|
if (!path) return;
|
|
4879
|
-
let name =
|
|
5556
|
+
let name = basename14(path);
|
|
4880
5557
|
return name && name !== "unknown" ? name : void 0;
|
|
4881
5558
|
}
|
|
4882
5559
|
function pathFromFileUri(raw) {
|
|
@@ -4895,11 +5572,11 @@ function pathFromFileUri(raw) {
|
|
|
4895
5572
|
function getClaudeDirs() {
|
|
4896
5573
|
let envVar = process.env.CLAUDE_CONFIG_DIR?.trim();
|
|
4897
5574
|
if (envVar)
|
|
4898
|
-
return envVar.split(",").map((p) => p.trim()).filter(Boolean).map((p) =>
|
|
5575
|
+
return envVar.split(",").map((p) => p.trim()).filter(Boolean).map((p) => join20(p, "projects"));
|
|
4899
5576
|
let home = homedir19();
|
|
4900
5577
|
return [
|
|
4901
|
-
|
|
4902
|
-
|
|
5578
|
+
join20(home, ".config", "claude", "projects"),
|
|
5579
|
+
join20(home, ".claude", "projects")
|
|
4903
5580
|
];
|
|
4904
5581
|
}
|
|
4905
5582
|
|
|
@@ -4944,10 +5621,10 @@ function shortHash(p) {
|
|
|
4944
5621
|
}
|
|
4945
5622
|
|
|
4946
5623
|
// src/pricing.ts
|
|
4947
|
-
import { mkdir as mkdir3, readFile as
|
|
5624
|
+
import { mkdir as mkdir3, readFile as readFile17, writeFile as writeFile3 } from "node:fs/promises";
|
|
4948
5625
|
import { homedir as homedir20 } from "node:os";
|
|
4949
|
-
import { join as
|
|
4950
|
-
var CACHE_DIR =
|
|
5626
|
+
import { join as join21 } from "node:path";
|
|
5627
|
+
var CACHE_DIR = join21(homedir20(), ".aiusage"), CACHE_PATH = join21(CACHE_DIR, "pricing-cache.json"), DEFAULT_CACHE_TTL_HOURS = 24, FETCH_TIMEOUT_MS = 5e3, NPM_CDN_URLS = [
|
|
4951
5628
|
"https://cdn.jsdelivr.net/npm/@aiusage/cli@latest/pricing-catalog.json",
|
|
4952
5629
|
"https://unpkg.com/@aiusage/cli@latest/pricing-catalog.json",
|
|
4953
5630
|
"https://cdn.jsdelivr.net/npm/@aiusage/pricing@latest/catalog.json",
|
|
@@ -5016,7 +5693,7 @@ function fromCache(cache) {
|
|
|
5016
5693
|
}
|
|
5017
5694
|
async function readPricingCache() {
|
|
5018
5695
|
try {
|
|
5019
|
-
let raw = await
|
|
5696
|
+
let raw = await readFile17(CACHE_PATH, "utf-8"), cache = JSON.parse(raw);
|
|
5020
5697
|
return assertPricingCatalog(cache.catalog), !cache.fetchedAt || !cache.sourceUrl ? null : cache;
|
|
5021
5698
|
} catch {
|
|
5022
5699
|
return null;
|