tokenusage-cli 0.4.4 → 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 CHANGED
@@ -3,6 +3,49 @@
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
+
28
+ ## 0.4.5
29
+
30
+ 2026-11-04。一轮审计修复:`sync` 读队列时把契约 v2 的项目拆分行压回余量行、随后照旧推进
31
+ 上传偏移,被归因的用量会永久丢失;上传确认、Windows 隐藏启动器编码与首同步统计也各有一处
32
+ 缺陷。无契约变更,服务端无需同步升级。
33
+
34
+ - **队列批次不再丢项目行**:`readQueueBatch` 的去重键原来只有 `source|model|hour`,
35
+ 契约 v2 的拆分行(同键不同 `project_key`)会被合并成余量行并随偏移推进永久丢失;
36
+ 现键含 `project_key`,每行独立上传。
37
+ - **拆分行按服务端 basename 身份合并**:写出/合并项目拆分行时统一走共享的
38
+ `lib/project-key.js`(`basenameKey()`),与服务端请求去重口径一致;同名不同 owner 的
39
+ 仓库不再互相覆盖。`reconcile` 对旧的 `owner/repo` 行做同样的归一,避免把正常数据报成漂移。
40
+ - **上传确认后才推进进度**:`ingest` 需响应含 `inserted` + `skipped`、session 上传需含
41
+ `sessions_upserted` + `sessions_skipped`,才推进队列偏移 / watermark;未确认的 2xx
42
+ 响应按失败处理,下次 `sync` 重传而不是静默跳数据。
43
+ - **Windows 隐藏启动器改 UTF-16LE + BOM**:`run-sync-hidden.vbs` 按 wscript 期望的编码
44
+ 写入,含非 ASCII 字符的安装路径不再乱码或被截断。
45
+ - **首同步统计修正**:`init` 的首次同步统计跳过 `kind` 控制行,并把 `project_key` 纳入
46
+ last-wins 键,项目用量不再被余量行盖掉。
47
+ - 回归测试:拆分行往返、basename 归一、VBS 编码、未确认 2xx 不推进偏移/watermark。
48
+
6
49
  ## 0.4.4
7
50
 
8
51
  2026-11-04。契约 v2 落地:小时用量桶按项目名拆行(`project_key`),项目键向上回退到真实
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokenusage-cli",
3
- "version": "0.4.4",
3
+ "version": "0.4.6",
4
4
  "description": "Self-hosted AI coding token usage collector for the Token Usage dashboard.",
