@aiusage/cli 1.7.2 → 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/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("/").filter(Boolean), name = parts[parts.length - 1] || "unknown";
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("/").filter(Boolean), display = parts[parts.length - 1] || "unknown", alias = aliases2?.[rawPath] ?? aliases2?.[display];
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 { readdir as readdir3, open, readFile as readFile2 } from "node:fs/promises";
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, STATS_CACHE_DEFAULT_INPUT_RATIO = 0.7;
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 Set(), sessionSets = /* @__PURE__ */ new Map(), fileJobs = [];
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$/, ""), fh;
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: fh.createReadStream({ encoding: "utf-8" }),
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 cacheWriteTokens = cache5m + cache1h, key = `${model}|${recordFields.project}`, sessionSetKey = `${usageDate}|${key}`;
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
- existing ? (existing.eventCount += 1, existing.inputTokens += usage.input_tokens ?? 0, existing.cachedInputTokens += usage.cache_read_input_tokens ?? 0, existing.cacheWriteTokens += cacheWriteTokens, existing.cacheWrite5mTokens = (existing.cacheWrite5mTokens ?? 0) + cache5m, existing.cacheWrite1hTokens = (existing.cacheWrite1hTokens ?? 0) + cache1h, existing.outputTokens += usage.output_tokens ?? 0, existing.costUSD = (existing.costUSD ?? 0) + costUSD) : grouped.set(key, {
275
- provider: "anthropic",
276
- product: "claude-code",
277
- channel: "cli",
278
- model,
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: "unknown",
286
+ project: recordFields.project,
287
+ projectDisplay: recordFields.projectDisplay,
288
+ projectAlias: recordFields.projectAlias,
329
289
  eventCount: 1,
330
- inputTokens,
331
- cachedInputTokens: 0,
332
- cacheWriteTokens: 0,
333
- outputTokens,
334
- reasoningOutputTokens: 0
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 { readdir as readdir4, open as open2, readFile as readFile3 } from "node:fs/promises";
370
- import { join as join4 } from "node:path";
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
 
@@ -964,16 +952,40 @@ var google = {
964
952
  var moonshot = {
965
953
  "kimi-code": {
966
954
  models: {
955
+ "kimi-k3": {
956
+ currency: "CNY",
957
+ effective_from: "2026-07-17",
958
+ input_per_million: 20,
959
+ cached_input_per_million: 2,
960
+ cache_write_per_million: 20,
961
+ output_per_million: 100
962
+ },
963
+ "kimi-k2.7-code": {
964
+ currency: "CNY",
965
+ input_per_million: 6.5,
966
+ cached_input_per_million: 1.3,
967
+ cache_write_per_million: 6.5,
968
+ output_per_million: 27
969
+ },
970
+ "kimi-k2.7-code-highspeed": {
971
+ currency: "CNY",
972
+ input_per_million: 13,
973
+ cached_input_per_million: 2.6,
974
+ cache_write_per_million: 13,
975
+ output_per_million: 54
976
+ },
967
977
  "kimi-k2.6": {
968
978
  currency: "CNY",
969
979
  input_per_million: 6.5,
970
980
  cached_input_per_million: 1.1,
981
+ cache_write_per_million: 6.5,
971
982
  output_per_million: 27
972
983
  },
973
984
  "kimi-k2.5": {
974
985
  currency: "CNY",
975
986
  input_per_million: 4,
976
987
  cached_input_per_million: 0.7,
988
+ cache_write_per_million: 4,
977
989
  output_per_million: 21
978
990
  },
979
991
  "kimi-k2-0905-preview": {
@@ -981,6 +993,7 @@ var moonshot = {
981
993
  notes: "will be retired 2026-05-25",
982
994
  input_per_million: 4,
983
995
  cached_input_per_million: 1,
996
+ cache_write_per_million: 4,
984
997
  output_per_million: 16
985
998
  },
986
999
  "kimi-k2-0711-preview": {
@@ -988,6 +1001,7 @@ var moonshot = {
988
1001
  notes: "will be retired 2026-05-25",
989
1002
  input_per_million: 4,
990
1003
  cached_input_per_million: 1,
1004
+ cache_write_per_million: 4,
991
1005
  output_per_million: 16
992
1006
  },
993
1007
  "kimi-k2-turbo-preview": {
@@ -995,48 +1009,57 @@ var moonshot = {
995
1009
  notes: "will be retired 2026-05-25",
996
1010
  input_per_million: 8,
997
1011
  cached_input_per_million: 1,
1012
+ cache_write_per_million: 8,
998
1013
  output_per_million: 58
999
1014
  },
1000
1015
  "kimi-k2-thinking": {
1001
1016
  currency: "CNY",
1002
1017
  input_per_million: 4,
1003
1018
  cached_input_per_million: 1,
1019
+ cache_write_per_million: 4,
1004
1020
  output_per_million: 16
1005
1021
  },
1006
1022
  "kimi-k2-thinking-turbo": {
1007
1023
  currency: "CNY",
1008
1024
  input_per_million: 8,
1009
1025
  cached_input_per_million: 1,
1026
+ cache_write_per_million: 8,
1010
1027
  output_per_million: 58
1011
1028
  },
1012
1029
  "moonshot-v1-8k": {
1013
1030
  currency: "CNY",
1014
1031
  input_per_million: 2,
1032
+ cache_write_per_million: 2,
1015
1033
  output_per_million: 10
1016
1034
  },
1017
1035
  "moonshot-v1-32k": {
1018
1036
  currency: "CNY",
1019
1037
  input_per_million: 5,
1038
+ cache_write_per_million: 5,
1020
1039
  output_per_million: 20
1021
1040
  },
1022
1041
  "moonshot-v1-128k": {
1023
1042
  currency: "CNY",
1024
1043
  input_per_million: 10,
1044
+ cache_write_per_million: 10,
1025
1045
  output_per_million: 30
1026
1046
  },
1027
1047
  "moonshot-v1-8k-vision-preview": {
1028
1048
  currency: "CNY",
1029
1049
  input_per_million: 2,
1050
+ cache_write_per_million: 2,
1030
1051
  output_per_million: 10
1031
1052
  },
1032
1053
  "moonshot-v1-32k-vision-preview": {
1033
1054
  currency: "CNY",
1034
1055
  input_per_million: 5,
1056
+ cache_write_per_million: 5,
1035
1057
  output_per_million: 20
1036
1058
  },
1037
1059
  "moonshot-v1-128k-vision-preview": {
1038
1060
  currency: "CNY",
1039
1061
  input_per_million: 10,
1062
+ cache_write_per_million: 10,
1040
1063
  output_per_million: 30
1041
1064
  }
1042
1065
  }
@@ -1287,14 +1310,16 @@ var inflection = {
1287
1310
  };
1288
1311
 
1289
1312
  // ../shared/src/pricing/catalog.ts
1290
- var PRICING_VERSION = "2026-07-10-gpt-5.6-v1", aliases = {
1313
+ var PRICING_VERSION = "2026-07-18-kimi-k3-v1", aliases = {
1291
1314
  "claude-opus-4-7-20260201": "claude-opus-4-7",
1292
1315
  "claude-sonnet-4-6-20250301": "claude-sonnet-4-6",
1293
1316
  "claude-opus-4-6-20250301": "claude-opus-4-6",
1294
1317
  "claude-haiku-4-5-20251001": "claude-haiku-4-5",
1295
1318
  "claude-sonnet-4.6": "claude-sonnet-4-6",
1296
1319
  "gpt-5.6": "gpt-5.6-sol",
1297
- "codex-auto-review": "gpt-5.4"
1320
+ "codex-auto-review": "gpt-5.4",
1321
+ k3: "kimi-k3",
1322
+ "kimi-code/k3": "kimi-k3"
1298
1323
  }, catalog = {
1299
1324
  version: PRICING_VERSION,
1300
1325
  // 汇率(1 USD ≈ N CNY)。Worker 启动时可被 env 覆盖。
@@ -1406,25 +1431,32 @@ async function scanCodexDates(targetDates, codexDir, projectAliases) {
1406
1431
  let baseDir = codexDir ?? join4(homedir3(), ".codex"), serviceTier = await detectCodexServiceTier(baseDir), sessionFiles = await collectSessionFiles(baseDir);
1407
1432
  if (sessionFiles.length === 0)
1408
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
+ });
1409
1438
  let globalSeenSigs = /* @__PURE__ */ new Set();
1410
- return await runWithConcurrency(sessionFiles, FILE_CONCURRENCY2, async (filePath) => {
1411
- await processCodexFile(filePath, targetDateSet, projectAliases, groupedByDate, globalSeenSigs, serviceTier);
1412
- }), new Map(
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(
1413
1443
  [...groupedByDate.entries()].map(([usageDate, grouped]) => [usageDate, [...grouped.values()]])
1414
1444
  );
1415
1445
  }
1416
- async function processCodexFile(filePath, targetDateSet, projectAliases, groupedByDate, globalSeenSigs, serviceTier) {
1417
- let fh;
1418
- try {
1419
- fh = await open2(filePath, "r");
1420
- } catch {
1421
- return;
1422
- }
1446
+ async function processCodexFile(filePath, projectAliases, serviceTier) {
1447
+ let events = [], input = createReadStream2(filePath, { encoding: "utf-8" });
1423
1448
  try {
1424
1449
  let rl = createInterface2({
1425
- input: fh.createReadStream({ encoding: "utf-8" }),
1450
+ input,
1426
1451
  crlfDelay: 1 / 0
1427
- }), currentModel = "unknown", currentProjectFields = { project: "unknown", projectDisplay: "unknown" }, previousTotal = {};
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
+ };
1428
1460
  for await (let line of rl) {
1429
1461
  if (!line || Buffer.byteLength(line) > MAX_LINE_BYTES2) continue;
1430
1462
  let record;
@@ -1433,78 +1465,216 @@ async function processCodexFile(filePath, targetDateSet, projectAliases, grouped
1433
1465
  } catch {
1434
1466
  continue;
1435
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
+ }
1436
1489
  if (record.type === "turn_context") {
1437
- let rawModel = record.payload?.model ?? currentModel;
1438
- 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));
1439
1491
  continue;
1440
1492
  }
1441
- if (record.type !== "event_msg" || record.payload?.type !== "token_count") continue;
1442
- let info = record.payload?.info;
1443
- if (!info?.total_token_usage) continue;
1444
- let ts = parseTimestamp2(record.timestamp);
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;
1445
1498
  if (!ts) continue;
1446
- let usageDate = toDateKey2(ts);
1447
- if (!targetDateSet.has(usageDate)) continue;
1448
- let total = info.total_token_usage;
1449
- if ((total.input_tokens ?? 0) + (total.cached_input_tokens ?? 0) + (total.output_tokens ?? 0) + (total.reasoning_output_tokens ?? 0) + (total.total_tokens ?? 0) === 0) continue;
1450
- let signature = `${total.input_tokens ?? 0}|${total.cached_input_tokens ?? 0}|${total.output_tokens ?? 0}|${total.reasoning_output_tokens ?? 0}|${total.total_tokens ?? 0}`;
1451
- if (globalSeenSigs.has(signature)) continue;
1452
- globalSeenSigs.add(signature);
1453
- let last = info.last_token_usage ?? {
1454
- input_tokens: Math.max(0, (total.input_tokens ?? 0) - (previousTotal.input_tokens ?? 0)),
1455
- cached_input_tokens: Math.max(0, (total.cached_input_tokens ?? 0) - (previousTotal.cached_input_tokens ?? 0)),
1456
- output_tokens: Math.max(0, (total.output_tokens ?? 0) - (previousTotal.output_tokens ?? 0)),
1457
- reasoning_output_tokens: Math.max(0, (total.reasoning_output_tokens ?? 0) - (previousTotal.reasoning_output_tokens ?? 0))
1458
- };
1459
- previousTotal = total;
1460
- 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, {
1461
1512
  inputTokens: nonCachedInput,
1462
1513
  cachedInputTokens: cachedInput,
1463
1514
  cacheWriteTokens: 0,
1464
1515
  outputTokens: output
1465
- }), exactEventCost = eventCost.costStatus === "exact" ? eventCost.estimatedCostUsd : void 0, grouped = groupedByDate.get(usageDate);
1466
- if (!grouped) continue;
1467
- let key = `${currentModel}|${currentProjectFields.project}`, existing = grouped.get(key);
1468
- if (existing)
1469
- existing.eventCount += 1, existing.inputTokens += nonCachedInput, existing.cachedInputTokens += cachedInput, existing.outputTokens += output, existing.reasoningOutputTokens += last.reasoning_output_tokens ?? 0, exactEventCost !== void 0 && (existing.costUSD = (existing.costUSD ?? 0) + exactEventCost, existing.pricingVersion = eventCost.pricingVersion);
1470
- else {
1471
- let breakdown = {
1472
- provider: "openai",
1473
- product: "codex",
1474
- channel: "cli",
1475
- model: currentModel,
1476
- project: currentProjectFields.project,
1477
- projectDisplay: currentProjectFields.projectDisplay,
1478
- projectAlias: currentProjectFields.projectAlias,
1479
- eventCount: 1,
1480
- inputTokens: nonCachedInput,
1481
- cachedInputTokens: cachedInput,
1482
- cacheWriteTokens: 0,
1483
- outputTokens: output,
1484
- reasoningOutputTokens: last.reasoning_output_tokens ?? 0
1485
- };
1486
- exactEventCost !== void 0 && (breakdown.costUSD = exactEventCost, breakdown.pricingVersion = eventCost.pricingVersion), grouped.set(key, breakdown);
1487
- }
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
+ });
1488
1529
  }
1530
+ } catch {
1489
1531
  } finally {
1490
- await fh.close();
1532
+ input.destroy();
1491
1533
  }
1534
+ return events;
1492
1535
  }
1493
- async function collectSessionFiles(baseDir) {
1494
- let paths = [], archivedDir = join4(baseDir, "archived_sessions");
1495
- try {
1496
- let files = await readdir4(archivedDir);
1497
- for (let f of files)
1498
- f.endsWith(".jsonl") && paths.push(join4(archivedDir, f));
1499
- } catch {
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;
1500
1543
  }
1501
- let sessionsDir = join4(baseDir, "sessions");
1502
- return await walkDir(sessionsDir, paths), paths;
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];
1503
1673
  }
1504
1674
  async function detectCodexServiceTier(baseDir) {
1505
1675
  let config = "";
1506
1676
  try {
1507
- config = await readFile3(join4(baseDir, "config.toml"), "utf-8");
1677
+ config = await readFile2(join4(baseDir, "config.toml"), "utf-8");
1508
1678
  } catch {
1509
1679
  return null;
1510
1680
  }
@@ -1543,30 +1713,33 @@ function toDateKey2(date) {
1543
1713
  }
1544
1714
 
1545
1715
  // src/scanners/copilot.ts
1546
- import { readFile as readFile4 } from "node:fs/promises";
1716
+ import { readFile as readFile3 } from "node:fs/promises";
1547
1717
  import { join as join5 } from "node:path";
1548
1718
  import { homedir as homedir4 } from "node:os";
1549
1719
  async function scanCopilotDates(targetDates, baseDir, projectAliases) {
1550
- let dates = new Set(targetDates), dir = baseDir ?? join5(homedir4(), ".copilot", "session-state"), files = await walkFiles(dir, ".jsonl");
1551
- if (files.length === 0) return emptyResult(dates);
1552
- 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();
1553
1723
  for (let filePath of files) {
1554
1724
  let content;
1555
1725
  try {
1556
- content = await readFile4(filePath, "utf-8");
1726
+ content = await readFile3(filePath, "utf-8");
1557
1727
  } catch {
1558
1728
  continue;
1559
1729
  }
1560
- let sessionProjectFields = { project: "unknown", projectDisplay: "unknown" }, lines = content.split(`
1561
- `);
1562
- for (let line of lines) {
1730
+ let sessionProjectFields = { project: "unknown", projectDisplay: "unknown" }, records = [];
1731
+ for (let line of content.split(`
1732
+ `)) {
1563
1733
  if (!line.trim()) continue;
1564
- let obj;
1734
+ let parsed;
1565
1735
  try {
1566
- obj = JSON.parse(line);
1736
+ parsed = JSON.parse(line);
1567
1737
  } catch {
1568
1738
  continue;
1569
1739
  }
1740
+ if (!isObject(parsed)) continue;
1741
+ records.push(parsed);
1742
+ let obj = parsed;
1570
1743
  if (obj.type === "session.start" || obj.type === "session.resume") {
1571
1744
  let ctx = obj.data?.context, raw = ctx?.gitRoot ?? ctx?.cwd;
1572
1745
  raw && (sessionProjectFields = resolveProjectFields(raw, projectAliases));
@@ -1581,7 +1754,7 @@ async function scanCopilotDates(targetDates, baseDir, projectAliases) {
1581
1754
  for (let [model, entry] of Object.entries(metrics)) {
1582
1755
  let usage = entry.usage;
1583
1756
  if (!usage) continue;
1584
- let rawInput = usage.inputTokens ?? 0, cacheRead = usage.cacheReadTokens ?? 0, output = usage.outputTokens ?? 0, input = Math.max(rawInput - cacheRead, 0);
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);
1585
1758
  accumulate(
1586
1759
  dayMap,
1587
1760
  `${model}|${sessionProjectFields.project}`,
@@ -1599,26 +1772,162 @@ async function scanCopilotDates(targetDates, baseDir, projectAliases) {
1599
1772
  outputTokens: 0,
1600
1773
  reasoningOutputTokens: 0
1601
1774
  },
1602
- { input, cached: cacheRead, cacheWrite: 0, output, reasoning: 0 }
1775
+ { input, cached: cacheRead, cacheWrite, output, reasoning }
1603
1776
  );
1604
1777
  }
1605
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
+ }
1606
1804
  }
1607
1805
  return finalize(grouped);
1608
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
+ }
1609
1913
 
1610
1914
  // src/scanners/copilot-vscode.ts
1611
- import { readFile as readFile5 } from "node:fs/promises";
1612
- import { basename as basename2, dirname, join as join6 } from "node:path";
1915
+ import { readFile as readFile4 } from "node:fs/promises";
1916
+ import { basename as basename3, dirname, join as join6 } from "node:path";
1613
1917
  import { homedir as homedir5 } from "node:os";
1614
1918
  async function scanCopilotVscodeDates(targetDates, baseDir, projectAliases, workspaceStorageDir) {
1615
- let dates = new Set(targetDates), dir = baseDir ?? join6(homedir5(), "Library", "Application Support", "Code", "logs"), workspaceDir = workspaceStorageDir ?? join6(homedir5(), "Library", "Application Support", "Code", "User", "workspaceStorage"), logFiles = (await walkFiles(dir, ".log")).filter((filePath) => basename2(filePath) === "GitHub Copilot Chat.log"), sessionFiles = (await walkFiles(workspaceDir, ".json")).filter((filePath) => filePath.includes("/chatSessions/"));
1616
- if (logFiles.length === 0 && sessionFiles.length === 0) return emptyResult(dates);
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);
1617
1926
  let grouped = initDateMap(dates), seenEvents = /* @__PURE__ */ new Set();
1618
1927
  for (let filePath of logFiles) {
1619
1928
  let content;
1620
1929
  try {
1621
- content = await readFile5(filePath, "utf-8");
1930
+ content = await readFile4(filePath, "utf-8");
1622
1931
  } catch {
1623
1932
  continue;
1624
1933
  }
@@ -1654,6 +1963,8 @@ async function scanCopilotVscodeDates(targetDates, baseDir, projectAliases, work
1654
1963
  }
1655
1964
  for (let filePath of sessionFiles)
1656
1965
  await collectWorkspaceSessionEvents(filePath, grouped, seenEvents, projectAliases);
1966
+ for (let filePath of crdtSessionFiles)
1967
+ await collectWorkspaceJsonlEvents(filePath, grouped, seenEvents, projectAliases);
1657
1968
  return finalize(grouped);
1658
1969
  }
1659
1970
  function extractSuccessEvent(line) {
@@ -1683,7 +1994,7 @@ function extractFileUriPath(line) {
1683
1994
  async function collectWorkspaceSessionEvents(filePath, grouped, seenEvents, projectAliases) {
1684
1995
  let content;
1685
1996
  try {
1686
- content = await readFile5(filePath, "utf-8");
1997
+ content = await readFile4(filePath, "utf-8");
1687
1998
  } catch {
1688
1999
  return;
1689
2000
  }
@@ -1722,16 +2033,82 @@ async function collectWorkspaceSessionEvents(filePath, grouped, seenEvents, proj
1722
2033
  ));
1723
2034
  }
1724
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
+ }
1725
2102
  async function readWorkspaceFolderPath(sessionFilePath) {
1726
2103
  let workspaceJsonPath = join6(dirname(sessionFilePath), "..", "workspace.json"), content;
1727
2104
  try {
1728
- content = await readFile5(workspaceJsonPath, "utf-8");
2105
+ content = await readFile4(workspaceJsonPath, "utf-8");
1729
2106
  } catch {
1730
2107
  return null;
1731
2108
  }
1732
2109
  try {
1733
- let raw = JSON.parse(content).folder;
1734
- return raw?.startsWith("file:///") ? decodeURIComponent(raw.replace(/^file:\/\//, "")) : null;
2110
+ let workspace = JSON.parse(content), raw = workspace.folder ?? workspace.workspace;
2111
+ return raw ? decodeURIComponent(raw.replace(/^file:\/\//, "")) : null;
1735
2112
  } catch {
1736
2113
  return null;
1737
2114
  }
@@ -1739,6 +2116,13 @@ async function readWorkspaceFolderPath(sessionFilePath) {
1739
2116
  function normalizeWorkspaceModel(raw) {
1740
2117
  return raw ? raw.replace(/^copilot\//, "").trim() : "";
1741
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
+ }
1742
2126
 
1743
2127
  // src/scanners/cursor.ts
1744
2128
  import { existsSync } from "node:fs";
@@ -1900,69 +2284,175 @@ async function scanCursorDates(targetDates) {
1900
2284
  }
1901
2285
 
1902
2286
  // src/scanners/gemini.ts
1903
- import { readFile as readFile6 } from "node:fs/promises";
1904
- import { basename as basename3, join as join8 } from "node:path";
2287
+ import { readFile as readFile5 } from "node:fs/promises";
2288
+ import { basename as basename4, extname, join as join8, relative, sep } from "node:path";
1905
2289
  import { homedir as homedir7 } from "node:os";
1906
2290
  async function scanGeminiDates(targetDates, baseDir, projectAliases) {
1907
- let dates = new Set(targetDates), dir = baseDir ?? join8(homedir7(), ".gemini", "tmp"), files = await walkFiles(dir, ".json");
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])];
1908
2295
  if (files.length === 0) return emptyResult(dates);
1909
- let grouped = initDateMap(dates), tokenBackedDates = /* @__PURE__ */ new Set();
2296
+ let grouped = initDateMap(dates), tokenBackedDates = /* @__PURE__ */ new Set(), seen = /* @__PURE__ */ new Set();
1910
2297
  for (let filePath of files) {
1911
- if (basename3(filePath) === "logs.json") continue;
2298
+ if (basename4(filePath) === "logs.json") continue;
1912
2299
  let content;
1913
2300
  try {
1914
- content = await readFile6(filePath, "utf-8");
1915
- } catch {
1916
- continue;
1917
- }
1918
- let session;
1919
- try {
1920
- session = JSON.parse(content);
2301
+ content = await readFile5(filePath, "utf-8");
1921
2302
  } catch {
1922
2303
  continue;
1923
2304
  }
1924
- let messages = session.messages ?? session.history ?? session.data?.messages ?? session.data?.history ?? [], fallbackModel = session.model ?? session.data?.model ?? "unknown", fallbackTs = session.createTime ?? session.startTime ?? session.data?.createTime;
1925
- for (let msg of messages) {
1926
- let tokens = extractTokens(msg);
1927
- if (!tokens) continue;
1928
- let model = normalizeModelName(msg.model ?? fallbackModel), ts = parseTs(msg.timestamp) ?? parseTs(msg.createTime) ?? parseTs(fallbackTs);
1929
- if (!ts) continue;
1930
- let dk = dateKey(ts), dayMap = grouped.get(dk);
1931
- dayMap && (tokenBackedDates.add(dk), accumulate(
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(
1932
2318
  dayMap,
1933
- `${model}|unknown`,
2319
+ `${model}|${fields.project}`,
1934
2320
  {
1935
2321
  provider: "google",
1936
2322
  product: "gemini-cli",
1937
2323
  channel: "cli",
1938
2324
  model,
1939
- project: "unknown",
1940
- projectDisplay: "unknown",
2325
+ project: fields.project,
2326
+ projectDisplay: fields.projectDisplay,
2327
+ projectAlias: fields.projectAlias,
1941
2328
  inputTokens: 0,
1942
2329
  cachedInputTokens: 0,
1943
2330
  cacheWriteTokens: 0,
1944
2331
  outputTokens: 0,
1945
2332
  reasoningOutputTokens: 0
1946
2333
  },
1947
- tokens
1948
- ));
2334
+ event.tokens
2335
+ );
1949
2336
  }
1950
2337
  }
1951
- let logFiles = files.filter((filePath) => basename3(filePath) === "logs.json");
1952
- for (let filePath of logFiles)
2338
+ for (let filePath of jsonFiles.filter((file) => basename4(file) === "logs.json"))
1953
2339
  await collectGeminiLogEvents(filePath, grouped, tokenBackedDates);
1954
2340
  return finalize(grouped);
1955
2341
  }
1956
- async function collectGeminiLogEvents(filePath, grouped, tokenBackedDates) {
1957
- let content;
2342
+ function parseGeminiJson(content, fallbackId, fallbackTs) {
2343
+ let value;
1958
2344
  try {
1959
- content = await readFile6(filePath, "utf-8");
2345
+ value = JSON.parse(content);
1960
2346
  } catch {
1961
- 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));
1962
2449
  }
2450
+ return { input: input + tool, cached: cached2, cacheWrite: 0, output, reasoning };
2451
+ }
2452
+ async function collectGeminiLogEvents(filePath, grouped, tokenBackedDates) {
1963
2453
  let rows;
1964
2454
  try {
1965
- rows = JSON.parse(content);
2455
+ rows = JSON.parse(await readFile5(filePath, "utf-8"));
1966
2456
  } catch {
1967
2457
  return;
1968
2458
  }
@@ -1983,6 +2473,7 @@ async function collectGeminiLogEvents(filePath, grouped, tokenBackedDates) {
1983
2473
  channel: "cli",
1984
2474
  model: "unknown",
1985
2475
  project: "unknown",
2476
+ projectDisplay: "unknown",
1986
2477
  inputTokens: 0,
1987
2478
  cachedInputTokens: 0,
1988
2479
  cacheWriteTokens: 0,
@@ -1993,31 +2484,53 @@ async function collectGeminiLogEvents(filePath, grouped, tokenBackedDates) {
1993
2484
  );
1994
2485
  }
1995
2486
  }
1996
- function extractTokens(msg) {
1997
- if (msg.tokens) {
1998
- let t2 = msg.tokens, cached2 = t2.cached ?? 0, input = Math.max((t2.input ?? 0) - cached2, 0), thoughts = t2.thoughts ?? 0, output = Math.max((t2.output ?? 0) - thoughts, 0);
1999
- return { input, cached: cached2, cacheWrite: 0, output, reasoning: thoughts };
2000
- }
2001
- let u = msg.usage ?? msg.usageMetadata;
2002
- if (u) {
2003
- let cached2 = u.cachedContentTokenCount ?? 0, input = Math.max((u.promptTokenCount ?? 0) - cached2, 0), thoughts = u.thoughtsTokenCount ?? 0, output = Math.max((u.candidatesTokenCount ?? 0) - thoughts, 0);
2004
- return { input, cached: cached2, cacheWrite: 0, output, reasoning: thoughts };
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;
2005
2501
  }
2006
- return null;
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;
2007
2520
  }
2008
2521
 
2009
2522
  // src/scanners/qwen.ts
2010
- import { readFile as readFile7 } from "node:fs/promises";
2011
- import { join as join9, basename as basename4, dirname as dirname2 } from "node:path";
2523
+ import { readFile as readFile6 } from "node:fs/promises";
2524
+ import { join as join9, basename as basename5, dirname as dirname2 } from "node:path";
2012
2525
  import { homedir as homedir8 } from "node:os";
2013
2526
  async function scanQwenDates(targetDates, baseDir, projectAliases) {
2014
- let dates = new Set(targetDates), dir = baseDir ?? join9(homedir8(), ".qwen", "tmp"), files = await walkFiles(dir, ".jsonl");
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())];
2015
2528
  if (files.length === 0) return emptyResult(dates);
2016
2529
  let grouped = initDateMap(dates), seen = /* @__PURE__ */ new Set();
2017
2530
  for (let filePath of files) {
2018
- let chatsDir = dirname2(filePath), projectDir = dirname2(chatsDir), projectId = basename4(projectDir), content;
2531
+ let chatsDir = dirname2(filePath), projectDir = dirname2(chatsDir), projectId = basename5(projectDir), pathSessionId = basename5(filePath, ".jsonl"), fallbackTs = await fileModifiedTs(filePath), assistantIndex = 0, content;
2019
2532
  try {
2020
- content = await readFile7(filePath, "utf-8");
2533
+ content = await readFile6(filePath, "utf-8");
2021
2534
  } catch {
2022
2535
  continue;
2023
2536
  }
@@ -2031,18 +2544,17 @@ async function scanQwenDates(targetDates, baseDir, projectAliases) {
2031
2544
  continue;
2032
2545
  }
2033
2546
  if (obj.type !== "assistant") continue;
2034
- let ts = parseTs(obj.timestamp);
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;
2035
2553
  if (!ts) continue;
2036
2554
  let dk = dateKey(ts), dayMap = grouped.get(dk);
2037
2555
  if (!dayMap) continue;
2038
- if (obj.uuid) {
2039
- if (seen.has(obj.uuid)) continue;
2040
- seen.add(obj.uuid);
2041
- }
2042
- let u = obj.usageMetadata;
2043
- if (!u) continue;
2044
- 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);
2045
- 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(
2046
2558
  dayMap,
2047
2559
  `${model}|${fields.project}`,
2048
2560
  {
@@ -2067,85 +2579,246 @@ async function scanQwenDates(targetDates, baseDir, projectAliases) {
2067
2579
  }
2068
2580
 
2069
2581
  // src/scanners/kimi.ts
2070
- import { readFile as readFile8 } from "node:fs/promises";
2071
- import { join as join10, basename as basename5, dirname as dirname3 } from "node:path";
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";
2072
2584
  import { homedir as homedir9 } from "node:os";
2073
- async function scanKimiDates(targetDates, baseDir, projectAliases) {
2074
- let dates = new Set(targetDates), kimiHome = baseDir ?? join10(homedir9(), ".kimi"), sessionsDir = join10(kimiHome, "sessions"), files = await walkFiles(sessionsDir, ".jsonl");
2075
- if (files.length === 0) return emptyResult(dates);
2076
- let workspaceMap = await loadWorkspaceMap(kimiHome), grouped = initDateMap(dates), seen = /* @__PURE__ */ new Set();
2077
- for (let filePath of files) {
2078
- let sessionDir = dirname3(filePath), hashDir = dirname3(sessionDir), workDirHash = basename5(hashDir), projectFields = resolveKimiProject(workDirHash, workspaceMap, projectAliases), content;
2585
+ var DEFAULT_MODEL = "kimi-for-coding";
2586
+ function resolveKimiCodeHome(home = homedir9()) {
2587
+ return process.env.KIMI_CODE_HOME?.trim() || join10(home, ".kimi-code");
2588
+ }
2589
+ async function scanKimiDates(targetDates, legacyBaseDir, projectAliases, kimiCodeBaseDir) {
2590
+ let dates = new Set(targetDates), legacyHome = legacyBaseDir ?? join10(homedir9(), ".kimi"), codeHome = kimiCodeBaseDir ?? (legacyBaseDir ? void 0 : resolveKimiCodeHome()), [legacyFiles, codeFiles] = await Promise.all([
2591
+ findWireFiles(join10(legacyHome, "sessions")),
2592
+ codeHome ? findWireFiles(join10(codeHome, "sessions")) : Promise.resolve([])
2593
+ ]);
2594
+ if (legacyFiles.length === 0 && codeFiles.length === 0) return emptyResult(dates);
2595
+ let [legacyWorkspaceMap, legacyModel, codeSessionIndex] = await Promise.all([
2596
+ loadLegacyWorkspaceMap(legacyHome),
2597
+ loadLegacyModel(legacyHome),
2598
+ codeHome ? loadKimiCodeSessionIndex(codeHome) : Promise.resolve(/* @__PURE__ */ new Map())
2599
+ ]), grouped = initDateMap(dates), sessionSets = /* @__PURE__ */ new Map(), codeProjectCache = /* @__PURE__ */ new Map();
2600
+ for (let filePath of legacyFiles) {
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);
2602
+ for (let usage of usages)
2603
+ addUsage(grouped, sessionSets, dates, usage, projectFields, sessionId);
2604
+ }
2605
+ for (let filePath of codeFiles) {
2606
+ let pathInfo = getKimiCodePathInfo(filePath);
2607
+ if (!pathInfo) continue;
2608
+ let projectFields = codeProjectCache.get(pathInfo.sessionDir);
2609
+ if (!projectFields) {
2610
+ let rawProject = await resolveKimiCodeProjectPath(pathInfo, codeSessionIndex);
2611
+ projectFields = resolveProjectFields(rawProject, projectAliases), codeProjectCache.set(pathInfo.sessionDir, projectFields);
2612
+ }
2613
+ let usages = await parseKimiCodeFile(filePath);
2614
+ for (let usage of usages)
2615
+ addUsage(grouped, sessionSets, dates, usage, projectFields, pathInfo.sessionId);
2616
+ }
2617
+ let result = finalize(grouped);
2618
+ for (let [usageDate, breakdowns] of result)
2619
+ for (let breakdown of breakdowns) {
2620
+ let key = `${usageDate}|${breakdown.model}|${breakdown.project}`;
2621
+ breakdown.sessionCount = sessionSets.get(key)?.size ?? 0;
2622
+ }
2623
+ return result;
2624
+ }
2625
+ async function findWireFiles(sessionsDir) {
2626
+ return (await walkFiles(sessionsDir, ".jsonl")).filter((filePath) => basename6(filePath) === "wire.jsonl");
2627
+ }
2628
+ async function parseLegacyFile(filePath, fallbackModel) {
2629
+ let content = await safeRead(filePath);
2630
+ if (content == null) return [];
2631
+ let fallbackTimestamp = await fileModifiedDate(filePath), usages = [], keyedIndices = /* @__PURE__ */ new Map(), currentModel = fallbackModel;
2632
+ for (let line of content.split(`
2633
+ `)) {
2634
+ if (!line.trim()) continue;
2635
+ let record;
2079
2636
  try {
2080
- content = await readFile8(filePath, "utf-8");
2637
+ record = JSON.parse(line);
2081
2638
  } catch {
2082
2639
  continue;
2083
2640
  }
2084
- let currentModel = "unknown";
2085
- for (let line of content.split(`
2641
+ let payload = record.message?.payload ?? record.payload;
2642
+ if (payload?.model && (currentModel = normalizeModel2(payload.model)), (record.message?.type ?? record.type) !== "StatusUpdate" || !payload?.token_usage) continue;
2643
+ let tokens = normalizeUsage(payload.token_usage);
2644
+ if (tokens.input + tokens.cached + tokens.cacheWrite + tokens.output === 0) continue;
2645
+ let timestamp = parseTs(record.timestamp) ?? fallbackTimestamp;
2646
+ if (!timestamp) continue;
2647
+ let usage = {
2648
+ timestamp,
2649
+ model: currentModel,
2650
+ ...tokens,
2651
+ messageId: payload.message_id
2652
+ };
2653
+ pushOrReplaceProgressiveUsage(usages, keyedIndices, usage);
2654
+ }
2655
+ return usages;
2656
+ }
2657
+ async function parseKimiCodeFile(filePath) {
2658
+ let content = await safeRead(filePath);
2659
+ if (content == null) return [];
2660
+ let fallbackTimestamp = await fileModifiedDate(filePath), usages = [];
2661
+ for (let line of content.split(`
2086
2662
  `)) {
2087
- if (!line.trim()) continue;
2088
- let obj;
2663
+ if (!line.trim()) continue;
2664
+ let record;
2665
+ try {
2666
+ record = JSON.parse(line);
2667
+ } catch {
2668
+ continue;
2669
+ }
2670
+ if (record.type !== "usage.record" || record.usageScope !== "turn" || !record.usage) continue;
2671
+ let tokens = normalizeUsage(record.usage);
2672
+ if (tokens.input + tokens.cached + tokens.cacheWrite + tokens.output === 0) continue;
2673
+ let timestamp = parseTs(record.time ?? record.created_at) ?? fallbackTimestamp;
2674
+ timestamp && usages.push({
2675
+ timestamp,
2676
+ model: normalizeModel2(record.model ?? DEFAULT_MODEL),
2677
+ ...tokens
2678
+ });
2679
+ }
2680
+ return usages;
2681
+ }
2682
+ function addUsage(grouped, sessionSets, dates, usage, projectFields, sessionId) {
2683
+ let usageDate = dateKey(usage.timestamp);
2684
+ if (!dates.has(usageDate)) return;
2685
+ let dayMap = grouped.get(usageDate);
2686
+ if (!dayMap) return;
2687
+ let breakdownKey = `${usage.model}|${projectFields.project}`;
2688
+ accumulate(
2689
+ dayMap,
2690
+ breakdownKey,
2691
+ {
2692
+ provider: "moonshot",
2693
+ product: "kimi-code",
2694
+ channel: "cli",
2695
+ model: usage.model,
2696
+ project: projectFields.project,
2697
+ projectDisplay: projectFields.projectDisplay,
2698
+ projectAlias: projectFields.projectAlias,
2699
+ sessionCount: 0,
2700
+ inputTokens: 0,
2701
+ cachedInputTokens: 0,
2702
+ cacheWriteTokens: 0,
2703
+ outputTokens: 0,
2704
+ reasoningOutputTokens: 0
2705
+ },
2706
+ {
2707
+ input: usage.input,
2708
+ cached: usage.cached,
2709
+ cacheWrite: usage.cacheWrite,
2710
+ output: usage.output,
2711
+ reasoning: 0
2712
+ }
2713
+ );
2714
+ let sessionKey = `${usageDate}|${breakdownKey}`, sessions = sessionSets.get(sessionKey);
2715
+ sessions || (sessions = /* @__PURE__ */ new Set(), sessionSets.set(sessionKey, sessions)), sessions.add(sessionId);
2716
+ }
2717
+ function normalizeUsage(usage) {
2718
+ return {
2719
+ input: normalizeTokenCount(usage.inputOther ?? usage.input_other),
2720
+ cached: normalizeTokenCount(usage.inputCacheRead ?? usage.input_cache_read),
2721
+ cacheWrite: normalizeTokenCount(usage.inputCacheCreation ?? usage.input_cache_creation),
2722
+ output: normalizeTokenCount(usage.output)
2723
+ };
2724
+ }
2725
+ function normalizeTokenCount(value) {
2726
+ return typeof value == "number" && Number.isFinite(value) && value > 0 ? Math.floor(value) : 0;
2727
+ }
2728
+ function normalizeModel2(model) {
2729
+ return model.trim().replace(/^kimi-code\//, "") || DEFAULT_MODEL;
2730
+ }
2731
+ function pushOrReplaceProgressiveUsage(usages, keyedIndices, candidate) {
2732
+ let messageId = candidate.messageId?.trim();
2733
+ if (!messageId) {
2734
+ usages.push(candidate);
2735
+ return;
2736
+ }
2737
+ let existingIndex = keyedIndices.get(messageId);
2738
+ if (existingIndex == null) {
2739
+ keyedIndices.set(messageId, usages.length), usages.push(candidate);
2740
+ return;
2741
+ }
2742
+ let existing = usages[existingIndex], existingTotal = totalUsage(existing), candidateTotal = totalUsage(candidate);
2743
+ (candidateTotal > existingTotal || candidateTotal === existingTotal && candidate.timestamp >= existing.timestamp) && (usages[existingIndex] = candidate);
2744
+ }
2745
+ function totalUsage(usage) {
2746
+ return usage.input + usage.cached + usage.cacheWrite + usage.output;
2747
+ }
2748
+ function getKimiCodePathInfo(filePath) {
2749
+ let agentDir = dirname3(filePath), agentsDir = dirname3(agentDir);
2750
+ if (basename6(agentsDir) !== "agents") return null;
2751
+ let sessionDir = dirname3(agentsDir);
2752
+ return {
2753
+ sessionDir,
2754
+ sessionId: basename6(sessionDir),
2755
+ workspaceKey: basename6(dirname3(sessionDir))
2756
+ };
2757
+ }
2758
+ async function resolveKimiCodeProjectPath(pathInfo, sessionIndex) {
2759
+ try {
2760
+ let raw = await readFile7(join10(pathInfo.sessionDir, "state.json"), "utf-8"), state = JSON.parse(raw);
2761
+ if (state.workDir?.trim()) return state.workDir;
2762
+ } catch {
2763
+ }
2764
+ let indexed = sessionIndex.get(pathInfo.sessionId);
2765
+ return indexed || workspaceLabel(pathInfo.workspaceKey);
2766
+ }
2767
+ function workspaceLabel(workspaceKey) {
2768
+ return workspaceKey.match(/^wd_(.+)_[0-9a-f]{12}$/i)?.[1] || workspaceKey;
2769
+ }
2770
+ async function loadKimiCodeSessionIndex(kimiCodeHome) {
2771
+ let map = /* @__PURE__ */ new Map(), content = await safeRead(join10(kimiCodeHome, "session_index.jsonl"));
2772
+ if (content == null) return map;
2773
+ for (let line of content.split(`
2774
+ `))
2775
+ if (line.trim())
2089
2776
  try {
2090
- obj = JSON.parse(line);
2777
+ let record = JSON.parse(line);
2778
+ record.sessionId?.trim() && record.workDir?.trim() && map.set(record.sessionId, record.workDir);
2091
2779
  } catch {
2092
2780
  continue;
2093
2781
  }
2094
- if (obj.payload?.model && (currentModel = obj.payload.model), obj.type !== "StatusUpdate") continue;
2095
- let usage = obj.payload?.token_usage;
2096
- if (!usage) continue;
2097
- let ts = parseTs(obj.timestamp);
2098
- if (!ts) continue;
2099
- let dk = dateKey(ts), dayMap = grouped.get(dk);
2100
- if (!dayMap) continue;
2101
- let msgId = obj.payload?.message_id;
2102
- if (msgId) {
2103
- if (seen.has(msgId)) continue;
2104
- seen.add(msgId);
2105
- }
2106
- let input = usage.input_other ?? 0, cached2 = usage.input_cache_read ?? 0, output = usage.output ?? 0;
2107
- accumulate(
2108
- dayMap,
2109
- `${currentModel}|${projectFields.project}`,
2110
- {
2111
- provider: "moonshot",
2112
- product: "kimi-code",
2113
- channel: "cli",
2114
- model: currentModel,
2115
- project: projectFields.project,
2116
- projectDisplay: projectFields.projectDisplay,
2117
- projectAlias: projectFields.projectAlias,
2118
- inputTokens: 0,
2119
- cachedInputTokens: 0,
2120
- cacheWriteTokens: 0,
2121
- outputTokens: 0,
2122
- reasoningOutputTokens: 0
2123
- },
2124
- { input, cached: cached2, cacheWrite: 0, output, reasoning: 0 }
2125
- );
2126
- }
2127
- }
2128
- return finalize(grouped);
2129
- }
2130
- function resolveKimiProject(hash, workspaceMap, aliases2) {
2131
- let wsPath = workspaceMap.get(hash);
2132
- return wsPath ? resolveProjectFields(wsPath, aliases2) : resolveProjectFields(hash, aliases2);
2782
+ return map;
2133
2783
  }
2134
- async function loadWorkspaceMap(kimiHome) {
2784
+ async function loadLegacyWorkspaceMap(kimiHome) {
2135
2785
  let map = /* @__PURE__ */ new Map();
2136
2786
  try {
2137
- let raw = await readFile8(join10(kimiHome, "kimi.json"), "utf-8"), config = JSON.parse(raw);
2138
- if (config.workspaces)
2139
- for (let [hash, info] of Object.entries(config.workspaces))
2140
- info.path && map.set(hash, info.path);
2787
+ let raw = await readFile7(join10(kimiHome, "kimi.json"), "utf-8"), config = JSON.parse(raw);
2788
+ for (let [hash, info] of Object.entries(config.workspaces ?? {}))
2789
+ info.path?.trim() && map.set(hash, info.path);
2141
2790
  } catch {
2142
2791
  }
2143
2792
  return map;
2144
2793
  }
2794
+ async function loadLegacyModel(kimiHome) {
2795
+ for (let name of ["config.json", "kimi.json"])
2796
+ try {
2797
+ let raw = await readFile7(join10(kimiHome, name), "utf-8"), config = JSON.parse(raw);
2798
+ if (config.model?.trim()) return normalizeModel2(config.model);
2799
+ } catch {
2800
+ continue;
2801
+ }
2802
+ return DEFAULT_MODEL;
2803
+ }
2804
+ async function safeRead(filePath) {
2805
+ try {
2806
+ return await readFile7(filePath, "utf-8");
2807
+ } catch {
2808
+ return null;
2809
+ }
2810
+ }
2811
+ async function fileModifiedDate(filePath) {
2812
+ try {
2813
+ return (await stat2(filePath)).mtime;
2814
+ } catch {
2815
+ return null;
2816
+ }
2817
+ }
2145
2818
 
2146
2819
  // src/scanners/amp.ts
2147
- import { readFile as readFile9 } from "node:fs/promises";
2148
- 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";
2149
2822
  import { homedir as homedir10 } from "node:os";
2150
2823
  function resolveAmpDir(baseDir) {
2151
2824
  if (baseDir) return baseDir;
@@ -2155,134 +2828,153 @@ function resolveAmpDir(baseDir) {
2155
2828
  return xdgDataHome ? join11(xdgDataHome, "amp", "threads") : join11(homedir10(), ".local", "share", "amp", "threads");
2156
2829
  }
2157
2830
  async function scanAmpDates(targetDates, baseDir, _projectAliases) {
2158
- let dates = new Set(targetDates), dir = resolveAmpDir(baseDir), threadFiles = (await walkFiles(dir, ".json")).filter((f) => {
2159
- let name = f.split("/").pop() ?? "";
2160
- return name.startsWith("T-") && name.endsWith(".json");
2161
- });
2162
- if (threadFiles.length === 0) return emptyResult(dates);
2831
+ let dates = new Set(targetDates), files = (await walkFiles(resolveAmpDir(baseDir), ".json")).filter(
2832
+ (file) => basename7(file).startsWith("T-")
2833
+ );
2834
+ if (files.length === 0) return emptyResult(dates);
2163
2835
  let grouped = initDateMap(dates);
2164
- for (let filePath of threadFiles) {
2165
- let raw;
2166
- try {
2167
- raw = await readFile9(filePath, "utf-8");
2168
- } catch {
2169
- continue;
2170
- }
2836
+ for (let filePath of files) {
2171
2837
  let thread;
2172
2838
  try {
2173
- thread = JSON.parse(raw);
2839
+ thread = JSON.parse(await readFile8(filePath, "utf-8"));
2174
2840
  } catch {
2175
2841
  continue;
2176
2842
  }
2177
- let ledgerEvents = thread.usageLedger?.events;
2178
- Array.isArray(ledgerEvents) && ledgerEvents.length > 0 ? processLedger(thread, ledgerEvents, dates, grouped) : processMessages(thread, dates, grouped);
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
+ }
2179
2871
  }
2180
2872
  return finalize(grouped);
2181
2873
  }
2182
- function getMessageByKey(messages, key) {
2183
- if (messages) {
2184
- if (Array.isArray(messages)) {
2185
- let idx = parseInt(key, 10);
2186
- return isNaN(idx) ? void 0 : messages[idx];
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;
2187
2921
  }
2188
- return messages[key];
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
+ };
2189
2937
  }
2938
+ return [...merged, ...unmatched].sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime());
2190
2939
  }
2191
- function processLedger(thread, events, dates, grouped) {
2192
- for (let event of events) {
2193
- let ts = parseTs(event.timestamp);
2194
- if (!ts) continue;
2195
- let dk = dateKey(ts), dayMap = grouped.get(dk);
2196
- if (!dayMap) continue;
2197
- let model = event.model ?? "unknown", input = event.tokens?.input ?? 0, output = event.tokens?.output ?? 0, cached2 = 0;
2198
- event.toMessageId && (cached2 = getMessageByKey(thread.messages, event.toMessageId)?.usage?.cacheReadInputTokens ?? 0), accumulate(
2199
- dayMap,
2200
- `${model}|unknown`,
2201
- {
2202
- provider: "sourcegraph",
2203
- product: "amp",
2204
- channel: "cli",
2205
- model,
2206
- project: "unknown",
2207
- projectDisplay: "unknown",
2208
- inputTokens: 0,
2209
- cachedInputTokens: 0,
2210
- cacheWriteTokens: 0,
2211
- outputTokens: 0,
2212
- reasoningOutputTokens: 0
2213
- },
2214
- { 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
2215
2944
  );
2945
+ if (byId >= 0) return byId;
2216
2946
  }
2947
+ return ledger.findIndex(
2948
+ (record, index) => !consumed.has(index) && record.model === message.model && tokenFingerprint(record.tokens) === tokenFingerprint(message.tokens)
2949
+ );
2217
2950
  }
2218
- function processMessages(thread, dates, grouped) {
2219
- let msgs2 = thread.messages;
2220
- if (!msgs2) return;
2221
- let entries = Array.isArray(msgs2) ? msgs2 : Object.values(msgs2);
2222
- for (let msg of entries) {
2223
- let usage = msg.usage;
2224
- if (!usage) continue;
2225
- let ts = parseTs(msg.timestamp ?? thread.created);
2226
- if (!ts) continue;
2227
- let dk = dateKey(ts), dayMap = grouped.get(dk);
2228
- if (!dayMap) continue;
2229
- let model = msg.model ?? "unknown", input = usage.inputTokens ?? 0, output = usage.outputTokens ?? 0, cached2 = usage.cacheReadInputTokens ?? 0;
2230
- accumulate(
2231
- dayMap,
2232
- `${model}|unknown`,
2233
- {
2234
- provider: "sourcegraph",
2235
- product: "amp",
2236
- channel: "cli",
2237
- model,
2238
- project: "unknown",
2239
- projectDisplay: "unknown",
2240
- inputTokens: 0,
2241
- cachedInputTokens: 0,
2242
- cacheWriteTokens: 0,
2243
- outputTokens: 0,
2244
- reasoningOutputTokens: 0
2245
- },
2246
- { input, cached: cached2, cacheWrite: 0, output, reasoning: 0 }
2247
- );
2248
- }
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);
2249
2960
  }
2250
2961
 
2251
2962
  // src/scanners/droid.ts
2252
- import { readFile as readFile10 } from "node:fs/promises";
2253
- import { join as join12, dirname as dirname4, basename as basename6 } from "node:path";
2963
+ import { readFile as readFile9 } from "node:fs/promises";
2964
+ import { join as join12, dirname as dirname4, basename as basename8 } from "node:path";
2254
2965
  import { homedir as homedir11 } from "node:os";
2255
2966
  function extractProjectFromSlug(dirPath) {
2256
- let parts = basename6(dirPath).split("-").filter(Boolean);
2967
+ let parts = basename8(dirPath).split("-").filter(Boolean);
2257
2968
  return parts[parts.length - 1] || "unknown";
2258
2969
  }
2259
2970
  async function scanDroidDates(targetDates, baseDir, projectAliases) {
2260
- let dates = new Set(targetDates), dir = baseDir ?? join12(homedir11(), ".factory", "sessions"), files = await walkFiles(dir, ".jsonl");
2971
+ let dates = new Set(targetDates), dir = baseDir ?? join12(homedir11(), ".factory", "sessions"), files = await walkFiles(dir, ".settings.json");
2261
2972
  if (files.length === 0) return emptyResult(dates);
2262
2973
  let grouped = initDateMap(dates);
2263
- for (let jsonlPath of files) {
2264
- let content;
2265
- try {
2266
- content = await readFile10(jsonlPath, "utf-8");
2267
- } catch {
2268
- continue;
2269
- }
2270
- let firstLine = content.split(`
2271
- `).find((l) => l.trim());
2272
- if (!firstLine) continue;
2273
- let firstObj;
2274
- try {
2275
- firstObj = JSON.parse(firstLine);
2276
- } catch {
2277
- continue;
2278
- }
2279
- let ts = parseTs(firstObj.timestamp);
2280
- if (!ts) continue;
2281
- let dk = dateKey(ts), dayMap = grouped.get(dk);
2282
- if (!dayMap) continue;
2283
- let sessionDir = dirname4(jsonlPath), jsonlName = basename6(jsonlPath, ".jsonl"), settingsPath = join12(sessionDir, `${jsonlName}.settings.json`), settingsRaw;
2974
+ for (let settingsPath of files) {
2975
+ let settingsRaw;
2284
2976
  try {
2285
- settingsRaw = await readFile10(settingsPath, "utf-8");
2977
+ settingsRaw = await readFile9(settingsPath, "utf-8");
2286
2978
  } catch {
2287
2979
  continue;
2288
2980
  }
@@ -2294,12 +2986,18 @@ async function scanDroidDates(targetDates, baseDir, projectAliases) {
2294
2986
  }
2295
2987
  let usage = settings.tokenUsage;
2296
2988
  if (!usage) continue;
2297
- let rawInput = usage.inputTokens ?? 0, cacheRead = usage.cacheReadTokens ?? 0, rawOutput = usage.outputTokens ?? 0, thinking = usage.thinkingTokens ?? 0, input = Math.max(rawInput - cacheRead, 0), output = Math.max(rawOutput - thinking, 0), model = settings.model ?? "unknown", rawProject = extractProjectFromSlug(sessionDir), alias = projectAliases?.[rawProject], project = alias ?? rawProject;
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;
2298
2996
  accumulate(
2299
2997
  dayMap,
2300
2998
  `${model}|${project}`,
2301
2999
  {
2302
- provider: "droid",
3000
+ provider,
2303
3001
  product: "droid",
2304
3002
  channel: "cli",
2305
3003
  model,
@@ -2312,80 +3010,187 @@ async function scanDroidDates(targetDates, baseDir, projectAliases) {
2312
3010
  outputTokens: 0,
2313
3011
  reasoningOutputTokens: 0
2314
3012
  },
2315
- { input, cached: cacheRead, cacheWrite: 0, output, reasoning: thinking }
3013
+ { input, cached: cacheRead, cacheWrite, output, reasoning: thinking }
2316
3014
  );
2317
3015
  }
2318
3016
  return finalize(grouped);
2319
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
+ }
2320
3030
 
2321
3031
  // src/scanners/opencode.ts
2322
- import { readFile as readFile11 } from "node:fs/promises";
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";
2323
3035
  import { homedir as homedir12 } from "node:os";
2324
3036
  async function scanOpencodeDates(targetDates, baseDir, projectAliases) {
2325
- let dates = new Set(targetDates), dir = baseDir ?? `${homedir12()}/.local/share/opencode/storage/message`, files = await walkFiles(dir, ".json");
2326
- if (files.length === 0) return emptyResult(dates);
2327
- let grouped = initDateMap(dates);
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");
2328
3041
  for (let filePath of files) {
2329
- let raw;
3042
+ let message;
2330
3043
  try {
2331
- raw = await readFile11(filePath, "utf-8");
3044
+ message = JSON.parse(await readFile10(filePath, "utf-8"));
2332
3045
  } catch {
2333
3046
  continue;
2334
3047
  }
2335
- let msg;
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"))
2336
3058
  try {
2337
- msg = JSON.parse(raw);
3059
+ let record = parseOpenCodeMessage(
3060
+ JSON.parse(await readFile10(filePath, "utf-8")),
3061
+ basename9(filePath, ".json")
3062
+ );
3063
+ record && result.add(dateKey(record.timestamp));
2338
3064
  } catch {
2339
- continue;
2340
3065
  }
2341
- let tokens = msg.tokens;
2342
- if (!tokens) continue;
2343
- let input = tokens.input ?? 0, output = tokens.output ?? 0;
2344
- if (input === 0 && output === 0) continue;
2345
- let ts = parseTs(msg.time?.created);
2346
- if (!ts) continue;
2347
- let dk = dateKey(ts), dayMap = grouped.get(dk);
2348
- if (!dayMap) continue;
2349
- let model = msg.modelID ?? "unknown", cached2 = tokens.cache?.read ?? 0, reasoning = tokens.reasoning ?? 0, rootPath = msg.path?.root, fields = rootPath ? resolveProjectFields(rootPath, projectAliases) : { project: "unknown", projectDisplay: "unknown" };
2350
- accumulate(
2351
- dayMap,
2352
- `${model}|${fields.project}`,
2353
- {
2354
- provider: "opencode",
2355
- product: "opencode",
2356
- channel: "cli",
2357
- model,
2358
- project: fields.project,
2359
- projectDisplay: fields.projectDisplay,
2360
- projectAlias: fields.projectAlias,
2361
- inputTokens: 0,
2362
- cachedInputTokens: 0,
2363
- cacheWriteTokens: 0,
2364
- outputTokens: 0,
2365
- reasoningOutputTokens: 0
2366
- },
2367
- { input, cached: cached2, cacheWrite: 0, output, reasoning }
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)
2368
3110
  );
2369
- }
2370
- return finalize(grouped);
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);
2371
3176
  }
2372
3177
 
2373
3178
  // src/scanners/pi.ts
2374
- import { readFile as readFile12 } from "node:fs/promises";
2375
- import { join as join13, basename as basename7, dirname as dirname5 } from "node:path";
3179
+ import { readFile as readFile11 } from "node:fs/promises";
3180
+ import { join as join14, basename as basename10, dirname as dirname5 } from "node:path";
2376
3181
  import { homedir as homedir13 } from "node:os";
2377
3182
  async function scanPiDates(targetDates, baseDir, projectAliases) {
2378
- let dates = new Set(targetDates), sessionsDir = baseDir ?? getSessionsDir(), files = await walkFiles(sessionsDir, ".jsonl");
3183
+ let dates = new Set(targetDates), sessionDirs = baseDir ? [baseDir] : getSessionDirs(), files = [...new Set((await Promise.all(sessionDirs.map((dir) => walkFiles(dir, ".jsonl")))).flat())];
2379
3184
  if (files.length === 0) return emptyResult(dates);
2380
3185
  let grouped = initDateMap(dates), seen = /* @__PURE__ */ new Set();
2381
3186
  for (let filePath of files) {
2382
3187
  let content;
2383
3188
  try {
2384
- content = await readFile12(filePath, "utf-8");
3189
+ content = await readFile11(filePath, "utf-8");
2385
3190
  } catch {
2386
3191
  continue;
2387
3192
  }
2388
- let parentDir = dirname5(filePath), encodedCwd = basename7(parentDir), sessionProjectFields = { project: extractProjectFromEncoded(encodedCwd), projectDisplay: extractProjectFromEncoded(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);
2389
3194
  for (let line of content.split(`
2390
3195
  `)) {
2391
3196
  if (!line.trim()) continue;
@@ -2396,7 +3201,11 @@ async function scanPiDates(targetDates, baseDir, projectAliases) {
2396
3201
  continue;
2397
3202
  }
2398
3203
  if (obj.type === "session" && obj.cwd) {
2399
- 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;
2400
3209
  continue;
2401
3210
  }
2402
3211
  if (obj.type !== "message") continue;
@@ -2404,20 +3213,19 @@ async function scanPiDates(targetDates, baseDir, projectAliases) {
2404
3213
  if (!msg || msg.role !== "assistant") continue;
2405
3214
  let usage = msg.usage;
2406
3215
  if (!usage || usage.input == null && usage.output == null) continue;
2407
- let ts = parseTs(obj.timestamp);
3216
+ let ts = parseTs(obj.timestamp) ?? fallbackTs;
2408
3217
  if (!ts) continue;
2409
3218
  let dk = dateKey(ts), dayMap = grouped.get(dk);
2410
3219
  if (!dayMap) continue;
2411
- if (obj.id) {
2412
- if (seen.has(obj.id)) continue;
2413
- seen.add(obj.id);
2414
- }
2415
- let model = msg.model ?? "unknown", input = usage.input ?? 0, cached2 = usage.cacheRead ?? 0, output = usage.output ?? 0;
2416
- 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(
2417
3225
  dayMap,
2418
3226
  `${model}|${sessionProjectFields.project}`,
2419
3227
  {
2420
- provider: "inflection",
3228
+ provider,
2421
3229
  product: "pi",
2422
3230
  channel: "cli",
2423
3231
  model,
@@ -2430,15 +3238,15 @@ async function scanPiDates(targetDates, baseDir, projectAliases) {
2430
3238
  outputTokens: 0,
2431
3239
  reasoningOutputTokens: 0
2432
3240
  },
2433
- { input, cached: cached2, cacheWrite: 0, output, reasoning: 0 }
3241
+ { input, cached: cached2, cacheWrite, output, reasoning: 0 }
2434
3242
  );
2435
3243
  }
2436
3244
  }
2437
3245
  return finalize(grouped);
2438
3246
  }
2439
- function getSessionsDir() {
3247
+ function getSessionDirs() {
2440
3248
  let envDir = process.env.PI_CODING_AGENT_DIR;
2441
- return envDir ? join13(envDir, "sessions") : join13(homedir13(), ".pi", "agent", "sessions");
3249
+ return [envDir ? join14(envDir, "sessions") : join14(homedir13(), ".pi", "agent", "sessions"), join14(homedir13(), ".omp", "agent", "sessions")];
2442
3250
  }
2443
3251
  function extractProjectFromEncoded(encoded) {
2444
3252
  let parts = encoded.split("-").filter(Boolean);
@@ -2579,7 +3387,7 @@ function chunkDateRange(startDate, endDate) {
2579
3387
  }
2580
3388
 
2581
3389
  // src/scanners/anthropic-csv.ts
2582
- import { readFile as readFile13 } from "node:fs/promises";
3390
+ import { readFile as readFile12 } from "node:fs/promises";
2583
3391
  async function scanAnthropicCsvDates(targetDates, csvFilePaths) {
2584
3392
  if (!targetDates.length) return /* @__PURE__ */ new Map();
2585
3393
  let targetDateSet = new Set(targetDates), grouped = new Map(
@@ -2588,7 +3396,7 @@ async function scanAnthropicCsvDates(targetDates, csvFilePaths) {
2588
3396
  for (let filePath of csvFilePaths) {
2589
3397
  let content;
2590
3398
  try {
2591
- content = await readFile13(filePath, "utf-8");
3399
+ content = await readFile12(filePath, "utf-8");
2592
3400
  } catch {
2593
3401
  continue;
2594
3402
  }
@@ -2646,9 +3454,9 @@ function parseCsv(content) {
2646
3454
  }
2647
3455
 
2648
3456
  // src/report.ts
2649
- import { readdir as readdir6, readFile as readFile14 } from "node:fs/promises";
3457
+ import { readdir as readdir5, readFile as readFile13 } from "node:fs/promises";
2650
3458
  import { homedir as homedir14 } from "node:os";
2651
- import { basename as basename8, join as join14 } from "node:path";
3459
+ import { basename as basename11, dirname as dirname6, join as join15 } from "node:path";
2652
3460
  async function buildLocalReport(range, options = {}) {
2653
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 });
2654
3462
  for (let result of results) {
@@ -2717,41 +3525,61 @@ function buildPresetDates(range) {
2717
3525
  }
2718
3526
  async function discoverAllDates() {
2719
3527
  let dates = /* @__PURE__ */ new Set(), home = homedir14();
2720
- return await Promise.all([
3528
+ await Promise.all([
2721
3529
  discoverClaudeDates(dates),
2722
3530
  discoverCodexDates(dates),
2723
3531
  discoverGeminiDates(dates),
2724
3532
  discoverCopilotVscodeDates(dates),
2725
3533
  discoverAntigravityDates(dates),
2726
- discoverGenericJsonlDates(join14(home, ".copilot", "session-state"), dates),
2727
- discoverGenericJsonlDates(join14(home, ".qwen", "tmp"), dates),
2728
- discoverGenericJsonlDates(join14(home, ".kimi", "sessions"), dates),
2729
- discoverGenericJsonDates(join14(home, ".local", "share", "amp", "threads"), dates),
2730
- discoverGenericJsonlDates(join14(home, ".factory", "sessions"), dates),
2731
- discoverGenericJsonDates(join14(home, ".local", "share", "opencode"), dates),
2732
- discoverGenericJsonlDates(join14(home, ".pi", "agent", "sessions"), dates)
2733
- ]), [...dates].sort();
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();
2734
3548
  }
2735
3549
  async function discoverGenericJsonlDates(baseDir, dates) {
2736
3550
  let files = [];
2737
3551
  await walkForFiles(baseDir, ".jsonl", files);
2738
3552
  for (let filePath of files) {
2739
3553
  let content = await safeReadUtf8(filePath);
2740
- if (content)
2741
- for (let line of content.split(`
3554
+ if (!content) continue;
3555
+ let foundDate = !1;
3556
+ for (let line of content.split(`
2742
3557
  `)) {
2743
- if (!line.trim()) continue;
2744
- let record;
2745
- try {
2746
- record = JSON.parse(line);
2747
- } catch {
2748
- continue;
2749
- }
2750
- let ts = parseTs(record.timestamp);
2751
- ts && dates.add(dateKey(ts));
3558
+ if (!line.trim()) continue;
3559
+ let record;
3560
+ try {
3561
+ record = JSON.parse(line);
3562
+ } catch {
3563
+ continue;
2752
3564
  }
3565
+ foundDate = collectRecordDates(record, dates) || foundDate;
3566
+ }
3567
+ foundDate || await addFileModifiedDate(filePath, dates);
2753
3568
  }
2754
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
+ }
2755
3583
  async function discoverGenericJsonDates(baseDir, dates) {
2756
3584
  let files = [];
2757
3585
  await walkForFiles(baseDir, ".json", files);
@@ -2764,78 +3592,84 @@ async function discoverGenericJsonDates(baseDir, dates) {
2764
3592
  } catch {
2765
3593
  continue;
2766
3594
  }
2767
- let topTs = parseTs(data.timestamp ?? data.createTime);
2768
- topTs && dates.add(dateKey(topTs));
2769
- let msgs2 = data.messages ?? data.history ?? [];
2770
- if (Array.isArray(msgs2))
2771
- for (let msg of msgs2) {
2772
- let ts = parseTs(msg.timestamp ?? msg.createTime);
2773
- ts && dates.add(dateKey(ts));
2774
- }
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);
2775
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));
2776
3648
  }
2777
3649
  async function walkForFiles(dir, ext, result) {
2778
3650
  let entries;
2779
3651
  try {
2780
- entries = await readdir6(dir, { withFileTypes: !0 });
3652
+ entries = await readdir5(dir, { withFileTypes: !0 });
2781
3653
  } catch {
2782
3654
  return;
2783
3655
  }
2784
3656
  for (let entry of entries) {
2785
- let fullPath = join14(dir, entry.name);
3657
+ let fullPath = join15(dir, entry.name);
2786
3658
  entry.isDirectory() ? await walkForFiles(fullPath, ext, result) : entry.name.endsWith(ext) && result.push(fullPath);
2787
3659
  }
2788
3660
  }
2789
3661
  async function discoverGeminiDates(dates) {
2790
- let baseDir = join14(homedir14(), ".gemini", "tmp"), files = [];
2791
- await walkForGeminiJsonl(baseDir, files);
2792
- for (let filePath of files) {
2793
- let content = await safeReadUtf8(filePath);
2794
- if (!content) continue;
2795
- let session;
2796
- try {
2797
- session = JSON.parse(content);
2798
- } catch {
2799
- continue;
2800
- }
2801
- if (Array.isArray(session)) {
2802
- for (let row of session) {
2803
- let ts = parseTs(row.timestamp);
2804
- ts && dates.add(dateKey(ts));
2805
- }
2806
- continue;
2807
- }
2808
- let topLevelTs = parseTs(session.timestamp ?? session.createTime ?? session.startTime ?? session.data?.createTime);
2809
- topLevelTs && dates.add(dateKey(topLevelTs));
2810
- let messages = [
2811
- ...session.messages ?? [],
2812
- ...session.history ?? [],
2813
- ...session.data?.messages ?? [],
2814
- ...session.data?.history ?? []
2815
- ];
2816
- for (let msg of messages) {
2817
- let ts = parseTs(msg.timestamp ?? msg.createTime);
2818
- ts && dates.add(dateKey(ts));
2819
- }
2820
- }
2821
- }
2822
- async function walkForGeminiJsonl(dir, result) {
2823
- let entries;
2824
- try {
2825
- entries = await readdir6(dir, { withFileTypes: !0 });
2826
- } catch {
2827
- return;
2828
- }
2829
- for (let entry of entries) {
2830
- let fullPath = join14(dir, entry.name);
2831
- entry.isDirectory() ? await walkForGeminiJsonl(fullPath, result) : entry.name.endsWith(".json") && result.push(fullPath);
2832
- }
3662
+ let baseDir = join15(homedir14(), ".gemini", "tmp");
3663
+ await Promise.all([
3664
+ discoverGenericJsonDates(baseDir, dates),
3665
+ discoverGenericJsonlDates(baseDir, dates)
3666
+ ]);
2833
3667
  }
2834
3668
  async function discoverCopilotVscodeDates(dates) {
2835
3669
  let home = homedir14(), logFiles = [];
2836
- await walkForFiles(join14(home, "Library", "Application Support", "Code", "logs"), ".log", logFiles);
3670
+ await walkForFiles(join15(home, "Library", "Application Support", "Code", "logs"), ".log", logFiles);
2837
3671
  for (let filePath of logFiles) {
2838
- if (basename8(filePath) !== "GitHub Copilot Chat.log") continue;
3672
+ if (basename11(filePath) !== "GitHub Copilot Chat.log") continue;
2839
3673
  let content = await safeReadUtf8(filePath);
2840
3674
  if (content)
2841
3675
  for (let line of content.split(`
@@ -2846,9 +3680,9 @@ async function discoverCopilotVscodeDates(dates) {
2846
3680
  }
2847
3681
  }
2848
3682
  let sessionFiles = [];
2849
- await walkForFiles(join14(home, "Library", "Application Support", "Code", "User", "workspaceStorage"), ".json", sessionFiles);
3683
+ await walkForFiles(join15(home, "Library", "Application Support", "Code", "User", "workspaceStorage"), ".json", sessionFiles);
2850
3684
  for (let filePath of sessionFiles) {
2851
- if (!filePath.includes("/chatSessions/")) continue;
3685
+ if (!isChatSessionFile2(filePath)) continue;
2852
3686
  let content = await safeReadUtf8(filePath);
2853
3687
  if (!content) continue;
2854
3688
  let session;
@@ -2863,12 +3697,44 @@ async function discoverCopilotVscodeDates(dates) {
2863
3697
  ts && dates.add(dateKey(ts));
2864
3698
  }
2865
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";
2866
3732
  }
2867
3733
  async function discoverAntigravityDates(dates) {
2868
3734
  let home = homedir14(), brainFiles = [], browserFiles = [];
2869
- await walkForFiles(join14(home, ".gemini", "antigravity", "brain"), ".json", brainFiles), await walkForFiles(join14(home, ".gemini", "antigravity", "browser_recordings"), ".json", browserFiles);
3735
+ await walkForFiles(join15(home, ".gemini", "antigravity", "brain"), ".json", brainFiles), await walkForFiles(join15(home, ".gemini", "antigravity", "browser_recordings"), ".json", browserFiles);
2870
3736
  for (let filePath of brainFiles) {
2871
- if (basename8(filePath) !== "task.md.metadata.json") continue;
3737
+ if (basename11(filePath) !== "task.md.metadata.json") continue;
2872
3738
  let content = await safeReadUtf8(filePath);
2873
3739
  if (!content) continue;
2874
3740
  let data;
@@ -2881,7 +3747,7 @@ async function discoverAntigravityDates(dates) {
2881
3747
  ts && dates.add(dateKey(ts));
2882
3748
  }
2883
3749
  for (let filePath of browserFiles) {
2884
- if (basename8(filePath) !== "metadata.json") continue;
3750
+ if (basename11(filePath) !== "metadata.json") continue;
2885
3751
  let content = await safeReadUtf8(filePath);
2886
3752
  if (!content) continue;
2887
3753
  let data;
@@ -2896,20 +3762,20 @@ async function discoverAntigravityDates(dates) {
2896
3762
  }
2897
3763
  async function discoverClaudeDates(dates) {
2898
3764
  let home = homedir14(), baseDirs = [
2899
- join14(home, ".config", "claude", "projects"),
2900
- join14(home, ".claude", "projects")
3765
+ join15(home, ".config", "claude", "projects"),
3766
+ join15(home, ".claude", "projects")
2901
3767
  ];
2902
3768
  for (let baseDir of baseDirs) {
2903
3769
  let projectDirs;
2904
3770
  try {
2905
- projectDirs = await readdir6(baseDir);
3771
+ projectDirs = await readdir5(baseDir);
2906
3772
  } catch {
2907
3773
  continue;
2908
3774
  }
2909
3775
  for (let projectDir of projectDirs) {
2910
3776
  let jsonlFiles = [];
2911
3777
  try {
2912
- await walkForClaudeJsonl(join14(baseDir, projectDir), jsonlFiles);
3778
+ await walkForClaudeJsonl(join15(baseDir, projectDir), jsonlFiles);
2913
3779
  } catch {
2914
3780
  continue;
2915
3781
  }
@@ -2933,7 +3799,7 @@ async function discoverClaudeDates(dates) {
2933
3799
  }
2934
3800
  }
2935
3801
  async function discoverCodexDates(dates) {
2936
- let baseDir = join14(homedir14(), ".codex"), files = await collectCodexSessionFiles(baseDir);
3802
+ let baseDir = join15(homedir14(), ".codex"), files = await collectCodexSessionFiles(baseDir);
2937
3803
  for (let filePath of files) {
2938
3804
  let content = await safeReadUtf8(filePath);
2939
3805
  if (content)
@@ -2955,35 +3821,35 @@ async function discoverCodexDates(dates) {
2955
3821
  async function collectCodexSessionFiles(baseDir) {
2956
3822
  let paths = [];
2957
3823
  try {
2958
- let archivedFiles = await readdir6(join14(baseDir, "archived_sessions"));
3824
+ let archivedFiles = await readdir5(join15(baseDir, "archived_sessions"));
2959
3825
  for (let file of archivedFiles)
2960
- file.endsWith(".jsonl") && paths.push(join14(baseDir, "archived_sessions", file));
3826
+ file.endsWith(".jsonl") && paths.push(join15(baseDir, "archived_sessions", file));
2961
3827
  } catch {
2962
3828
  }
2963
- return await walkForCodexJsonl(join14(baseDir, "sessions"), paths), paths;
3829
+ return await walkForCodexJsonl(join15(baseDir, "sessions"), paths), paths;
2964
3830
  }
2965
3831
  async function walkForClaudeJsonl(dir, result) {
2966
- let entries = await readdir6(dir, { withFileTypes: !0 });
3832
+ let entries = await readdir5(dir, { withFileTypes: !0 });
2967
3833
  for (let entry of entries) {
2968
- let fullPath = join14(dir, entry.name);
3834
+ let fullPath = join15(dir, entry.name);
2969
3835
  entry.isDirectory() ? await walkForClaudeJsonl(fullPath, result) : entry.name.endsWith(".jsonl") && result.push(fullPath);
2970
3836
  }
2971
3837
  }
2972
3838
  async function walkForCodexJsonl(dir, result) {
2973
3839
  let entries;
2974
3840
  try {
2975
- entries = await readdir6(dir, { withFileTypes: !0 });
3841
+ entries = await readdir5(dir, { withFileTypes: !0 });
2976
3842
  } catch {
2977
3843
  return;
2978
3844
  }
2979
3845
  for (let entry of entries) {
2980
- let fullPath = join14(dir, entry.name);
3846
+ let fullPath = join15(dir, entry.name);
2981
3847
  entry.isDirectory() ? await walkForCodexJsonl(fullPath, result) : entry.name.startsWith("rollout-") && entry.name.endsWith(".jsonl") && result.push(fullPath);
2982
3848
  }
2983
3849
  }
2984
3850
  async function safeReadUtf8(filePath) {
2985
3851
  try {
2986
- return await readFile14(filePath, "utf-8");
3852
+ return await readFile13(filePath, "utf-8");
2987
3853
  } catch {
2988
3854
  return null;
2989
3855
  }
@@ -3267,10 +4133,10 @@ function fmtDateShort(dateStr) {
3267
4133
  }
3268
4134
 
3269
4135
  // src/activity.ts
3270
- import { open as open3, readdir as readdir7 } from "node:fs/promises";
4136
+ import { open, readdir as readdir6 } from "node:fs/promises";
3271
4137
  import { createInterface as createInterface3 } from "node:readline";
3272
4138
  import { homedir as homedir15 } from "node:os";
3273
- import { basename as basename9, join as join15 } from "node:path";
4139
+ import { basename as basename12, join as join16 } from "node:path";
3274
4140
  var FILE_CONCURRENCY3 = 16, MAX_LINE_BYTES3 = 64 * 1024 * 1024;
3275
4141
  async function buildActivityReport(range, options = {}) {
3276
4142
  let targetDates = options.dates ? new Set(options.dates) : void 0, [codex, claude] = await Promise.all([
@@ -3367,7 +4233,7 @@ function renderActivityReport(report, opts) {
3367
4233
  `);
3368
4234
  }
3369
4235
  async function scanCodexActivity(targetDates, options) {
3370
- let baseDir = options.codexDir ?? join15(homedir15(), ".codex"), acc = createAccumulator(targetDates, options.projectAliases), files = await collectCodexSessionFiles2(baseDir);
4236
+ let baseDir = options.codexDir ?? join16(homedir15(), ".codex"), acc = createAccumulator(targetDates, options.projectAliases), files = await collectCodexSessionFiles2(baseDir);
3371
4237
  return acc.stats.filesScanned = files.length, await runWithConcurrency(files, FILE_CONCURRENCY3, async (filePath) => {
3372
4238
  await processCodexFile2(filePath, acc);
3373
4239
  }), finalizeActivity(acc);
@@ -3375,11 +4241,11 @@ async function scanCodexActivity(targetDates, options) {
3375
4241
  async function processCodexFile2(filePath, acc) {
3376
4242
  let fh;
3377
4243
  try {
3378
- fh = await open3(filePath, "r");
4244
+ fh = await open(filePath, "r");
3379
4245
  } catch {
3380
4246
  return;
3381
4247
  }
3382
- let sessionId = basename9(filePath).replace(/\.jsonl$/, ""), projectFields = { project: "unknown", projectDisplay: "unknown" };
4248
+ let sessionId = basename12(filePath).replace(/\.jsonl$/, ""), projectFields = { project: "unknown", projectDisplay: "unknown" };
3383
4249
  try {
3384
4250
  let rl = createInterface3({
3385
4251
  input: fh.createReadStream({ encoding: "utf-8" }),
@@ -3394,12 +4260,12 @@ async function processCodexFile2(filePath, acc) {
3394
4260
  continue;
3395
4261
  }
3396
4262
  if (record.type === "session_meta") {
3397
- let id = stringValue(record.payload?.id);
4263
+ let id = stringValue2(record.payload?.id);
3398
4264
  id && (sessionId = id), acc.stats.sessions.add(`codex:${sessionId}`);
3399
4265
  continue;
3400
4266
  }
3401
4267
  if (record.type === "turn_context") {
3402
- let cwd = stringValue(record.payload?.cwd);
4268
+ let cwd = stringValue2(record.payload?.cwd);
3403
4269
  cwd && (projectFields = resolveProjectFields(cwd, acc.projectAliases));
3404
4270
  continue;
3405
4271
  }
@@ -3443,7 +4309,7 @@ function handleCodexResponseItem(item, usageDate, projectFields, sessionId, file
3443
4309
  projectFields,
3444
4310
  sessionId,
3445
4311
  kind,
3446
- name: kind === "agent_call" ? stringValue(args.agent_type) ?? name : name,
4312
+ name: kind === "agent_call" ? stringValue2(args.agent_type) ?? name : name,
3447
4313
  confidence: "exact",
3448
4314
  dedupeKey: baseKey
3449
4315
  });
@@ -3497,14 +4363,14 @@ function handleCodexEvent(record, usageDate, projectFields, sessionId, filePath,
3497
4363
  projectFields,
3498
4364
  sessionId,
3499
4365
  timestamp: record.timestamp ?? "",
3500
- content: stringValue(record.payload?.message),
4366
+ content: stringValue2(record.payload?.message),
3501
4367
  fallbackKey: `${filePath}:${usageDate}:${sessionId}:event_user_message:${record.timestamp ?? ""}`
3502
4368
  });
3503
4369
  return;
3504
4370
  }
3505
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;
3506
4372
  if (!kind) return;
3507
- let callId = stringValue(record.payload?.call_id);
4373
+ let callId = stringValue2(record.payload?.call_id);
3508
4374
  addActivity(acc, {
3509
4375
  usageDate,
3510
4376
  provider: "openai",
@@ -3522,13 +4388,13 @@ async function scanClaudeActivity(targetDates, options) {
3522
4388
  for (let baseDir of getClaudeProjectDirs2(options.claudeProjectsDirs)) {
3523
4389
  let projectDirs;
3524
4390
  try {
3525
- projectDirs = await readdir7(baseDir, { withFileTypes: !0 });
4391
+ projectDirs = await readdir6(baseDir, { withFileTypes: !0 });
3526
4392
  } catch {
3527
4393
  continue;
3528
4394
  }
3529
4395
  for (let entry of projectDirs) {
3530
4396
  if (!entry.isDirectory()) continue;
3531
- let projectPath = join15(baseDir, entry.name), jsonlFiles = [];
4397
+ let projectPath = join16(baseDir, entry.name), jsonlFiles = [];
3532
4398
  await walkJsonl(projectPath, jsonlFiles);
3533
4399
  let fields = resolveClaudeProject(projectPath, acc.projectAliases);
3534
4400
  for (let filePath of jsonlFiles) fileJobs.push({ filePath, projectFields: fields });
@@ -3541,11 +4407,11 @@ async function scanClaudeActivity(targetDates, options) {
3541
4407
  async function processClaudeFile(filePath, fallbackFields, acc) {
3542
4408
  let fh;
3543
4409
  try {
3544
- fh = await open3(filePath, "r");
4410
+ fh = await open(filePath, "r");
3545
4411
  } catch {
3546
4412
  return;
3547
4413
  }
3548
- let fallbackSessionId = basename9(filePath).replace(/\.jsonl$/, "");
4414
+ let fallbackSessionId = basename12(filePath).replace(/\.jsonl$/, "");
3549
4415
  try {
3550
4416
  let rl = createInterface3({
3551
4417
  input: fh.createReadStream({ encoding: "utf-8" }),
@@ -3666,38 +4532,38 @@ function acceptsDate(acc, usageDate) {
3666
4532
  async function collectCodexSessionFiles2(baseDir) {
3667
4533
  let paths = [];
3668
4534
  try {
3669
- let files = await readdir7(join15(baseDir, "archived_sessions"));
4535
+ let files = await readdir6(join16(baseDir, "archived_sessions"));
3670
4536
  for (let file of files)
3671
- file.endsWith(".jsonl") && paths.push(join15(baseDir, "archived_sessions", file));
4537
+ file.endsWith(".jsonl") && paths.push(join16(baseDir, "archived_sessions", file));
3672
4538
  } catch {
3673
4539
  }
3674
- return await walkJsonl(join15(baseDir, "sessions"), paths), paths;
4540
+ return await walkJsonl(join16(baseDir, "sessions"), paths), paths;
3675
4541
  }
3676
4542
  function getClaudeProjectDirs2(configured) {
3677
4543
  if (configured?.length) return configured;
3678
4544
  let envVar = process.env.CLAUDE_CONFIG_DIR?.trim();
3679
4545
  if (envVar)
3680
- return envVar.split(",").map((p) => p.trim()).filter(Boolean).map((p) => join15(p, "projects"));
4546
+ return envVar.split(",").map((p) => p.trim()).filter(Boolean).map((p) => join16(p, "projects"));
3681
4547
  let home = homedir15();
3682
4548
  return [
3683
- join15(home, ".config", "claude", "projects"),
3684
- join15(home, ".claude", "projects")
4549
+ join16(home, ".config", "claude", "projects"),
4550
+ join16(home, ".claude", "projects")
3685
4551
  ];
3686
4552
  }
3687
4553
  async function walkJsonl(dir, result) {
3688
4554
  let entries;
3689
4555
  try {
3690
- entries = await readdir7(dir, { withFileTypes: !0 });
4556
+ entries = await readdir6(dir, { withFileTypes: !0 });
3691
4557
  } catch {
3692
4558
  return;
3693
4559
  }
3694
4560
  for (let entry of entries) {
3695
- let fullPath = join15(dir, entry.name);
4561
+ let fullPath = join16(dir, entry.name);
3696
4562
  entry.isDirectory() ? await walkJsonl(fullPath, result) : entry.name.endsWith(".jsonl") && result.push(fullPath);
3697
4563
  }
3698
4564
  }
3699
4565
  function resolveClaudeProject(projectPath, aliases2) {
3700
- let rawName = basename9(projectPath), display = rawName.split("-").filter(Boolean).at(-1) || rawName || "unknown", alias = aliases2?.[projectPath] ?? aliases2?.[display];
4566
+ let rawName = basename12(projectPath), display = rawName.split("-").filter(Boolean).at(-1) || rawName || "unknown", alias = aliases2?.[projectPath] ?? aliases2?.[display];
3701
4567
  return {
3702
4568
  project: projectPath,
3703
4569
  projectDisplay: display,
@@ -3708,22 +4574,22 @@ function classifyClaudeTool(name) {
3708
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";
3709
4575
  }
3710
4576
  function getClaudeMetricName(toolName, input) {
3711
- return toolName === "Skill" ? stringValue(input?.skill) ?? "unknown" : toolName === "Agent" ? stringValue(input?.description) ?? stringValue(input?.subagent_type) ?? "unknown" : toolName;
4577
+ return toolName === "Skill" ? stringValue2(input?.skill) ?? "unknown" : toolName === "Agent" ? stringValue2(input?.description) ?? stringValue2(input?.subagent_type) ?? "unknown" : toolName;
3712
4578
  }
3713
4579
  function isClaudeUserMessage(record) {
3714
4580
  if (record.type !== "user" || record.message?.role !== "user" || record.isMeta || record.toolUseResult || record.sourceToolAssistantUUID || record.sourceToolUseID) return !1;
3715
4581
  let content = record.message.content;
3716
- 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" && stringValue(block.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));
3717
4583
  }
3718
4584
  function hasCodexUserMessageContent(content) {
3719
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");
3720
4586
  }
3721
4587
  function extractCodexMessageText(content) {
3722
- return typeof content == "string" ? content : Array.isArray(content) && content.map((block) => stringValue(block.text)).filter(Boolean).join(`
4588
+ return typeof content == "string" ? content : Array.isArray(content) && content.map((block) => stringValue2(block.text)).filter(Boolean).join(`
3723
4589
  `) || void 0;
3724
4590
  }
3725
4591
  function extractClaudeMessageText(content) {
3726
- return typeof content == "string" ? content : Array.isArray(content) && content.filter((block) => block?.type === "text").map((block) => stringValue(block.text)).filter(Boolean).join(`
4592
+ return typeof content == "string" ? content : Array.isArray(content) && content.filter((block) => block?.type === "text").map((block) => stringValue2(block.text)).filter(Boolean).join(`
3727
4593
  `) || void 0;
3728
4594
  }
3729
4595
  function normalizeMessageText(value) {
@@ -3731,7 +4597,7 @@ function normalizeMessageText(value) {
3731
4597
  }
3732
4598
  function extractSkillProxyNames(rawArguments) {
3733
4599
  if (!rawArguments) return [];
3734
- let args = parseJsonObject(rawArguments), command2 = stringValue(args.cmd) ?? stringValue(args.command) ?? "";
4600
+ let args = parseJsonObject(rawArguments), command2 = stringValue2(args.cmd) ?? stringValue2(args.command) ?? "";
3735
4601
  if (!command2.includes("SKILL.md")) return [];
3736
4602
  let names = /* @__PURE__ */ new Set();
3737
4603
  for (let match of command2.matchAll(/([^\s'"]*SKILL\.md)/g))
@@ -3751,7 +4617,7 @@ function skillNameFromPath(rawPath) {
3751
4617
  let parts = rawPath.replace(/^[`'"]+|[`'"]+$/g, "").split("/").filter(Boolean), idx = parts.lastIndexOf("SKILL.md"), name = idx > 0 ? parts[idx - 1] : void 0;
3752
4618
  return !name || name === "$d" || name === "s#" ? "unknown-skill" : name;
3753
4619
  }
3754
- function stringValue(value) {
4620
+ function stringValue2(value) {
3755
4621
  return typeof value == "string" && value.length > 0 ? value : void 0;
3756
4622
  }
3757
4623
  function summarize(items, keyFn, labelFn, limit) {
@@ -3844,10 +4710,10 @@ function stripAnsi(s) {
3844
4710
  }
3845
4711
 
3846
4712
  // src/config.ts
3847
- import { mkdir, readFile as readFile15, writeFile } from "node:fs/promises";
4713
+ import { mkdir, readFile as readFile14, writeFile } from "node:fs/promises";
3848
4714
  import { homedir as homedir16, hostname } from "node:os";
3849
- import { basename as basename10, join as join16 } from "node:path";
3850
- var CONFIG_DIR = join16(homedir16(), ".aiusage"), CONFIG_PATH = join16(CONFIG_DIR, "config.json");
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");
3851
4717
  function getConfigPath() {
3852
4718
  return CONFIG_PATH;
3853
4719
  }
@@ -3874,7 +4740,7 @@ function migrateConfig(config) {
3874
4740
  }
3875
4741
  async function readConfig() {
3876
4742
  try {
3877
- let raw = await readFile15(CONFIG_PATH, "utf-8");
4743
+ let raw = await readFile14(CONFIG_PATH, "utf-8");
3878
4744
  return migrateConfig(JSON.parse(raw));
3879
4745
  } catch {
3880
4746
  return {};
@@ -3982,13 +4848,13 @@ import { hostname as hostname2 } from "node:os";
3982
4848
 
3983
4849
  // src/version.ts
3984
4850
  import { readFileSync } from "node:fs";
3985
- import { resolve as resolve2, dirname as dirname6 } from "node:path";
4851
+ import { resolve as resolve2, dirname as dirname7 } from "node:path";
3986
4852
  import { fileURLToPath } from "node:url";
3987
4853
  var cached;
3988
4854
  function getVersion() {
3989
4855
  if (cached !== void 0) return cached;
3990
4856
  try {
3991
- let pkg = resolve2(dirname6(fileURLToPath(import.meta.url)), "..", "package.json");
4857
+ let pkg = resolve2(dirname7(fileURLToPath(import.meta.url)), "..", "package.json");
3992
4858
  cached = JSON.parse(readFileSync(pkg, "utf-8")).version;
3993
4859
  } catch {
3994
4860
  cached = "unknown";
@@ -4061,12 +4927,12 @@ async function requestJson(url, init) {
4061
4927
  }
4062
4928
 
4063
4929
  // src/schedule.ts
4064
- import { mkdir as mkdir2, readFile as readFile16, stat, unlink, writeFile as writeFile2 } from "node:fs/promises";
4065
- 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";
4066
4932
  import { promisify } from "node:util";
4067
4933
  import { homedir as homedir17, platform, tmpdir as tmpdir2 } from "node:os";
4068
- import { join as join17, resolve as resolve3 } from "node:path";
4069
- var execFileAsync = promisify(execFile), LABEL = "com.aiusage.sync", PLIST_PATH = join17(homedir17(), "Library", "LaunchAgents", `${LABEL}.plist`), LOG_PATH = join17(homedir17(), ".aiusage", "sync.log"), CRON_MARKER = "# aiusage-sync";
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";
4070
4936
  function parseInterval(value) {
4071
4937
  let match = value.match(/^(\d+)(m|h|d)$/);
4072
4938
  if (!match) throw new Error("--every \u683C\u5F0F\u9519\u8BEF\uFF0C\u793A\u4F8B: 30m, 1h, 2h, 1d");
@@ -4111,7 +4977,7 @@ function resolveCommandPaths() {
4111
4977
  }
4112
4978
  async function enableLaunchd(intervalSeconds) {
4113
4979
  let { nodePath, scriptPath } = resolveCommandPaths();
4114
- await mkdir2(join17(homedir17(), ".aiusage"), { recursive: !0 });
4980
+ await mkdir2(join18(homedir17(), ".aiusage"), { recursive: !0 });
4115
4981
  let plist = [
4116
4982
  '<?xml version="1.0" encoding="UTF-8"?>',
4117
4983
  '<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">',
@@ -4160,12 +5026,12 @@ async function disableLaunchd() {
4160
5026
  }
4161
5027
  async function getLaunchdStatus() {
4162
5028
  try {
4163
- await stat(PLIST_PATH);
5029
+ await stat3(PLIST_PATH);
4164
5030
  } catch {
4165
5031
  return { enabled: !1 };
4166
5032
  }
4167
5033
  try {
4168
- let content = await readFile16(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];
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];
4169
5035
  return {
4170
5036
  enabled: !0,
4171
5037
  interval,
@@ -4180,8 +5046,8 @@ async function getLaunchdStatus() {
4180
5046
  }
4181
5047
  }
4182
5048
  async function enableCron(intervalSeconds) {
4183
- let { nodePath, scriptPath } = resolveCommandPaths(), cronExpr = secondsToCron(intervalSeconds), logPath = join17(homedir17(), ".aiusage", "sync.log"), cronLine = `${cronExpr} ${nodePath} ${scriptPath} sync --today >> ${logPath} 2>&1 ${CRON_MARKER}`;
4184
- await mkdir2(join17(homedir17(), ".aiusage"), { recursive: !0 });
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 });
4185
5051
  let existing = "";
4186
5052
  try {
4187
5053
  let { stdout } = await execFileAsync("crontab", ["-l"]);
@@ -4239,7 +5105,7 @@ async function getCronStatus() {
4239
5105
  }
4240
5106
  }
4241
5107
  async function writeCrontab(content) {
4242
- let tmpFile = join17(tmpdir2(), `aiusage-cron-${Date.now()}`);
5108
+ let tmpFile = join18(tmpdir2(), `aiusage-cron-${Date.now()}`);
4243
5109
  await writeFile2(tmpFile, content, "utf-8");
4244
5110
  try {
4245
5111
  await execFileAsync("crontab", [tmpFile]);
@@ -4270,9 +5136,9 @@ function escapeXml(value) {
4270
5136
  }
4271
5137
 
4272
5138
  // src/doctor.ts
4273
- import { readdir as readdir8, stat as stat2 } from "node:fs/promises";
5139
+ import { readdir as readdir7, stat as stat4 } from "node:fs/promises";
4274
5140
  import { homedir as homedir18 } from "node:os";
4275
- import { join as join18 } from "node:path";
5141
+ import { join as join19 } from "node:path";
4276
5142
  var msgs = {
4277
5143
  en: {
4278
5144
  groupConfig: "Configuration",
@@ -4328,13 +5194,13 @@ async function countFiles(dir, exts, cap = 1e3) {
4328
5194
  for (; queue.length > 0 && count < cap; ) {
4329
5195
  let current = queue.pop(), entries;
4330
5196
  try {
4331
- entries = await readdir8(current, { withFileTypes: !0 });
5197
+ entries = await readdir7(current, { withFileTypes: !0 });
4332
5198
  } catch {
4333
5199
  continue;
4334
5200
  }
4335
5201
  for (let e of entries) {
4336
5202
  if (count >= cap) break;
4337
- let full = join18(current, e.name);
5203
+ let full = join19(current, e.name);
4338
5204
  e.isDirectory() ? queue.push(full) : exts.some((ext) => e.name.endsWith(ext)) && count++;
4339
5205
  }
4340
5206
  }
@@ -4343,7 +5209,7 @@ async function countFiles(dir, exts, cap = 1e3) {
4343
5209
  async function runDoctor(lang = "zh") {
4344
5210
  let s = msgs[lang], checks = [], config = await readConfig(), g1 = s.groupConfig, configPath = getConfigPath();
4345
5211
  try {
4346
- await stat2(configPath), checks.push({ group: g1, name: s.config, status: "ok", message: configPath });
5212
+ await stat4(configPath), checks.push({ group: g1, name: s.config, status: "ok", message: configPath });
4347
5213
  } catch {
4348
5214
  checks.push({ group: g1, name: s.config, status: "fail", message: s.configMissing });
4349
5215
  }
@@ -4364,28 +5230,39 @@ async function runDoctor(lang = "zh") {
4364
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 });
4365
5231
  }
4366
5232
  let g3 = s.groupTools, home = homedir18(), tools = [
4367
- { dir: join18(home, ".claude", "projects"), label: "Claude Code", exts: [".jsonl"] },
4368
- { dir: join18(home, ".codex"), label: "Codex CLI", exts: [".jsonl"] },
4369
- { dir: join18(home, "Library", "Application Support", "Cursor", "User", "globalStorage"), label: "Cursor", exts: [".vscdb"] },
4370
- { dir: join18(home, ".copilot", "session-state"), label: "Copilot CLI", exts: [".jsonl"] },
4371
- { dir: join18(home, "Library", "Application Support", "Code", "logs"), label: "Copilot VS Code", exts: [".log"] },
4372
- { dir: join18(home, ".gemini", "tmp"), label: "Gemini CLI", exts: [".json"] },
4373
- { dir: join18(home, ".gemini", "antigravity"), label: "Antigravity", exts: [".json"] },
4374
- { dir: join18(home, ".qwen", "tmp"), label: "Qwen Code", exts: [".jsonl"] },
4375
- { dir: join18(home, ".kimi", "sessions"), label: "Kimi Code", exts: [".jsonl"] },
4376
- { dir: join18(home, ".local", "share", "amp", "threads"), label: "Amp", exts: [".json"] },
4377
- { dir: join18(home, ".factory", "sessions"), label: "Droid", exts: [".jsonl", ".json"] },
4378
- { dir: join18(home, ".local", "share", "opencode"), label: "OpenCode", exts: [".json"] },
4379
- { dir: join18(home, ".pi", "agent", "sessions"), label: "Pi", exts: [".jsonl"] }
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"] }
4380
5254
  ];
4381
5255
  for (let tool of tools) {
4382
- try {
4383
- await stat2(tool.dir);
4384
- } catch {
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) {
4385
5263
  checks.push({ group: g3, name: tool.label, status: "warn", message: s.notInstalled });
4386
5264
  continue;
4387
5265
  }
4388
- let n = await countFiles(tool.dir, tool.exts);
4389
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 });
4390
5267
  }
4391
5268
  let g4 = s.groupSchedule, schedule = await getScheduleStatus();
@@ -4398,8 +5275,8 @@ async function runDoctor(lang = "zh") {
4398
5275
  }
4399
5276
 
4400
5277
  // src/project.ts
4401
- import { open as open4, readdir as readdir9, readFile as readFile17 } from "node:fs/promises";
4402
- import { basename as basename11, join as join19 } from "node:path";
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";
4403
5280
  import { homedir as homedir19 } from "node:os";
4404
5281
  async function discoverProjects(projectAliases) {
4405
5282
  let projectMap = /* @__PURE__ */ new Map();
@@ -4426,7 +5303,9 @@ async function discoverProjects(projectAliases) {
4426
5303
  discoverGeminiProjects().then((names) => names.forEach((n) => add(n, "gemini"))),
4427
5304
  // Antigravity: ~/.gemini/antigravity/knowledge/*/metadata.json
4428
5305
  // 仅读取知识项元数据标题,不读取对话内容
4429
- discoverAntigravityProjects().then((names) => names.forEach((n) => add(n, "antigravity")))
5306
+ discoverAntigravityProjects().then((names) => names.forEach((n) => add(n, "antigravity"))),
5307
+ // Kimi CLI / Kimi Code: legacy workspace map + new session metadata.
5308
+ discoverKimiProjects().then((names) => names.forEach((n) => add(n, "kimi")))
4430
5309
  ]);
4431
5310
  let results = [];
4432
5311
  for (let [name, sources] of projectMap) {
@@ -4444,20 +5323,20 @@ async function discoverClaudeProjects() {
4444
5323
  for (let baseDir of getClaudeDirs()) {
4445
5324
  let entries;
4446
5325
  try {
4447
- entries = await readdir9(baseDir, { withFileTypes: !0 });
5326
+ entries = await readdir8(baseDir, { withFileTypes: !0 });
4448
5327
  } catch {
4449
5328
  continue;
4450
5329
  }
4451
5330
  for (let entry of entries) {
4452
5331
  if (!entry.isDirectory() || entry.name.startsWith(".")) continue;
4453
- let projectDir = join19(baseDir, entry.name), name = await extractCwdFromFirstJsonl(projectDir);
5332
+ let projectDir = join20(baseDir, entry.name), name = await extractCwdFromFirstJsonl(projectDir);
4454
5333
  name && name !== "unknown" && names.push(name);
4455
5334
  }
4456
5335
  }
4457
5336
  return names;
4458
5337
  }
4459
5338
  async function discoverCodexProjects() {
4460
- let sessionsDir = join19(homedir19(), ".codex", "sessions"), files = await walkJsonlFiles(sessionsDir), projects = /* @__PURE__ */ new Set();
5339
+ let sessionsDir = join20(homedir19(), ".codex", "sessions"), files = await walkJsonlFiles(sessionsDir), projects = /* @__PURE__ */ new Set();
4461
5340
  for (let filePath of files) {
4462
5341
  let name = await extractCwdFromSessionMeta(filePath);
4463
5342
  name && name !== "unknown" && projects.add(name);
@@ -4467,7 +5346,7 @@ async function discoverCodexProjects() {
4467
5346
  async function extractCwdFromSessionMeta(filePath) {
4468
5347
  let fh;
4469
5348
  try {
4470
- fh = await open4(filePath, "r");
5349
+ fh = await open2(filePath, "r");
4471
5350
  let buf = Buffer.alloc(4096), { bytesRead } = await fh.read(buf, 0, buf.length, 0);
4472
5351
  if (bytesRead === 0) return;
4473
5352
  let line = buf.subarray(0, bytesRead).toString("utf-8").split(`
@@ -4489,12 +5368,12 @@ async function walkFiles2(dir, ext) {
4489
5368
  async function walk2(d) {
4490
5369
  let entries;
4491
5370
  try {
4492
- entries = await readdir9(d, { withFileTypes: !0 });
5371
+ entries = await readdir8(d, { withFileTypes: !0 });
4493
5372
  } catch {
4494
5373
  return;
4495
5374
  }
4496
5375
  for (let entry of entries) {
4497
- let full = join19(d, entry.name);
5376
+ let full = join20(d, entry.name);
4498
5377
  entry.isDirectory() ? await walk2(full) : entry.name.endsWith(ext) && result.push(full);
4499
5378
  }
4500
5379
  }
@@ -4505,7 +5384,7 @@ async function extractCwdFromFirstJsonl(dir) {
4505
5384
  if (!jsonlPath) return;
4506
5385
  let fh;
4507
5386
  try {
4508
- fh = await open4(jsonlPath, "r");
5387
+ fh = await open2(jsonlPath, "r");
4509
5388
  let buf = Buffer.alloc(32 * 1024), { bytesRead } = await fh.read(buf, 0, buf.length, 0);
4510
5389
  if (bytesRead === 0) return;
4511
5390
  let lines = buf.subarray(0, bytesRead).toString("utf-8").split(`
@@ -4531,27 +5410,27 @@ async function extractCwdFromFirstJsonl(dir) {
4531
5410
  async function findFirstJsonl(dir) {
4532
5411
  let entries;
4533
5412
  try {
4534
- entries = await readdir9(dir, { withFileTypes: !0 });
5413
+ entries = await readdir8(dir, { withFileTypes: !0 });
4535
5414
  } catch {
4536
5415
  return;
4537
5416
  }
4538
5417
  let topJsonl = entries.find((e) => e.isFile() && e.name.endsWith(".jsonl"));
4539
- if (topJsonl) return join19(dir, topJsonl.name);
5418
+ if (topJsonl) return join20(dir, topJsonl.name);
4540
5419
  for (let entry of entries)
4541
5420
  if (!(!entry.isDirectory() || entry.name.startsWith(".")))
4542
5421
  try {
4543
- let sub = (await readdir9(join19(dir, entry.name))).find((f) => f.endsWith(".jsonl"));
4544
- if (sub) return join19(dir, entry.name, sub);
5422
+ let sub = (await readdir8(join20(dir, entry.name))).find((f) => f.endsWith(".jsonl"));
5423
+ if (sub) return join20(dir, entry.name, sub);
4545
5424
  } catch {
4546
5425
  continue;
4547
5426
  }
4548
5427
  }
4549
5428
  async function discoverCopilotProjects() {
4550
- let dir = join19(homedir19(), ".copilot", "session-state"), files = await walkJsonlFiles(dir), projects = /* @__PURE__ */ new Set();
5429
+ let dir = join20(homedir19(), ".copilot", "session-state"), files = await walkJsonlFiles(dir), projects = /* @__PURE__ */ new Set();
4551
5430
  for (let filePath of files) {
4552
5431
  let fh;
4553
5432
  try {
4554
- fh = await open4(filePath, "r");
5433
+ fh = await open2(filePath, "r");
4555
5434
  let buf = Buffer.alloc(4096), { bytesRead } = await fh.read(buf, 0, buf.length, 0);
4556
5435
  if (bytesRead === 0) continue;
4557
5436
  let line = buf.subarray(0, bytesRead).toString("utf-8").split(`
@@ -4569,9 +5448,9 @@ async function discoverCopilotProjects() {
4569
5448
  return [...projects];
4570
5449
  }
4571
5450
  async function discoverGeminiProjects() {
4572
- let filePath = join19(homedir19(), ".gemini", "projects.json");
5451
+ let filePath = join20(homedir19(), ".gemini", "projects.json");
4573
5452
  try {
4574
- let raw = await readFile17(filePath, "utf-8"), projects = JSON.parse(raw)?.projects;
5453
+ let raw = await readFile16(filePath, "utf-8"), projects = JSON.parse(raw)?.projects;
4575
5454
  if (!projects || typeof projects != "object") return [];
4576
5455
  let names = [];
4577
5456
  for (let [path, _name] of Object.entries(projects)) {
@@ -4584,9 +5463,9 @@ async function discoverGeminiProjects() {
4584
5463
  }
4585
5464
  }
4586
5465
  async function discoverCursorProjects() {
4587
- let storagePath = join19(homedir19(), "Library", "Application Support", "Cursor", "User", "globalStorage", "storage.json");
5466
+ let storagePath = join20(homedir19(), "Library", "Application Support", "Cursor", "User", "globalStorage", "storage.json");
4588
5467
  try {
4589
- let raw = await readFile17(storagePath, "utf-8"), data = JSON.parse(raw), projects = /* @__PURE__ */ new Set(), workspaceUris = Object.keys(data.profileAssociations?.workspaces ?? {});
5468
+ let raw = await readFile16(storagePath, "utf-8"), data = JSON.parse(raw), projects = /* @__PURE__ */ new Set(), workspaceUris = Object.keys(data.profileAssociations?.workspaces ?? {});
4590
5469
  for (let uri of workspaceUris) {
4591
5470
  let name = nameFromFileUri(uri);
4592
5471
  name && projects.add(name);
@@ -4601,11 +5480,11 @@ async function discoverCursorProjects() {
4601
5480
  }
4602
5481
  }
4603
5482
  async function discoverCopilotVscodeProjects() {
4604
- let dir = join19(homedir19(), "Library", "Application Support", "Code", "logs"), files = (await walkFiles2(dir, ".log")).filter((filePath) => filePath.endsWith("GitHub Copilot Chat.log")), projects = /* @__PURE__ */ new Set();
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();
4605
5484
  for (let filePath of files) {
4606
5485
  let content;
4607
5486
  try {
4608
- content = await readFile17(filePath, "utf-8");
5487
+ content = await readFile16(filePath, "utf-8");
4609
5488
  } catch {
4610
5489
  continue;
4611
5490
  }
@@ -4618,18 +5497,18 @@ async function discoverCopilotVscodeProjects() {
4618
5497
  return [...projects];
4619
5498
  }
4620
5499
  async function discoverAntigravityProjects() {
4621
- let dir = join19(homedir19(), ".gemini", "antigravity", "knowledge"), entries;
5500
+ let dir = join20(homedir19(), ".gemini", "antigravity", "knowledge"), entries;
4622
5501
  try {
4623
- entries = await readdir9(dir, { withFileTypes: !0 });
5502
+ entries = await readdir8(dir, { withFileTypes: !0 });
4624
5503
  } catch {
4625
5504
  return [];
4626
5505
  }
4627
5506
  let projects = /* @__PURE__ */ new Set();
4628
5507
  for (let entry of entries) {
4629
5508
  if (!entry.isDirectory()) continue;
4630
- let metadataPath = join19(dir, entry.name, "metadata.json");
5509
+ let metadataPath = join20(dir, entry.name, "metadata.json");
4631
5510
  try {
4632
- let raw = await readFile17(metadataPath, "utf-8"), name = JSON.parse(raw).title?.trim() || entry.name.trim();
5511
+ let raw = await readFile16(metadataPath, "utf-8"), name = JSON.parse(raw).title?.trim() || entry.name.trim();
4633
5512
  name && name !== "unknown" && projects.add(name);
4634
5513
  } catch {
4635
5514
  continue;
@@ -4637,10 +5516,44 @@ async function discoverAntigravityProjects() {
4637
5516
  }
4638
5517
  return [...projects];
4639
5518
  }
5519
+ async function discoverKimiProjects() {
5520
+ let projects = /* @__PURE__ */ new Set(), home = homedir19();
5521
+ try {
5522
+ let raw = await readFile16(join20(home, ".kimi", "kimi.json"), "utf-8"), data = JSON.parse(raw);
5523
+ for (let workspace of Object.values(data.workspaces ?? {})) {
5524
+ let name = basename14(workspace.path?.trim() ?? "");
5525
+ name && name !== "unknown" && projects.add(name);
5526
+ }
5527
+ } catch {
5528
+ }
5529
+ let codeHome = resolveKimiCodeHome(home);
5530
+ try {
5531
+ let raw = await readFile16(join20(codeHome, "session_index.jsonl"), "utf-8");
5532
+ for (let line of raw.split(`
5533
+ `))
5534
+ if (line.trim())
5535
+ try {
5536
+ let record = JSON.parse(line), name = basename14(record.workDir?.trim() ?? "");
5537
+ name && name !== "unknown" && projects.add(name);
5538
+ } catch {
5539
+ continue;
5540
+ }
5541
+ } catch {
5542
+ }
5543
+ let stateFiles = (await walkFiles2(join20(codeHome, "sessions"), ".json")).filter((filePath) => basename14(filePath) === "state.json");
5544
+ for (let filePath of stateFiles)
5545
+ try {
5546
+ let raw = await readFile16(filePath, "utf-8"), state = JSON.parse(raw), name = basename14(state.workDir?.trim() ?? "");
5547
+ name && name !== "unknown" && projects.add(name);
5548
+ } catch {
5549
+ continue;
5550
+ }
5551
+ return [...projects];
5552
+ }
4640
5553
  function nameFromFileUri(raw) {
4641
5554
  let path = pathFromFileUri(raw);
4642
5555
  if (!path) return;
4643
- let name = basename11(path);
5556
+ let name = basename14(path);
4644
5557
  return name && name !== "unknown" ? name : void 0;
4645
5558
  }
4646
5559
  function pathFromFileUri(raw) {
@@ -4659,11 +5572,11 @@ function pathFromFileUri(raw) {
4659
5572
  function getClaudeDirs() {
4660
5573
  let envVar = process.env.CLAUDE_CONFIG_DIR?.trim();
4661
5574
  if (envVar)
4662
- return envVar.split(",").map((p) => p.trim()).filter(Boolean).map((p) => join19(p, "projects"));
5575
+ return envVar.split(",").map((p) => p.trim()).filter(Boolean).map((p) => join20(p, "projects"));
4663
5576
  let home = homedir19();
4664
5577
  return [
4665
- join19(home, ".config", "claude", "projects"),
4666
- join19(home, ".claude", "projects")
5578
+ join20(home, ".config", "claude", "projects"),
5579
+ join20(home, ".claude", "projects")
4667
5580
  ];
4668
5581
  }
4669
5582
 
@@ -4708,10 +5621,10 @@ function shortHash(p) {
4708
5621
  }
4709
5622
 
4710
5623
  // src/pricing.ts
4711
- import { mkdir as mkdir3, readFile as readFile18, writeFile as writeFile3 } from "node:fs/promises";
5624
+ import { mkdir as mkdir3, readFile as readFile17, writeFile as writeFile3 } from "node:fs/promises";
4712
5625
  import { homedir as homedir20 } from "node:os";
4713
- import { join as join20 } from "node:path";
4714
- var CACHE_DIR = join20(homedir20(), ".aiusage"), CACHE_PATH = join20(CACHE_DIR, "pricing-cache.json"), DEFAULT_CACHE_TTL_HOURS = 24, FETCH_TIMEOUT_MS = 5e3, NPM_CDN_URLS = [
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 = [
4715
5628
  "https://cdn.jsdelivr.net/npm/@aiusage/cli@latest/pricing-catalog.json",
4716
5629
  "https://unpkg.com/@aiusage/cli@latest/pricing-catalog.json",
4717
5630
  "https://cdn.jsdelivr.net/npm/@aiusage/pricing@latest/catalog.json",
@@ -4780,7 +5693,7 @@ function fromCache(cache) {
4780
5693
  }
4781
5694
  async function readPricingCache() {
4782
5695
  try {
4783
- let raw = await readFile18(CACHE_PATH, "utf-8"), cache = JSON.parse(raw);
5696
+ let raw = await readFile17(CACHE_PATH, "utf-8"), cache = JSON.parse(raw);
4784
5697
  return assertPricingCatalog(cache.catalog), !cache.fetchedAt || !cache.sourceUrl ? null : cache;
4785
5698
  } catch {
4786
5699
  return null;