tokenusage-cli 0.4.5 → 0.4.7
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/CHANGELOG.md +113 -115
- package/README.md +88 -21
- package/package.json +1 -1
- package/src/cli.js +2 -0
- package/src/commands/doctor.js +3 -0
- package/src/commands/init.js +20 -2
- package/src/commands/reconcile.js +5 -0
- package/src/commands/status.js +143 -1
- package/src/commands/sync.js +101 -28
- package/src/commands/upload.js +4 -0
- package/src/lib/account-usage-dedup.js +1 -1
- package/src/lib/cursor-config.js +113 -17
- package/src/lib/device-identity.js +84 -0
- package/src/lib/doctor.js +32 -2
- package/src/lib/pricing/index.js +1 -1
- package/src/lib/pricing-coverage.js +1 -1
- package/src/lib/progress.js +29 -0
- package/src/lib/qoder-limits.js +224 -54
- package/src/lib/rollout.js +29 -6
- package/src/lib/trae-cn-config.js +36 -14
package/src/lib/qoder-limits.js
CHANGED
|
@@ -43,6 +43,18 @@ const QODER_LIMITS_CACHE_FILE = "qoder-usage-limits-cache.json";
|
|
|
43
43
|
// at 24h — it feeds campaign buckets, not quota readings.
|
|
44
44
|
const QODER_LIMITS_CACHE_MAX_AGE_MS = 12 * 60 * 60 * 1000;
|
|
45
45
|
const QODER_LIMITS_CACHE_UNKNOWN_RESET_TTL_MS = 12 * 60 * 60 * 1000;
|
|
46
|
+
// Qoder Desktop 0.4+ writes its account usage summary to main.log, and a
|
|
47
|
+
// session can append for hours before the quota is read, so the line is not
|
|
48
|
+
// necessarily near EOF. Scan a bounded window backwards instead of reading the
|
|
49
|
+
// whole file.
|
|
50
|
+
const QODER_LOG_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
|
|
51
|
+
const QODER_LOG_SCAN_MAX_BYTES = 8 * 1024 * 1024;
|
|
52
|
+
const QODER_LOG_SCAN_CHUNK_BYTES = 512 * 1024;
|
|
53
|
+
const QODER_LOG_SCAN_OVERLAP_BYTES = 64 * 1024;
|
|
54
|
+
const QODER_LOG_MAX_FILES = 24;
|
|
55
|
+
// Total budget for one probe: sessions append for hours, so a directory can
|
|
56
|
+
// hold many files. Per-file reads are capped too (QODER_LOG_SCAN_MAX_BYTES).
|
|
57
|
+
const QODER_LOG_SCAN_TOTAL_BYTES = 24 * 1024 * 1024;
|
|
46
58
|
const QODER_SERVER_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
|
|
47
59
|
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDA8iMH5c02LilrsERw9t6Pv5Nc
|
|
48
60
|
4k6Pz1EaDicBMpdpxKduSZu5OANqUq8er4GM95omAGIOPOh+Nx0spthYA2BqGz+l
|
|
@@ -264,6 +276,13 @@ function normalizeQoderAddOnQuota(quota) {
|
|
|
264
276
|
};
|
|
265
277
|
}
|
|
266
278
|
|
|
279
|
+
function qoderPlanLabel(userType) {
|
|
280
|
+
if (typeof userType !== "string") return null;
|
|
281
|
+
const label = userType.trim();
|
|
282
|
+
// The desktop log stamps plan requests it could not resolve as "invalid".
|
|
283
|
+
return label && label.toLowerCase() !== "invalid" ? label : null;
|
|
284
|
+
}
|
|
285
|
+
|
|
267
286
|
function normalizeQoderRpcUsage(response) {
|
|
268
287
|
if (!response || typeof response !== "object") return null;
|
|
269
288
|
const quota = response.userQuota;
|
|
@@ -274,22 +293,21 @@ function normalizeQoderRpcUsage(response) {
|
|
|
274
293
|
const used = quota ? finiteNumber(quota.used, "userQuota.used") : 0;
|
|
275
294
|
const total = quota ? finiteNumber(quota.total, "userQuota.total") : 0;
|
|
276
295
|
const remaining = quota ? finiteNumber(quota.remaining, "userQuota.remaining") : 0;
|
|
277
|
-
|
|
296
|
+
// `totalUsagePercentage` aggregates the plan and add-on buckets and reaches
|
|
297
|
+
// this function on mixed scales (the OpenAPI returns fractions, the desktop
|
|
298
|
+
// IPC and log summaries return percents), so derive the primary window's
|
|
299
|
+
// percent from its own quota numbers instead of trusting the flag.
|
|
278
300
|
const usedPercent = total === 0
|
|
279
301
|
? 0
|
|
280
|
-
: addOnWindow
|
|
281
|
-
?
|
|
282
|
-
:
|
|
283
|
-
? 100
|
|
284
|
-
: Number.isFinite(reportedPercent)
|
|
285
|
-
? reportedPercent
|
|
286
|
-
: (used / total) * 100;
|
|
302
|
+
: response.isQuotaExceeded === true && !addOnWindow
|
|
303
|
+
? 100
|
|
304
|
+
: (used / total) * 100;
|
|
287
305
|
const normalizedExpiry = normalizeResetAt(response.expiresAt);
|
|
288
306
|
const expiryMs = normalizedExpiry ? Date.parse(normalizedExpiry) : NaN;
|
|
289
307
|
return {
|
|
290
308
|
configured: true,
|
|
291
309
|
error: null,
|
|
292
|
-
plan_label:
|
|
310
|
+
plan_label: qoderPlanLabel(response.userType),
|
|
293
311
|
quota_exceeded: response.isQuotaExceeded === true,
|
|
294
312
|
primary_window: quota ? {
|
|
295
313
|
used_percent: Math.max(0, Math.min(100, usedPercent)),
|
|
@@ -451,6 +469,10 @@ function writeQoderLimitsCache(limits, {
|
|
|
451
469
|
} = {}) {
|
|
452
470
|
if (!limits?.configured || limits.error || (!limits.primary_window && !limits.secondary_window && !limits.tertiary_window)) return;
|
|
453
471
|
const cachePath = qoderLimitsCachePath({ home, namespace });
|
|
472
|
+
// A log-derived snapshot carries the time it was observed. Recording the
|
|
473
|
+
// read time instead would make the next run present an old quota as fresh.
|
|
474
|
+
const observedAtMs = Date.parse(limits.cached_at || "");
|
|
475
|
+
const cachedAtMs = Number.isFinite(observedAtMs) && observedAtMs <= nowMs ? observedAtMs : nowMs;
|
|
454
476
|
const payload = {
|
|
455
477
|
qoder: {
|
|
456
478
|
plan_label: limits.plan_label || null,
|
|
@@ -458,7 +480,7 @@ function writeQoderLimitsCache(limits, {
|
|
|
458
480
|
primary_window: limits.primary_window || null,
|
|
459
481
|
secondary_window: limits.secondary_window || null,
|
|
460
482
|
...(limits.tertiary_window ? { tertiary_window: limits.tertiary_window } : {}),
|
|
461
|
-
cached_at: new Date(
|
|
483
|
+
cached_at: new Date(cachedAtMs).toISOString(),
|
|
462
484
|
},
|
|
463
485
|
};
|
|
464
486
|
try {
|
|
@@ -578,7 +600,40 @@ async function fetchQoderUsage(cookieHeader, site, fetchImpl) {
|
|
|
578
600
|
return normalizeQoderUsageResponse(await response.json());
|
|
579
601
|
}
|
|
580
602
|
|
|
581
|
-
function
|
|
603
|
+
function qoderLogRoots({
|
|
604
|
+
home = os.homedir(),
|
|
605
|
+
platform = process.platform,
|
|
606
|
+
env = process.env,
|
|
607
|
+
appDir = "Qoder",
|
|
608
|
+
envPrefix = "QODER",
|
|
609
|
+
} = {}) {
|
|
610
|
+
const explicitLogRoot = env[`${envPrefix}_LOG_ROOT`];
|
|
611
|
+
if (typeof explicitLogRoot === "string" && explicitLogRoot.trim()) {
|
|
612
|
+
return [path.resolve(explicitLogRoot.trim())];
|
|
613
|
+
}
|
|
614
|
+
const configuredHome = env[`${envPrefix}_HOME`];
|
|
615
|
+
if (typeof configuredHome === "string" && configuredHome.trim()) {
|
|
616
|
+
return [path.join(path.resolve(configuredHome.trim()), "logs")];
|
|
617
|
+
}
|
|
618
|
+
const base = platform === "darwin"
|
|
619
|
+
? path.join(home, "Library", "Application Support")
|
|
620
|
+
: platform === "win32"
|
|
621
|
+
? (env.APPDATA || path.join(home, "AppData", "Roaming"))
|
|
622
|
+
: path.join(home, ".config");
|
|
623
|
+
// Qoder Desktop 0.4.x moved its Electron profile from Qoder[CN]/ to the
|
|
624
|
+
// bundle-id directory and writes the account usage summary to main.log
|
|
625
|
+
// there. Scan both layouts so the legacy renderer.log fallback keeps working
|
|
626
|
+
// across the transition.
|
|
627
|
+
const bundleId = appDir === "QoderCN" || envPrefix === "QODER_CN"
|
|
628
|
+
? "com.qodercn.app.stable"
|
|
629
|
+
: "com.qoder.app.stable";
|
|
630
|
+
return [
|
|
631
|
+
path.join(base, appDir, "logs"),
|
|
632
|
+
path.join(base, bundleId, "logs"),
|
|
633
|
+
];
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
function listQoderLogs(logRoot) {
|
|
582
637
|
if (!fs.existsSync(logRoot)) return [];
|
|
583
638
|
const files = [];
|
|
584
639
|
const stack = [{ dir: logRoot, depth: 0 }];
|
|
@@ -594,19 +649,19 @@ function listRecentQoderRendererLogs(logRoot, maxFiles = 12) {
|
|
|
594
649
|
const full = path.join(current.dir, entry.name);
|
|
595
650
|
if (entry.isDirectory() && current.depth < 4) {
|
|
596
651
|
stack.push({ dir: full, depth: current.depth + 1 });
|
|
597
|
-
} else if (entry.isFile() && entry.name === "renderer.log") {
|
|
652
|
+
} else if (entry.isFile() && (entry.name === "main.log" || entry.name === "renderer.log")) {
|
|
598
653
|
let mtimeMs = 0;
|
|
654
|
+
let size = 0;
|
|
599
655
|
try {
|
|
600
|
-
|
|
656
|
+
const stat = fs.statSync(full);
|
|
657
|
+
mtimeMs = stat.mtimeMs;
|
|
658
|
+
size = stat.size;
|
|
601
659
|
} catch (_error) {}
|
|
602
|
-
files.push({ full, mtimeMs });
|
|
660
|
+
files.push({ full, name: entry.name, mtimeMs, size });
|
|
603
661
|
}
|
|
604
662
|
}
|
|
605
663
|
}
|
|
606
|
-
return files
|
|
607
|
-
.sort((a, b) => b.mtimeMs - a.mtimeMs)
|
|
608
|
-
.slice(0, maxFiles)
|
|
609
|
-
.map((entry) => entry.full);
|
|
664
|
+
return files;
|
|
610
665
|
}
|
|
611
666
|
|
|
612
667
|
function parseQoderQuotaLog(text) {
|
|
@@ -625,7 +680,7 @@ function parseQoderQuotaLog(text) {
|
|
|
625
680
|
return {
|
|
626
681
|
configured: true,
|
|
627
682
|
error: null,
|
|
628
|
-
plan_label: match[1],
|
|
683
|
+
plan_label: qoderPlanLabel(match[1]),
|
|
629
684
|
quota_exceeded: quotaExceeded,
|
|
630
685
|
primary_window: {
|
|
631
686
|
used_percent: total === 0
|
|
@@ -643,46 +698,160 @@ function parseQoderQuotaLog(text) {
|
|
|
643
698
|
};
|
|
644
699
|
}
|
|
645
700
|
|
|
701
|
+
/**
|
|
702
|
+
* Qoder Desktop 0.4.x logs its account usage summary as a `qoderUsage` object
|
|
703
|
+
* on an `[Auth] [AccountUsage]` line (`main.log`). The object has the same
|
|
704
|
+
* shape the local IPC `credit/usage` call returns, so it feeds the shared
|
|
705
|
+
* normalizer. A line can be truncated or carry trailing text, so the parser
|
|
706
|
+
* retries with the last closing brace before giving up.
|
|
707
|
+
*/
|
|
708
|
+
function parseQoderAccountUsageLog(text, { fallbackObservedAtMs = null } = {}) {
|
|
709
|
+
if (typeof text !== "string" || !text.includes('"qoderUsage"')) return null;
|
|
710
|
+
const lines = text.split(/\r?\n/);
|
|
711
|
+
for (let index = lines.length - 1; index >= 0; index -= 1) {
|
|
712
|
+
const line = lines[index];
|
|
713
|
+
if (!line.includes('"qoderUsage"')) continue;
|
|
714
|
+
const jsonStart = line.indexOf('{"') >= 0 ? line.indexOf('{"') : line.indexOf("{");
|
|
715
|
+
if (jsonStart < 0) continue;
|
|
716
|
+
let payload;
|
|
717
|
+
try {
|
|
718
|
+
payload = JSON.parse(line.slice(jsonStart));
|
|
719
|
+
} catch (_error) {
|
|
720
|
+
try {
|
|
721
|
+
payload = JSON.parse(line.slice(jsonStart, line.lastIndexOf("}") + 1));
|
|
722
|
+
} catch (_error2) {
|
|
723
|
+
continue;
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
const usage = payload?.qoderUsage;
|
|
727
|
+
if (!usage || typeof usage !== "object") continue;
|
|
728
|
+
let limits;
|
|
729
|
+
try {
|
|
730
|
+
limits = normalizeQoderRpcUsage({
|
|
731
|
+
userType: usage.userType,
|
|
732
|
+
expiresAt: usage.expiresAt,
|
|
733
|
+
isQuotaExceeded: usage.isQuotaExceeded,
|
|
734
|
+
totalUsagePercentage: usage.totalUsagePercentage,
|
|
735
|
+
userQuota: usage.userQuota,
|
|
736
|
+
addOnQuota: usage.addOnQuota,
|
|
737
|
+
});
|
|
738
|
+
} catch (_error) {
|
|
739
|
+
continue;
|
|
740
|
+
}
|
|
741
|
+
if (!limits) continue;
|
|
742
|
+
limits.source = "local-log";
|
|
743
|
+
const timestampMatch = /^\[([^\]]+)\]/.exec(line);
|
|
744
|
+
const lineObservedAtMs = timestampMatch ? Date.parse(timestampMatch[1]) : NaN;
|
|
745
|
+
return {
|
|
746
|
+
limits,
|
|
747
|
+
observedAtMs: Number.isFinite(lineObservedAtMs) ? lineObservedAtMs : fallbackObservedAtMs,
|
|
748
|
+
// The summary's own timestamp, or null when it fell back to file mtime.
|
|
749
|
+
// Ordering snapshots across files must use this, not observedAtMs: an
|
|
750
|
+
// unrelated append bumps mtime without making the summary any newer.
|
|
751
|
+
lineObservedAtMs: Number.isFinite(lineObservedAtMs) ? lineObservedAtMs : null,
|
|
752
|
+
};
|
|
753
|
+
}
|
|
754
|
+
return null;
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
/**
|
|
758
|
+
* Scan a log backwards in overlapping chunks. A hit returns the parser's value;
|
|
759
|
+
* a completed scan with no hit returns null; an unreadable file returns
|
|
760
|
+
* undefined so callers can tell "no summary" from "could not look".
|
|
761
|
+
*/
|
|
762
|
+
function scanQoderLogFromEnd(logPath, parse, {
|
|
763
|
+
maxBytes = QODER_LOG_SCAN_MAX_BYTES,
|
|
764
|
+
chunkBytes = QODER_LOG_SCAN_CHUNK_BYTES,
|
|
765
|
+
overlapBytes = QODER_LOG_SCAN_OVERLAP_BYTES,
|
|
766
|
+
} = {}) {
|
|
767
|
+
let fd;
|
|
768
|
+
try {
|
|
769
|
+
fd = fs.openSync(logPath, "r");
|
|
770
|
+
} catch (_error) {
|
|
771
|
+
return undefined;
|
|
772
|
+
}
|
|
773
|
+
try {
|
|
774
|
+
const size = fs.fstatSync(fd).size;
|
|
775
|
+
const floor = Math.max(0, size - maxBytes);
|
|
776
|
+
let end = size;
|
|
777
|
+
let carry = "";
|
|
778
|
+
while (end > floor) {
|
|
779
|
+
const start = Math.max(floor, end - chunkBytes);
|
|
780
|
+
const length = end - start;
|
|
781
|
+
const buffer = Buffer.alloc(length);
|
|
782
|
+
const read = fs.readSync(fd, buffer, 0, length, start);
|
|
783
|
+
const text = buffer.subarray(0, read).toString("utf8") + carry;
|
|
784
|
+
const parsed = parse(text);
|
|
785
|
+
if (parsed) return parsed;
|
|
786
|
+
// Keep this chunk's head so a line split across the boundary parses
|
|
787
|
+
// once the previous chunk is prepended.
|
|
788
|
+
carry = text.slice(0, overlapBytes);
|
|
789
|
+
end = start;
|
|
790
|
+
}
|
|
791
|
+
} catch (_error) {
|
|
792
|
+
return undefined;
|
|
793
|
+
} finally {
|
|
794
|
+
fs.closeSync(fd);
|
|
795
|
+
}
|
|
796
|
+
return null;
|
|
797
|
+
}
|
|
798
|
+
|
|
646
799
|
function readQoderLocalQuota({
|
|
647
800
|
home = os.homedir(),
|
|
648
801
|
platform = process.platform,
|
|
649
802
|
env = process.env,
|
|
650
803
|
appDir = "Qoder",
|
|
651
804
|
envPrefix = "QODER",
|
|
805
|
+
nowMs = Date.now(),
|
|
806
|
+
maxAgeMs = QODER_LOG_MAX_AGE_MS,
|
|
652
807
|
} = {}) {
|
|
653
|
-
const
|
|
654
|
-
const
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
808
|
+
const files = [];
|
|
809
|
+
for (const logRoot of qoderLogRoots({ home, platform, env, appDir, envPrefix })) {
|
|
810
|
+
files.push(...listQoderLogs(logRoot));
|
|
811
|
+
}
|
|
812
|
+
const fresh = files.filter((entry) => nowMs - entry.mtimeMs <= maxAgeMs);
|
|
813
|
+
// Rank each log kind on its own: a burst of renderer.log files must not
|
|
814
|
+
// push the newer main.log summaries out of the bounded scan.
|
|
815
|
+
const pick = (name) => fresh
|
|
816
|
+
.filter((entry) => entry.name === name)
|
|
817
|
+
.sort((a, b) => b.mtimeMs - a.mtimeMs)
|
|
818
|
+
.slice(0, QODER_LOG_MAX_FILES);
|
|
819
|
+
|
|
820
|
+
let best = null;
|
|
821
|
+
let scannedBytes = 0;
|
|
822
|
+
for (const { full, size, mtimeMs } of pick("main.log")) {
|
|
823
|
+
if (scannedBytes >= QODER_LOG_SCAN_TOTAL_BYTES) break;
|
|
824
|
+
scannedBytes += Math.min(size, QODER_LOG_SCAN_MAX_BYTES);
|
|
825
|
+
// A line's time never exceeds its file's mtime, so once the best hit is at
|
|
826
|
+
// least as new as this file, no older file can beat it.
|
|
827
|
+
if (best && mtimeMs <= (best.lineObservedAtMs ?? 0)) continue;
|
|
828
|
+
const parsed = scanQoderLogFromEnd(full, (text) => (
|
|
829
|
+
parseQoderAccountUsageLog(text, { fallbackObservedAtMs: mtimeMs })
|
|
830
|
+
));
|
|
831
|
+
if (!parsed) continue;
|
|
832
|
+
const observedAtMs = parsed.observedAtMs ?? mtimeMs;
|
|
833
|
+
if (nowMs - observedAtMs > maxAgeMs) continue;
|
|
834
|
+
// File mtime order need not match summary-line order, so keep the newest
|
|
835
|
+
// eligible line across the whole scan rather than the first hit.
|
|
836
|
+
if (!best || (parsed.lineObservedAtMs ?? 0) > (best.lineObservedAtMs ?? 0)) best = parsed;
|
|
837
|
+
}
|
|
838
|
+
if (!best) {
|
|
839
|
+
// Legacy (pre-0.4.x) clients logged the quota text in renderer.log only.
|
|
840
|
+
scannedBytes = 0;
|
|
841
|
+
for (const { full, size, mtimeMs } of pick("renderer.log")) {
|
|
842
|
+
if (scannedBytes >= QODER_LOG_SCAN_TOTAL_BYTES) break;
|
|
843
|
+
scannedBytes += Math.min(size, QODER_LOG_SCAN_MAX_BYTES);
|
|
844
|
+
const legacy = scanQoderLogFromEnd(full, (text) => parseQoderQuotaLog(text));
|
|
845
|
+
if (legacy) {
|
|
846
|
+
best = { limits: legacy, observedAtMs: mtimeMs, lineObservedAtMs: null };
|
|
847
|
+
break;
|
|
682
848
|
}
|
|
683
|
-
}
|
|
849
|
+
}
|
|
684
850
|
}
|
|
685
|
-
return null;
|
|
851
|
+
if (!best) return null;
|
|
852
|
+
// Provenance must describe when the snapshot was taken, not when we read it.
|
|
853
|
+
best.limits.cached_at = new Date(best.observedAtMs ?? nowMs).toISOString();
|
|
854
|
+
return best.limits;
|
|
686
855
|
}
|
|
687
856
|
|
|
688
857
|
function siteFromEnv(value) {
|
|
@@ -739,7 +908,7 @@ async function fetchQoderLimits({
|
|
|
739
908
|
}
|
|
740
909
|
if (rpcUsage) {
|
|
741
910
|
if (!rpcUsage.plan_label && typeof rpcAuth?.userType === "string") {
|
|
742
|
-
rpcUsage.plan_label = rpcAuth.userType;
|
|
911
|
+
rpcUsage.plan_label = qoderPlanLabel(rpcAuth.userType);
|
|
743
912
|
}
|
|
744
913
|
if (activityWindow) rpcUsage.secondary_window = activityWindow;
|
|
745
914
|
rpcUsage.source = activityWindow
|
|
@@ -796,7 +965,7 @@ async function fetchQoderLimits({
|
|
|
796
965
|
// Preserve that status as metadata, but match Qoder's Credits UI by
|
|
797
966
|
// rendering an empty 0/0 bucket as 0%, not a full red 100% bar.
|
|
798
967
|
const local = result.primary_window?.limit_credits === 0
|
|
799
|
-
? readQoderLocalQuota({ home, platform, env, appDir, envPrefix })
|
|
968
|
+
? readQoderLocalQuota({ home, platform, env, appDir, envPrefix, nowMs })
|
|
800
969
|
: null;
|
|
801
970
|
if (local) {
|
|
802
971
|
result.quota_exceeded = local.quota_exceeded === true;
|
|
@@ -820,7 +989,7 @@ async function fetchQoderLimits({
|
|
|
820
989
|
}
|
|
821
990
|
}
|
|
822
991
|
|
|
823
|
-
const local = readQoderLocalQuota({ home, platform, env, appDir, envPrefix });
|
|
992
|
+
const local = readQoderLocalQuota({ home, platform, env, appDir, envPrefix, nowMs });
|
|
824
993
|
if (local) {
|
|
825
994
|
if (activityWindow) {
|
|
826
995
|
local.secondary_window = activityWindow;
|
|
@@ -833,7 +1002,7 @@ async function fetchQoderLimits({
|
|
|
833
1002
|
return {
|
|
834
1003
|
configured: true,
|
|
835
1004
|
error: null,
|
|
836
|
-
plan_label:
|
|
1005
|
+
plan_label: qoderPlanLabel(rpcAuth?.userType),
|
|
837
1006
|
primary_window: null,
|
|
838
1007
|
secondary_window: activityWindow,
|
|
839
1008
|
source: activitySource === "disk-cache" ? "cached-activity" : "local-ipc+provider-api",
|
|
@@ -877,6 +1046,7 @@ module.exports = {
|
|
|
877
1046
|
readQoderLimitsCache,
|
|
878
1047
|
writeQoderLimitsCache,
|
|
879
1048
|
parseQoderQuotaLog,
|
|
1049
|
+
parseQoderAccountUsageLog,
|
|
880
1050
|
readQoderLocalQuota,
|
|
881
1051
|
fetchQoderLimits,
|
|
882
1052
|
fetchQoderCnLimits,
|
package/src/lib/rollout.js
CHANGED
|
@@ -7123,21 +7123,40 @@ function qoderNewMessageKey(record, filePath, lineIndex = 0) {
|
|
|
7123
7123
|
return `jsonl:${fallbackSuffix}|${record?.uuid || ""}`;
|
|
7124
7124
|
}
|
|
7125
7125
|
|
|
7126
|
+
// 8.64e15 is the ECMAScript TimeClip limit. A larger finite number (nanosecond
|
|
7127
|
+
// epochs, clock garbage) passes coerceEpochMs untouched, and `new Date(ms)`
|
|
7128
|
+
// yields Invalid Date whose .toISOString() THROWS RangeError — outside the
|
|
7129
|
+
// per-line JSON.parse try/catch, aborting the whole source on one bad row.
|
|
7130
|
+
// Clamp to a drop instead.
|
|
7131
|
+
const MAX_QODER_TIMESTAMP_MS = 8.64e15;
|
|
7132
|
+
|
|
7126
7133
|
function qoderNewTimestampMs(record) {
|
|
7127
|
-
|
|
7134
|
+
const ms = coerceEpochMs(record?.timestamp)
|
|
7128
7135
|
|| coerceEpochMs(record?.message?.timestamp)
|
|
7129
7136
|
|| parseIsoTimestampMs(record?.timestamp)
|
|
7130
7137
|
|| parseIsoTimestampMs(record?.message?.timestamp)
|
|
7131
7138
|
|| 0;
|
|
7139
|
+
return ms > MAX_QODER_TIMESTAMP_MS ? 0 : ms;
|
|
7132
7140
|
}
|
|
7133
7141
|
|
|
7134
7142
|
// Vendor credits (Qoder) ride along on token rows and are the only counter on
|
|
7135
7143
|
// credits-only rows. They are a display-only dimension
|
|
7136
7144
|
// (docs/sources-capture-audit.md §2): summed for visibility, never converted
|
|
7137
7145
|
// to tokens and never merged into any token column.
|
|
7146
|
+
//
|
|
7147
|
+
// `credits` and `original_credits` coexist (the latter is the pre-discount
|
|
7148
|
+
// value) and either alone can be 0, so take the larger instead of
|
|
7149
|
+
// `credits ?? original_credits` — `??` does not skip a present-but-zero
|
|
7150
|
+
// `credits`, which would drop real activity.
|
|
7151
|
+
const MIN_QODER_CREDIT_ACTIVITY = 1e-6;
|
|
7152
|
+
|
|
7138
7153
|
function qoderUsageCredits(usage) {
|
|
7139
|
-
|
|
7140
|
-
|
|
7154
|
+
let max = 0;
|
|
7155
|
+
for (const raw of [usage?.credits, usage?.original_credits]) {
|
|
7156
|
+
const credits = Number(raw);
|
|
7157
|
+
if (Number.isFinite(credits) && credits > max) max = credits;
|
|
7158
|
+
}
|
|
7159
|
+
return max >= MIN_QODER_CREDIT_ACTIVITY ? Math.round(max * 1e6) / 1e6 : 0;
|
|
7141
7160
|
}
|
|
7142
7161
|
|
|
7143
7162
|
function normalizeQoderNewTokens(usage) {
|
|
@@ -7256,9 +7275,13 @@ async function parseQoderNewIncremental({
|
|
|
7256
7275
|
const usage = msg.usage;
|
|
7257
7276
|
if (!usage || typeof usage !== "object") continue;
|
|
7258
7277
|
const base = normalizeQoderNewTokens(usage);
|
|
7259
|
-
//
|
|
7278
|
+
// Three admission signals: authoritative token fields, the older
|
|
7279
|
+
// credit-billed shape (billable absent/true), and Qoder 0.4.x rows that
|
|
7280
|
+
// report nominal credits while flagging billable=false. Rows with none
|
|
7281
|
+
// of them carry no activity at all.
|
|
7260
7282
|
const isBillable = usage.billable !== false;
|
|
7261
|
-
|
|
7283
|
+
const nominalCredits = qoderUsageCredits(usage);
|
|
7284
|
+
if (!base && !isBillable && nominalCredits <= 0) continue;
|
|
7262
7285
|
const timestampMs = qoderNewTimestampMs(record);
|
|
7263
7286
|
if (!timestampMs) continue;
|
|
7264
7287
|
const bucketStart = toUtcHalfHourStart(new Date(timestampMs).toISOString());
|
|
@@ -7291,7 +7314,7 @@ async function parseQoderNewIncremental({
|
|
|
7291
7314
|
total_tokens: 0,
|
|
7292
7315
|
billable_total_tokens: 0,
|
|
7293
7316
|
total_cost_usd: 0,
|
|
7294
|
-
credits:
|
|
7317
|
+
credits: nominalCredits,
|
|
7295
7318
|
conversation_count: 1,
|
|
7296
7319
|
};
|
|
7297
7320
|
let projectKey = null;
|
|
@@ -31,7 +31,9 @@ function isTraeCnUsageEnabled(env = process.env) {
|
|
|
31
31
|
const normalized = typeof value === "string" ? value.trim().toLowerCase() : "";
|
|
32
32
|
return normalized === "1" || normalized === "true";
|
|
33
33
|
}
|
|
34
|
-
const
|
|
34
|
+
const TRAE_CN_APP_DIRS = ["TRAE SOLO CN", "Trae CN"];
|
|
35
|
+
// Kept for callers that need the primary (Work) app dir by name.
|
|
36
|
+
const TRAE_CN_APP_DIR = TRAE_CN_APP_DIRS[0];
|
|
35
37
|
const TRAE_CN_AUTH_KEY = "iCubeAuthInfo://icube.cloudide";
|
|
36
38
|
|
|
37
39
|
const TRAE_CN_USAGE_URL = "https://api.trae.cn/trae/api/v1/pay/query_user_usage_group_by_session";
|
|
@@ -77,25 +79,44 @@ const TRAE_CN_KG = Buffer.from([
|
|
|
77
79
|
// Path resolution
|
|
78
80
|
// ---------------------------------------------------------------------------
|
|
79
81
|
|
|
82
|
+
function traeCnDataParent({ env = process.env, home = os.homedir(), platform = process.platform } = {}) {
|
|
83
|
+
if (platform === "darwin") {
|
|
84
|
+
return path.join(home, "Library", "Application Support");
|
|
85
|
+
}
|
|
86
|
+
if (platform === "win32") {
|
|
87
|
+
// Windows keeps the CN app under the roaming profile, mirroring the
|
|
88
|
+
// macOS Application Support layout (<parent>/<app dir>/User/...).
|
|
89
|
+
return typeof env.APPDATA === "string" && env.APPDATA.trim()
|
|
90
|
+
? env.APPDATA.trim()
|
|
91
|
+
: path.join(home, "AppData", "Roaming");
|
|
92
|
+
}
|
|
93
|
+
// No verified CN app-data layout on other platforms yet.
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
|
|
80
97
|
function resolveTraeCnHome({ env = process.env, home = os.homedir(), platform = process.platform } = {}) {
|
|
81
98
|
const override = env[TRAE_CN_HOME_ENV];
|
|
82
99
|
if (typeof override === "string" && override.trim()) {
|
|
83
100
|
return path.resolve(override.trim());
|
|
84
101
|
}
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
102
|
+
const parent = traeCnDataParent({ env, home, platform });
|
|
103
|
+
if (!parent) return null;
|
|
104
|
+
// Both CN clients share the same storage schema. Prefer an installed
|
|
105
|
+
// directory; otherwise fall back to the primary app dir so `status` can
|
|
106
|
+
// still render a diagnostic path on a machine where the app is absent.
|
|
107
|
+
let fallback = null;
|
|
108
|
+
for (const dir of TRAE_CN_APP_DIRS) {
|
|
109
|
+
const candidate = path.join(parent, dir);
|
|
110
|
+
if (!fallback) fallback = candidate;
|
|
111
|
+
try {
|
|
112
|
+
if (fs.statSync(candidate).isDirectory()) return candidate;
|
|
113
|
+
} catch (err) {
|
|
114
|
+
// Permission failures must reach the reader's diagnostics rather than
|
|
115
|
+
// masquerade as an absent installation (same policy as trae-db.js).
|
|
116
|
+
if (err.code !== "ENOENT" && err.code !== "ENOTDIR") return candidate;
|
|
117
|
+
}
|
|
96
118
|
}
|
|
97
|
-
|
|
98
|
-
return null;
|
|
119
|
+
return fallback;
|
|
99
120
|
}
|
|
100
121
|
|
|
101
122
|
function resolveTraeCnStoragePath(options = {}) {
|
|
@@ -525,6 +546,7 @@ module.exports = {
|
|
|
525
546
|
TRAE_CN_USAGE_ENV,
|
|
526
547
|
isTraeCnUsageEnabled,
|
|
527
548
|
TRAE_CN_APP_DIR,
|
|
549
|
+
TRAE_CN_APP_DIRS,
|
|
528
550
|
TRAE_CN_AUTH_KEY,
|
|
529
551
|
TRAE_CN_USAGE_URL,
|
|
530
552
|
TRAE_CN_USAGE_TYPE,
|