5
5
  "keywords": [
6
6
  "token-usage",
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",
@@ -2807,7 +2807,14 @@ function readFirstSyncTotals(trackerDir) {
2807
2807
  if (!trimmed) continue;
2808
2808
  try {
2809
2809
  const row = JSON.parse(trimmed);
2810
- const key = `${row.source || ""}|${row.model || ""}|${row.hour_start || ""}`;
2810
+ // Control records (account session states / watermarks) carry a
2811
+ // `total_tokens` too; they are not usage buckets and must not inflate
2812
+ // the first-sync counter.
2813
+ if (!row || typeof row !== "object" || Object.hasOwn(row, "kind")) continue;
2814
+ // Contract v2: project_key joins the last-wins identity. Without it the
2815
+ // residual row (appended last) hides every attributed project row, and a
2816
+ // fully attributed hour would display as 0 tokens.
2817
+ const key = `${row.source || ""}|${row.model || ""}|${row.hour_start || ""}|${row.project_key || ""}`;
2811
2818
  latest.set(key, row);
2812
2819
  } catch {
2813
2820
  // skip malformed
@@ -40,6 +40,7 @@ const { functionUrlFor, fetchFunctionResponse } = require("../lib/function-url")
40
40
  const { iterateQueueLines } = require("../lib/upload-queue");
41
41
  const { normalizeQueueRow } = require("../lib/queue-row-normalize");
42
42
  const { sanitizeBucketForUpload } = require("../lib/ingest-sanitize");
43
+ const { basenameKey } = require("../lib/project-key");
43
44
  const { TOKEN_COLUMNS } = require("../lib/account-usage-dedup");
44
45
  const { UsageError, unknownOptionError } = require("../lib/cli-errors");
45
46
 
@@ -208,7 +209,13 @@ async function collectBuckets({ queuePath, fromMs, toMs, start = 0 }) {
208
209
  });
209
210
  const sanitized = sanitizeBucketForUpload(row);
210
211
  if (!sanitized) continue;
211
- const project = typeof sanitized.project_key === "string" ? sanitized.project_key.trim() : "";
212
+ // The server stores only the basename (§2.4). Normalizing here keeps
213
+ // pre-v2 queues whose rows still carry `owner/repo` comparable with the
214
+ // cloud instead of reporting permanent missing_on_server drift.
215
+ const project =
216
+ typeof sanitized.project_key === "string"
217
+ ? basenameKey(sanitized.project_key) || ""
218
+ : "";
212
219
  buckets.set(bucketKey(hourMs, source, model, project), sanitized);
213
220
  }
214
221
  } finally {
@@ -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 = { cmdStatus, summarizeQoderDetail };
1886
+ module.exports = {
1887
+ cmdStatus,
1888
+ formatUsageLimitRows,
1889
+ parseArgs,
1890
+ summarizeQoderDetail,
1891
+ };
@@ -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 cursorUsageFetcher({ cookie: cursorAuth.cookie });
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) {
@@ -4721,6 +4726,14 @@ async function drainQueueToCloud({ baseUrl, anonKey, deviceToken, queuePath, que
4721
4726
  throw err;
4722
4727
  }
4723
4728
 
4729
+ if (!isConfirmedIngestResponse(data)) {
4730
+ const err = new Error(
4731
+ `Unconfirmed ingest response (HTTP ${res.status}): ${rawText.substring(0, 300)}`,
4732
+ );
4733
+ err.status = res.status;
4734
+ err.code = "CLOUD_UPLOAD_UNCONFIRMED";
4735
+ throw err;
4736
+ }
4724
4737
  cloudAccess = data;
4725
4738
  if (data.upload_scope === "community") batchBudget = Math.min(batchBudget, 10);
4726
4739
  inserted += Number(data?.inserted || 0);
@@ -4755,6 +4768,23 @@ async function drainQueueToCloud({ baseUrl, anonKey, deviceToken, queuePath, que
4755
4768
  return resultSoFar();
4756
4769
  }
4757
4770
 
4771
+ // A 200 is not proof the ingest committed: captive portals / reverse proxies
4772
+ // return 200 HTML and maintenance pages return an empty body. Advancing the
4773
+ // queue offset on those silently drops the batch forever, so the drain only
4774
+ // accepts the contract's success shape (docs/cli-contract.md §2.4).
4775
+ function isCount(value) {
4776
+ return (
4777
+ (typeof value === "number" || typeof value === "string") &&
4778
+ value !== "" &&
4779
+ Number.isFinite(Number(value))
4780
+ );
4781
+ }
4782
+
4783
+ function isConfirmedIngestResponse(data) {
4784
+ return Boolean(data) && typeof data === "object" && !Array.isArray(data) &&
4785
+ isCount(data.inserted) && isCount(data.skipped);
4786
+ }
4787
+
4758
4788
  async function readQueueBatch(queuePath, startOffset, maxBuckets) {
4759
4789
  const st = await fs.stat(queuePath).catch(() => null);
4760
4790
  if (!st || !st.isFile()) return { buckets: [], sessionStates: [], nextOffset: startOffset };
@@ -4862,7 +4892,17 @@ async function readQueueBatch(queuePath, startOffset, maxBuckets) {
4862
4892
  // otherwise 400 the whole ingest batch and stall the queue.
4863
4893
  const sanitized = sanitizeBucketForUpload(bucket);
4864
4894
  if (!sanitized) continue;
4865
- bucketMap.set(`${source}|${model}|${hourStart}`, sanitized);
4895
+ // Contract v2: project_key is part of the bucket identity. Split hours
4896
+ // carry several rows with the same (source, model, hour) under different
4897
+ // project keys (plus the '' residual); omitting it here collapsed them
4898
+ // to the last row and then advanced the offset past the rest, losing the
4899
+ // attributed usage permanently. New queue rows already carry the
4900
+ // server-normalized basename (rollout's appendProjectSplitRows); old
4901
+ // owner/repo rows stay distinct here and let the server's own basename
4902
+ // dedupe pick the larger total instead of collapsing them locally.
4903
+ const projectKey =
4904
+ typeof sanitized.project_key === "string" ? sanitized.project_key.trim() : "";
4905
+ bucketMap.set(`${source}|${model}|${hourStart}|${projectKey}`, sanitized);
4866
4906
  linesRead += 1;
4867
4907
  if (linesRead >= maxBuckets) break;
4868
4908
  }
@@ -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/source-metadata.js)
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
  *
@@ -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 from cli-config.json → authInfo.authId
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
- return { cookie: auth.cookie, userId: auth.userId };
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. Extract userId — try cli-config.json first, fall back to JWT decode
103
- let userId = extractUserIdFromCliConfig(cliConfigPath);
104
- if (!userId) {
105
- userId = extractUserIdFromJwt(jwt);
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 cookie = `WorkosCursorSessionToken=${userId}%3A%3A${jwt}`;
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 extractUserIdFromCliConfig(configPath) {
130
+ function readCursorCliAuthId(configPath) {
129
131
  try {
130
132
  const config = JSON.parse(fs.readFileSync(configPath, "utf8"));
131
- return normalizeCursorSubject(config?.authInfo?.authId || "");
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 extractUserIdFromJwt(jwt) {
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 normalizeCursorSubject(payload.sub || "");
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
- throw new Error("Cursor session expired — re-login in Cursor to refresh");
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
- if (record.totalTokens <= 0 && record.inputTokens <= 0 && record.outputTokens <= 0) continue;
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,
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+
3
+ // Contract v2 (docs/cli-contract.md §2.4): the server keeps only the project
4
+ // basename for both hourly buckets and sessions. The CLI must apply the same
5
+ // rule before it writes a queue row or keys a reconciliation baseline —
6
+ // otherwise `owner/repo` and `repo` are two different local identities while
7
+ // the cloud stores one, which under-counts same-basename repos and makes
8
+ // reconcile report permanent false drift.
9
+ //
10
+ // This is the single implementation shared by the hourly writer, the session
11
+ // uploader and reconcile.
12
+ function basenameKey(value) {
13
+ const raw = String(value || "").replace(/[\\/]+$/, "");
14
+ if (!raw || raw === "." || raw === "..") return null;
15
+ const base = raw.split(/[\\/]/).pop().trim();
16
+ if (!base || base === "." || base === "..") return null;
17
+ // Control characters are rejected server-side; strip instead of failing.
18
+ // eslint-disable-next-line no-control-regex
19
+ const clean = base.replace(/[\u0000-\u001f\u007f]/g, "").slice(0, 120);
20
+ return clean || null;
21
+ }
22
+
23
+ module.exports = { basenameKey };
@@ -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
- const reportedPercent = Number(response.totalUsagePercentage ?? quota?.percentage);
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
- ? (used / total) * 100
282
- : response.isQuotaExceeded === true
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: typeof response.userType === "string" ? response.userType : null,
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(nowMs).toISOString(),
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 listRecentQoderRendererLogs(logRoot, maxFiles = 12) {
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
- mtimeMs = fs.statSync(full).mtimeMs;
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 logRootKey = `${envPrefix}_LOG_ROOT`;
654
- const homeKey = `${envPrefix}_HOME`;
655
- const explicitLogRoot =
656
- typeof env[logRootKey] === "string" && env[logRootKey].trim()
657
- ? path.resolve(env[logRootKey].trim())
658
- : null;
659
- const configuredRoot =
660
- typeof env[homeKey] === "string" && env[homeKey].trim()
661
- ? path.resolve(env[homeKey].trim())
662
- : null;
663
- const logRoot = explicitLogRoot || (configuredRoot
664
- ? path.join(configuredRoot, "logs")
665
- : platform === "darwin"
666
- ? path.join(home, "Library", "Application Support", appDir, "logs")
667
- : platform === "win32"
668
- ? path.join(env.APPDATA || path.join(home, "AppData", "Roaming"), appDir, "logs")
669
- : path.join(home, ".config", appDir, "logs"));
670
- for (const logPath of listRecentQoderRendererLogs(logRoot)) {
671
- try {
672
- const fd = fs.openSync(logPath, "r");
673
- try {
674
- const stat = fs.fstatSync(fd);
675
- const length = Math.min(stat.size, 512 * 1024);
676
- const buffer = Buffer.alloc(length);
677
- fs.readSync(fd, buffer, 0, length, Math.max(0, stat.size - length));
678
- const parsed = parseQoderQuotaLog(buffer.toString("utf8"));
679
- if (parsed) return parsed;
680
- } finally {
681
- fs.closeSync(fd);
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
- } catch (_error) {}
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: typeof rpcAuth?.userType === "string" ? rpcAuth.userType : null,
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,
@@ -13,6 +13,7 @@ const { readSqliteJsonRows, readSqliteJsonRowsAsync } = require("./sqlite-reader
13
13
  const wsl = require("./wsl-probe");
14
14
  const { resolveInstallPaths } = require("./install-resolver");
15
15
  const { expandHome } = require("./scan-roots");
16
+ const { basenameKey } = require("./project-key");
16
17
  const {
17
18
  consumeUsageDelta,
18
19
  createUsageDeltaState,
@@ -3575,27 +3576,48 @@ function appendProjectSplitRows({ group, model, aggregateBucket, projects, toApp
3575
3576
  if (!projects || projects.size === 0) return;
3576
3577
  const attributed = initTotals();
3577
3578
  const projectKeys = [...projects.keys()].sort();
3579
+ // The server stores only the basename (docs/cli-contract.md §2.4), so two
3580
+ // local projects such as `alice/api` and `bob/api` share one cloud identity.
3581
+ // Merge their totals under that normalized key here: emitting two rows with
3582
+ // the same wire key would make the server's request dedupe keep just one of
3583
+ // them and silently drop the other project's usage.
3584
+ const normalizedProjects = new Map();
3578
3585
  for (const projectKey of projectKeys) {
3579
3586
  const projectBucket = projects.get(projectKey);
3580
3587
  if (!projectBucket.totals) continue;
3581
3588
  addTotals(attributed, projectBucket.totals);
3582
- const totals = projectBucket.totals;
3583
- const usagePrecision = projectBucket.usage_precision || aggregateBucket.usage_precision || null;
3589
+ const normalizedKey = basenameKey(projectKey);
3590
+ if (!normalizedKey) continue;
3591
+ let entry = normalizedProjects.get(normalizedKey);
3592
+ if (!entry) {
3593
+ entry = { totals: initTotals(), usagePrecision: null, buckets: [] };
3594
+ normalizedProjects.set(normalizedKey, entry);
3595
+ }
3596
+ addTotals(entry.totals, projectBucket.totals);
3597
+ entry.usagePrecision = entry.usagePrecision || projectBucket.usage_precision || null;
3598
+ entry.buckets.push(projectBucket);
3599
+ }
3600
+
3601
+ for (const [normalizedKey, entry] of normalizedProjects) {
3602
+ const totals = entry.totals;
3603
+ const usagePrecision = entry.usagePrecision || aggregateBucket.usage_precision || null;
3584
3604
  const marker = usagePrecision ? `${totalsKey(totals)}|${usagePrecision}` : totalsKey(totals);
3585
- if (projectBucket.queuedHourlyKey === marker) continue;
3605
+ // Every contributing bucket must agree that this normalized row was
3606
+ // already queued; one changed contributor re-emits the merged total.
3607
+ if (entry.buckets.every((bucket) => bucket.queuedHourlyKey === marker)) continue;
3586
3608
  toAppend.push(
3587
3609
  JSON.stringify({
3588
3610
  source: group.source,
3589
3611
  model,
3590
3612
  hour_start: group.hourStart,
3591
- project_key: projectKey,
3613
+ project_key: normalizedKey,
3592
3614
  ...totalsRowFields(totals),
3593
3615
  usage_precision: usagePrecision || undefined,
3594
3616
  ...prioritySubsetOf(totals),
3595
3617
  ...creditsSubsetOf(totals),
3596
3618
  }),
3597
3619
  );
3598
- projectBucket.queuedHourlyKey = marker;
3620
+ for (const bucket of entry.buckets) bucket.queuedHourlyKey = marker;
3599
3621
  }
3600
3622
 
3601
3623
  const residual = cloneTotals(aggregateBucket.totals);
@@ -7101,21 +7123,40 @@ function qoderNewMessageKey(record, filePath, lineIndex = 0) {
7101
7123
  return `jsonl:${fallbackSuffix}|${record?.uuid || ""}`;
7102
7124
  }
7103
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
+
7104
7133
  function qoderNewTimestampMs(record) {
7105
- return coerceEpochMs(record?.timestamp)
7134
+ const ms = coerceEpochMs(record?.timestamp)
7106
7135
  || coerceEpochMs(record?.message?.timestamp)
7107
7136
  || parseIsoTimestampMs(record?.timestamp)
7108
7137
  || parseIsoTimestampMs(record?.message?.timestamp)
7109
7138
  || 0;
7139
+ return ms > MAX_QODER_TIMESTAMP_MS ? 0 : ms;
7110
7140
  }
7111
7141
 
7112
7142
  // Vendor credits (Qoder) ride along on token rows and are the only counter on
7113
7143
  // credits-only rows. They are a display-only dimension
7114
7144
  // (docs/sources-capture-audit.md §2): summed for visibility, never converted
7115
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
+
7116
7153
  function qoderUsageCredits(usage) {
7117
- const credits = Number(usage?.credits ?? usage?.original_credits ?? 0);
7118
- return Number.isFinite(credits) && credits > 0 ? Math.round(credits * 1e6) / 1e6 : 0;
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;
7119
7160
  }
7120
7161
 
7121
7162
  function normalizeQoderNewTokens(usage) {
@@ -7234,9 +7275,13 @@ async function parseQoderNewIncremental({
7234
7275
  const usage = msg.usage;
7235
7276
  if (!usage || typeof usage !== "object") continue;
7236
7277
  const base = normalizeQoderNewTokens(usage);
7237
- // Allow billable zero-token messages to still count conversation (no token delta)
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.
7238
7282
  const isBillable = usage.billable !== false;
7239
- if (!base && !isBillable) continue;
7283
+ const nominalCredits = qoderUsageCredits(usage);
7284
+ if (!base && !isBillable && nominalCredits <= 0) continue;
7240
7285
  const timestampMs = qoderNewTimestampMs(record);
7241
7286
  if (!timestampMs) continue;
7242
7287
  const bucketStart = toUtcHalfHourStart(new Date(timestampMs).toISOString());
@@ -7269,7 +7314,7 @@ async function parseQoderNewIncremental({
7269
7314
  total_tokens: 0,
7270
7315
  billable_total_tokens: 0,
7271
7316
  total_cost_usd: 0,
7272
- credits: qoderUsageCredits(usage),
7317
+ credits: nominalCredits,
7273
7318
  conversation_count: 1,
7274
7319
  };
7275
7320
  let projectKey = null;
@@ -158,7 +158,13 @@ function writeHiddenRunner({
158
158
  }) {
159
159
  fs.mkdirSync(binDir, { recursive: true });
160
160
  const vbsPath = vbsPathFor(binDir);
161
- fs.writeFileSync(vbsPath, buildHiddenRunnerVbs({ nodeExe, cliJs, fallbackCliJs }), { mode: 0o600 });
161
+ // wscript.exe reads a BOM-less .vbs with the system ANSI code page (GBK on
162
+ // Chinese Windows), so a UTF-8 path containing a non-ASCII username turns
163
+ // into mojibake and the hourly run cannot find node. UTF-16LE + BOM is what
164
+ // Windows Script Host expects; the XML definition already follows the same
165
+ // rule.
166
+ const body = buildHiddenRunnerVbs({ nodeExe, cliJs, fallbackCliJs });
167
+ fs.writeFileSync(vbsPath, Buffer.from(`\uFEFF${body}`, "utf16le"), { mode: 0o600 });
162
168
  return vbsPath;
163
169
  }
164
170
 
@@ -17,6 +17,7 @@ const path = require("node:path");
17
17
  const crypto = require("node:crypto");
18
18
 
19
19
  const { functionUrlFor, fetchFunctionResponse } = require("./function-url");
20
+ const { basenameKey } = require("./project-key");
20
21
 
21
22
  const INGEST_SLUG = "token-usage-ingest";
22
23
  const MAX_SESSIONS_PER_BATCH = 200;
@@ -66,17 +67,6 @@ function foldReasoningIntoOutput(tokens) {
66
67
  }
67
68
  }
68
69
 
69
- function basenameKey(value) {
70
- const raw = String(value || "").replace(/[\\/]+$/, "");
71
- if (!raw || raw === "." || raw === "..") return null;
72
- const base = raw.split(/[\\/]/).pop().trim();
73
- if (!base || base === "." || base === "..") return null;
74
- // Control characters are rejected server-side; strip instead of failing.
75
- // eslint-disable-next-line no-control-regex
76
- const clean = base.replace(/[\u0000-\u001f\u007f]/g, "").slice(0, 120);
77
- return clean || null;
78
- }
79
-
80
70
  function validSessionId(value) {
81
71
  if (typeof value !== "string") return false;
82
72
  const id = value.trim();
@@ -347,7 +337,30 @@ async function uploadSessions({
347
337
  error.upserted = upserted;
348
338
  throw error;
349
339
  }
350
- const data = await res.json().catch(() => ({}));
340
+ // A 2xx is not a confirmation: captive portals and reverse proxies answer
341
+ // with 200 HTML/empty bodies. Advancing the watermark on those would skip
342
+ // the batch forever, so require the contract's counter fields
343
+ // (docs/cli-contract.md §2.4) before recording progress.
344
+ const data = await res.json().catch(() => null);
345
+ const isCount = (value) =>
346
+ (typeof value === "number" || typeof value === "string") &&
347
+ value !== "" &&
348
+ Number.isFinite(Number(value));
349
+
350
+ if (
351
+ !data ||
352
+ typeof data !== "object" ||
353
+ !isCount(data.sessions_upserted) ||
354
+ !isCount(data.sessions_skipped)
355
+ ) {
356
+ const error = new Error(
357
+ `sessions upload was not confirmed (HTTP ${res.status}): unexpected response body`,
358
+ );
359
+ error.status = res.status;
360
+ error.uploaded = uploaded;
361
+ error.upserted = upserted;
362
+ throw error;
363
+ }
351
364
  batches += 1;
352
365
  uploaded += batch.length;
353
366
  upserted += Number(data?.sessions_upserted || 0);
@@ -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 TRAE_CN_APP_DIR = "TRAE SOLO CN";
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
- if (platform === "darwin") {
86
- return path.join(home, "Library", "Application Support", TRAE_CN_APP_DIR);
87
- }
88
- if (platform === "win32") {
89
- // Windows keeps the CN Work app under the roaming profile, mirroring the
90
- // macOS Application Support layout (APPDATA/TRAE SOLO CN/User/...).
91
- const appData =
92
- typeof env.APPDATA === "string" && env.APPDATA.trim()
93
- ? env.APPDATA.trim()
94
- : path.join(home, "AppData", "Roaming");
95
- return path.join(appData, TRAE_CN_APP_DIR);
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
- // No verified CN Work app-data layout on other platforms yet.
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,