@yishiguji/tokenarena 0.20.0 → 0.20.1

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/index.js CHANGED
@@ -219,6 +219,19 @@ function extractSessions(events, entries = []) {
219
219
  return sessions;
220
220
  }
221
221
 
222
+ // src/domain/transcript-roles.ts
223
+ function asRecord(value) {
224
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : null;
225
+ }
226
+ function isHumanPromptRecord(record) {
227
+ if (record.type !== "user") return false;
228
+ if (record.isMeta === true || record.isCompactSummary === true || record.isSidechain === true || record.toolUseResult !== void 0) {
229
+ return false;
230
+ }
231
+ const content = asRecord(record.message)?.content;
232
+ return Array.isArray(content) ? content.some((part) => asRecord(part)?.type !== "tool_result") : true;
233
+ }
234
+
222
235
  // src/infrastructure/fs/utils.ts
223
236
  import { existsSync, readdirSync, readFileSync } from "fs";
224
237
  import { basename, join, sep } from "path";
@@ -272,6 +285,11 @@ function parseJsonl(content) {
272
285
  function extractSessionId(filePath) {
273
286
  return basename(filePath, ".jsonl");
274
287
  }
288
+ function trimTrailingSeparators(value, separators = "/") {
289
+ let end = value.length;
290
+ while (end > 0 && separators.includes(value[end - 1])) end--;
291
+ return value.slice(0, end);
292
+ }
275
293
 
276
294
  // src/parsers/registry.ts
277
295
  import { existsSync as existsSync2 } from "fs";
@@ -342,7 +360,7 @@ function extractProject(filePath, projectsDir) {
342
360
  const parts = firstSegment.split("-").filter(Boolean);
343
361
  return parts.length > 0 ? parts[parts.length - 1] : "unknown";
344
362
  }
345
- function asRecord(value) {
363
+ function asRecord2(value) {
346
364
  return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
347
365
  }
348
366
  function getIdentifier(value) {
@@ -399,13 +417,13 @@ var ClaudeCodeParser = class {
399
417
  for (const [lineIndex, line] of content.split("\n").entries()) {
400
418
  if (!line.trim()) continue;
401
419
  try {
402
- const record = asRecord(JSON.parse(line));
420
+ const record = asRecord2(JSON.parse(line));
403
421
  if (!record || typeof record.timestamp !== "string" && typeof record.timestamp !== "number") {
404
422
  continue;
405
423
  }
406
424
  const timestamp = new Date(record.timestamp);
407
425
  if (Number.isNaN(timestamp.getTime())) continue;
408
- const message = asRecord(record.message);
426
+ const message = asRecord2(record.message);
409
427
  const messageId = getIdentifier(message?.id);
410
428
  const requestId = getIdentifier(record.requestId) ?? getIdentifier(record.request_id) ?? "";
411
429
  const uuid = getIdentifier(record.uuid);
@@ -423,14 +441,14 @@ var ClaudeCodeParser = class {
423
441
  source: "claude-code",
424
442
  project,
425
443
  timestamp,
426
- role: record.type === "user" ? "user" : "assistant"
444
+ role: isHumanPromptRecord(record) ? "user" : "assistant"
427
445
  });
428
446
  }
429
447
  if (!includeUsage || record.type !== "assistant" || !message)
430
448
  continue;
431
- const usage = asRecord(message.usage);
449
+ const usage = asRecord2(message.usage);
432
450
  if (!usage) continue;
433
- const cacheCreation = asRecord(usage.cache_creation);
451
+ const cacheCreation = asRecord2(usage.cache_creation);
434
452
  const cacheCreationTokens = tokenCount(
435
453
  usage.cache_creation_input_tokens ?? tokenCount(cacheCreation?.ephemeral_5m_input_tokens) + tokenCount(cacheCreation?.ephemeral_1h_input_tokens)
436
454
  );
@@ -626,13 +644,28 @@ function filenameThreadId(path) {
626
644
  /([\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12})\.jsonl$/i
627
645
  )?.[1] ?? null;
628
646
  }
647
+ function repositorySlug(repositoryUrl) {
648
+ const remote = repositoryUrl.replace(
649
+ /^([a-z][a-z0-9+.-]*:\/\/)[^/@]*@/i,
650
+ "$1"
651
+ );
652
+ const lastSlash = remote.lastIndexOf("/");
653
+ if (lastSlash <= 0 || lastSlash === remote.length - 1) return null;
654
+ const owner = remote.slice(
655
+ remote.lastIndexOf("/", lastSlash - 1) + 1,
656
+ lastSlash
657
+ );
658
+ if (!owner) return null;
659
+ const name = remote.slice(lastSlash + 1);
660
+ return `${owner}/${name.length > 4 && name.endsWith(".git") ? name.slice(0, -4) : name}`;
661
+ }
629
662
  function resolveCodexProject(payload) {
630
663
  const repositoryUrl = payload?.git?.repository_url;
631
664
  if (typeof repositoryUrl === "string" && repositoryUrl) {
632
- const match = repositoryUrl.match(/([^/]+\/[^/]+?)(?:\.git)?$/);
633
- if (match) return match[1];
665
+ const slug = repositorySlug(repositoryUrl);
666
+ if (slug) return slug;
634
667
  }
635
- const normalized = typeof payload?.cwd === "string" ? payload.cwd.replace(/\\/g, "/").replace(/\/+$/, "") : "";
668
+ const normalized = typeof payload?.cwd === "string" ? trimTrailingSeparators(payload.cwd.replace(/\\/g, "/")) : "";
636
669
  return normalized?.split("/").filter(Boolean).pop() || "unknown";
637
670
  }
638
671
  function readRollout(path) {
@@ -892,14 +925,44 @@ var CodexParser = class {
892
925
  thread.status = "done";
893
926
  return true;
894
927
  };
895
- let incomplete = false;
928
+ const deferred = [];
896
929
  for (const thread of threads.values()) {
897
- if (!processThread(thread)) incomplete = true;
930
+ if (!processThread(thread)) deferred.push(thread);
931
+ }
932
+ if (deferred.length === 0) {
933
+ return {
934
+ buckets: aggregateToBuckets(entries),
935
+ sessions: extractSessions(sessionEvents, entries)
936
+ };
898
937
  }
938
+ const withheldKey = (model, timestamp) => `${model}|${roundToHalfHour(timestamp).toISOString()}`;
939
+ const withheldKeys = /* @__PURE__ */ new Set();
940
+ for (const thread of deferred) {
941
+ for (const file of thread.files) {
942
+ for (const token of file.tokens) {
943
+ if (token.timestamp) {
944
+ withheldKeys.add(withheldKey(token.model, token.timestamp));
945
+ }
946
+ }
947
+ }
948
+ }
949
+ const keptEntries = entries.filter(
950
+ (entry) => !withheldKeys.has(withheldKey(entry.model, entry.timestamp))
951
+ );
952
+ const withheldSessionIds = new Set(
953
+ entries.filter(
954
+ (entry) => withheldKeys.has(withheldKey(entry.model, entry.timestamp))
955
+ ).map((entry) => entry.sessionId)
956
+ );
899
957
  return {
900
- buckets: aggregateToBuckets(entries),
901
- sessions: extractSessions(sessionEvents, entries),
902
- ...incomplete ? { incomplete: true } : {}
958
+ buckets: aggregateToBuckets(keptEntries),
959
+ sessions: extractSessions(
960
+ sessionEvents.filter(
961
+ (event) => !withheldSessionIds.has(event.sessionId)
962
+ ),
963
+ keptEntries.filter((entry) => !withheldSessionIds.has(entry.sessionId))
964
+ ),
965
+ partial: true
903
966
  };
904
967
  }
905
968
  };
@@ -924,12 +987,12 @@ function toSafeNumber(value) {
924
987
  return Number.isFinite(numberValue) ? numberValue : 0;
925
988
  }
926
989
  function getPathLeaf(value) {
927
- const normalized = value.replace(/\\/g, "/").replace(/\/+$/, "");
990
+ const normalized = trimTrailingSeparators(value.replace(/\\/g, "/"));
928
991
  const leaf = normalized.split("/").filter(Boolean).pop();
929
992
  return leaf || "unknown";
930
993
  }
931
994
  function normalizeForPrefix(value) {
932
- return value.replace(/\\/g, "/").replace(/\/+$/, "");
995
+ return trimTrailingSeparators(value.replace(/\\/g, "/"));
933
996
  }
934
997
  function getUsageNumber(usage, ...keys) {
935
998
  for (const key of keys) {
@@ -1164,7 +1227,7 @@ function projectFromDirectories(directories) {
1164
1227
  if (!directories || directories.length === 0) return "unknown";
1165
1228
  const first = directories[0];
1166
1229
  if (!first) return "unknown";
1167
- return basename3(String(first).replace(/[\\/]+$/, "")) || "unknown";
1230
+ return basename3(trimTrailingSeparators(String(first), "\\/")) || "unknown";
1168
1231
  }
1169
1232
  function tokenCount2(value) {
1170
1233
  return typeof value === "number" && Number.isFinite(value) && value >= 0 ? Math.trunc(value) : 0;
@@ -1274,14 +1337,61 @@ var GeminiCliParser = class {
1274
1337
  registerParser(new GeminiCliParser());
1275
1338
 
1276
1339
  // src/parsers/hermes.ts
1277
- import { existsSync as existsSync7 } from "fs";
1340
+ import { existsSync as existsSync8 } from "fs";
1278
1341
  import { homedir as homedir5 } from "os";
1279
1342
  import { dirname, join as join6 } from "path";
1280
1343
 
1281
1344
  // src/infrastructure/sqlite.ts
1282
- import { execFileSync } from "child_process";
1345
+ import { execFileSync as execFileSync2 } from "child_process";
1283
1346
  import { statSync } from "fs";
1284
1347
  import { pathToFileURL } from "url";
1348
+
1349
+ // src/utils/command.ts
1350
+ import { execFileSync } from "child_process";
1351
+ import { existsSync as existsSync7 } from "fs";
1352
+ import { platform } from "os";
1353
+ import { win32 } from "path";
1354
+ function getWindowsSystemCommand(name, env = process.env) {
1355
+ return win32.join(
1356
+ env.SystemRoot || env.SYSTEMROOT || "C:\\Windows",
1357
+ "System32",
1358
+ name
1359
+ );
1360
+ }
1361
+ function resolveCommandPath(command, options = {}) {
1362
+ if ((options.platform ?? platform()) !== "win32" || /[\\/]/.test(command)) {
1363
+ return command;
1364
+ }
1365
+ const env = options.env ?? process.env;
1366
+ const exists = options.exists ?? existsSync7;
1367
+ const extensions = win32.extname(command) ? [""] : (env.PATHEXT || ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean);
1368
+ for (const entry of (env.PATH || env.Path || "").split(";")) {
1369
+ const dir = entry.trim().replaceAll('"', "");
1370
+ if (!dir || !win32.isAbsolute(dir)) continue;
1371
+ for (const extension of extensions) {
1372
+ const candidate = win32.join(dir, `${command}${extension}`);
1373
+ if (exists(candidate)) return candidate;
1374
+ }
1375
+ }
1376
+ return null;
1377
+ }
1378
+ function getCommandCheck(command, currentPlatform = platform()) {
1379
+ if (currentPlatform === "win32") {
1380
+ return { command: getWindowsSystemCommand("where.exe"), args: [command] };
1381
+ }
1382
+ return { command: "/bin/sh", args: ["-c", 'command -v "$1"', "sh", command] };
1383
+ }
1384
+ function isCommandAvailable(command) {
1385
+ const check = getCommandCheck(command);
1386
+ try {
1387
+ execFileSync(check.command, check.args, { stdio: "ignore", timeout: 5e3 });
1388
+ return true;
1389
+ } catch {
1390
+ return false;
1391
+ }
1392
+ }
1393
+
1394
+ // src/infrastructure/sqlite.ts
1285
1395
  var warningScope = Promise.resolve();
1286
1396
  async function withSuppressedSqliteWarning(fn) {
1287
1397
  const previousScope = warningScope;
@@ -1358,17 +1468,17 @@ async function readSqliteRowsWithBuiltin(dbPath, query) {
1358
1468
  throw err;
1359
1469
  }
1360
1470
  }
1471
+ function getSqliteCliCandidates() {
1472
+ const candidates = [process.env.TOKEN_ARENA_SQLITE3, "sqlite3", "sqlite3.exe"].filter((value) => Boolean(value)).map((command) => resolveCommandPath(command)).filter((value) => value !== null);
1473
+ return Array.from(new Set(candidates));
1474
+ }
1361
1475
  function readSqliteRowsWithCli(dbPath, query, readOnly = false) {
1362
- const candidates = [
1363
- process.env.TOKEN_ARENA_SQLITE3,
1364
- "sqlite3",
1365
- "sqlite3.exe"
1366
- ].filter((value) => Boolean(value));
1476
+ const candidates = getSqliteCliCandidates();
1367
1477
  let lastError = null;
1368
1478
  for (const command of candidates) {
1369
1479
  try {
1370
1480
  const args = [...readOnly ? ["-readonly"] : [], "-json", dbPath, query];
1371
- const output = execFileSync(command, args, {
1481
+ const output = execFileSync2(command, args, {
1372
1482
  encoding: "utf-8",
1373
1483
  maxBuffer: 100 * 1024 * 1024,
1374
1484
  timeout: 3e4,
@@ -1480,7 +1590,7 @@ var HermesParser = class {
1480
1590
  this.tool = createToolDefinition2(this.dbPath);
1481
1591
  }
1482
1592
  async parse() {
1483
- if (!existsSync7(this.dbPath)) {
1593
+ if (!existsSync8(this.dbPath)) {
1484
1594
  return { buckets: [], sessions: [] };
1485
1595
  }
1486
1596
  const sessionRows = await this.queryRows(
@@ -1546,13 +1656,13 @@ var HermesParser = class {
1546
1656
  };
1547
1657
  }
1548
1658
  isInstalled() {
1549
- return existsSync7(this.dbPath);
1659
+ return existsSync8(this.dbPath);
1550
1660
  }
1551
1661
  };
1552
1662
  registerParser(new HermesParser());
1553
1663
 
1554
1664
  // src/parsers/mimocode.ts
1555
- import { existsSync as existsSync8 } from "fs";
1665
+ import { existsSync as existsSync9 } from "fs";
1556
1666
  import { homedir as homedir6 } from "os";
1557
1667
  import { join as join7 } from "path";
1558
1668
  var TOOL_ID4 = "mimocode";
@@ -1625,7 +1735,7 @@ var MimocodeParser = class {
1625
1735
  const allSessionEvents = [];
1626
1736
  let incomplete = false;
1627
1737
  for (const dbPath of this.resolveDbPaths()) {
1628
- if (!existsSync8(dbPath)) continue;
1738
+ if (!existsSync9(dbPath)) continue;
1629
1739
  try {
1630
1740
  const { entries, sessionEvents } = await this.parseDb(dbPath);
1631
1741
  allEntries.push(...entries);
@@ -1645,7 +1755,7 @@ var MimocodeParser = class {
1645
1755
  };
1646
1756
  }
1647
1757
  isInstalled() {
1648
- return this.resolveDbPaths().some((p) => existsSync8(p));
1758
+ return this.resolveDbPaths().some((p) => existsSync9(p));
1649
1759
  }
1650
1760
  async parseDb(dbPath) {
1651
1761
  const messageRows = await readSqliteRows(
@@ -1705,7 +1815,7 @@ var MimocodeParser = class {
1705
1815
  registerParser(new MimocodeParser());
1706
1816
 
1707
1817
  // src/parsers/mcode.ts
1708
- import { existsSync as existsSync9 } from "fs";
1818
+ import { existsSync as existsSync10 } from "fs";
1709
1819
  import { homedir as homedir7 } from "os";
1710
1820
  import { join as join8 } from "path";
1711
1821
  function getMcodeDbPath(env = process.env) {
@@ -1726,7 +1836,7 @@ var McodeParser = class {
1726
1836
  this.tool = { id: "mcode", name: "MiniMax Code", dataDir: this.dbPath };
1727
1837
  }
1728
1838
  async parse() {
1729
- if (!existsSync9(this.dbPath)) return { buckets: [], sessions: [] };
1839
+ if (!existsSync10(this.dbPath)) return { buckets: [], sessions: [] };
1730
1840
  let rows;
1731
1841
  try {
1732
1842
  rows = await this.queryRows(
@@ -1753,7 +1863,7 @@ var McodeParser = class {
1753
1863
  "SELECT session_id AS sessionId, workspace_dir AS directory FROM local_runtime_sessions"
1754
1864
  );
1755
1865
  for (const row of sessions) {
1756
- const project = row.directory?.replace(/[\\/]+$/, "").split(/[\\/]/).pop();
1866
+ const project = row.directory ? trimTrailingSeparators(row.directory, "\\/").split(/[\\/]/).pop() : void 0;
1757
1867
  if (project) projects.set(row.sessionId, project);
1758
1868
  }
1759
1869
  } catch (error) {
@@ -1810,14 +1920,14 @@ var McodeParser = class {
1810
1920
  };
1811
1921
  }
1812
1922
  isInstalled() {
1813
- return existsSync9(this.dbPath);
1923
+ return existsSync10(this.dbPath);
1814
1924
  }
1815
1925
  };
1816
1926
  registerParser(new McodeParser());
1817
1927
 
1818
1928
  // src/parsers/mirasim.ts
1819
1929
  import { createHash as createHash3 } from "crypto";
1820
- import { existsSync as existsSync10 } from "fs";
1930
+ import { existsSync as existsSync11 } from "fs";
1821
1931
  import { homedir as homedir8, hostname as hostname3 } from "os";
1822
1932
  import { join as join9 } from "path";
1823
1933
  var TOOL_ID5 = "mirasim";
@@ -1862,7 +1972,7 @@ function getPathLeaf2(value) {
1862
1972
  if (!value) {
1863
1973
  return "unknown";
1864
1974
  }
1865
- const normalized = value.replace(/\\/g, "/").replace(/\/+$/, "");
1975
+ const normalized = trimTrailingSeparators(value.replace(/\\/g, "/"));
1866
1976
  const leaf = normalized.split("/").filter(Boolean).pop();
1867
1977
  return leaf || "unknown";
1868
1978
  }
@@ -2058,13 +2168,13 @@ var MirasimParser = class {
2058
2168
  };
2059
2169
  }
2060
2170
  isInstalled() {
2061
- return this.insightsDirs.some((dir) => existsSync10(dir));
2171
+ return this.insightsDirs.some((dir) => existsSync11(dir));
2062
2172
  }
2063
2173
  };
2064
2174
  registerParser(new MirasimParser());
2065
2175
 
2066
2176
  // src/parsers/copilot-cli.ts
2067
- import { existsSync as existsSync11, readdirSync as readdirSync3, readFileSync as readFileSync3 } from "fs";
2177
+ import { existsSync as existsSync12, readdirSync as readdirSync3, readFileSync as readFileSync3 } from "fs";
2068
2178
  import { homedir as homedir9 } from "os";
2069
2179
  import { basename as basename4, dirname as dirname2, join as join10 } from "path";
2070
2180
  var ROOT_DIR = join10(homedir9(), ".copilot");
@@ -2074,7 +2184,7 @@ var TOOL3 = {
2074
2184
  dataDir: ROOT_DIR
2075
2185
  };
2076
2186
  function collectEventFiles(dir, results, visited) {
2077
- if (!existsSync11(dir) || visited.has(dir)) {
2187
+ if (!existsSync12(dir) || visited.has(dir)) {
2078
2188
  return;
2079
2189
  }
2080
2190
  visited.add(dir);
@@ -2103,7 +2213,7 @@ function findEventFiles(baseDir) {
2103
2213
  function getProjectFromContext(context) {
2104
2214
  const projectPath = context?.gitRoot || context?.cwd;
2105
2215
  if (!projectPath) return "unknown";
2106
- return basename4(projectPath.replace(/[\\/]+$/, "")) || "unknown";
2216
+ return basename4(trimTrailingSeparators(projectPath, "\\/")) || "unknown";
2107
2217
  }
2108
2218
  var CopilotCliParser = class {
2109
2219
  tool = TOOL3;
@@ -2218,13 +2328,13 @@ var CopilotCliParser = class {
2218
2328
  };
2219
2329
  }
2220
2330
  isInstalled() {
2221
- return existsSync11(ROOT_DIR);
2331
+ return existsSync12(ROOT_DIR);
2222
2332
  }
2223
2333
  };
2224
2334
  registerParser(new CopilotCliParser());
2225
2335
 
2226
2336
  // src/parsers/oh-my-pi.ts
2227
- import { existsSync as existsSync12 } from "fs";
2337
+ import { existsSync as existsSync13 } from "fs";
2228
2338
  import { homedir as homedir10 } from "os";
2229
2339
  import { join as join11 } from "path";
2230
2340
  var TOOL_ID6 = "oh-my-pi";
@@ -2242,12 +2352,12 @@ function toSafeNumber4(value) {
2242
2352
  return Number.isFinite(numberValue) ? numberValue : 0;
2243
2353
  }
2244
2354
  function getPathLeaf3(value) {
2245
- const normalized = value.replace(/\\/g, "/").replace(/\/+$/, "");
2355
+ const normalized = trimTrailingSeparators(value.replace(/\\/g, "/"));
2246
2356
  const leaf = normalized.split("/").filter(Boolean).pop();
2247
2357
  return leaf || "unknown";
2248
2358
  }
2249
2359
  function normalizeForPrefix2(value) {
2250
- return value.replace(/\\/g, "/").replace(/\/+$/, "");
2360
+ return trimTrailingSeparators(value.replace(/\\/g, "/"));
2251
2361
  }
2252
2362
  function getUsageNumber2(usage, ...keys) {
2253
2363
  for (const key of keys) {
@@ -2376,14 +2486,14 @@ var OhMyPiParser = class {
2376
2486
  };
2377
2487
  }
2378
2488
  isInstalled() {
2379
- return existsSync12(this.sessionsDir);
2489
+ return existsSync13(this.sessionsDir);
2380
2490
  }
2381
2491
  };
2382
2492
  registerParser(new OhMyPiParser());
2383
2493
 
2384
2494
  // src/parsers/opencode.ts
2385
- import { execFileSync as execFileSync2 } from "child_process";
2386
- import { existsSync as existsSync13, readdirSync as readdirSync4, readFileSync as readFileSync4 } from "fs";
2495
+ import { execFileSync as execFileSync3 } from "child_process";
2496
+ import { existsSync as existsSync14, readdirSync as readdirSync4, readFileSync as readFileSync4 } from "fs";
2387
2497
  import { homedir as homedir11 } from "os";
2388
2498
  import { basename as basename5, join as join12 } from "path";
2389
2499
  var DEFAULT_DATA_DIR2 = join12(homedir11(), ".local", "share", "opencode");
@@ -2440,15 +2550,11 @@ async function readSqliteRowsWithBuiltin2(dbPath, query) {
2440
2550
  }
2441
2551
  }
2442
2552
  function readSqliteRowsWithCli2(dbPath, query) {
2443
- const candidates = [
2444
- process.env.TOKEN_ARENA_SQLITE3,
2445
- "sqlite3",
2446
- "sqlite3.exe"
2447
- ].filter((value) => Boolean(value));
2553
+ const candidates = getSqliteCliCandidates();
2448
2554
  let lastError = null;
2449
2555
  for (const command of candidates) {
2450
2556
  try {
2451
- const output = execFileSync2(command, ["-json", dbPath, query], {
2557
+ const output = execFileSync3(command, ["-json", dbPath, query], {
2452
2558
  encoding: "utf-8",
2453
2559
  maxBuffer: 100 * 1024 * 1024,
2454
2560
  timeout: 3e4,
@@ -2497,12 +2603,12 @@ var OpenCodeParser = class {
2497
2603
  return { buckets, sessions, ...incomplete ? { incomplete: true } : {} };
2498
2604
  }
2499
2605
  isInstalled() {
2500
- return this.resolveRoots().some((dir) => existsSync13(dir));
2606
+ return this.resolveRoots().some((dir) => existsSync14(dir));
2501
2607
  }
2502
2608
  async parseRoot(rootDir, seen) {
2503
2609
  const dbPath = join12(rootDir, "opencode.db");
2504
2610
  const messagesDir = join12(rootDir, "storage", "message");
2505
- if (existsSync13(dbPath)) {
2611
+ if (existsSync14(dbPath)) {
2506
2612
  try {
2507
2613
  return await this.parseFromSqlite(dbPath, seen);
2508
2614
  } catch (err) {
@@ -2573,7 +2679,7 @@ var OpenCodeParser = class {
2573
2679
  };
2574
2680
  }
2575
2681
  parseFromJson(messagesDir, seen) {
2576
- if (!existsSync13(messagesDir)) return { buckets: [], sessions: [] };
2682
+ if (!existsSync14(messagesDir)) return { buckets: [], sessions: [] };
2577
2683
  const entries = [];
2578
2684
  const sessionEvents = [];
2579
2685
  let sessionDirs;
@@ -2644,7 +2750,7 @@ var OpenCodeParser = class {
2644
2750
  registerParser(new OpenCodeParser());
2645
2751
 
2646
2752
  // src/parsers/openclaw.ts
2647
- import { existsSync as existsSync14, readdirSync as readdirSync5, readFileSync as readFileSync5 } from "fs";
2753
+ import { existsSync as existsSync15, readdirSync as readdirSync5, readFileSync as readFileSync5 } from "fs";
2648
2754
  import { homedir as homedir12 } from "os";
2649
2755
  import { join as join13 } from "path";
2650
2756
  var TOOL_ID7 = "openclaw";
@@ -2686,7 +2792,7 @@ var OpenClawParser = class {
2686
2792
  const sessionEvents = [];
2687
2793
  for (const root of this.resolveRoots()) {
2688
2794
  const agentsDir = join13(root, "agents");
2689
- if (!existsSync14(agentsDir)) continue;
2795
+ if (!existsSync15(agentsDir)) continue;
2690
2796
  let agentDirs;
2691
2797
  try {
2692
2798
  agentDirs = readdirSync5(agentsDir, { withFileTypes: true }).filter(
@@ -2698,7 +2804,7 @@ var OpenClawParser = class {
2698
2804
  for (const agentDir of agentDirs) {
2699
2805
  const project = agentDir.name;
2700
2806
  const sessionsDir = join13(agentsDir, agentDir.name, "sessions");
2701
- if (!existsSync14(sessionsDir)) continue;
2807
+ if (!existsSync15(sessionsDir)) continue;
2702
2808
  let files;
2703
2809
  try {
2704
2810
  files = readdirSync5(sessionsDir).filter((f) => f.endsWith(".jsonl"));
@@ -2779,15 +2885,15 @@ var OpenClawParser = class {
2779
2885
  };
2780
2886
  }
2781
2887
  isInstalled() {
2782
- return this.resolveRoots().some((root) => existsSync14(join13(root, "agents")));
2888
+ return this.resolveRoots().some((root) => existsSync15(join13(root, "agents")));
2783
2889
  }
2784
2890
  };
2785
2891
  registerParser(new OpenClawParser());
2786
2892
 
2787
2893
  // src/parsers/qwen-code.ts
2788
- import { existsSync as existsSync15, readdirSync as readdirSync6 } from "fs";
2894
+ import { existsSync as existsSync16, readdirSync as readdirSync6 } from "fs";
2789
2895
  import { homedir as homedir13 } from "os";
2790
- import { join as join14 } from "path";
2896
+ import { dirname as dirname3, join as join14 } from "path";
2791
2897
  var TOOL_ID8 = "qwen-code";
2792
2898
  var TOOL_NAME7 = "Qwen Code";
2793
2899
  var DEFAULT_DATA_DIR4 = join14(homedir13(), ".qwen", "tmp");
@@ -2803,21 +2909,21 @@ function toSafeNumber5(value) {
2803
2909
  return Number.isFinite(numberValue) ? numberValue : 0;
2804
2910
  }
2805
2911
  function getPathLeaf4(value) {
2806
- const normalized = value.replace(/\\/g, "/").replace(/\/+$/, "");
2912
+ const normalized = trimTrailingSeparators(value.replace(/\\/g, "/"));
2807
2913
  const leaf = normalized.split("/").filter(Boolean).pop();
2808
2914
  return leaf || "unknown";
2809
2915
  }
2810
2916
  function normalizeForPrefix3(value) {
2811
- return value.replace(/\\/g, "/").replace(/\/+$/, "");
2917
+ return trimTrailingSeparators(value.replace(/\\/g, "/"));
2812
2918
  }
2813
2919
  function findSessionFiles2(baseDir) {
2814
2920
  const results = [];
2815
- if (!existsSync15(baseDir)) return results;
2921
+ if (!existsSync16(baseDir)) return results;
2816
2922
  try {
2817
2923
  for (const entry of readdirSync6(baseDir, { withFileTypes: true })) {
2818
2924
  if (!entry.isDirectory()) continue;
2819
2925
  const chatsDir = join14(baseDir, entry.name, "chats");
2820
- if (!existsSync15(chatsDir)) continue;
2926
+ if (!existsSync16(chatsDir)) continue;
2821
2927
  try {
2822
2928
  for (const file of readdirSync6(chatsDir)) {
2823
2929
  if (file.endsWith(".jsonl")) {
@@ -2850,18 +2956,35 @@ var QwenCodeParser = class {
2850
2956
  constructor(dataDir = DEFAULT_DATA_DIR4) {
2851
2957
  this.dataDir = dataDir;
2852
2958
  this.tool = createToolDefinition4(dataDir);
2959
+ this.projectsDir = join14(dirname3(dataDir), "projects");
2853
2960
  }
2854
2961
  dataDir;
2855
2962
  tool;
2963
+ /**
2964
+ * Where current releases keep chats: `<qwen home>/projects/<cwd>/chats`,
2965
+ * beside the `tmp` directory older ones used (0.25.0 writes only here).
2966
+ * Reading `tmp` alone found nothing while `isInstalled()` stayed true,
2967
+ * which made the whole source a silent zero, as ffbd1ad found for dsh.
2968
+ */
2969
+ projectsDir;
2856
2970
  async parse() {
2857
- const sessionFiles = findSessionFiles2(this.dataDir);
2971
+ const sessionFiles = [
2972
+ ...findSessionFiles2(this.dataDir).map((filePath) => ({
2973
+ filePath,
2974
+ root: this.dataDir
2975
+ })),
2976
+ ...findSessionFiles2(this.projectsDir).map((filePath) => ({
2977
+ filePath,
2978
+ root: this.projectsDir
2979
+ }))
2980
+ ];
2858
2981
  if (sessionFiles.length === 0) {
2859
2982
  return { buckets: [], sessions: [] };
2860
2983
  }
2861
2984
  const entries = [];
2862
2985
  const sessionEvents = [];
2863
2986
  const seenUuids = /* @__PURE__ */ new Set();
2864
- for (const filePath of sessionFiles) {
2987
+ for (const { filePath, root } of sessionFiles) {
2865
2988
  const content = readFileSafe(filePath);
2866
2989
  if (!content) continue;
2867
2990
  const sessionId = filePath;
@@ -2872,7 +2995,11 @@ var QwenCodeParser = class {
2872
2995
  if (!obj.timestamp) continue;
2873
2996
  const timestamp = new Date(obj.timestamp);
2874
2997
  if (Number.isNaN(timestamp.getTime())) continue;
2875
- const project = resolveQwenProject(obj.cwd, filePath, this.dataDir);
2998
+ const project = resolveQwenProject(obj.cwd, filePath, root);
2999
+ if (obj.uuid) {
3000
+ if (seenUuids.has(obj.uuid)) continue;
3001
+ seenUuids.add(obj.uuid);
3002
+ }
2876
3003
  if (obj.type === "user" || obj.type === "assistant") {
2877
3004
  sessionEvents.push({
2878
3005
  sessionId,
@@ -2892,10 +3019,6 @@ var QwenCodeParser = class {
2892
3019
  if (totalInput === 0 && totalOutput === 0 && cachedTokens === 0 && reasoningTokens === 0) {
2893
3020
  continue;
2894
3021
  }
2895
- if (obj.uuid) {
2896
- if (seenUuids.has(obj.uuid)) continue;
2897
- seenUuids.add(obj.uuid);
2898
- }
2899
3022
  entries.push({
2900
3023
  sessionId,
2901
3024
  source: TOOL_ID8,
@@ -2917,13 +3040,13 @@ var QwenCodeParser = class {
2917
3040
  };
2918
3041
  }
2919
3042
  isInstalled() {
2920
- return existsSync15(this.dataDir);
3043
+ return existsSync16(this.dataDir) || existsSync16(this.projectsDir);
2921
3044
  }
2922
3045
  };
2923
3046
  registerParser(new QwenCodeParser());
2924
3047
 
2925
3048
  // src/parsers/kimi-code.ts
2926
- import { existsSync as existsSync16, readdirSync as readdirSync7 } from "fs";
3049
+ import { existsSync as existsSync17, readdirSync as readdirSync7 } from "fs";
2927
3050
  import { homedir as homedir14 } from "os";
2928
3051
  import { join as join15 } from "path";
2929
3052
  var TOOL_ID9 = "kimi-code";
@@ -2955,7 +3078,7 @@ function toSafeNumber6(value) {
2955
3078
  return Number.isFinite(numberValue) ? numberValue : 0;
2956
3079
  }
2957
3080
  function getPathLeaf5(value) {
2958
- const normalized = value.replace(/\\/g, "/").replace(/\/+$/, "");
3081
+ const normalized = trimTrailingSeparators(value.replace(/\\/g, "/"));
2959
3082
  const leaf = normalized.split("/").filter(Boolean).pop();
2960
3083
  return leaf || "unknown";
2961
3084
  }
@@ -2964,7 +3087,7 @@ function isModelPlaceholder(value) {
2964
3087
  }
2965
3088
  function findWireFiles(baseDir) {
2966
3089
  const results = [];
2967
- if (!existsSync16(baseDir)) return results;
3090
+ if (!existsSync17(baseDir)) return results;
2968
3091
  try {
2969
3092
  for (const workDir of readdirSync7(baseDir, { withFileTypes: true })) {
2970
3093
  if (!workDir.isDirectory()) continue;
@@ -2981,12 +3104,12 @@ function findWireFiles(baseDir) {
2981
3104
  "main",
2982
3105
  "wire.jsonl"
2983
3106
  );
2984
- if (existsSync16(newWireFile)) {
3107
+ if (existsSync17(newWireFile)) {
2985
3108
  results.push({ filePath: newWireFile, workDirHash: workDir.name });
2986
3109
  continue;
2987
3110
  }
2988
3111
  const legacyWireFile = join15(workDirPath, session.name, "wire.jsonl");
2989
- if (existsSync16(legacyWireFile)) {
3112
+ if (existsSync17(legacyWireFile)) {
2990
3113
  results.push({
2991
3114
  filePath: legacyWireFile,
2992
3115
  workDirHash: workDir.name
@@ -3190,13 +3313,13 @@ var KimiCodeParser = class {
3190
3313
  };
3191
3314
  }
3192
3315
  isInstalled() {
3193
- return existsSync16(this.sessionsDir);
3316
+ return existsSync17(this.sessionsDir);
3194
3317
  }
3195
3318
  };
3196
3319
  registerParser(new KimiCodeParser());
3197
3320
 
3198
3321
  // src/parsers/letcode.ts
3199
- import { existsSync as existsSync17 } from "fs";
3322
+ import { existsSync as existsSync18 } from "fs";
3200
3323
  import { homedir as homedir15 } from "os";
3201
3324
  import { basename as basename6, join as join16 } from "path";
3202
3325
  var TOOL_ID10 = "letcode";
@@ -3215,6 +3338,36 @@ function toNonNegativeNumber(value) {
3215
3338
  const numberValue = Number(value);
3216
3339
  return Number.isFinite(numberValue) && numberValue >= 0 ? numberValue : 0;
3217
3340
  }
3341
+ function splitProviderUsage(row) {
3342
+ const input2 = toNonNegativeNumber(row.provider_input_tokens);
3343
+ const output = toNonNegativeNumber(row.provider_output_tokens);
3344
+ const cached = toNonNegativeNumber(row.provider_cached_tokens);
3345
+ const reasoning = toNonNegativeNumber(row.provider_reasoning_tokens);
3346
+ let cachedInInput = cached <= input2;
3347
+ let reasoningInOutput = reasoning <= output;
3348
+ if (row.provider_total_tokens !== void 0) {
3349
+ const total = toNonNegativeNumber(row.provider_total_tokens);
3350
+ if (total === input2 + output) {
3351
+ cachedInInput = true;
3352
+ reasoningInOutput = true;
3353
+ } else if (total === input2 + output + reasoning) {
3354
+ cachedInInput = true;
3355
+ reasoningInOutput = false;
3356
+ } else if (total === input2 + output + cached) {
3357
+ cachedInInput = false;
3358
+ reasoningInOutput = true;
3359
+ } else if (total === input2 + output + cached + reasoning) {
3360
+ cachedInInput = false;
3361
+ reasoningInOutput = false;
3362
+ }
3363
+ }
3364
+ return {
3365
+ inputTokens: cachedInInput ? Math.max(0, input2 - cached) : input2,
3366
+ outputTokens: reasoningInOutput ? Math.max(0, output - reasoning) : output,
3367
+ cachedTokens: cached,
3368
+ reasoningTokens: reasoning
3369
+ };
3370
+ }
3218
3371
  function parseTimestamp2(value) {
3219
3372
  if (typeof value === "number" && Number.isFinite(value)) {
3220
3373
  const timestamp = new Date(value);
@@ -3293,12 +3446,7 @@ var LetcodeParser = class {
3293
3446
  if (!shouldCountTelemetry(row)) {
3294
3447
  continue;
3295
3448
  }
3296
- const inputTokens = toNonNegativeNumber(row.provider_input_tokens);
3297
- const outputTokens = toNonNegativeNumber(row.provider_output_tokens);
3298
- const cachedTokens = toNonNegativeNumber(row.provider_cached_tokens);
3299
- const reasoningTokens = toNonNegativeNumber(
3300
- row.provider_reasoning_tokens
3301
- );
3449
+ const { inputTokens, outputTokens, cachedTokens, reasoningTokens } = splitProviderUsage(row);
3302
3450
  if (inputTokens + outputTokens + cachedTokens + reasoningTokens === 0) {
3303
3451
  continue;
3304
3452
  }
@@ -3336,15 +3484,15 @@ var LetcodeParser = class {
3336
3484
  };
3337
3485
  }
3338
3486
  isInstalled() {
3339
- return this.sessionsDirs.some((dir) => existsSync17(dir));
3487
+ return this.sessionsDirs.some((dir) => existsSync18(dir));
3340
3488
  }
3341
3489
  };
3342
3490
  registerParser(new LetcodeParser());
3343
3491
 
3344
3492
  // src/parsers/droid.ts
3345
- import { existsSync as existsSync18, readdirSync as readdirSync8 } from "fs";
3493
+ import { existsSync as existsSync19, readdirSync as readdirSync8 } from "fs";
3346
3494
  import { homedir as homedir16 } from "os";
3347
- import { basename as basename7, dirname as dirname3, join as join17 } from "path";
3495
+ import { basename as basename7, dirname as dirname4, join as join17 } from "path";
3348
3496
  var TOOL_ID11 = "droid";
3349
3497
  var TOOL_NAME10 = "Droid";
3350
3498
  var DEFAULT_DATA_DIR5 = join17(homedir16(), ".factory", "sessions");
@@ -3357,7 +3505,7 @@ function createToolDefinition6(dataDir) {
3357
3505
  }
3358
3506
  function findSessionFiles3(dir) {
3359
3507
  const results = [];
3360
- if (!existsSync18(dir)) return results;
3508
+ if (!existsSync19(dir)) return results;
3361
3509
  try {
3362
3510
  for (const entry of readdirSync8(dir, { withFileTypes: true })) {
3363
3511
  const fullPath = join17(dir, entry.name);
@@ -3395,7 +3543,7 @@ var DroidParser = class {
3395
3543
  const sessionEvents = [];
3396
3544
  for (const filePath of sessionFiles) {
3397
3545
  const sessionId = filePath;
3398
- const project = extractDroidProject(basename7(dirname3(filePath)));
3546
+ const project = extractDroidProject(basename7(dirname4(filePath)));
3399
3547
  let firstMessageTimestamp = null;
3400
3548
  const content = readFileSafe(filePath);
3401
3549
  if (!content) continue;
@@ -3424,7 +3572,7 @@ var DroidParser = class {
3424
3572
  });
3425
3573
  }
3426
3574
  const settingsPath = join17(
3427
- dirname3(filePath),
3575
+ dirname4(filePath),
3428
3576
  `${basename7(filePath, ".jsonl")}.settings.json`
3429
3577
  );
3430
3578
  const settingsContent = readFileSafe(settingsPath);
@@ -3468,14 +3616,14 @@ var DroidParser = class {
3468
3616
  };
3469
3617
  }
3470
3618
  isInstalled() {
3471
- return existsSync18(this.dataDir);
3619
+ return existsSync19(this.dataDir);
3472
3620
  }
3473
3621
  };
3474
3622
  registerParser(new DroidParser());
3475
3623
 
3476
3624
  // src/parsers/pi-coding-agent.ts
3477
3625
  import { createHash as createHash4 } from "crypto";
3478
- import { existsSync as existsSync19, statSync as statSync2 } from "fs";
3626
+ import { existsSync as existsSync20, statSync as statSync2 } from "fs";
3479
3627
  import { homedir as homedir17 } from "os";
3480
3628
  import { join as join18 } from "path";
3481
3629
  var TOOL_ID12 = "pi-coding-agent";
@@ -3493,12 +3641,12 @@ function toSafeNumber8(value) {
3493
3641
  return Number.isFinite(numberValue) && numberValue >= 0 ? Math.trunc(numberValue) : 0;
3494
3642
  }
3495
3643
  function getPathLeaf6(value) {
3496
- const normalized = value.replace(/\\/g, "/").replace(/\/+$/, "");
3644
+ const normalized = trimTrailingSeparators(value.replace(/\\/g, "/"));
3497
3645
  const leaf = normalized.split("/").filter(Boolean).pop();
3498
3646
  return leaf || "unknown";
3499
3647
  }
3500
3648
  function normalizeForPrefix4(value) {
3501
- return value.replace(/\\/g, "/").replace(/\/+$/, "");
3649
+ return trimTrailingSeparators(value.replace(/\\/g, "/"));
3502
3650
  }
3503
3651
  function getUsageNumber3(usage, ...keys) {
3504
3652
  for (const key of keys) {
@@ -3719,13 +3867,13 @@ var PiCodingAgentParser = class {
3719
3867
  };
3720
3868
  }
3721
3869
  isInstalled() {
3722
- return existsSync19(this.sessionsDir);
3870
+ return existsSync20(this.sessionsDir);
3723
3871
  }
3724
3872
  };
3725
3873
  registerParser(new PiCodingAgentParser());
3726
3874
 
3727
3875
  // src/parsers/qwenpaw.ts
3728
- import { existsSync as existsSync20, readdirSync as readdirSync9 } from "fs";
3876
+ import { existsSync as existsSync21, readdirSync as readdirSync9 } from "fs";
3729
3877
  import { homedir as homedir18, hostname as hostname4 } from "os";
3730
3878
  import { join as join19 } from "path";
3731
3879
  var TOOL_ID13 = "qwenpaw";
@@ -3815,7 +3963,7 @@ var QwenPawParser = class {
3815
3963
  }
3816
3964
  async parseWorkspaceSessions() {
3817
3965
  const events = [];
3818
- if (!existsSync20(this.workspacePath)) {
3966
+ if (!existsSync21(this.workspacePath)) {
3819
3967
  return events;
3820
3968
  }
3821
3969
  try {
@@ -3867,7 +4015,7 @@ var QwenPawParser = class {
3867
4015
  }
3868
4016
  getSessionFiles(sessionsPath) {
3869
4017
  const files = /* @__PURE__ */ new Map();
3870
- if (!existsSync20(sessionsPath)) {
4018
+ if (!existsSync21(sessionsPath)) {
3871
4019
  return files;
3872
4020
  }
3873
4021
  try {
@@ -3974,7 +4122,7 @@ var QwenPawParser = class {
3974
4122
  });
3975
4123
  }
3976
4124
  isInstalled() {
3977
- return existsSync20(this.usagePath) || existsSync20(this.workspacePath);
4125
+ return existsSync21(this.usagePath) || existsSync21(this.workspacePath);
3978
4126
  }
3979
4127
  };
3980
4128
  registerParser(new QwenPawParser());
@@ -4032,7 +4180,7 @@ function readJsonSafe(path) {
4032
4180
  }
4033
4181
  function projectFromPath(absPath) {
4034
4182
  if (!absPath || typeof absPath !== "string") return "unknown";
4035
- const trimmed = absPath.replace(/[\\/]+$/, "");
4183
+ const trimmed = trimTrailingSeparators(absPath, "\\/");
4036
4184
  const name = basename8(trimmed);
4037
4185
  return name || "unknown";
4038
4186
  }
@@ -4127,10 +4275,10 @@ var ClineParser = class {
4127
4275
  registerParser(new ClineParser());
4128
4276
 
4129
4277
  // src/parsers/kiro.ts
4130
- import { execFileSync as execFileSync3 } from "child_process";
4278
+ import { execFileSync as execFileSync4 } from "child_process";
4131
4279
  import {
4132
4280
  copyFileSync,
4133
- existsSync as existsSync21,
4281
+ existsSync as existsSync22,
4134
4282
  mkdtempSync,
4135
4283
  readdirSync as readdirSync10,
4136
4284
  readFileSync as readFileSync7,
@@ -4166,17 +4314,21 @@ function getKiroBasePath() {
4166
4314
  const explicit = process.env.KIRO_BASE_PATH?.trim();
4167
4315
  if (explicit) {
4168
4316
  const r = resolve(explicit);
4169
- return existsSync21(r) ? r : null;
4317
+ return existsSync22(r) ? r : null;
4170
4318
  }
4171
4319
  const def = getDefaultBasePath();
4172
- return existsSync21(def) ? def : null;
4320
+ return existsSync22(def) ? def : null;
4173
4321
  }
4174
4322
  function isLockError(err) {
4175
4323
  return err instanceof Error && typeof err.message === "string" && /database is locked/i.test(err.message);
4176
4324
  }
4177
4325
  var TOKENS_SQL = "SELECT id, model, tokens_prompt, tokens_generated, timestamp FROM tokens_generated WHERE tokens_prompt > 0 OR tokens_generated > 0 ORDER BY id ASC";
4178
4326
  function queryDb(dbPath, sql) {
4179
- const out = execFileSync3("sqlite3", ["-json", dbPath, sql], {
4327
+ const [command] = getSqliteCliCandidates();
4328
+ if (!command) {
4329
+ throw new Error("spawnSync sqlite3 ENOENT");
4330
+ }
4331
+ const out = execFileSync4(command, ["-json", dbPath, sql], {
4180
4332
  encoding: "utf-8",
4181
4333
  maxBuffer: 100 * 1024 * 1024,
4182
4334
  timeout: 3e4
@@ -4195,7 +4347,7 @@ function readDb(dbPath) {
4195
4347
  copyFileSync(dbPath, queryPath);
4196
4348
  for (const suffix of ["-shm", "-wal"]) {
4197
4349
  const companion = `${dbPath}${suffix}`;
4198
- if (existsSync21(companion))
4350
+ if (existsSync22(companion))
4199
4351
  copyFileSync(companion, `${queryPath}${suffix}`);
4200
4352
  }
4201
4353
  try {
@@ -4309,9 +4461,9 @@ var KiroParser = class {
4309
4461
  const jsonlPath = join21(base, "dev_data", "tokens_generated.jsonl");
4310
4462
  let rows;
4311
4463
  try {
4312
- if (existsSync21(dbPath)) {
4464
+ if (existsSync22(dbPath)) {
4313
4465
  rows = readDb(dbPath);
4314
- } else if (existsSync21(jsonlPath)) {
4466
+ } else if (existsSync22(jsonlPath)) {
4315
4467
  rows = readJsonl(jsonlPath);
4316
4468
  } else {
4317
4469
  return { buckets: [], sessions: [] };
@@ -4413,10 +4565,19 @@ function readJsonSafe2(path) {
4413
4565
  }
4414
4566
  function projectFromPath2(absPath) {
4415
4567
  if (!absPath || typeof absPath !== "string") return "unknown";
4416
- const trimmed = absPath.replace(/[\\/]+$/, "");
4568
+ const trimmed = trimTrailingSeparators(absPath, "\\/");
4417
4569
  const name = basename9(trimmed);
4418
4570
  return name || "unknown";
4419
4571
  }
4572
+ function uncachedInputTokens(input2) {
4573
+ if (input2.apiProtocol === "anthropic" || input2.apiProtocol === "openai") {
4574
+ return Math.max(0, input2.tokensIn - input2.cacheWrites - input2.cacheReads);
4575
+ }
4576
+ if (input2.cacheWrites > 0 || input2.tokensIn < input2.cacheReads) {
4577
+ return input2.tokensIn;
4578
+ }
4579
+ return input2.tokensIn - input2.cacheReads;
4580
+ }
4420
4581
  function readHistoryItems(extDir) {
4421
4582
  const tasksDir = join22(extDir, "tasks");
4422
4583
  const index = readJsonSafe2(
@@ -4476,10 +4637,16 @@ var RooCodeParser = class {
4476
4637
  } catch {
4477
4638
  }
4478
4639
  if (!info) continue;
4479
- const inputTokens = Math.max(0, Number(info.tokensIn) || 0);
4640
+ const tokensIn = Math.max(0, Number(info.tokensIn) || 0);
4480
4641
  const outputTokens = Math.max(0, Number(info.tokensOut) || 0);
4481
4642
  const cacheWrites = Math.max(0, Number(info.cacheWrites) || 0);
4482
4643
  const cacheReads = Math.max(0, Number(info.cacheReads) || 0);
4644
+ const inputTokens = uncachedInputTokens({
4645
+ tokensIn,
4646
+ cacheWrites,
4647
+ cacheReads,
4648
+ apiProtocol: msg.apiProtocol
4649
+ });
4483
4650
  if (inputTokens + outputTokens + cacheWrites + cacheReads === 0)
4484
4651
  continue;
4485
4652
  const model = info.model && String(info.model).trim() || fallbackModel;
@@ -4526,7 +4693,7 @@ var RooCodeParser = class {
4526
4693
  registerParser(new RooCodeParser());
4527
4694
 
4528
4695
  // src/parsers/snow.ts
4529
- import { existsSync as existsSync22, readdirSync as readdirSync12, statSync as statSync6 } from "fs";
4696
+ import { existsSync as existsSync23, readdirSync as readdirSync12, statSync as statSync6 } from "fs";
4530
4697
  import { homedir as homedir22 } from "os";
4531
4698
  import { basename as basename10, join as join23 } from "path";
4532
4699
  var DEFAULT_SNOW_DIR = join23(homedir22(), ".snow");
@@ -4792,7 +4959,7 @@ var SnowParser = class {
4792
4959
  )) {
4793
4960
  const content = readFileSafe(filePath);
4794
4961
  if (content === null) {
4795
- if (existsSync22(filePath)) incomplete = true;
4962
+ if (existsSync23(filePath)) incomplete = true;
4796
4963
  continue;
4797
4964
  }
4798
4965
  for (const line of content.split("\n")) {
@@ -4833,7 +5000,7 @@ var SnowParser = class {
4833
5000
  return { entries, incomplete };
4834
5001
  }
4835
5002
  isInstalled() {
4836
- return existsSync22(join23(this.snowDir, USAGE_DIR_NAME));
5003
+ return existsSync23(join23(this.snowDir, USAGE_DIR_NAME));
4837
5004
  }
4838
5005
  };
4839
5006
  registerParser(new SnowParser());
@@ -4841,7 +5008,7 @@ registerParser(new SnowParser());
4841
5008
  // src/parsers/snow-app.ts
4842
5009
  import { statSync as statSync7 } from "fs";
4843
5010
  import { homedir as homedir23 } from "os";
4844
- import { dirname as dirname4, join as join24 } from "path";
5011
+ import { dirname as dirname5, join as join24 } from "path";
4845
5012
  var TOOL_ID14 = "snow-app";
4846
5013
  var DEFAULT_DB_PATH3 = join24(homedir23(), ".snowapp", "snowapp.db");
4847
5014
  var SNAPSHOT_QUERY = `SELECT 'usage' AS kind, u.id, u.conversation_id AS sessionId,
@@ -4947,7 +5114,7 @@ var SnowAppParser = class {
4947
5114
  this.tool = {
4948
5115
  id: TOOL_ID14,
4949
5116
  name: "Snow App",
4950
- dataDir: dirname4(this.dbPath)
5117
+ dataDir: dirname5(this.dbPath)
4951
5118
  };
4952
5119
  }
4953
5120
  isInstalled() {
@@ -5046,10 +5213,10 @@ var SnowAppParser = class {
5046
5213
  registerParser(new SnowAppParser());
5047
5214
 
5048
5215
  // src/parsers/cursor.ts
5049
- import { execFileSync as execFileSync4 } from "child_process";
5050
- import { copyFileSync as copyFileSync2, existsSync as existsSync23, mkdtempSync as mkdtempSync2, rmSync as rmSync2 } from "fs";
5216
+ import { execFileSync as execFileSync5 } from "child_process";
5217
+ import { copyFileSync as copyFileSync2, existsSync as existsSync24, mkdtempSync as mkdtempSync2, rmSync as rmSync2 } from "fs";
5051
5218
  import { homedir as homedir24, tmpdir as tmpdir2 } from "os";
5052
- import { dirname as dirname5, join as join25, resolve as resolve2 } from "path";
5219
+ import { dirname as dirname6, join as join25, resolve as resolve2 } from "path";
5053
5220
  var TOOL_ID15 = "cursor";
5054
5221
  var TOOL_NAME13 = "Cursor";
5055
5222
  var STATE_DB_RELATIVE = join25("User", "globalStorage", "state.vscdb");
@@ -5077,7 +5244,7 @@ function getCursorStateDbPath() {
5077
5244
  const explicit = process.env.CURSOR_STATE_DB_PATH?.trim();
5078
5245
  if (explicit) {
5079
5246
  const resolved = resolve2(explicit);
5080
- return existsSync23(resolved) ? resolved : null;
5247
+ return existsSync24(resolved) ? resolved : null;
5081
5248
  }
5082
5249
  const configDirs = process.env.CURSOR_CONFIG_DIR?.trim();
5083
5250
  const candidates = configDirs ? configDirs.split(",").map((v) => v.trim()).filter(Boolean).map((v) => {
@@ -5085,20 +5252,16 @@ function getCursorStateDbPath() {
5085
5252
  return r.endsWith(".vscdb") ? r : join25(r, STATE_DB_RELATIVE);
5086
5253
  }) : [getDefaultStateDbPath()];
5087
5254
  for (const c of candidates) {
5088
- if (existsSync23(c)) return c;
5255
+ if (existsSync24(c)) return c;
5089
5256
  }
5090
5257
  return null;
5091
5258
  }
5092
5259
  function queryAccessToken(dbPath) {
5093
5260
  const sql = `SELECT value FROM ItemTable WHERE key = '${ACCESS_TOKEN_KEY}' LIMIT 1`;
5094
- const candidates = [
5095
- process.env.TOKEN_ARENA_SQLITE3,
5096
- "sqlite3",
5097
- "sqlite3.exe"
5098
- ].filter((value) => Boolean(value));
5261
+ const candidates = getSqliteCliCandidates();
5099
5262
  for (const command of candidates) {
5100
5263
  try {
5101
- const out = execFileSync4(command, ["-json", dbPath, sql], {
5264
+ const out = execFileSync5(command, ["-json", dbPath, sql], {
5102
5265
  encoding: "utf-8",
5103
5266
  maxBuffer: 4 * 1024 * 1024,
5104
5267
  timeout: 15e3,
@@ -5131,7 +5294,7 @@ function readAccessToken(dbPath) {
5131
5294
  copyFileSync2(dbPath, queryPath);
5132
5295
  for (const suffix of ["-shm", "-wal"]) {
5133
5296
  const companion = `${dbPath}${suffix}`;
5134
- if (existsSync23(companion))
5297
+ if (existsSync24(companion))
5135
5298
  copyFileSync2(companion, `${queryPath}${suffix}`);
5136
5299
  }
5137
5300
  return queryAccessToken(queryPath);
@@ -5156,7 +5319,9 @@ function decodeJwtSub(token) {
5156
5319
  }
5157
5320
  }
5158
5321
  async function fetchUsageCsv(token) {
5159
- const baseUrl = (process.env.CURSOR_WEB_BASE_URL?.trim() || "https://cursor.com").replace(/\/+$/, "");
5322
+ const baseUrl = trimTrailingSeparators(
5323
+ process.env.CURSOR_WEB_BASE_URL?.trim() || "https://cursor.com"
5324
+ );
5160
5325
  const url = `${baseUrl}/api/dashboard/export-usage-events-csv?strategy=tokens`;
5161
5326
  const sub = decodeJwtSub(token);
5162
5327
  const cookieValues = sub ? [token, `${sub}::${token}`] : [token];
@@ -5261,7 +5426,7 @@ function createToolDefinition9(dbPath) {
5261
5426
  return {
5262
5427
  id: TOOL_ID15,
5263
5428
  name: TOOL_NAME13,
5264
- dataDir: dirname5(dbPath)
5429
+ dataDir: dirname6(dbPath)
5265
5430
  };
5266
5431
  }
5267
5432
  var CursorParser = class {
@@ -5276,7 +5441,7 @@ var CursorParser = class {
5276
5441
  this.tool = createToolDefinition9(this.dbPath);
5277
5442
  }
5278
5443
  async parse() {
5279
- if (!this.dbPath || !existsSync23(this.dbPath)) {
5444
+ if (!this.dbPath || !existsSync24(this.dbPath)) {
5280
5445
  return { buckets: [], sessions: [] };
5281
5446
  }
5282
5447
  let token;
@@ -5291,17 +5456,21 @@ var CursorParser = class {
5291
5456
  throw err;
5292
5457
  }
5293
5458
  if (!token) return { buckets: [], sessions: [] };
5459
+ const unavailable = (reason) => {
5460
+ logger.warn(`Cursor usage export unavailable (${reason}).`);
5461
+ return { buckets: [], sessions: [], incomplete: true };
5462
+ };
5294
5463
  let csv;
5295
5464
  try {
5296
5465
  csv = await this.fetchCsv(token);
5297
5466
  } catch (err) {
5298
- if (err.skip)
5299
- return { buckets: [], sessions: [] };
5467
+ if (err.skip) {
5468
+ return unavailable(err.message);
5469
+ }
5300
5470
  throw err;
5301
5471
  }
5302
5472
  const rows = parseCsv(csv);
5303
- if (rows.length < 2) return { buckets: [], sessions: [] };
5304
- const header = rows[0].map((h) => h.trim());
5473
+ const header = (rows[0] ?? []).map((h) => h.trim());
5305
5474
  const idx = (name) => header.indexOf(name);
5306
5475
  const dateIdx = idx("Date");
5307
5476
  const modelIdx = idx("Model");
@@ -5309,7 +5478,10 @@ var CursorParser = class {
5309
5478
  const inputNoCacheIdx = idx("Input (w/o Cache Write)");
5310
5479
  const cacheReadIdx = idx("Cache Read");
5311
5480
  const outputIdx = idx("Output Tokens");
5312
- if (dateIdx < 0 || modelIdx < 0) return { buckets: [], sessions: [] };
5481
+ if (dateIdx < 0 || modelIdx < 0) {
5482
+ return unavailable("unexpected response");
5483
+ }
5484
+ if (rows.length < 2) return { buckets: [], sessions: [] };
5313
5485
  const entries = [];
5314
5486
  for (let r = 1; r < rows.length; r++) {
5315
5487
  const row = rows[r];
@@ -5340,16 +5512,16 @@ var CursorParser = class {
5340
5512
  };
5341
5513
  }
5342
5514
  isInstalled() {
5343
- return existsSync23(this.dbPath);
5515
+ return existsSync24(this.dbPath);
5344
5516
  }
5345
5517
  };
5346
5518
  registerParser(new CursorParser());
5347
5519
 
5348
5520
  // src/parsers/zcode.ts
5349
5521
  import { createHash as createHash5 } from "crypto";
5350
- import { existsSync as existsSync24 } from "fs";
5522
+ import { existsSync as existsSync25 } from "fs";
5351
5523
  import { homedir as homedir25, hostname as hostname5 } from "os";
5352
- import { dirname as dirname6, join as join26 } from "path";
5524
+ import { dirname as dirname7, join as join26 } from "path";
5353
5525
  var TOOL_ID16 = "zcode";
5354
5526
  var TOOL_NAME14 = "ZCode";
5355
5527
  var DEFAULT_DB_PATH4 = join26(homedir25(), ".zcode", "cli", "db", "db.sqlite");
@@ -5391,7 +5563,7 @@ function createToolDefinition10(dbPath) {
5391
5563
  return {
5392
5564
  id: TOOL_ID16,
5393
5565
  name: TOOL_NAME14,
5394
- dataDir: dirname6(dbPath)
5566
+ dataDir: dirname7(dbPath)
5395
5567
  };
5396
5568
  }
5397
5569
  function toSafeNumber10(value) {
@@ -5413,7 +5585,7 @@ function getPathLeaf7(value) {
5413
5585
  if (!value) {
5414
5586
  return "unknown";
5415
5587
  }
5416
- const normalized = value.replace(/\\/g, "/").replace(/\/+$/, "");
5588
+ const normalized = trimTrailingSeparators(value.replace(/\\/g, "/"));
5417
5589
  const leaf = normalized.split("/").filter(Boolean).pop();
5418
5590
  return leaf || "unknown";
5419
5591
  }
@@ -5616,7 +5788,7 @@ var ZCodeParser = class {
5616
5788
  this.tool = createToolDefinition10(this.dbPath);
5617
5789
  }
5618
5790
  async parse() {
5619
- if (!existsSync24(this.dbPath)) {
5791
+ if (!existsSync25(this.dbPath)) {
5620
5792
  return { buckets: [], sessions: [] };
5621
5793
  }
5622
5794
  const usageRows = await this.queryRows(
@@ -5682,13 +5854,13 @@ var ZCodeParser = class {
5682
5854
  };
5683
5855
  }
5684
5856
  isInstalled() {
5685
- return existsSync24(this.dbPath);
5857
+ return existsSync25(this.dbPath);
5686
5858
  }
5687
5859
  };
5688
5860
  registerParser(new ZCodeParser());
5689
5861
 
5690
5862
  // src/parsers/qodercli.ts
5691
- import { existsSync as existsSync25, readdirSync as readdirSync13 } from "fs";
5863
+ import { existsSync as existsSync26, readdirSync as readdirSync13 } from "fs";
5692
5864
  import { homedir as homedir26 } from "os";
5693
5865
  import { basename as basename11, join as join27 } from "path";
5694
5866
  var TOOL_ID17 = "qodercli";
@@ -5711,7 +5883,7 @@ function toSafeNumber11(value) {
5711
5883
  return Number.isFinite(numberValue) ? numberValue : 0;
5712
5884
  }
5713
5885
  function normalizeForPrefix5(value) {
5714
- return value.replace(/\\/g, "/").replace(/\/+$/, "");
5886
+ return trimTrailingSeparators(value.replace(/\\/g, "/"));
5715
5887
  }
5716
5888
  function extractQoderProject(filePath, projectsDir) {
5717
5889
  const normalizedFilePath = normalizeForPrefix5(filePath);
@@ -5747,7 +5919,7 @@ function isQodercliBinaryPresent() {
5747
5919
  join27(home, ".qoder", "bin", "qodercli"),
5748
5920
  join27(home, ".qoder-cli")
5749
5921
  ];
5750
- return candidates.some((path) => existsSync25(path));
5922
+ return candidates.some((path) => existsSync26(path));
5751
5923
  }
5752
5924
  function projectFromEncodedSlug(slug) {
5753
5925
  const parts = slug.split("-").filter(Boolean);
@@ -5755,7 +5927,7 @@ function projectFromEncodedSlug(slug) {
5755
5927
  }
5756
5928
  function projectFromCwd(cwd) {
5757
5929
  if (!cwd) return "unknown";
5758
- const leaf = basename11(cwd.replace(/[\\/]+$/, ""));
5930
+ const leaf = basename11(trimTrailingSeparators(cwd, "\\/"));
5759
5931
  return leaf || "unknown";
5760
5932
  }
5761
5933
  function totalCreditsUsed(quota) {
@@ -5856,7 +6028,7 @@ var QoderCliParser = class {
5856
6028
  };
5857
6029
  }
5858
6030
  parseProjectSessions(sessionEvents) {
5859
- if (!existsSync25(this.projectsDir)) return;
6031
+ if (!existsSync26(this.projectsDir)) return;
5860
6032
  for (const filePath of findJsonlFiles(this.projectsDir)) {
5861
6033
  if (basename11(filePath).startsWith("verified-")) continue;
5862
6034
  const content = readFileSafe(filePath);
@@ -5881,7 +6053,7 @@ var QoderCliParser = class {
5881
6053
  source: TOOL_ID17,
5882
6054
  project,
5883
6055
  timestamp: ts,
5884
- role: obj.type === "user" ? "user" : "assistant"
6056
+ role: isHumanPromptRecord(obj) ? "user" : "assistant"
5885
6057
  });
5886
6058
  } catch {
5887
6059
  }
@@ -5893,7 +6065,7 @@ var QoderCliParser = class {
5893
6065
  * There is no token data here — only quota/usage credit totals.
5894
6066
  */
5895
6067
  parseCreditDeltas() {
5896
- if (!existsSync25(this.runsDir)) return [];
6068
+ if (!existsSync26(this.runsDir)) return [];
5897
6069
  let runDirs;
5898
6070
  try {
5899
6071
  runDirs = readdirSync13(this.runsDir, { withFileTypes: true }).filter(
@@ -5906,7 +6078,7 @@ var QoderCliParser = class {
5906
6078
  for (const dir of runDirs) {
5907
6079
  const runPath = join27(this.runsDir, dir.name);
5908
6080
  const logPath = join27(runPath, "qodercli.log");
5909
- if (!existsSync25(logPath)) continue;
6081
+ if (!existsSync26(logPath)) continue;
5910
6082
  const logContent = readFileSafe(logPath);
5911
6083
  if (!logContent?.includes("quota/usage response:")) {
5912
6084
  continue;
@@ -5924,13 +6096,13 @@ var QoderCliParser = class {
5924
6096
  return creditSnapshotsToEntries(allSnapshots);
5925
6097
  }
5926
6098
  isInstalled() {
5927
- return isQodercliBinaryPresent() || existsSync25(this.runsDir) || existsSync25(this.logsDir) || existsSync25(this.projectsDir);
6099
+ return isQodercliBinaryPresent() || existsSync26(this.runsDir) || existsSync26(this.logsDir) || existsSync26(this.projectsDir);
5928
6100
  }
5929
6101
  };
5930
6102
  registerParser(new QoderCliParser());
5931
6103
 
5932
6104
  // src/parsers/grok-build.ts
5933
- import { existsSync as existsSync26, readdirSync as readdirSync14 } from "fs";
6105
+ import { existsSync as existsSync27, readdirSync as readdirSync14 } from "fs";
5934
6106
  import { homedir as homedir27 } from "os";
5935
6107
  import { basename as basename12, join as join28 } from "path";
5936
6108
  var TOOL_ID18 = "grok-build";
@@ -5951,7 +6123,7 @@ function toSafeNumber12(value) {
5951
6123
  function projectFromEncodedCwd(encoded) {
5952
6124
  try {
5953
6125
  const decoded = decodeURIComponent(encoded);
5954
- const leaf = basename12(decoded.replace(/[\\/]+$/, ""));
6126
+ const leaf = basename12(trimTrailingSeparators(decoded, "\\/"));
5955
6127
  return leaf || "unknown";
5956
6128
  } catch {
5957
6129
  const leaf = basename12(encoded);
@@ -6005,7 +6177,7 @@ function pushUsageEntries(entries, args) {
6005
6177
  }
6006
6178
  function findSessionDirs(dataDir) {
6007
6179
  const results = [];
6008
- if (!existsSync26(dataDir)) return results;
6180
+ if (!existsSync27(dataDir)) return results;
6009
6181
  let projectDirs;
6010
6182
  try {
6011
6183
  projectDirs = readdirSync14(dataDir, { withFileTypes: true });
@@ -6026,7 +6198,7 @@ function findSessionDirs(dataDir) {
6026
6198
  for (const sessionEntry of sessionEntries) {
6027
6199
  if (!sessionEntry.isDirectory()) continue;
6028
6200
  const sessionDir = join28(projectDir, sessionEntry.name);
6029
- if (!existsSync26(join28(sessionDir, "updates.jsonl"))) continue;
6201
+ if (!existsSync27(join28(sessionDir, "updates.jsonl"))) continue;
6030
6202
  results.push({
6031
6203
  sessionDir,
6032
6204
  project,
@@ -6141,13 +6313,13 @@ var GrokBuildParser = class {
6141
6313
  };
6142
6314
  }
6143
6315
  isInstalled() {
6144
- return existsSync26(this.dataDir) || Boolean(this.archiveDir && existsSync26(this.archiveDir)) || existsSync26(join28(homedir27(), ".grok")) || existsSync26(join28(homedir27(), ".local", "bin", "grok"));
6316
+ return existsSync27(this.dataDir) || Boolean(this.archiveDir && existsSync27(this.archiveDir)) || existsSync27(join28(homedir27(), ".grok")) || existsSync27(join28(homedir27(), ".local", "bin", "grok"));
6145
6317
  }
6146
6318
  };
6147
6319
  registerParser(new GrokBuildParser());
6148
6320
 
6149
6321
  // src/parsers/atomcode.ts
6150
- import { existsSync as existsSync27 } from "fs";
6322
+ import { existsSync as existsSync28 } from "fs";
6151
6323
  import { homedir as homedir28 } from "os";
6152
6324
  import { basename as basename13, join as join29 } from "path";
6153
6325
  var TOOL_ID19 = "atomcode";
@@ -6289,15 +6461,15 @@ var AtomCodeParser = class {
6289
6461
  };
6290
6462
  }
6291
6463
  isInstalled() {
6292
- return this.sessionsDirs.some((dir) => existsSync27(dir));
6464
+ return this.sessionsDirs.some((dir) => existsSync28(dir));
6293
6465
  }
6294
6466
  };
6295
6467
  registerParser(new AtomCodeParser());
6296
6468
 
6297
6469
  // src/parsers/dsh.ts
6298
- import { existsSync as existsSync28, readdirSync as readdirSync15, readFileSync as readFileSync9 } from "fs";
6470
+ import { existsSync as existsSync29, readdirSync as readdirSync15, readFileSync as readFileSync9 } from "fs";
6299
6471
  import { homedir as homedir29 } from "os";
6300
- import { basename as basename14, dirname as dirname7, join as join30 } from "path";
6472
+ import { basename as basename14, dirname as dirname8, join as join30 } from "path";
6301
6473
  import * as zlib from "zlib";
6302
6474
  var TOOL_ID20 = "dsh";
6303
6475
  var TOOL_NAME18 = "DeepSeek Harness";
@@ -6410,7 +6582,7 @@ function readSessionLog(log2) {
6410
6582
  }
6411
6583
  function findSessionLogs(dir, rootDir = dir) {
6412
6584
  const results = [];
6413
- if (!existsSync28(dir)) return results;
6585
+ if (!existsSync29(dir)) return results;
6414
6586
  try {
6415
6587
  for (const entry of readdirSync15(dir, { withFileTypes: true })) {
6416
6588
  const fullPath = join30(dir, entry.name);
@@ -6441,7 +6613,7 @@ function isNewerLog(candidate, current) {
6441
6613
  function selectCurrentSessionLogs(logs) {
6442
6614
  const byDirectory = /* @__PURE__ */ new Map();
6443
6615
  for (const log2 of logs) {
6444
- const directory = dirname7(log2.filePath);
6616
+ const directory = dirname8(log2.filePath);
6445
6617
  const current = byDirectory.get(directory);
6446
6618
  if (!current || isNewerLog(log2, current)) {
6447
6619
  byDirectory.set(directory, log2);
@@ -6510,7 +6682,7 @@ var DshParser = class {
6510
6682
  for (const log2 of logs) {
6511
6683
  const { text: content, damaged } = readSessionLog(log2);
6512
6684
  if (content === null) {
6513
- if (existsSync28(log2.filePath)) incomplete = true;
6685
+ if (existsSync29(log2.filePath)) incomplete = true;
6514
6686
  continue;
6515
6687
  }
6516
6688
  if (damaged) {
@@ -6631,15 +6803,15 @@ var DshParser = class {
6631
6803
  return currentSessionLogs(this.sessionsDirs).map((log2) => log2.filePath);
6632
6804
  }
6633
6805
  isInstalled() {
6634
- return this.sessionsDirs.some((dir) => existsSync28(dir));
6806
+ return this.sessionsDirs.some((dir) => existsSync29(dir));
6635
6807
  }
6636
6808
  };
6637
6809
  registerParser(new DshParser());
6638
6810
 
6639
6811
  // src/parsers/cherry-studio.ts
6640
- import { existsSync as existsSync29 } from "fs";
6812
+ import { existsSync as existsSync30 } from "fs";
6641
6813
  import { homedir as homedir30 } from "os";
6642
- import { dirname as dirname8, join as join31, resolve as resolve3 } from "path";
6814
+ import { dirname as dirname9, join as join31, resolve as resolve3 } from "path";
6643
6815
  var TOOL_ID21 = "cherry-studio";
6644
6816
  var TOOL_NAME19 = "Cherry Studio";
6645
6817
  var DB_RELATIVE = join31("Data", "cherrystudio.sqlite");
@@ -6688,13 +6860,13 @@ function getCherryStudioDbPaths(env = process.env) {
6688
6860
  }
6689
6861
  function resolveCherryStudioDbPath() {
6690
6862
  const candidates = getCherryStudioDbPaths();
6691
- return candidates.find((candidate) => existsSync29(candidate)) ?? "";
6863
+ return candidates.find((candidate) => existsSync30(candidate)) ?? "";
6692
6864
  }
6693
6865
  function createToolDefinition13(dbPath) {
6694
6866
  return {
6695
6867
  id: TOOL_ID21,
6696
6868
  name: TOOL_NAME19,
6697
- dataDir: dbPath ? dirname8(dbPath) : join31(getDefaultUserDataDir(), "Data")
6869
+ dataDir: dbPath ? dirname9(dbPath) : join31(getDefaultUserDataDir(), "Data")
6698
6870
  };
6699
6871
  }
6700
6872
  function toSafeCount(value) {
@@ -6729,7 +6901,7 @@ var CherryStudioParser = class {
6729
6901
  this.tool = createToolDefinition13(this.dbPath);
6730
6902
  }
6731
6903
  async parse() {
6732
- if (!this.dbPath || !existsSync29(this.dbPath)) {
6904
+ if (!this.dbPath || !existsSync30(this.dbPath)) {
6733
6905
  return { buckets: [], sessions: [] };
6734
6906
  }
6735
6907
  const usageRows = await this.queryRows(
@@ -6804,7 +6976,7 @@ var CherryStudioParser = class {
6804
6976
  };
6805
6977
  }
6806
6978
  isInstalled() {
6807
- return Boolean(this.dbPath) && existsSync29(this.dbPath);
6979
+ return Boolean(this.dbPath) && existsSync30(this.dbPath);
6808
6980
  }
6809
6981
  };
6810
6982
  registerParser(new CherryStudioParser());
@@ -6812,16 +6984,82 @@ registerParser(new CherryStudioParser());
6812
6984
  // src/cli.ts
6813
6985
  import { Command, Option } from "commander";
6814
6986
 
6987
+ // src/infrastructure/api/url-policy.ts
6988
+ import { isIP } from "net";
6989
+ function isLocalHost(hostname8) {
6990
+ const host = hostname8.toLowerCase().replace(/^\[|\]$/g, "");
6991
+ if (host === "localhost" || host.endsWith(".localhost")) return true;
6992
+ if (isIP(host) === 4) {
6993
+ const [a, b] = host.split(".").map(Number);
6994
+ return a === 127 || a === 10 || a === 172 && b >= 16 && b <= 31 || a === 192 && b === 168 || a === 169 && b === 254 || a === 100 && b >= 64 && b <= 127;
6995
+ }
6996
+ if (isIP(host) === 6) {
6997
+ return host === "::1" || /^f[cd][0-9a-f]{2}:/.test(host) || /^fe[89ab][0-9a-f]:/.test(host);
6998
+ }
6999
+ return !host.includes(".") || [".local", ".lan", ".internal", ".home.arpa"].some(
7000
+ (suffix) => host.endsWith(suffix)
7001
+ );
7002
+ }
7003
+ function getInsecureApiUrlReason(apiUrl) {
7004
+ let url;
7005
+ try {
7006
+ url = new URL(apiUrl);
7007
+ } catch {
7008
+ return `Invalid API URL: ${apiUrl}`;
7009
+ }
7010
+ if (url.protocol === "https:") return null;
7011
+ if (url.protocol !== "http:") {
7012
+ return `Unsupported API URL protocol "${url.protocol}". Use https://.`;
7013
+ }
7014
+ return isLocalHost(url.hostname) ? null : `Refusing to send the API key over plain HTTP to ${url.host}. Use https://${url.host}${url.pathname === "/" ? "" : url.pathname} instead.`;
7015
+ }
7016
+
6815
7017
  // src/infrastructure/config/manager.ts
7018
+ import { randomUUID as randomUUID2 } from "crypto";
7019
+ import { existsSync as existsSync31, readFileSync as readFileSync10, unlinkSync } from "fs";
7020
+ import { join as join33 } from "path";
7021
+
7022
+ // src/infrastructure/fs/private-files.ts
6816
7023
  import { randomUUID } from "crypto";
6817
7024
  import {
6818
- existsSync as existsSync30,
7025
+ chmodSync,
6819
7026
  mkdirSync,
6820
- readFileSync as readFileSync10,
6821
- unlinkSync,
7027
+ renameSync,
7028
+ rmSync as rmSync3,
7029
+ statSync as statSync8,
6822
7030
  writeFileSync
6823
7031
  } from "fs";
6824
- import { join as join33 } from "path";
7032
+ var PRIVATE_DIR_MODE = 448;
7033
+ var PRIVATE_FILE_MODE = 384;
7034
+ function restrictToOwner(path) {
7035
+ if (process.platform === "win32") {
7036
+ return;
7037
+ }
7038
+ try {
7039
+ const { mode } = statSync8(path);
7040
+ if ((mode & 63) !== 0) {
7041
+ chmodSync(path, mode & 448);
7042
+ }
7043
+ } catch {
7044
+ }
7045
+ }
7046
+ function ensurePrivateDir(path) {
7047
+ mkdirSync(path, { recursive: true, mode: PRIVATE_DIR_MODE });
7048
+ restrictToOwner(path);
7049
+ }
7050
+ function writePrivateFile(path, content) {
7051
+ const temporaryPath = `${path}.${process.pid}.${randomUUID()}.tmp`;
7052
+ writeFileSync(temporaryPath, content, {
7053
+ encoding: "utf-8",
7054
+ mode: PRIVATE_FILE_MODE
7055
+ });
7056
+ try {
7057
+ renameSync(temporaryPath, path);
7058
+ } catch (error) {
7059
+ rmSync3(temporaryPath, { force: true });
7060
+ throw error;
7061
+ }
7062
+ }
6825
7063
 
6826
7064
  // src/infrastructure/xdg.ts
6827
7065
  import { homedir as homedir31 } from "os";
@@ -6855,7 +7093,9 @@ function getConfigDir() {
6855
7093
  return CONFIG_DIR;
6856
7094
  }
6857
7095
  function loadConfig() {
6858
- if (!existsSync30(CONFIG_FILE)) return null;
7096
+ if (!existsSync31(CONFIG_FILE)) return null;
7097
+ restrictToOwner(CONFIG_DIR);
7098
+ restrictToOwner(CONFIG_FILE);
6859
7099
  try {
6860
7100
  const raw = readFileSync10(CONFIG_FILE, "utf-8");
6861
7101
  const config = JSON.parse(raw);
@@ -6868,18 +7108,18 @@ function loadConfig() {
6868
7108
  }
6869
7109
  }
6870
7110
  function saveConfig(config) {
6871
- mkdirSync(CONFIG_DIR, { recursive: true });
6872
- writeFileSync(CONFIG_FILE, `${JSON.stringify(config, null, 2)}
6873
- `, "utf-8");
7111
+ ensurePrivateDir(CONFIG_DIR);
7112
+ writePrivateFile(CONFIG_FILE, `${JSON.stringify(config, null, 2)}
7113
+ `);
6874
7114
  }
6875
7115
  function deleteConfig() {
6876
- if (existsSync30(CONFIG_FILE)) {
7116
+ if (existsSync31(CONFIG_FILE)) {
6877
7117
  unlinkSync(CONFIG_FILE);
6878
7118
  }
6879
7119
  }
6880
7120
  function getOrCreateDeviceId(config) {
6881
7121
  if (config.deviceId) return config.deviceId;
6882
- const next = randomUUID();
7122
+ const next = randomUUID2();
6883
7123
  saveConfig({ ...config, deviceId: next });
6884
7124
  return next;
6885
7125
  }
@@ -7253,6 +7493,11 @@ async function handleConfig(args) {
7253
7493
  logger.error("apiUrl must be a valid URL");
7254
7494
  process.exit(1);
7255
7495
  }
7496
+ const insecureUrlReason = getInsecureApiUrlReason(String(normalized));
7497
+ if (insecureUrlReason) {
7498
+ logger.error(insecureUrlReason);
7499
+ process.exit(1);
7500
+ }
7256
7501
  }
7257
7502
  if (key === "syncInterval") {
7258
7503
  normalized = Number.parseInt(value, 10);
@@ -7267,7 +7512,7 @@ async function handleConfig(args) {
7267
7512
  logger.info(formatHeader("\u914D\u7F6E\u5DF2\u66F4\u65B0"));
7268
7513
  logger.info(formatKeyValue(key, formatConfigValue(key, normalized)));
7269
7514
  } else {
7270
- logger.info(`Set ${key} = ${normalized}`);
7515
+ logger.info(`Set ${key} = ${formatConfigValue(key, normalized)}`);
7271
7516
  }
7272
7517
  break;
7273
7518
  }
@@ -7276,7 +7521,13 @@ async function handleConfig(args) {
7276
7521
  printConfigShow();
7277
7522
  } else {
7278
7523
  const config = loadConfig();
7279
- console.log(config ? JSON.stringify(config, null, 2) : "{}");
7524
+ console.log(
7525
+ config ? JSON.stringify(
7526
+ { ...config, apiKey: maskSecret(config.apiKey) },
7527
+ null,
7528
+ 2
7529
+ ) : "{}"
7530
+ );
7280
7531
  }
7281
7532
  break;
7282
7533
  }
@@ -7466,6 +7717,44 @@ import { URL as URL2 } from "url";
7466
7717
  var MAX_RETRIES = 3;
7467
7718
  var INITIAL_DELAY = 1e3;
7468
7719
  var TIMEOUT_MS = 6e4;
7720
+ var MAX_RESPONSE_BYTES = 1024 * 1024;
7721
+ var MAX_ERROR_TEXT_LENGTH = 500;
7722
+ var ESCAPE_SEQUENCE = (
7723
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: matching them is the point
7724
+ /\u001b(?:\][^\u0007\u001b]*(?:\u0007|\u001b\\)?|\[[0-?]*[ -/]*[@-~]|[@-Z\\-_])/g
7725
+ );
7726
+ var CONTROL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f]+/g;
7727
+ function sanitizeServerText(text2, maxLength = MAX_ERROR_TEXT_LENGTH) {
7728
+ const printable = text2.replace(ESCAPE_SEQUENCE, "").replace(CONTROL_CHARACTERS, " ").trim();
7729
+ return printable.length > maxLength ? `${printable.slice(0, maxLength)}\u2026` : printable;
7730
+ }
7731
+ function collectBody(res, onDone, onTooLarge) {
7732
+ const chunks = [];
7733
+ let size = 0;
7734
+ res.on("data", (chunk) => {
7735
+ size += chunk.length;
7736
+ if (size > MAX_RESPONSE_BYTES) {
7737
+ res.destroy();
7738
+ onTooLarge();
7739
+ return;
7740
+ }
7741
+ chunks.push(chunk);
7742
+ });
7743
+ res.on("end", () => {
7744
+ if (size <= MAX_RESPONSE_BYTES) {
7745
+ onDone(Buffer.concat(chunks).toString("utf-8"));
7746
+ }
7747
+ });
7748
+ }
7749
+ var InsecureApiUrlError = class extends Error {
7750
+ };
7751
+ function httpError(statusCode, data) {
7752
+ const err = new Error(
7753
+ `HTTP ${statusCode}: ${sanitizeServerText(data)}`
7754
+ );
7755
+ err.statusCode = statusCode;
7756
+ return err;
7757
+ }
7469
7758
  function buildIngestPayload(device, buckets, sessions, options) {
7470
7759
  return {
7471
7760
  schemaVersion: 2,
@@ -7487,6 +7776,14 @@ var ApiClient = class {
7487
7776
  }
7488
7777
  apiUrl;
7489
7778
  apiKey;
7779
+ /** Endpoint URL, refusing one the key must not be sent to. */
7780
+ endpoint(path) {
7781
+ const reason = getInsecureApiUrlReason(this.apiUrl);
7782
+ if (reason) {
7783
+ throw new InsecureApiUrlError(reason);
7784
+ }
7785
+ return new URL2(path, this.apiUrl);
7786
+ }
7490
7787
  /**
7491
7788
  * Ingest buckets and sessions to server
7492
7789
  */
@@ -7504,7 +7801,7 @@ var ApiClient = class {
7504
7801
  } catch (err) {
7505
7802
  lastError = err;
7506
7803
  const httpErr = err;
7507
- if (httpErr.message === "UNAUTHORIZED" || httpErr.statusCode && httpErr.statusCode >= 400 && httpErr.statusCode < 500) {
7804
+ if (err instanceof InsecureApiUrlError || httpErr.message === "UNAUTHORIZED" || httpErr.statusCode && httpErr.statusCode >= 400 && httpErr.statusCode < 500) {
7508
7805
  throw err;
7509
7806
  }
7510
7807
  if (attempt < MAX_RETRIES - 1) {
@@ -7517,7 +7814,7 @@ var ApiClient = class {
7517
7814
  }
7518
7815
  sendIngest(device, buckets, sessions, onProgress, options) {
7519
7816
  return new Promise((resolve5, reject) => {
7520
- const url = new URL2("/api/usage/ingest", this.apiUrl);
7817
+ const url = this.endpoint("/api/usage/ingest");
7521
7818
  const body = Buffer.from(
7522
7819
  JSON.stringify(buildIngestPayload(device, buckets, sessions, options))
7523
7820
  );
@@ -7535,33 +7832,33 @@ var ApiClient = class {
7535
7832
  }
7536
7833
  },
7537
7834
  (res) => {
7538
- let data = "";
7539
- res.on("data", (chunk) => {
7540
- data += chunk;
7541
- });
7542
- res.on("end", () => {
7543
- if (res.statusCode === 401) {
7544
- reject(new Error("UNAUTHORIZED"));
7545
- return;
7546
- }
7547
- if (!res.statusCode || res.statusCode < 200 || res.statusCode >= 300) {
7548
- const err = new Error(
7549
- `HTTP ${res.statusCode}: ${data}`
7550
- );
7551
- err.statusCode = res.statusCode;
7552
- reject(err);
7553
- return;
7554
- }
7555
- try {
7556
- const response = JSON.parse(data);
7557
- resolve5({
7558
- ingested: response.bucketCount ?? response.ingested,
7559
- sessions: response.sessionCount ?? response.sessions
7560
- });
7561
- } catch {
7562
- reject(new Error(`Invalid JSON response: ${data}`));
7563
- }
7564
- });
7835
+ collectBody(
7836
+ res,
7837
+ (data) => {
7838
+ if (res.statusCode === 401) {
7839
+ reject(new Error("UNAUTHORIZED"));
7840
+ return;
7841
+ }
7842
+ if (!res.statusCode || res.statusCode < 200 || res.statusCode >= 300) {
7843
+ reject(httpError(res.statusCode, data));
7844
+ return;
7845
+ }
7846
+ try {
7847
+ const response = JSON.parse(data);
7848
+ resolve5({
7849
+ ingested: response.bucketCount ?? response.ingested,
7850
+ sessions: response.sessionCount ?? response.sessions
7851
+ });
7852
+ } catch {
7853
+ reject(
7854
+ new Error(
7855
+ `Invalid JSON response: ${sanitizeServerText(data)}`
7856
+ )
7857
+ );
7858
+ }
7859
+ },
7860
+ () => reject(new Error("Response too large"))
7861
+ );
7565
7862
  }
7566
7863
  );
7567
7864
  req.on("error", (err) => reject(err));
@@ -7593,7 +7890,7 @@ var ApiClient = class {
7593
7890
  */
7594
7891
  async fetchSettings() {
7595
7892
  return new Promise((resolve5, reject) => {
7596
- const url = new URL2("/api/usage/settings", this.apiUrl);
7893
+ const url = this.endpoint("/api/usage/settings");
7597
7894
  const mod = url.protocol === "https:" ? https : http;
7598
7895
  const req = mod.request(
7599
7896
  url,
@@ -7605,30 +7902,30 @@ var ApiClient = class {
7605
7902
  }
7606
7903
  },
7607
7904
  (res) => {
7608
- let data = "";
7609
- res.on("data", (chunk) => {
7610
- data += chunk;
7611
- });
7612
- res.on("end", () => {
7613
- if (res.statusCode === 401) {
7614
- reject(new Error("UNAUTHORIZED"));
7615
- return;
7616
- }
7617
- if (!res.statusCode || res.statusCode < 200 || res.statusCode >= 300) {
7618
- resolve5(null);
7619
- return;
7620
- }
7621
- try {
7622
- const settings = JSON.parse(data);
7623
- if (settings.schemaVersion !== 2 || !settings.projectMode || !settings.projectHashSalt || !settings.timezone) {
7905
+ collectBody(
7906
+ res,
7907
+ (data) => {
7908
+ if (res.statusCode === 401) {
7909
+ reject(new Error("UNAUTHORIZED"));
7910
+ return;
7911
+ }
7912
+ if (!res.statusCode || res.statusCode < 200 || res.statusCode >= 300) {
7624
7913
  resolve5(null);
7625
7914
  return;
7626
7915
  }
7627
- resolve5(settings);
7628
- } catch {
7629
- resolve5(null);
7630
- }
7631
- });
7916
+ try {
7917
+ const settings = JSON.parse(data);
7918
+ if (settings.schemaVersion !== 2 || !settings.projectMode || !settings.projectHashSalt || !settings.timezone) {
7919
+ resolve5(null);
7920
+ return;
7921
+ }
7922
+ resolve5(settings);
7923
+ } catch {
7924
+ resolve5(null);
7925
+ }
7926
+ },
7927
+ () => resolve5(null)
7928
+ );
7632
7929
  }
7633
7930
  );
7634
7931
  req.on("error", () => resolve5(null));
@@ -7641,7 +7938,7 @@ var ApiClient = class {
7641
7938
  }
7642
7939
  async deleteDeviceData(deviceId) {
7643
7940
  return new Promise((resolve5, reject) => {
7644
- const url = new URL2("/api/usage/ingest", this.apiUrl);
7941
+ const url = this.endpoint("/api/usage/ingest");
7645
7942
  url.searchParams.set("deviceId", deviceId);
7646
7943
  const mod = url.protocol === "https:" ? https : http;
7647
7944
  const req = mod.request(
@@ -7654,29 +7951,29 @@ var ApiClient = class {
7654
7951
  }
7655
7952
  },
7656
7953
  (res) => {
7657
- let data = "";
7658
- res.on("data", (chunk) => {
7659
- data += chunk;
7660
- });
7661
- res.on("end", () => {
7662
- if (res.statusCode === 401) {
7663
- reject(new Error("UNAUTHORIZED"));
7664
- return;
7665
- }
7666
- if (!res.statusCode || res.statusCode < 200 || res.statusCode >= 300) {
7667
- const err = new Error(
7668
- `HTTP ${res.statusCode}: ${data}`
7669
- );
7670
- err.statusCode = res.statusCode;
7671
- reject(err);
7672
- return;
7673
- }
7674
- try {
7675
- resolve5(JSON.parse(data));
7676
- } catch {
7677
- reject(new Error(`Invalid JSON response: ${data}`));
7678
- }
7679
- });
7954
+ collectBody(
7955
+ res,
7956
+ (data) => {
7957
+ if (res.statusCode === 401) {
7958
+ reject(new Error("UNAUTHORIZED"));
7959
+ return;
7960
+ }
7961
+ if (!res.statusCode || res.statusCode < 200 || res.statusCode >= 300) {
7962
+ reject(httpError(res.statusCode, data));
7963
+ return;
7964
+ }
7965
+ try {
7966
+ resolve5(JSON.parse(data));
7967
+ } catch {
7968
+ reject(
7969
+ new Error(
7970
+ `Invalid JSON response: ${sanitizeServerText(data)}`
7971
+ )
7972
+ );
7973
+ }
7974
+ },
7975
+ () => reject(new Error("Response too large"))
7976
+ );
7680
7977
  }
7681
7978
  );
7682
7979
  req.on("error", (err) => reject(err));
@@ -7692,15 +7989,14 @@ var ApiClient = class {
7692
7989
  // src/infrastructure/runtime/lock.ts
7693
7990
  import {
7694
7991
  closeSync,
7695
- existsSync as existsSync31,
7992
+ existsSync as existsSync32,
7696
7993
  openSync,
7697
7994
  readFileSync as readFileSync11,
7698
- rmSync as rmSync3,
7995
+ rmSync as rmSync4,
7699
7996
  writeFileSync as writeFileSync2
7700
7997
  } from "fs";
7701
7998
 
7702
7999
  // src/infrastructure/runtime/paths.ts
7703
- import { mkdirSync as mkdirSync2 } from "fs";
7704
8000
  import { join as join34 } from "path";
7705
8001
  var APP_NAME = "tokenarena";
7706
8002
  function getRuntimeDirPath() {
@@ -7719,8 +8015,8 @@ function getUploadManifestPath() {
7719
8015
  return join34(getStateDir(), "upload-manifest.json");
7720
8016
  }
7721
8017
  function ensureAppDirs() {
7722
- mkdirSync2(getRuntimeDirPath(), { recursive: true });
7723
- mkdirSync2(getStateDir(), { recursive: true });
8018
+ ensurePrivateDir(getRuntimeDirPath());
8019
+ ensurePrivateDir(getStateDir());
7724
8020
  }
7725
8021
 
7726
8022
  // src/infrastructure/runtime/lock.ts
@@ -7734,7 +8030,7 @@ function isProcessAlive(pid) {
7734
8030
  }
7735
8031
  }
7736
8032
  function readLockMetadata(lockPath) {
7737
- if (!existsSync31(lockPath)) {
8033
+ if (!existsSync32(lockPath)) {
7738
8034
  return null;
7739
8035
  }
7740
8036
  try {
@@ -7746,18 +8042,18 @@ function readLockMetadata(lockPath) {
7746
8042
  function removeStaleLock(lockPath) {
7747
8043
  const metadata = readLockMetadata(lockPath);
7748
8044
  if (!metadata) {
7749
- rmSync3(lockPath, { force: true });
8045
+ rmSync4(lockPath, { force: true });
7750
8046
  return;
7751
8047
  }
7752
8048
  if (!isProcessAlive(metadata.pid)) {
7753
- rmSync3(lockPath, { force: true });
8049
+ rmSync4(lockPath, { force: true });
7754
8050
  }
7755
8051
  }
7756
8052
  function tryAcquireSyncLock(source) {
7757
8053
  ensureAppDirs();
7758
8054
  const lockPath = getSyncLockPath();
7759
8055
  try {
7760
- const fd = openSync(lockPath, "wx");
8056
+ const fd = openSync(lockPath, "wx", 384);
7761
8057
  const metadata = {
7762
8058
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
7763
8059
  pid: process.pid,
@@ -7767,7 +8063,7 @@ function tryAcquireSyncLock(source) {
7767
8063
  closeSync(fd);
7768
8064
  return {
7769
8065
  release() {
7770
- rmSync3(lockPath, { force: true });
8066
+ rmSync4(lockPath, { force: true });
7771
8067
  }
7772
8068
  };
7773
8069
  } catch (error) {
@@ -7778,7 +8074,7 @@ function tryAcquireSyncLock(source) {
7778
8074
  }
7779
8075
  removeStaleLock(lockPath);
7780
8076
  try {
7781
- const fd = openSync(lockPath, "wx");
8077
+ const fd = openSync(lockPath, "wx", 384);
7782
8078
  const metadata = {
7783
8079
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
7784
8080
  pid: process.pid,
@@ -7788,7 +8084,7 @@ function tryAcquireSyncLock(source) {
7788
8084
  closeSync(fd);
7789
8085
  return {
7790
8086
  release() {
7791
- rmSync3(lockPath, { force: true });
8087
+ rmSync4(lockPath, { force: true });
7792
8088
  }
7793
8089
  };
7794
8090
  } catch (error) {
@@ -7808,13 +8104,13 @@ function describeExistingSyncLock() {
7808
8104
  }
7809
8105
 
7810
8106
  // src/infrastructure/runtime/state.ts
7811
- import { existsSync as existsSync32, readFileSync as readFileSync12, writeFileSync as writeFileSync3 } from "fs";
8107
+ import { existsSync as existsSync33, readFileSync as readFileSync12 } from "fs";
7812
8108
  function getDefaultState() {
7813
8109
  return { status: "idle" };
7814
8110
  }
7815
8111
  function loadSyncState() {
7816
8112
  const path = getSyncStatePath();
7817
- if (!existsSync32(path)) {
8113
+ if (!existsSync33(path)) {
7818
8114
  return getDefaultState();
7819
8115
  }
7820
8116
  try {
@@ -7828,12 +8124,8 @@ function loadSyncState() {
7828
8124
  }
7829
8125
  function saveSyncState(next) {
7830
8126
  ensureAppDirs();
7831
- writeFileSync3(
7832
- getSyncStatePath(),
7833
- `${JSON.stringify(next, null, 2)}
7834
- `,
7835
- "utf-8"
7836
- );
8127
+ writePrivateFile(getSyncStatePath(), `${JSON.stringify(next, null, 2)}
8128
+ `);
7837
8129
  }
7838
8130
  function markSyncStarted(source) {
7839
8131
  const current = loadSyncState();
@@ -7875,7 +8167,7 @@ function markSyncFailed(source, error, status) {
7875
8167
  }
7876
8168
 
7877
8169
  // src/infrastructure/runtime/upload-manifest.ts
7878
- import { existsSync as existsSync33, readFileSync as readFileSync13, writeFileSync as writeFileSync4 } from "fs";
8170
+ import { existsSync as existsSync34, readFileSync as readFileSync13 } from "fs";
7879
8171
  function isRecordOfStrings(value) {
7880
8172
  if (!value || typeof value !== "object" || Array.isArray(value)) {
7881
8173
  return false;
@@ -7891,7 +8183,7 @@ function isUploadManifest(value) {
7891
8183
  }
7892
8184
  function loadUploadManifest() {
7893
8185
  const path = getUploadManifestPath();
7894
- if (!existsSync33(path)) {
8186
+ if (!existsSync34(path)) {
7895
8187
  return null;
7896
8188
  }
7897
8189
  try {
@@ -7912,22 +8204,21 @@ function loadUploadManifest() {
7912
8204
  }
7913
8205
  function saveUploadManifest(manifest) {
7914
8206
  ensureAppDirs();
7915
- writeFileSync4(
8207
+ writePrivateFile(
7916
8208
  getUploadManifestPath(),
7917
8209
  `${JSON.stringify(manifest, null, 2)}
7918
- `,
7919
- "utf-8"
8210
+ `
7920
8211
  );
7921
8212
  }
7922
8213
 
7923
8214
  // src/services/parse-cache.ts
7924
8215
  import { createHash as createHash7 } from "crypto";
7925
- import { mkdirSync as mkdirSync3, readFileSync as readFileSync14, statSync as statSync8, writeFileSync as writeFileSync5 } from "fs";
8216
+ import { readFileSync as readFileSync14, statSync as statSync9 } from "fs";
7926
8217
  import { hostname as hostname6 } from "os";
7927
8218
  import { join as join36 } from "path";
7928
8219
 
7929
8220
  // src/infrastructure/runtime/cli-version.ts
7930
- import { dirname as dirname9, join as join35 } from "path";
8221
+ import { dirname as dirname10, join as join35 } from "path";
7931
8222
  import { fileURLToPath } from "url";
7932
8223
  var FALLBACK_VERSION = "0.0.0";
7933
8224
  var versionCache = /* @__PURE__ */ new Map();
@@ -7943,7 +8234,7 @@ function readPackageVersion(startDir) {
7943
8234
  return void 0;
7944
8235
  }
7945
8236
  }
7946
- const parent = dirname9(dir);
8237
+ const parent = dirname10(dir);
7947
8238
  if (parent === dir) {
7948
8239
  return void 0;
7949
8240
  }
@@ -7951,7 +8242,7 @@ function readPackageVersion(startDir) {
7951
8242
  }
7952
8243
  }
7953
8244
  function getCliVersion(metaUrl = import.meta.url) {
7954
- const startDir = dirname9(fileURLToPath(metaUrl));
8245
+ const startDir = dirname10(fileURLToPath(metaUrl));
7955
8246
  const cached = versionCache.get(startDir);
7956
8247
  if (cached !== void 0) {
7957
8248
  return cached;
@@ -7978,7 +8269,7 @@ function computeScanFingerprint(files, now = Date.now()) {
7978
8269
  for (const file of [...files].sort()) {
7979
8270
  let stats;
7980
8271
  try {
7981
- stats = statSync8(file);
8272
+ stats = statSync9(file);
7982
8273
  } catch {
7983
8274
  return null;
7984
8275
  }
@@ -8009,7 +8300,7 @@ function loadCachedParseResult(toolId, fingerprint2) {
8009
8300
  }
8010
8301
  }
8011
8302
  function saveCachedParseResult(toolId, fingerprint2, result) {
8012
- if (!fingerprint2 || result.incomplete) {
8303
+ if (!fingerprint2 || result.incomplete || result.partial) {
8013
8304
  return;
8014
8305
  }
8015
8306
  const envelope = {
@@ -8018,8 +8309,8 @@ function saveCachedParseResult(toolId, fingerprint2, result) {
8018
8309
  result: { buckets: result.buckets, sessions: result.sessions }
8019
8310
  };
8020
8311
  try {
8021
- mkdirSync3(getParseCacheDir(), { recursive: true });
8022
- writeFileSync5(getParseCachePath(toolId), JSON.stringify(envelope), "utf-8");
8312
+ ensurePrivateDir(getParseCacheDir());
8313
+ writePrivateFile(getParseCachePath(toolId), JSON.stringify(envelope));
8023
8314
  } catch {
8024
8315
  }
8025
8316
  }
@@ -8076,7 +8367,7 @@ async function runAllParsers() {
8076
8367
  logger.warn(`${parser.tool.id} parser failed: ${outcome.message}`);
8077
8368
  continue;
8078
8369
  }
8079
- const { buckets, sessions, incomplete } = outcome.result;
8370
+ const { buckets, sessions, incomplete, partial } = outcome.result;
8080
8371
  if (incomplete) {
8081
8372
  failedSources.add(parser.tool.id);
8082
8373
  logger.warn(
@@ -8084,6 +8375,12 @@ async function runAllParsers() {
8084
8375
  );
8085
8376
  continue;
8086
8377
  }
8378
+ if (partial) {
8379
+ failedSources.add(parser.tool.id);
8380
+ logger.warn(
8381
+ `${parser.tool.id} parser withheld usage it could not verify; uploading the rest and preserving its remote history.`
8382
+ );
8383
+ }
8087
8384
  if (buckets.length > 0) allBuckets.push(...buckets);
8088
8385
  if (sessions.length > 0) allSessions.push(...sessions);
8089
8386
  if (buckets.length > 0 || sessions.length > 0) {
@@ -8383,6 +8680,10 @@ async function runSync(config, opts = {}) {
8383
8680
  }
8384
8681
  }
8385
8682
  const apiUrl = config.apiUrl || "https://token.guji.uno";
8683
+ const insecureUrlReason = getInsecureApiUrlReason(apiUrl);
8684
+ if (insecureUrlReason) {
8685
+ throw new SyncFailure(insecureUrlReason, "error");
8686
+ }
8386
8687
  const apiClient = new ApiClient(apiUrl, config.apiKey);
8387
8688
  let settings;
8388
8689
  try {
@@ -8641,39 +8942,20 @@ View your dashboard at: ${apiUrl}/usage`);
8641
8942
 
8642
8943
  // src/commands/init.ts
8643
8944
  import { execFileSync as execFileSync8, spawn } from "child_process";
8644
- import { existsSync as existsSync36 } from "fs";
8945
+ import { existsSync as existsSync37 } from "fs";
8645
8946
  import { appendFile, mkdir, readFile } from "fs/promises";
8646
8947
  import { homedir as homedir34, platform as platform5 } from "os";
8647
- import { dirname as dirname10, join as join37, posix as posix3, win32 } from "path";
8948
+ import { dirname as dirname11, join as join37, posix as posix3, win32 as win322 } from "path";
8648
8949
 
8649
8950
  // src/infrastructure/service/index.ts
8650
8951
  import { platform as platform4 } from "os";
8651
8952
 
8652
8953
  // src/infrastructure/service/linux-systemd.ts
8653
8954
  import { execFileSync as execFileSync6 } from "child_process";
8654
- import { existsSync as existsSync34, mkdirSync as mkdirSync4, rmSync as rmSync4, writeFileSync as writeFileSync6 } from "fs";
8955
+ import { existsSync as existsSync35, mkdirSync as mkdirSync2, rmSync as rmSync5, writeFileSync as writeFileSync3 } from "fs";
8655
8956
  import { homedir as homedir32, platform as platform2 } from "os";
8656
8957
  import { posix } from "path";
8657
8958
 
8658
- // src/utils/command.ts
8659
- import { execFileSync as execFileSync5 } from "child_process";
8660
- import { platform } from "os";
8661
- function getCommandCheck(command, currentPlatform = platform()) {
8662
- if (currentPlatform === "win32") {
8663
- return { command: "where", args: [command] };
8664
- }
8665
- return { command: "/bin/sh", args: ["-c", 'command -v "$1"', "sh", command] };
8666
- }
8667
- function isCommandAvailable(command) {
8668
- const check = getCommandCheck(command);
8669
- try {
8670
- execFileSync5(check.command, check.args, { stdio: "ignore", timeout: 5e3 });
8671
- return true;
8672
- } catch {
8673
- return false;
8674
- }
8675
- }
8676
-
8677
8959
  // src/infrastructure/service/utils.ts
8678
8960
  var SERVICE_PATH_FALLBACKS = [
8679
8961
  "/opt/homebrew/bin",
@@ -8793,7 +9075,7 @@ function ensureSystemdAvailable() {
8793
9075
  }
8794
9076
  function createLinuxSystemdServiceBackend() {
8795
9077
  function isInstalled() {
8796
- return existsSync34(getLinuxSystemdServiceFile());
9078
+ return existsSync35(getLinuxSystemdServiceFile());
8797
9079
  }
8798
9080
  async function setup(skipPrompt = false) {
8799
9081
  if (!ensureSystemdAvailable()) {
@@ -8819,8 +9101,8 @@ function createLinuxSystemdServiceBackend() {
8819
9101
  execPath: command.execPath,
8820
9102
  args: command.args
8821
9103
  });
8822
- mkdirSync4(serviceDir, { recursive: true });
8823
- writeFileSync6(serviceFile, content, "utf-8");
9104
+ mkdirSync2(serviceDir, { recursive: true });
9105
+ writeFileSync3(serviceFile, content, "utf-8");
8824
9106
  execSystemctl(["daemon-reload"]);
8825
9107
  execSystemctl(["enable", SYSTEMD_SERVICE_NAME]);
8826
9108
  execSystemctl(["start", SYSTEMD_SERVICE_NAME]);
@@ -8918,7 +9200,7 @@ function createLinuxSystemdServiceBackend() {
8918
9200
  }
8919
9201
  async function uninstall(skipPrompt = false) {
8920
9202
  const serviceFile = getLinuxSystemdServiceFile();
8921
- if (!existsSync34(serviceFile)) {
9203
+ if (!existsSync35(serviceFile)) {
8922
9204
  logger.info(formatBullet("\u670D\u52A1\u6587\u4EF6\u4E0D\u5B58\u5728\u3002", "warning"));
8923
9205
  return;
8924
9206
  }
@@ -8951,7 +9233,7 @@ function createLinuxSystemdServiceBackend() {
8951
9233
  );
8952
9234
  }
8953
9235
  try {
8954
- rmSync4(serviceFile);
9236
+ rmSync5(serviceFile);
8955
9237
  if (support.ok) {
8956
9238
  execSystemctl(["daemon-reload"]);
8957
9239
  }
@@ -8979,7 +9261,7 @@ function createLinuxSystemdServiceBackend() {
8979
9261
 
8980
9262
  // src/infrastructure/service/macos-launchd.ts
8981
9263
  import { execFileSync as execFileSync7 } from "child_process";
8982
- import { existsSync as existsSync35, mkdirSync as mkdirSync5, rmSync as rmSync5, writeFileSync as writeFileSync7 } from "fs";
9264
+ import { existsSync as existsSync36, mkdirSync as mkdirSync3, rmSync as rmSync6, writeFileSync as writeFileSync4 } from "fs";
8983
9265
  import { homedir as homedir33, platform as platform3 } from "os";
8984
9266
  import { posix as posix2 } from "path";
8985
9267
  var MACOS_LAUNCHD_LABEL = "com.guji.tokenarena";
@@ -9121,8 +9403,8 @@ function writeLaunchAgentPlist() {
9121
9403
  standardErrorPath: stderrPath
9122
9404
  });
9123
9405
  ensureAppDirs();
9124
- mkdirSync5(getMacosLaunchAgentDir(), { recursive: true });
9125
- writeFileSync7(plistFile, plist, "utf-8");
9406
+ mkdirSync3(getMacosLaunchAgentDir(), { recursive: true });
9407
+ writeFileSync4(plistFile, plist, "utf-8");
9126
9408
  return plistFile;
9127
9409
  }
9128
9410
  function bootstrapLaunchAgent() {
@@ -9141,7 +9423,7 @@ function bootstrapLaunchAgent() {
9141
9423
  }
9142
9424
  function createMacosLaunchdServiceBackend() {
9143
9425
  function isInstalled() {
9144
- return existsSync35(getMacosLaunchAgentFile());
9426
+ return existsSync36(getMacosLaunchAgentFile());
9145
9427
  }
9146
9428
  async function setup(skipPrompt = false) {
9147
9429
  if (!ensureLaunchctlAvailable()) {
@@ -9282,7 +9564,7 @@ function createMacosLaunchdServiceBackend() {
9282
9564
  }
9283
9565
  async function uninstall(skipPrompt = false) {
9284
9566
  const plistFile = getMacosLaunchAgentFile();
9285
- if (!existsSync35(plistFile)) {
9567
+ if (!existsSync36(plistFile)) {
9286
9568
  logger.info(formatBullet("\u670D\u52A1\u6587\u4EF6\u4E0D\u5B58\u5728\u3002", "warning"));
9287
9569
  return;
9288
9570
  }
@@ -9312,9 +9594,9 @@ function createMacosLaunchdServiceBackend() {
9312
9594
  }
9313
9595
  try {
9314
9596
  const { stdoutPath, stderrPath } = getMacosLaunchdLogPaths();
9315
- rmSync5(plistFile);
9316
- rmSync5(stdoutPath, { force: true });
9317
- rmSync5(stderrPath, { force: true });
9597
+ rmSync6(plistFile);
9598
+ rmSync6(stdoutPath, { force: true });
9599
+ rmSync6(stderrPath, { force: true });
9318
9600
  logger.info(formatSection("\u670D\u52A1\u5DF2\u5378\u8F7D"));
9319
9601
  logger.info(formatBullet("\u670D\u52A1\u5DF2\u505C\u7528\u5E76\u5220\u9664", "success"));
9320
9602
  } catch (err) {
@@ -9351,7 +9633,7 @@ function getServiceBackend(currentPlatform = platform4()) {
9351
9633
 
9352
9634
  // src/commands/init.ts
9353
9635
  function joinForPlatform(currentPlatform, ...parts) {
9354
- return currentPlatform === "win32" ? win32.join(...parts) : posix3.join(...parts);
9636
+ return currentPlatform === "win32" ? win322.join(...parts) : posix3.join(...parts);
9355
9637
  }
9356
9638
  function basenameLikeShell(input2) {
9357
9639
  return input2.split(/[\\/]+/).pop()?.replace(/\.exe$/i, "") ?? input2;
@@ -9365,7 +9647,7 @@ function getBrowserLaunchCommand(url, currentPlatform = platform5()) {
9365
9647
  };
9366
9648
  case "win32":
9367
9649
  return {
9368
- command: "cmd.exe",
9650
+ command: getWindowsSystemCommand("cmd.exe"),
9369
9651
  args: ["/d", "/s", "/c", "start", "", url]
9370
9652
  };
9371
9653
  default:
@@ -9392,9 +9674,9 @@ function openBrowser(url) {
9392
9674
  function resolvePowerShellProfilePath() {
9393
9675
  const systemRoot = process.env.SYSTEMROOT || "C:\\Windows";
9394
9676
  const candidates = [
9395
- "pwsh.exe",
9677
+ resolveCommandPath("pwsh.exe"),
9396
9678
  join37(systemRoot, "System32", "WindowsPowerShell", "v1.0", "powershell.exe")
9397
- ];
9679
+ ].filter((command) => command !== null);
9398
9680
  for (const command of candidates) {
9399
9681
  try {
9400
9682
  const output = execFileSync8(
@@ -9423,7 +9705,7 @@ function resolveShellAliasSetup(options = {}) {
9423
9705
  const currentPlatform = options.currentPlatform ?? platform5();
9424
9706
  const env = options.env ?? process.env;
9425
9707
  const homeDir = options.homeDir ?? homedir34();
9426
- const pathExists = options.exists ?? existsSync36;
9708
+ const pathExists = options.exists ?? existsSync37;
9427
9709
  const shellFromEnv = env.SHELL ? basenameLikeShell(env.SHELL).toLowerCase() : "";
9428
9710
  const shellName = shellFromEnv || (currentPlatform === "win32" ? "powershell" : "");
9429
9711
  const aliasName = "ta";
@@ -9512,6 +9794,11 @@ async function runInit(opts = {}) {
9512
9794
  }
9513
9795
  }
9514
9796
  const apiUrl = opts.apiUrl || getDefaultApiUrl();
9797
+ const insecureUrlReason = getInsecureApiUrlReason(apiUrl);
9798
+ if (insecureUrlReason) {
9799
+ logger.error(insecureUrlReason);
9800
+ process.exit(1);
9801
+ }
9515
9802
  const cliKeysUrl = `${apiUrl}/zh/settings/cli-keys`;
9516
9803
  logger.info(formatSection("\u7B2C 1 \u6B65\uFF1A\u51C6\u5907 API Key"));
9517
9804
  logger.info(formatBullet("\u6D4F\u89C8\u5668\u5C06\u5C1D\u8BD5\u81EA\u52A8\u6253\u5F00 CLI Key \u9875\u9762\u3002"));
@@ -9618,9 +9905,9 @@ async function setupShellAlias() {
9618
9905
  return;
9619
9906
  }
9620
9907
  try {
9621
- await mkdir(dirname10(setup.configFile), { recursive: true });
9908
+ await mkdir(dirname11(setup.configFile), { recursive: true });
9622
9909
  let existingContent = "";
9623
- if (existsSync36(setup.configFile)) {
9910
+ if (existsSync37(setup.configFile)) {
9624
9911
  existingContent = await readFile(setup.configFile, "utf-8");
9625
9912
  }
9626
9913
  const normalizedContent = existingContent.toLowerCase();
@@ -10281,7 +10568,7 @@ async function runSyncCommand(opts = {}) {
10281
10568
  }
10282
10569
 
10283
10570
  // src/commands/uninstall.ts
10284
- import { existsSync as existsSync37, readFileSync as readFileSync15, rmSync as rmSync6, writeFileSync as writeFileSync8 } from "fs";
10571
+ import { existsSync as existsSync38, readFileSync as readFileSync15, rmSync as rmSync7, writeFileSync as writeFileSync5 } from "fs";
10285
10572
  import { homedir as homedir35, platform as platform6 } from "os";
10286
10573
  function removeShellAlias() {
10287
10574
  const shell = process.env.SHELL;
@@ -10294,7 +10581,7 @@ function removeShellAlias() {
10294
10581
  configFile = `${homedir35()}/.zshrc`;
10295
10582
  break;
10296
10583
  case "bash":
10297
- if (platform6() === "darwin" && existsSync37(`${homedir35()}/.bash_profile`)) {
10584
+ if (platform6() === "darwin" && existsSync38(`${homedir35()}/.bash_profile`)) {
10298
10585
  configFile = `${homedir35()}/.bash_profile`;
10299
10586
  } else {
10300
10587
  configFile = `${homedir35()}/.bashrc`;
@@ -10306,7 +10593,7 @@ function removeShellAlias() {
10306
10593
  default:
10307
10594
  return;
10308
10595
  }
10309
- if (!existsSync37(configFile)) return;
10596
+ if (!existsSync38(configFile)) return;
10310
10597
  try {
10311
10598
  let content = readFileSync15(configFile, "utf-8");
10312
10599
  const aliasPatterns = [
@@ -10330,7 +10617,7 @@ function removeShellAlias() {
10330
10617
  content = next;
10331
10618
  }
10332
10619
  }
10333
- writeFileSync8(configFile, content, "utf-8");
10620
+ writeFileSync5(configFile, content, "utf-8");
10334
10621
  logger.info(`Removed shell alias from ${configFile}`);
10335
10622
  } catch (err) {
10336
10623
  logger.warn(
@@ -10345,7 +10632,7 @@ async function runUninstall() {
10345
10632
  const runtimeDir = getRuntimeDirPath();
10346
10633
  const serviceBackend = getServiceBackend();
10347
10634
  const hasInstalledService = serviceBackend?.isInstalled() ?? false;
10348
- const hasLocalArtifacts = existsSync37(configPath) || existsSync37(configDir) || existsSync37(stateDir) || existsSync37(runtimeDir) || hasInstalledService;
10635
+ const hasLocalArtifacts = existsSync38(configPath) || existsSync38(configDir) || existsSync38(stateDir) || existsSync38(runtimeDir) || hasInstalledService;
10349
10636
  if (!hasLocalArtifacts) {
10350
10637
  logger.info(formatHeader("\u5378\u8F7D TokenArena"));
10351
10638
  logger.info(formatBullet("\u672A\u53D1\u73B0\u672C\u5730\u914D\u7F6E\uFF0C\u65E0\u9700\u5378\u8F7D\u3002"));
@@ -10389,23 +10676,23 @@ async function runUninstall() {
10389
10676
  }
10390
10677
  }
10391
10678
  logger.info(formatSection("\u6267\u884C\u7ED3\u679C"));
10392
- if (existsSync37(configPath)) {
10679
+ if (existsSync38(configPath)) {
10393
10680
  deleteConfig();
10394
10681
  logger.info(formatBullet("\u5DF2\u5220\u9664\u914D\u7F6E\u6587\u4EF6\u3002", "success"));
10395
10682
  }
10396
- if (existsSync37(configDir)) {
10683
+ if (existsSync38(configDir)) {
10397
10684
  try {
10398
- rmSync6(configDir, { recursive: false, force: true });
10685
+ rmSync7(configDir, { recursive: false, force: true });
10399
10686
  logger.info(formatBullet("\u5DF2\u5220\u9664\u914D\u7F6E\u76EE\u5F55\u3002", "success"));
10400
10687
  } catch {
10401
10688
  }
10402
10689
  }
10403
- if (existsSync37(stateDir)) {
10404
- rmSync6(stateDir, { recursive: true, force: true });
10690
+ if (existsSync38(stateDir)) {
10691
+ rmSync7(stateDir, { recursive: true, force: true });
10405
10692
  logger.info(formatBullet("\u5DF2\u5220\u9664\u72B6\u6001\u6570\u636E\u3002", "success"));
10406
10693
  }
10407
- if (existsSync37(runtimeDir)) {
10408
- rmSync6(runtimeDir, { recursive: true, force: true });
10694
+ if (existsSync38(runtimeDir)) {
10695
+ rmSync7(runtimeDir, { recursive: true, force: true });
10409
10696
  logger.info(formatBullet("\u5DF2\u5220\u9664\u8FD0\u884C\u65F6\u6570\u636E\u3002", "success"));
10410
10697
  }
10411
10698
  removeShellAlias();
@@ -10638,7 +10925,7 @@ function createCli() {
10638
10925
  }
10639
10926
 
10640
10927
  // src/infrastructure/runtime/main-module.ts
10641
- import { existsSync as existsSync38, realpathSync as realpathSync2 } from "fs";
10928
+ import { existsSync as existsSync39, realpathSync as realpathSync2 } from "fs";
10642
10929
  import { resolve as resolve4 } from "path";
10643
10930
  import { fileURLToPath as fileURLToPath2 } from "url";
10644
10931
  function isMainModule(metaUrl, argvEntry = process.argv[1]) {
@@ -10649,7 +10936,7 @@ function isMainModule(metaUrl, argvEntry = process.argv[1]) {
10649
10936
  try {
10650
10937
  return realpathSync2(argvEntry) === realpathSync2(currentModulePath);
10651
10938
  } catch {
10652
- if (!existsSync38(argvEntry)) {
10939
+ if (!existsSync39(argvEntry)) {
10653
10940
  return false;
10654
10941
  }
10655
10942
  return resolve4(argvEntry) === resolve4(currentModulePath);
@@ -10674,6 +10961,7 @@ function reportFatalError(error) {
10674
10961
  process.exitCode = 1;
10675
10962
  }
10676
10963
  if (isMainModule(import.meta.url)) {
10964
+ process.env.NoDefaultCurrentDirectoryInExePath ??= "1";
10677
10965
  run().catch(reportFatalError);
10678
10966
  }
10679
10967
  export {