tokenusage-cli 0.4.5 → 0.4.6
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 +22 -0
- package/package.json +1 -1
- package/src/cli.js +1 -0
- package/src/commands/status.js +127 -1
- package/src/commands/sync.js +6 -1
- package/src/lib/account-usage-dedup.js +1 -1
- package/src/lib/cursor-config.js +113 -17
- 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/CHANGELOG.md
CHANGED
|
@@ -3,6 +3,28 @@
|
|
|
3
3
|
本包(`tokenusage-cli`)的用户可见变更记录。发版时在顶部新增一节,
|
|
4
4
|
`## <版本号>` 行会被 release workflow 取作 GitHub Release 正文。
|
|
5
5
|
|
|
6
|
+
## 0.4.6
|
|
7
|
+
|
|
8
|
+
2026-11-05。上游对齐补丁 + 限额面板落地:Cursor cache-only 行、Qoder credits/准入/时间戳、
|
|
9
|
+
Trae CN 双目录,Qoder Desktop 0.4.x 的限额改读本机 `main.log` 快照(带 provenance),
|
|
10
|
+
`status --limits` 首次把 18 家限额读数暴露出来。无契约变更,服务端无需同步升级。
|
|
11
|
+
|
|
12
|
+
- **Cursor 准入按 token 分量判断**:CSV 行改用 input / cache write / cache read / output 四列
|
|
13
|
+
判断是否有用量,`Total Tokens=0` 的 cache-only 行不再被丢;0-token request-only 行仍按
|
|
14
|
+
A8 决策不入库(会把 bot/automation 计成对话、凭空造出活跃日)。
|
|
15
|
+
- **Qoder credits 与准入**:credits 取 `credits` / `original_credits` 较大值;`billable:false`
|
|
16
|
+
但 credits>0 的 0.4.x 行不再被丢;坏时间戳(> 8.64e15)按行丢弃,不再中断整源。
|
|
17
|
+
- **Trae CN 账户级目录**:同时发现 `TRAE SOLO CN` 与 `Trae CN`,优先已安装目录。
|
|
18
|
+
- **Qoder Desktop 0.4.x 限额快照**:扫 `main.log` 的 `[Auth] [AccountUsage]` 摘要
|
|
19
|
+
(bundle-id 与旧 `Qoder[CN]` 两种布局、单文件逆向 8 MB 分块、7 天新鲜度、跨文件取最新行、
|
|
20
|
+
旧 `renderer.log` 保留为回退),`cached_at` 记录快照自身观测时间而非读取时间。
|
|
21
|
+
- **`status --limits`(新增)**:opt-in 渲染 18 家 provider 的限额行(plan + 各窗口 +
|
|
22
|
+
credits + provenance 的 source/stale/年龄),`--json` 输出 `limits` 键;默认 `status`
|
|
23
|
+
仍是纯本地快路径。
|
|
24
|
+
- **文档校正**:Cursor CSV 的 Cost 列实际未接线(成本仍按 token × 定价估算),
|
|
25
|
+
`docs/sources-capture-audit.md` 里 reported-first 的错误表述已改正。
|
|
26
|
+
- 回归测试:`qoder-log-limits`(7 例)、`status-usage-limits`(5 例),CLI 共 244 例全绿。
|
|
27
|
+
|
|
6
28
|
## 0.4.5
|
|
7
29
|
|
|
8
30
|
2026-11-04。一轮审计修复:`sync` 读队列时把契约 v2 的项目拆分行压回余量行、随后照旧推进
|
package/package.json
CHANGED
package/src/cli.js
CHANGED
|
@@ -162,6 +162,7 @@ const COMMANDS = [
|
|
|
162
162
|
" --diagnostics Include diagnostics (paths, cursors, WSL/Kiro probes)",
|
|
163
163
|
" --json Machine-readable output",
|
|
164
164
|
" --light Deterministic ASCII table (no ANSI, no emoji)",
|
|
165
|
+
" --limits Include the provider quota panel (reads local credentials and provider APIs)",
|
|
165
166
|
" --no-spinner Disable the progress spinner",
|
|
166
167
|
" --probe-keychain Probe the macOS keychain (may prompt)",
|
|
167
168
|
" --probe-keychain-details Include per-item keychain details",
|
package/src/commands/status.js
CHANGED
|
@@ -35,6 +35,7 @@ const {
|
|
|
35
35
|
const { collectLocalSubscriptions } = require("../lib/subscriptions");
|
|
36
36
|
const {
|
|
37
37
|
describeCopilotOtelStatus,
|
|
38
|
+
getUsageLimits,
|
|
38
39
|
readCopilotOauthToken,
|
|
39
40
|
} = require("../lib/usage-limits");
|
|
40
41
|
const {
|
|
@@ -379,6 +380,19 @@ async function cmdStatus(argv = []) {
|
|
|
379
380
|
});
|
|
380
381
|
const subscriptionLines =
|
|
381
382
|
subscriptions.length > 0 ? subscriptions.map(formatSubscriptionLine) : [];
|
|
383
|
+
// Quota panel (opt-in, `--limits`): the aggregate reads local app credentials
|
|
384
|
+
// and provider APIs, so it stays off the default status path. The payload
|
|
385
|
+
// carries per-provider provenance, which is what makes a stale log snapshot
|
|
386
|
+
// distinguishable from a live reading.
|
|
387
|
+
const usageLimits = opts.limits
|
|
388
|
+
? await getUsageLimits({
|
|
389
|
+
home,
|
|
390
|
+
env: process.env,
|
|
391
|
+
platform: process.platform,
|
|
392
|
+
})
|
|
393
|
+
: null;
|
|
394
|
+
const usageLimitRows = formatUsageLimitRows(usageLimits);
|
|
395
|
+
const usageLimitLines = usageLimitRows.map(([label, value]) => `- ${label}: ${value}`);
|
|
382
396
|
|
|
383
397
|
const kimiWireFiles = resolveKimiWireFiles(process.env);
|
|
384
398
|
const kimiHome = process.env.KIMI_HOME || path.join(home, ".kimi");
|
|
@@ -1282,6 +1296,7 @@ async function cmdStatus(argv = []) {
|
|
|
1282
1296
|
}
|
|
1283
1297
|
: {}),
|
|
1284
1298
|
subscriptions,
|
|
1299
|
+
...(usageLimits ? { limits: usageLimits } : {}),
|
|
1285
1300
|
// Pricing data provenance + staleness, so a $0 cost row can be triaged
|
|
1286
1301
|
// as "not collected" vs "not priced" from `status --json` alone.
|
|
1287
1302
|
pricing: getPricingMeta(),
|
|
@@ -1501,6 +1516,7 @@ async function cmdStatus(argv = []) {
|
|
|
1501
1516
|
return lines;
|
|
1502
1517
|
})() : []),
|
|
1503
1518
|
...subscriptionLines,
|
|
1519
|
+
...usageLimitLines,
|
|
1504
1520
|
"",
|
|
1505
1521
|
]
|
|
1506
1522
|
.filter(Boolean)
|
|
@@ -1597,11 +1613,111 @@ function formatSubscriptionLine(entry = {}) {
|
|
|
1597
1613
|
return `- ${toolLabel} ${productLabel}: ${planType}`;
|
|
1598
1614
|
}
|
|
1599
1615
|
|
|
1616
|
+
const USAGE_LIMIT_PROVIDERS = [
|
|
1617
|
+
["claude", "Claude"],
|
|
1618
|
+
["codex", "Codex"],
|
|
1619
|
+
["cursor", "Cursor"],
|
|
1620
|
+
["grok", "Grok"],
|
|
1621
|
+
["kimi", "Kimi"],
|
|
1622
|
+
["gemini", "Gemini"],
|
|
1623
|
+
["kiro", "Kiro"],
|
|
1624
|
+
["antigravity", "Antigravity"],
|
|
1625
|
+
["copilot", "Copilot"],
|
|
1626
|
+
["zcode", "ZCode"],
|
|
1627
|
+
["opencodeGo", "OpenCode Go"],
|
|
1628
|
+
["commandCode", "CommandCode"],
|
|
1629
|
+
["devin", "Devin"],
|
|
1630
|
+
["qoder", "Qoder"],
|
|
1631
|
+
["qoderCn", "Qoder CN"],
|
|
1632
|
+
["codingPlan", "Ark Coding Plan"],
|
|
1633
|
+
["agentPlan", "Ark Agent Plan"],
|
|
1634
|
+
["deepseek", "DeepSeek"],
|
|
1635
|
+
];
|
|
1636
|
+
|
|
1637
|
+
// Primary window first and unprefixed (it is the headline quota); the rest keep
|
|
1638
|
+
// their role so a three-window provider stays readable on one row.
|
|
1639
|
+
const USAGE_LIMIT_WINDOWS = [
|
|
1640
|
+
["primary_window", null],
|
|
1641
|
+
["secondary_window", "secondary"],
|
|
1642
|
+
["tertiary_window", "add-on"],
|
|
1643
|
+
["quaternary_window", "other"],
|
|
1644
|
+
];
|
|
1645
|
+
|
|
1646
|
+
function formatLimitAge(seconds) {
|
|
1647
|
+
const value = Number(seconds);
|
|
1648
|
+
if (!Number.isFinite(value) || value < 0) return null;
|
|
1649
|
+
if (value < 60) return `${Math.round(value)}s ago`;
|
|
1650
|
+
if (value < 3600) return `${Math.round(value / 60)}m ago`;
|
|
1651
|
+
if (value < 86_400) return `${Math.round(value / 3600)}h ago`;
|
|
1652
|
+
return `${Math.round(value / 86_400)}d ago`;
|
|
1653
|
+
}
|
|
1654
|
+
|
|
1655
|
+
function formatLimitCredits(value) {
|
|
1656
|
+
const number = Number(value);
|
|
1657
|
+
if (!Number.isFinite(number)) return null;
|
|
1658
|
+
return String(Math.round(number * 100) / 100);
|
|
1659
|
+
}
|
|
1660
|
+
|
|
1661
|
+
function formatUsageLimitWindow(window) {
|
|
1662
|
+
if (!window || typeof window !== "object") return null;
|
|
1663
|
+
const parts = [];
|
|
1664
|
+
const percent = Number(window.used_percent);
|
|
1665
|
+
if (Number.isFinite(percent)) parts.push(`${Math.round(percent * 10) / 10}%`);
|
|
1666
|
+
const used = formatLimitCredits(window.used_credits);
|
|
1667
|
+
const limit = formatLimitCredits(window.limit_credits);
|
|
1668
|
+
if (used !== null && limit !== null && Number(window.limit_credits) > 0) {
|
|
1669
|
+
parts.push(`${used}/${limit} credits`);
|
|
1670
|
+
}
|
|
1671
|
+
if (window.reset_at) parts.push(`resets ${window.reset_at}`);
|
|
1672
|
+
return parts.length > 0 ? parts.join(", ") : null;
|
|
1673
|
+
}
|
|
1674
|
+
|
|
1675
|
+
/**
|
|
1676
|
+
* Pure formatter for the opt-in quota panel (`status --limits`). One row per
|
|
1677
|
+
* configured provider; plan, windows, error and provenance share a row so
|
|
1678
|
+
* `--light` output stays greppable by provider name.
|
|
1679
|
+
*/
|
|
1680
|
+
function formatUsageLimitRows(limits) {
|
|
1681
|
+
if (!limits || typeof limits !== "object") return [];
|
|
1682
|
+
const rows = [];
|
|
1683
|
+
|
|
1684
|
+
for (const [key, label] of USAGE_LIMIT_PROVIDERS) {
|
|
1685
|
+
const entry = limits[key];
|
|
1686
|
+
if (!entry || typeof entry !== "object" || entry.configured === false) continue;
|
|
1687
|
+
const parts = [];
|
|
1688
|
+
if (entry.error) parts.push(`error: ${entry.error}`);
|
|
1689
|
+
const plan = entry.plan_label || entry.plan_name || entry.plan_type || null;
|
|
1690
|
+
if (plan) parts.push(String(plan));
|
|
1691
|
+
for (const [windowKey, prefix] of USAGE_LIMIT_WINDOWS) {
|
|
1692
|
+
const windowText = formatUsageLimitWindow(entry[windowKey]);
|
|
1693
|
+
if (!windowText) continue;
|
|
1694
|
+
parts.push(prefix ? `${prefix}: ${windowText}` : windowText);
|
|
1695
|
+
}
|
|
1696
|
+
const provenance = entry.provenance;
|
|
1697
|
+
if (provenance && typeof provenance === "object") {
|
|
1698
|
+
const age = formatLimitAge(provenance.age_seconds);
|
|
1699
|
+
parts.push(
|
|
1700
|
+
[
|
|
1701
|
+
provenance.source || "unknown",
|
|
1702
|
+
provenance.stale === true ? "stale" : null,
|
|
1703
|
+
age,
|
|
1704
|
+
]
|
|
1705
|
+
.filter(Boolean)
|
|
1706
|
+
.join(", "),
|
|
1707
|
+
);
|
|
1708
|
+
}
|
|
1709
|
+
rows.push([`Limit · ${label}`, parts.length > 0 ? parts.join(", ") : "—"]);
|
|
1710
|
+
}
|
|
1711
|
+
|
|
1712
|
+
return rows;
|
|
1713
|
+
}
|
|
1714
|
+
|
|
1600
1715
|
function parseArgs(argv) {
|
|
1601
1716
|
const out = {
|
|
1602
1717
|
diagnostics: false,
|
|
1603
1718
|
json: false,
|
|
1604
1719
|
light: false,
|
|
1720
|
+
limits: false,
|
|
1605
1721
|
noSpinner: false,
|
|
1606
1722
|
probeKeychain: false,
|
|
1607
1723
|
probeKeychainDetails: false,
|
|
@@ -1612,6 +1728,7 @@ function parseArgs(argv) {
|
|
|
1612
1728
|
if (a === "--diagnostics") out.diagnostics = true;
|
|
1613
1729
|
else if (a === "--json") out.json = true;
|
|
1614
1730
|
else if (a === "--light") out.light = true;
|
|
1731
|
+
else if (a === "--limits") out.limits = true;
|
|
1615
1732
|
else if (a === "--no-spinner") out.noSpinner = true;
|
|
1616
1733
|
else if (a === "--probe-keychain") out.probeKeychain = true;
|
|
1617
1734
|
else if (a === "--probe-keychain-details") {
|
|
@@ -1670,6 +1787,10 @@ function renderLightTable(summary) {
|
|
|
1670
1787
|
push(`Provider · ${name}`, detail.length ? detail.join(", ") : "—");
|
|
1671
1788
|
}
|
|
1672
1789
|
|
|
1790
|
+
for (const [label, value] of formatUsageLimitRows(summary.limits)) {
|
|
1791
|
+
push(label, value);
|
|
1792
|
+
}
|
|
1793
|
+
|
|
1673
1794
|
// Mirror formatCopilotLines(): stay silent for machines with no Copilot
|
|
1674
1795
|
// signal at all instead of printing "not found" rows for everyone.
|
|
1675
1796
|
const copilotDetected =
|
|
@@ -1762,4 +1883,9 @@ function parseEpochMsToIso(v) {
|
|
|
1762
1883
|
return d.toISOString();
|
|
1763
1884
|
}
|
|
1764
1885
|
|
|
1765
|
-
module.exports = {
|
|
1886
|
+
module.exports = {
|
|
1887
|
+
cmdStatus,
|
|
1888
|
+
formatUsageLimitRows,
|
|
1889
|
+
parseArgs,
|
|
1890
|
+
summarizeQoderDetail,
|
|
1891
|
+
};
|
package/src/commands/sync.js
CHANGED
|
@@ -182,6 +182,7 @@ const {
|
|
|
182
182
|
isCursorInstalled,
|
|
183
183
|
extractCursorSessionToken,
|
|
184
184
|
fetchCursorUsageCsv,
|
|
185
|
+
fetchCursorUsageCsvWithFallback,
|
|
185
186
|
parseCursorCsv,
|
|
186
187
|
} = require("../lib/cursor-config");
|
|
187
188
|
const { purgeProjectUsage } = require("../lib/project-usage-purge");
|
|
@@ -2259,7 +2260,11 @@ async function cmdSync(argv, context = {}) {
|
|
|
2259
2260
|
if (progress?.enabled) {
|
|
2260
2261
|
progress.start(`Fetching Cursor usage...`);
|
|
2261
2262
|
}
|
|
2262
|
-
const csvText = await
|
|
2263
|
+
const csvText = await fetchCursorUsageCsvWithFallback({
|
|
2264
|
+
cookies: cursorAuth.cookies,
|
|
2265
|
+
cookie: cursorAuth.cookie,
|
|
2266
|
+
cookieFetcher: cursorUsageFetcher,
|
|
2267
|
+
});
|
|
2263
2268
|
const records = parseCursorCsv(csvText);
|
|
2264
2269
|
if (records.length > 0) {
|
|
2265
2270
|
if (progress?.enabled) {
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
/**
|
|
4
4
|
* Account-level cross-device truth - JS reference implementation.
|
|
5
5
|
*
|
|
6
|
-
* Account-level sources (ACCOUNT_LEVEL_SOURCES in src/lib/
|
|
6
|
+
* Account-level sources (ACCOUNT_LEVEL_SOURCES in src/lib/session-upload.js)
|
|
7
7
|
* come from a per-ACCOUNT cloud API, so every device that syncs them stores
|
|
8
8
|
* its own copy of the SAME account data. How to dedup depends on the source:
|
|
9
9
|
*
|
package/src/lib/cursor-config.js
CHANGED
|
@@ -67,11 +67,11 @@ function readCursorAccessTokenFromStateDb(stateDbPath, deps = {}) {
|
|
|
67
67
|
|
|
68
68
|
/**
|
|
69
69
|
* Extract Cursor session cookie from local SQLite + cli-config.json.
|
|
70
|
-
* Returns { cookie, userId } or null on failure.
|
|
70
|
+
* Returns { cookie, cookies, userId, userIds } or null on failure.
|
|
71
71
|
*
|
|
72
72
|
* Cookie format: WorkosCursorSessionToken=<userId>%3A%3A<jwt>
|
|
73
73
|
* - JWT from state.vscdb → ItemTable → cursorAuth/accessToken
|
|
74
|
-
* - userId
|
|
74
|
+
* - userId candidates, JWT subject first, then cli-config.json authInfo.authId:
|
|
75
75
|
* - native Cursor email/password: "auth0|user_XXXXX" → "user_XXXXX"
|
|
76
76
|
* - Google sign-in via WorkOS: "google-oauth2|<numeric>" → kept verbatim
|
|
77
77
|
* - other WorkOS subjects: "github|…", "oidc|…" → kept verbatim
|
|
@@ -79,7 +79,9 @@ function readCursorAccessTokenFromStateDb(stateDbPath, deps = {}) {
|
|
|
79
79
|
function extractCursorSessionToken({ home, platform, env, deps } = {}) {
|
|
80
80
|
const auth = extractCursorAuth({ home, platform, env, deps });
|
|
81
81
|
if (!auth) return null;
|
|
82
|
-
|
|
82
|
+
// `cookies` is additive: callers that only need one session cookie keep
|
|
83
|
+
// using `cookie`, while sync can retry the remaining userId candidates.
|
|
84
|
+
return { cookie: auth.cookie, cookies: auth.cookies, userId: auth.userId };
|
|
83
85
|
}
|
|
84
86
|
|
|
85
87
|
/**
|
|
@@ -99,16 +101,16 @@ function extractCursorAuth({ home, platform, env, deps } = {}) {
|
|
|
99
101
|
const jwt = readCursorAccessTokenFromStateDb(stateDbPath, deps);
|
|
100
102
|
if (!jwt || jwt.length < 10) return null;
|
|
101
103
|
|
|
102
|
-
// 2.
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
104
|
+
// 2. Build every userId candidate — JWT subject first (cli-config.json can
|
|
105
|
+
// hold a stale account and pairing it with the current token is a
|
|
106
|
+
// persistent 401), then the cli-config authId as a fallback.
|
|
107
|
+
const userIds = collectCursorSessionUserIds(jwt, readCursorCliAuthId(cliConfigPath));
|
|
108
|
+
const userId = userIds[0] || null;
|
|
107
109
|
if (!userId) return null;
|
|
108
110
|
|
|
109
|
-
// 3. Build cookie
|
|
110
|
-
const
|
|
111
|
-
return { cookie, userId, accessToken: jwt };
|
|
111
|
+
// 3. Build cookie(s)
|
|
112
|
+
const cookies = userIds.map((id) => `${CURSOR_SESSION_COOKIE}=${id}%3A%3A${jwt}`);
|
|
113
|
+
return { cookie: cookies[0], cookies, userId, userIds, accessToken: jwt };
|
|
112
114
|
}
|
|
113
115
|
|
|
114
116
|
// WorkOS OAuth subject prefixes Cursor accepts as-is in the session cookie.
|
|
@@ -125,26 +127,57 @@ function normalizeCursorSubject(subject) {
|
|
|
125
127
|
return null;
|
|
126
128
|
}
|
|
127
129
|
|
|
128
|
-
function
|
|
130
|
+
function readCursorCliAuthId(configPath) {
|
|
129
131
|
try {
|
|
130
132
|
const config = JSON.parse(fs.readFileSync(configPath, "utf8"));
|
|
131
|
-
|
|
133
|
+
const raw = typeof config?.authInfo?.authId === "string" ? config.authInfo.authId.trim() : "";
|
|
134
|
+
return raw || null;
|
|
132
135
|
} catch {
|
|
133
136
|
return null;
|
|
134
137
|
}
|
|
135
138
|
}
|
|
136
139
|
|
|
137
|
-
function
|
|
140
|
+
function decodeJwtSubject(jwt) {
|
|
138
141
|
try {
|
|
139
142
|
const parts = jwt.split(".");
|
|
140
143
|
if (parts.length !== 3) return null;
|
|
141
144
|
const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString());
|
|
142
|
-
return
|
|
145
|
+
return typeof payload.sub === "string" && payload.sub.trim() ? payload.sub.trim() : null;
|
|
143
146
|
} catch {
|
|
144
147
|
return null;
|
|
145
148
|
}
|
|
146
149
|
}
|
|
147
150
|
|
|
151
|
+
const CURSOR_SESSION_COOKIE = "WorkosCursorSessionToken";
|
|
152
|
+
const CURSOR_USER_ID_RE = /^user_[A-Za-z0-9_]+$/;
|
|
153
|
+
|
|
154
|
+
function addCursorUserIdCandidate(ids, value) {
|
|
155
|
+
const trimmed = typeof value === "string" ? value.trim() : "";
|
|
156
|
+
if (!trimmed) return;
|
|
157
|
+
// Same acceptance rule as normalizeCursorSubject: bare `user_*` ids or a
|
|
158
|
+
// WorkOS provider subject. Anything else is not a cookie identity.
|
|
159
|
+
if (!normalizeCursorSubject(trimmed) && !CURSOR_USER_ID_RE.test(trimmed)) return;
|
|
160
|
+
if (!ids.includes(trimmed)) ids.push(trimmed);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Ordered userId candidates for the Cursor session cookie.
|
|
165
|
+
*
|
|
166
|
+
* The JWT subject is authoritative: cli-config.json can still hold a different
|
|
167
|
+
* (stale) account, and pairing that id with the current access token is a
|
|
168
|
+
* persistent 401. Both the normalized and the raw subject are kept because
|
|
169
|
+
* Cursor accepts `auth0|user_x` and `user_x` for the same login.
|
|
170
|
+
*/
|
|
171
|
+
function collectCursorSessionUserIds(jwt, cliAuthId) {
|
|
172
|
+
const ids = [];
|
|
173
|
+
const jwtSubject = decodeJwtSubject(jwt);
|
|
174
|
+
addCursorUserIdCandidate(ids, normalizeCursorSubject(jwtSubject || ""));
|
|
175
|
+
addCursorUserIdCandidate(ids, jwtSubject);
|
|
176
|
+
addCursorUserIdCandidate(ids, normalizeCursorSubject(cliAuthId || ""));
|
|
177
|
+
addCursorUserIdCandidate(ids, cliAuthId);
|
|
178
|
+
return ids;
|
|
179
|
+
}
|
|
180
|
+
|
|
148
181
|
// ── API client ──
|
|
149
182
|
|
|
150
183
|
const CURSOR_CSV_URL = "https://cursor.com/api/dashboard/export-usage-events-csv?strategy=tokens";
|
|
@@ -207,7 +240,11 @@ function fetchCursorUsageCsv({ cookie, timeoutMs = 30000, fetchImpl = fetch }) {
|
|
|
207
240
|
signal: AbortSignal.timeout(timeoutMs),
|
|
208
241
|
}).then(async (res) => {
|
|
209
242
|
if (res.status === 401 || res.status === 403) {
|
|
210
|
-
|
|
243
|
+
const error = new Error("Cursor session expired — re-login in Cursor to refresh");
|
|
244
|
+
// Lets sync retry the remaining userId candidates instead of treating
|
|
245
|
+
// one stale cli-config account as a dead session.
|
|
246
|
+
error.code = "AUTH_EXPIRED";
|
|
247
|
+
throw error;
|
|
211
248
|
}
|
|
212
249
|
if (res.status === 308 || res.status === 301 || res.status === 302) {
|
|
213
250
|
// Follow redirect once. Keep this hop on redirect:"manual" so the
|
|
@@ -224,6 +261,48 @@ function fetchCursorUsageCsv({ cookie, timeoutMs = 30000, fetchImpl = fetch }) {
|
|
|
224
261
|
}).catch(remapCursorFetchTimeout);
|
|
225
262
|
}
|
|
226
263
|
|
|
264
|
+
/**
|
|
265
|
+
* Fetch the CSV trying each userId candidate in order.
|
|
266
|
+
*
|
|
267
|
+
* Only an auth rejection (`AUTH_EXPIRED`) moves to the next candidate: a stale
|
|
268
|
+
* cli-config account produces exactly that, while a network/timeout failure
|
|
269
|
+
* says nothing about the identity and must surface immediately.
|
|
270
|
+
*/
|
|
271
|
+
async function fetchCursorUsageCsvWithFallback({
|
|
272
|
+
cookies,
|
|
273
|
+
cookie,
|
|
274
|
+
timeoutMs,
|
|
275
|
+
fetchImpl = fetch,
|
|
276
|
+
cookieFetcher,
|
|
277
|
+
} = {}) {
|
|
278
|
+
const candidates = Array.isArray(cookies) && cookies.length > 0
|
|
279
|
+
? cookies
|
|
280
|
+
: (cookie ? [cookie] : []);
|
|
281
|
+
if (candidates.length === 0) {
|
|
282
|
+
throw new Error("Cursor session cookie is missing — re-login in Cursor to refresh");
|
|
283
|
+
}
|
|
284
|
+
const fetcher = typeof cookieFetcher === "function"
|
|
285
|
+
? cookieFetcher
|
|
286
|
+
: (opts) => fetchCursorUsageCsv({
|
|
287
|
+
cookie: opts.cookie,
|
|
288
|
+
fetchImpl,
|
|
289
|
+
...(timeoutMs ? { timeoutMs } : {}),
|
|
290
|
+
});
|
|
291
|
+
let lastAuthError = null;
|
|
292
|
+
for (const candidate of candidates) {
|
|
293
|
+
try {
|
|
294
|
+
return await fetcher({ cookie: candidate });
|
|
295
|
+
} catch (err) {
|
|
296
|
+
if (err && err.code === "AUTH_EXPIRED") {
|
|
297
|
+
lastAuthError = err;
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
throw err;
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
throw lastAuthError;
|
|
304
|
+
}
|
|
305
|
+
|
|
227
306
|
/**
|
|
228
307
|
* Fetch Cursor usage summary JSON.
|
|
229
308
|
* Returns parsed JSON body or throws on error.
|
|
@@ -502,7 +581,22 @@ function parseCursorCsv(csvText) {
|
|
|
502
581
|
cost: toFloat(fields[costIdx]),
|
|
503
582
|
};
|
|
504
583
|
|
|
505
|
-
|
|
584
|
+
// Token presence is judged on the component columns (not the Total
|
|
585
|
+
// column) so a cache-read-only or cache-write-only row survives even when
|
|
586
|
+
// Cursor's Total disagrees — normalizeCursorUsage and the downstream
|
|
587
|
+
// isAllZeroUsage gate read these same component fields. Rows with no
|
|
588
|
+
// token component at all stay dropped on purpose (A8 decision,
|
|
589
|
+
// 2026-11-05): a 0-token request-only row would add a conversation but no
|
|
590
|
+
// tokens, and the dashboard derives active days from day buckets, so
|
|
591
|
+
// admitting them invents active days and counts bot/automation traffic as
|
|
592
|
+
// conversations. Upstream keeps them to pair with its cloud-side request
|
|
593
|
+
// retention, which this project does not have.
|
|
594
|
+
const hasTokens =
|
|
595
|
+
record.inputTokens > 0 ||
|
|
596
|
+
record.cacheWriteTokens > 0 ||
|
|
597
|
+
record.cacheReadTokens > 0 ||
|
|
598
|
+
record.outputTokens > 0;
|
|
599
|
+
if (!hasTokens) continue;
|
|
506
600
|
|
|
507
601
|
records.push(record);
|
|
508
602
|
}
|
|
@@ -597,7 +691,9 @@ module.exports = {
|
|
|
597
691
|
readCursorAccessTokenFromStateDb,
|
|
598
692
|
extractCursorAuth,
|
|
599
693
|
extractCursorSessionToken,
|
|
694
|
+
collectCursorSessionUserIds,
|
|
600
695
|
fetchCursorUsageCsv,
|
|
696
|
+
fetchCursorUsageCsvWithFallback,
|
|
601
697
|
fetchCursorUsageSummary,
|
|
602
698
|
decodeCursorSandAccessStatus,
|
|
603
699
|
decodeCursorSandUsageStatus,
|
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,
|