tokenusage-cli 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/CHANGELOG.md +46 -19
  2. package/LICENSE +22 -22
  3. package/README.md +123 -94
  4. package/THIRD_PARTY_NOTICES.md +140 -140
  5. package/bin/tokenusage.js +69 -69
  6. package/package.json +59 -59
  7. package/src/cli.js +146 -134
  8. package/src/commands/device-login.js +205 -205
  9. package/src/commands/diagnostics.js +38 -38
  10. package/src/commands/doctor.js +110 -110
  11. package/src/commands/init.js +2484 -2436
  12. package/src/commands/pause.js +77 -0
  13. package/src/commands/sessions.js +29 -29
  14. package/src/commands/status.js +1758 -1747
  15. package/src/commands/sync.js +8048 -7934
  16. package/src/commands/uninstall.js +322 -312
  17. package/src/lib/account-usage-dedup.js +267 -267
  18. package/src/lib/antigravity-paths.js +48 -48
  19. package/src/lib/ark-agent-plan-limits.js +438 -438
  20. package/src/lib/ark-coding-plan-limits.js +537 -537
  21. package/src/lib/async-queue-reader.js +138 -138
  22. package/src/lib/atomic-json.js +27 -27
  23. package/src/lib/bearer-token.js +11 -11
  24. package/src/lib/categorizer-utils.js +232 -232
  25. package/src/lib/claude-categorizer.js +1343 -1343
  26. package/src/lib/claude-config.js +279 -279
  27. package/src/lib/claude-user-identity.js +56 -56
  28. package/src/lib/cli-ui.js +179 -179
  29. package/src/lib/cloud-account.js +541 -541
  30. package/src/lib/cloud-device-token.js +141 -141
  31. package/src/lib/cloud-sync-prefs.js +14 -14
  32. package/src/lib/cloud-usage-reset.js +115 -115
  33. package/src/lib/codex-config.js +595 -595
  34. package/src/lib/codex-context-breakdown.js +806 -806
  35. package/src/lib/codex-model-attribution.js +128 -128
  36. package/src/lib/codex-rollout-parser.js +1471 -1471
  37. package/src/lib/codex-service-tier.js +49 -49
  38. package/src/lib/codex-token-refresh.js +140 -140
  39. package/src/lib/codex-token-usage.js +195 -195
  40. package/src/lib/codex-usage-record.js +195 -195
  41. package/src/lib/collection-pause.js +77 -0
  42. package/src/lib/command-runner.js +313 -313
  43. package/src/lib/commandcode-limits.js +317 -317
  44. package/src/lib/context-health.js +124 -124
  45. package/src/lib/cursor-config.js +605 -605
  46. package/src/lib/cursor-store.js +1918 -1918
  47. package/src/lib/debug-flags.js +7 -7
  48. package/src/lib/devin-limits.js +249 -249
  49. package/src/lib/devin-usage.js +212 -212
  50. package/src/lib/diagnostics.js +383 -383
  51. package/src/lib/doctor.js +385 -385
  52. package/src/lib/dumate.js +95 -95
  53. package/src/lib/fs.js +455 -455
  54. package/src/lib/function-url.js +14 -14
  55. package/src/lib/gemini-config.js +291 -291
  56. package/src/lib/git-outcomes.js +243 -243
  57. package/src/lib/grok-context-breakdown.js +890 -890
  58. package/src/lib/grok-hook.js +360 -360
  59. package/src/lib/grok-limits.js +865 -865
  60. package/src/lib/grok-usage.js +98 -98
  61. package/src/lib/heatmap-compact.js +114 -114
  62. package/src/lib/ingest-sanitize.js +41 -41
  63. package/src/lib/init-flow.js +42 -42
  64. package/src/lib/install-resolver.js +170 -170
  65. package/src/lib/jsonl-lines.js +134 -134
  66. package/src/lib/kimi-model-repair.js +173 -173
  67. package/src/lib/kimi-profile.js +61 -61
  68. package/src/lib/kimi-session.js +216 -216
  69. package/src/lib/local-api.js +3588 -3588
  70. package/src/lib/machine-id.js +238 -238
  71. package/src/lib/multi-install-parser.js +113 -113
  72. package/src/lib/notify-command.js +38 -38
  73. package/src/lib/omp-hook.js +589 -589
  74. package/src/lib/openclaw-cli.js +104 -104
  75. package/src/lib/openclaw-hook.js +375 -375
  76. package/src/lib/openclaw-session-plugin.js +560 -560
  77. package/src/lib/opencode-config.js +121 -121
  78. package/src/lib/opencode-go-limits.js +807 -807
  79. package/src/lib/outcomes-engine.js +253 -253
  80. package/src/lib/passive-mode.js +219 -219
  81. package/src/lib/pet-packages.js +722 -722
  82. package/src/lib/pricing/curated-overrides.json +822 -822
  83. package/src/lib/pricing/index.js +379 -379
  84. package/src/lib/pricing/litellm-fetcher.js +172 -172
  85. package/src/lib/pricing/matcher.js +456 -456
  86. package/src/lib/pricing/seed-snapshot.json +1 -1
  87. package/src/lib/progress.js +76 -76
  88. package/src/lib/project-usage-purge.js +117 -117
  89. package/src/lib/prompt.js +24 -24
  90. package/src/lib/provider-status.js +104 -104
  91. package/src/lib/proxy-env.js +489 -489
  92. package/src/lib/proxy-settings.js +163 -163
  93. package/src/lib/qoder-cn-cli-limits.js +119 -119
  94. package/src/lib/qoder-limits.js +880 -880
  95. package/src/lib/quiet-warnings.js +26 -26
  96. package/src/lib/rollout.js +26005 -25966
  97. package/src/lib/runtime-config.js +9 -4
  98. package/src/lib/scan-roots.js +277 -277
  99. package/src/lib/scheduled-task.js +145 -0
  100. package/src/lib/sentry.js +231 -231
  101. package/src/lib/session-analytics.js +2972 -2972
  102. package/src/lib/session-performance.js +237 -237
  103. package/src/lib/session-upload.js +379 -379
  104. package/src/lib/skill-usage.js +267 -267
  105. package/src/lib/skills-manager.js +1591 -1591
  106. package/src/lib/source-metadata.js +48 -48
  107. package/src/lib/sqlite-reader.js +215 -215
  108. package/src/lib/star-cta.js +73 -73
  109. package/src/lib/subscription-manager.js +293 -293
  110. package/src/lib/subscriptions.js +508 -508
  111. package/src/lib/sync-report.js +138 -0
  112. package/src/lib/telemetry.js +193 -193
  113. package/src/lib/tracker-paths.js +16 -16
  114. package/src/lib/trae-cn-config.js +548 -548
  115. package/src/lib/trae-db.js +127 -127
  116. package/src/lib/trae-snapshot.js +230 -230
  117. package/src/lib/trae-sqlite.js +143 -143
  118. package/src/lib/trae-usage.js +121 -121
  119. package/src/lib/upload-queue.js +134 -134
  120. package/src/lib/upload-throttle.js +171 -171
  121. package/src/lib/usage-limits.js +4552 -4552
  122. package/src/lib/wrapped-aggregator.js +236 -236
  123. package/src/lib/wsl-probe.js +281 -281
  124. package/src/lib/zcode-limits.js +1172 -1172
  125. package/src/lib/zcode-reset-credits.js +66 -66
  126. package/test/audit-fixes.test.js +200 -0
  127. package/test/cli-smoke.test.js +53 -53
  128. package/test/collection-controls.test.js +210 -0
  129. package/test/ingest-sanitize.test.js +162 -162
  130. package/test/quiet-warnings.test.js +53 -53
  131. package/test/session-upload.test.js +427 -427
@@ -1,880 +1,880 @@
1
- "use strict";
2
-
3
- const crypto = require("node:crypto");
4
- const fs = require("node:fs");
5
- const net = require("node:net");
6
- const os = require("node:os");
7
- const path = require("node:path");
8
- const { fetchQoderCnCliLimits } = require("./qoder-cn-cli-limits");
9
-
10
- const QODER_SITES = {
11
- international: {
12
- id: "international",
13
- origin: "https://qoder.com",
14
- usageUrl: "https://qoder.com/api/v2/me/usages/big_model_credits",
15
- activityUrl: "https://openapi.qoder.sh/algo/api/v2/activity",
16
- domains: new Set(["qoder.com", "www.qoder.com"]),
17
- },
18
- china: {
19
- id: "china",
20
- origin: "https://qoder.cn",
21
- usageUrl: "https://qoder.cn/api/v2/me/usages/big_model_credits",
22
- activityUrl: "https://openapi.qoder.com.cn/algo/api/v2/activity",
23
- domains: new Set(["qoder.cn", "www.qoder.cn", "qoder.com.cn", "www.qoder.com.cn"]),
24
- },
25
- };
26
-
27
- const QODER_USER_AGENT =
28
- "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) " +
29
- "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36";
30
-
31
- // Qoder 1.18 serves promotional call buckets (including Ultimate Free Calls)
32
- // from its OpenAPI activity endpoint. The request uses the same COSY envelope
33
- // as Qoder CLI 1.0.22. Authentication comes from Qoder's already-running local
34
- // service over JSON-RPC; Token Usage never persists or logs those credentials.
35
- const QODER_ACTIVITY_URL = "https://openapi.qoder.sh/algo/api/v2/activity";
36
- const QODER_ULTIMATE_ACTIVITY_ID = "ultimate_200_free_invoke";
37
- const QODER_COSY_VERSION = "1.0.22";
38
- const QODER_ACTIVITY_CACHE_FILE = "qoder-activity-cache.json";
39
- const QODER_ACTIVITY_CACHE_MAX_AGE_MS = 24 * 60 * 60 * 1000;
40
- const QODER_LIMITS_CACHE_FILE = "qoder-usage-limits-cache.json";
41
- const QODER_LIMITS_CACHE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
42
- const QODER_LIMITS_CACHE_UNKNOWN_RESET_TTL_MS = 12 * 60 * 60 * 1000;
43
- const QODER_SERVER_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
44
- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDA8iMH5c02LilrsERw9t6Pv5Nc
45
- 4k6Pz1EaDicBMpdpxKduSZu5OANqUq8er4GM95omAGIOPOh+Nx0spthYA2BqGz+l
46
- 6HRkPJ7S236FZz73In/KVuLnwI8JJ2CbuJap8kvheCCZpmAWpb/cPx/3Vr/J6I17
47
- XcW+ML9FoCI6AOvOzwIDAQAB
48
- -----END PUBLIC KEY-----`;
49
-
50
- function finiteNumber(value, field) {
51
- const number = Number(value);
52
- if (!Number.isFinite(number)) {
53
- throw new Error(`Qoder usage response is missing ${field}.`);
54
- }
55
- return number;
56
- }
57
-
58
- function firstDefined(object, camel, snake) {
59
- return object?.[camel] ?? object?.[snake];
60
- }
61
-
62
- function normalizeResetAt(value) {
63
- if (value === null || value === undefined || value === "") return null;
64
- if (typeof value === "number" || /^\d+(?:\.\d+)?$/.test(String(value).trim())) {
65
- const raw = Number(value);
66
- if (!Number.isFinite(raw)) return null;
67
- const milliseconds = raw > 10_000_000_000 ? raw : raw * 1000;
68
- const date = new Date(milliseconds);
69
- return Number.isFinite(date.getTime()) ? date.toISOString() : null;
70
- }
71
- const timestamp = Date.parse(String(value));
72
- return Number.isFinite(timestamp) ? new Date(timestamp).toISOString() : null;
73
- }
74
-
75
- function quotaSummary(container) {
76
- return firstDefined(container, "quotaSummary", "quota_summary") || null;
77
- }
78
-
79
- function normalizeQuotaSummary(summary) {
80
- if (!summary || typeof summary !== "object") {
81
- throw new Error("Qoder usage response is missing totalQuota.quotaSummary.");
82
- }
83
- const used = finiteNumber(firstDefined(summary, "usedValue", "used_value"), "usedValue");
84
- const total = finiteNumber(firstDefined(summary, "limitValue", "limit_value"), "limitValue");
85
- const rawRemaining = firstDefined(summary, "remainingValue", "remaining_value");
86
- const remaining = rawRemaining === null || rawRemaining === undefined
87
- ? Math.max(0, total - used)
88
- : finiteNumber(rawRemaining, "remainingValue");
89
- const rawPercentage = firstDefined(summary, "usagePercentage", "usage_percentage");
90
- const providedPercentage = rawPercentage === null || rawPercentage === undefined
91
- ? null
92
- : finiteNumber(rawPercentage, "usagePercentage");
93
-
94
- if (used < 0 || total < 0 || remaining < 0) {
95
- throw new Error("Qoder quota values must be nonnegative.");
96
- }
97
- if (total === 0 && (used !== 0 || remaining !== 0)) {
98
- throw new Error("Qoder zero total quota must have zero usage and remaining.");
99
- }
100
- const usagePercentage = providedPercentage ?? (total > 0 ? (used / total) * 100 : 100);
101
- return {
102
- used,
103
- total,
104
- remaining,
105
- usagePercentage: Math.max(0, Math.min(100, usagePercentage)),
106
- unit: typeof summary.unit === "string" && summary.unit.trim() ? summary.unit.trim() : null,
107
- };
108
- }
109
-
110
- function normalizeQoderUsageResponse(response) {
111
- if (!response || typeof response !== "object") {
112
- throw new Error("Qoder usage response is not an object.");
113
- }
114
- const totalContainer = firstDefined(response, "totalQuota", "total_quota");
115
- const sharedContainer = firstDefined(response, "sharedQuota", "shared_quota");
116
- const base = normalizeQuotaSummary(quotaSummary(totalContainer));
117
- const sharedSummary = quotaSummary(sharedContainer);
118
- const shared = sharedSummary ? normalizeQuotaSummary(sharedSummary) : null;
119
-
120
- const used = base.used + (shared?.used || 0);
121
- const total = base.total + (shared?.total || 0);
122
- const remaining = base.remaining + (shared?.remaining || 0);
123
- const usedPercent = shared
124
- ? total > 0
125
- ? (used / total) * 100
126
- : 100
127
- : base.usagePercentage;
128
-
129
- return {
130
- configured: true,
131
- error: null,
132
- primary_window: {
133
- used_percent: Math.max(0, Math.min(100, usedPercent)),
134
- reset_at: normalizeResetAt(firstDefined(response, "nextResetAt", "next_reset_at")),
135
- used_credits: used,
136
- limit_credits: total,
137
- remaining_credits: remaining,
138
- unit: base.unit || shared?.unit || null,
139
- },
140
- source: "provider-api",
141
- };
142
- }
143
-
144
- function qoderDataRoot({
145
- home = os.homedir(),
146
- env = process.env,
147
- platform = process.platform,
148
- appDir = "Qoder",
149
- envPrefix = "QODER",
150
- } = {}) {
151
- const homeKey = `${envPrefix}_HOME`;
152
- if (typeof env[homeKey] === "string" && env[homeKey].trim()) {
153
- return path.resolve(env[homeKey].trim());
154
- }
155
- if (platform === "darwin") {
156
- return path.join(home, "Library", "Application Support", appDir);
157
- }
158
- if (platform === "win32") {
159
- return path.join(env.APPDATA || path.join(home, "AppData", "Roaming"), appDir);
160
- }
161
- return path.join(home, ".config", appDir);
162
- }
163
-
164
- function qoderRpcRequest(method, params = {}, {
165
- home = os.homedir(),
166
- env = process.env,
167
- platform = process.platform,
168
- appDir = "Qoder",
169
- envPrefix = "QODER",
170
- timeoutMs = 1500,
171
- netModule = net,
172
- } = {}) {
173
- return new Promise((resolve, reject) => {
174
- const infoPath = path.join(qoderDataRoot({ home, env, platform, appDir, envPrefix }), "SharedClientCache", ".info.json");
175
- let info;
176
- try {
177
- info = JSON.parse(fs.readFileSync(infoPath, "utf8"));
178
- } catch (_error) {
179
- reject(new Error("Qoder local service is not running."));
180
- return;
181
- }
182
- const socketPath = typeof info?.ipcServerPath === "string" ? info.ipcServerPath.trim() : "";
183
- if (!socketPath) {
184
- reject(new Error("Qoder local service endpoint is unavailable."));
185
- return;
186
- }
187
-
188
- let settled = false;
189
- let buffer = Buffer.alloc(0);
190
- const socket = netModule.createConnection(socketPath);
191
- const timer = setTimeout(() => finish(new Error("Qoder local service request timed out.")), timeoutMs);
192
-
193
- function finish(error, value) {
194
- if (settled) return;
195
- settled = true;
196
- clearTimeout(timer);
197
- socket.destroy();
198
- if (error) reject(error);
199
- else resolve(value);
200
- }
201
-
202
- socket.on("connect", () => {
203
- const body = Buffer.from(JSON.stringify({
204
- jsonrpc: "2.0",
205
- id: 1,
206
- method,
207
- params,
208
- }));
209
- socket.write(`Content-Length: ${body.length}\r\n\r\n`);
210
- socket.write(body);
211
- });
212
- socket.on("error", (error) => finish(error));
213
- socket.on("data", (chunk) => {
214
- buffer = Buffer.concat([buffer, chunk]);
215
- const headerEnd = buffer.indexOf("\r\n\r\n");
216
- if (headerEnd < 0) return;
217
- const match = /Content-Length:\s*(\d+)/i.exec(buffer.subarray(0, headerEnd).toString("ascii"));
218
- if (!match) {
219
- finish(new Error("Qoder local service returned an invalid response."));
220
- return;
221
- }
222
- const bodyLength = Number(match[1]);
223
- const bodyStart = headerEnd + 4;
224
- if (!Number.isFinite(bodyLength) || bodyLength < 0 || bodyLength > 4 * 1024 * 1024) {
225
- finish(new Error("Qoder local service response is too large."));
226
- return;
227
- }
228
- if (buffer.length < bodyStart + bodyLength) return;
229
- try {
230
- const message = JSON.parse(buffer.subarray(bodyStart, bodyStart + bodyLength).toString("utf8"));
231
- if (message.error) {
232
- finish(new Error(message.error.message || "Qoder local service request failed."));
233
- } else {
234
- finish(null, message.result);
235
- }
236
- } catch (_error) {
237
- finish(new Error("Qoder local service returned invalid JSON."));
238
- }
239
- });
240
- });
241
- }
242
-
243
- function normalizeQoderAddOnQuota(quota) {
244
- if (quota == null) return null;
245
- const used = Number(quota.used);
246
- const total = Number(quota.total);
247
- const remaining = quota.remaining == null ? Math.max(0, total - used) : Number(quota.remaining);
248
- if (quota.used == null || quota.total == null
249
- || ![used, total, remaining].every(Number.isFinite) || Math.min(used, total, remaining) < 0
250
- || (total === 0 && (used !== 0 || remaining !== 0))) {
251
- throw new Error("Qoder add-on quota values are invalid.");
252
- }
253
- return {
254
- used_percent: total > 0 ? Math.min(100, (used / total) * 100) : 0,
255
- // The official addOnQuota has no renewal date. Plan expiry does not apply.
256
- reset_at: null,
257
- used_credits: used,
258
- limit_credits: total,
259
- remaining_credits: remaining,
260
- unit: typeof quota.unit === "string" && quota.unit.trim() ? quota.unit.trim() : "credits",
261
- };
262
- }
263
-
264
- function normalizeQoderRpcUsage(response) {
265
- if (!response || typeof response !== "object") return null;
266
- const quota = response.userQuota;
267
- // Qoder CN CLI 1.1.71 renders userQuota and addOnQuota as separate buckets.
268
- // Only its account-level total_remaining adds them together.
269
- const addOnWindow = normalizeQoderAddOnQuota(response.addOnQuota);
270
- if ((!quota || typeof quota !== "object") && !addOnWindow) return null;
271
- const used = quota ? finiteNumber(quota.used, "userQuota.used") : 0;
272
- const total = quota ? finiteNumber(quota.total, "userQuota.total") : 0;
273
- const remaining = quota ? finiteNumber(quota.remaining, "userQuota.remaining") : 0;
274
- const reportedPercent = Number(response.totalUsagePercentage ?? quota?.percentage);
275
- const usedPercent = total === 0
276
- ? 0
277
- : addOnWindow
278
- ? (used / total) * 100
279
- : response.isQuotaExceeded === true
280
- ? 100
281
- : Number.isFinite(reportedPercent)
282
- ? reportedPercent
283
- : (used / total) * 100;
284
- const normalizedExpiry = normalizeResetAt(response.expiresAt);
285
- const expiryMs = normalizedExpiry ? Date.parse(normalizedExpiry) : NaN;
286
- return {
287
- configured: true,
288
- error: null,
289
- plan_label: typeof response.userType === "string" ? response.userType : null,
290
- quota_exceeded: response.isQuotaExceeded === true,
291
- primary_window: quota ? {
292
- used_percent: Math.max(0, Math.min(100, usedPercent)),
293
- // Qoder uses 9999-12-31 as a no-expiry sentinel for Free accounts.
294
- reset_at: Number.isFinite(expiryMs) && expiryMs < Date.UTC(2100, 0, 1)
295
- ? normalizedExpiry
296
- : null,
297
- used_credits: used,
298
- limit_credits: total,
299
- remaining_credits: remaining,
300
- unit: typeof quota.unit === "string" && quota.unit.trim() ? quota.unit.trim() : "credits",
301
- } : null,
302
- ...(addOnWindow ? { tertiary_window: addOnWindow } : {}),
303
- source: "local-ipc",
304
- };
305
- }
306
-
307
- function normalizeQoderActivityResponse(response, { nowMs = Date.now() } = {}) {
308
- if (!response || typeof response !== "object") {
309
- throw new Error("Qoder activity response is not an object.");
310
- }
311
- if (response.code !== undefined && Number(response.code) !== 0) {
312
- throw new Error(`Qoder activity API returned ${response.msg || `code ${response.code}`}.`);
313
- }
314
- const activities = Array.isArray(response.data?.activities) ? response.data.activities : [];
315
- const activity = activities.find((entry) => {
316
- if (!entry || entry.activityId !== QODER_ULTIMATE_ACTIVITY_ID || entry.eligible === false) return false;
317
- if (String(entry.tagStyle || "").toUpperCase() === "EXPIRED") return false;
318
- const endAt = Number(entry.activityEndAt);
319
- return !Number.isFinite(endAt) || endAt <= 0 || endAt > nowMs;
320
- });
321
- if (!activity) return null;
322
- const used = finiteNumber(activity.used, "activity.used");
323
- const total = finiteNumber(activity.limit, "activity.limit");
324
- const rawRemaining = Number(activity.remaining);
325
- const remaining = Number.isFinite(rawRemaining) ? rawRemaining : Math.max(0, total - used);
326
- if (used < 0 || total <= 0 || remaining < 0) {
327
- throw new Error("Qoder activity quota values are invalid.");
328
- }
329
- return {
330
- used_percent: Math.max(0, Math.min(100, (used / total) * 100)),
331
- reset_at: normalizeResetAt(activity.activityEndAt),
332
- used_credits: used,
333
- limit_credits: total,
334
- remaining_credits: remaining,
335
- unit: "calls",
336
- activity_id: QODER_ULTIMATE_ACTIVITY_ID,
337
- };
338
- }
339
-
340
- function qoderActivityCachePath({ home = os.homedir(), namespace } = {}) {
341
- const file = namespace
342
- ? `qoder-${namespace}-activity-cache.json`
343
- : QODER_ACTIVITY_CACHE_FILE;
344
- return path.join(home, ".tokenusage", "tracker", file);
345
- }
346
-
347
- function readQoderActivityCache({
348
- home = os.homedir(),
349
- nowMs = Date.now(),
350
- namespace,
351
- maxAgeMs = QODER_ACTIVITY_CACHE_MAX_AGE_MS,
352
- } = {}) {
353
- try {
354
- const parsed = JSON.parse(fs.readFileSync(qoderActivityCachePath({ home, namespace }), "utf8"));
355
- const window = parsed?.activity_window;
356
- const cachedAtMs = Date.parse(parsed?.cached_at || "");
357
- if (!window || !Number.isFinite(cachedAtMs) || cachedAtMs > nowMs + 60_000) return null;
358
- const resetAtMs = Date.parse(window.reset_at || "");
359
- if (Number.isFinite(resetAtMs)) {
360
- if (resetAtMs <= nowMs) return null;
361
- } else if (nowMs - cachedAtMs > maxAgeMs) {
362
- return null;
363
- }
364
- const used = Number(window.used_credits);
365
- const total = Number(window.limit_credits);
366
- const remaining = Number(window.remaining_credits);
367
- if (!Number.isFinite(used) || !Number.isFinite(total) || !Number.isFinite(remaining)
368
- || used < 0 || total <= 0 || remaining < 0) return null;
369
- return window;
370
- } catch (_error) {
371
- return null;
372
- }
373
- }
374
-
375
- function writeQoderActivityCache(window, {
376
- home = os.homedir(),
377
- nowMs = Date.now(),
378
- namespace,
379
- } = {}) {
380
- if (!window) return;
381
- const cachePath = qoderActivityCachePath({ home, namespace });
382
- const payload = {
383
- activity_window: window,
384
- cached_at: new Date(nowMs).toISOString(),
385
- };
386
- try {
387
- fs.mkdirSync(path.dirname(cachePath), { recursive: true });
388
- const tmpPath = `${cachePath}.${process.pid}.tmp`;
389
- fs.writeFileSync(tmpPath, JSON.stringify(payload, null, 2), { encoding: "utf8", mode: 0o600 });
390
- fs.renameSync(tmpPath, cachePath);
391
- } catch (_error) {}
392
- }
393
-
394
- function qoderLimitsCachePath({ home = os.homedir(), namespace } = {}) {
395
- const file = namespace
396
- ? `qoder-${namespace}-usage-limits-cache.json`
397
- : QODER_LIMITS_CACHE_FILE;
398
- return path.join(home, ".tokenusage", "tracker", file);
399
- }
400
-
401
- function qoderCachedWindow(window, { cachedAtMs, nowMs } = {}) {
402
- if (!window || typeof window !== "object") return null;
403
- const resetAtMs = Date.parse(window.reset_at || "");
404
- if (Number.isFinite(resetAtMs)) return resetAtMs > nowMs ? window : null;
405
- return nowMs - cachedAtMs <= QODER_LIMITS_CACHE_UNKNOWN_RESET_TTL_MS ? window : null;
406
- }
407
-
408
- function readQoderLimitsCache({
409
- home = os.homedir(),
410
- nowMs = Date.now(),
411
- namespace,
412
- } = {}) {
413
- try {
414
- const raw = JSON.parse(fs.readFileSync(qoderLimitsCachePath({ home, namespace }), "utf8"))?.qoder;
415
- const cachedAtMs = Date.parse(raw?.cached_at || "");
416
- if (!Number.isFinite(cachedAtMs) || cachedAtMs > nowMs + 60_000) return null;
417
- const primaryWindow = qoderCachedWindow(raw.primary_window, { cachedAtMs, nowMs });
418
- const secondaryWindow = qoderCachedWindow(raw.secondary_window, { cachedAtMs, nowMs });
419
- const tertiaryWindow = qoderCachedWindow(raw.tertiary_window, { cachedAtMs, nowMs });
420
- if (!primaryWindow && !secondaryWindow && !tertiaryWindow) return null;
421
- const hasUnexpiredDatedWindow = [primaryWindow, secondaryWindow, tertiaryWindow]
422
- .some((window) => Number.isFinite(Date.parse(window?.reset_at || "")));
423
- if (nowMs - cachedAtMs > QODER_LIMITS_CACHE_MAX_AGE_MS && !hasUnexpiredDatedWindow) {
424
- return null;
425
- }
426
- return {
427
- configured: true,
428
- error: null,
429
- plan_label: typeof raw.plan_label === "string" ? raw.plan_label : null,
430
- quota_exceeded: raw.quota_exceeded === true,
431
- primary_window: primaryWindow,
432
- secondary_window: secondaryWindow,
433
- ...(tertiaryWindow ? { tertiary_window: tertiaryWindow } : {}),
434
- cached: true,
435
- stale: true,
436
- cached_at: raw.cached_at,
437
- source: "disk-cache",
438
- };
439
- } catch (_error) {
440
- return null;
441
- }
442
- }
443
-
444
- function writeQoderLimitsCache(limits, {
445
- home = os.homedir(),
446
- nowMs = Date.now(),
447
- namespace,
448
- } = {}) {
449
- if (!limits?.configured || limits.error || (!limits.primary_window && !limits.secondary_window && !limits.tertiary_window)) return;
450
- const cachePath = qoderLimitsCachePath({ home, namespace });
451
- const payload = {
452
- qoder: {
453
- plan_label: limits.plan_label || null,
454
- quota_exceeded: limits.quota_exceeded === true,
455
- primary_window: limits.primary_window || null,
456
- secondary_window: limits.secondary_window || null,
457
- ...(limits.tertiary_window ? { tertiary_window: limits.tertiary_window } : {}),
458
- cached_at: new Date(nowMs).toISOString(),
459
- },
460
- };
461
- try {
462
- fs.mkdirSync(path.dirname(cachePath), { recursive: true });
463
- const tmpPath = `${cachePath}.${process.pid}.tmp`;
464
- fs.writeFileSync(tmpPath, JSON.stringify(payload, null, 2), { encoding: "utf8", mode: 0o600 });
465
- fs.renameSync(tmpPath, cachePath);
466
- } catch (_error) {}
467
- }
468
-
469
- function buildQoderActivityHeaders(authStatus, {
470
- nowMs = Date.now(),
471
- randomUUID = crypto.randomUUID,
472
- } = {}) {
473
- const userId = String(authStatus?.id || authStatus?.accountId || "").trim();
474
- const accessToken = String(authStatus?.token || "").trim();
475
- if (!userId || !accessToken) {
476
- throw new Error("Qoder local session is missing activity credentials.");
477
- }
478
- const temporaryKey = Buffer.from(randomUUID().replace(/-/g, "").slice(0, 16), "ascii");
479
- const cosyKey = crypto.publicEncrypt(
480
- { key: QODER_SERVER_PUBLIC_KEY, padding: crypto.constants.RSA_PKCS1_PADDING },
481
- temporaryKey,
482
- ).toString("base64");
483
- const identity = {
484
- name: authStatus.name || "",
485
- aid: userId,
486
- uid: userId,
487
- yx_uid: authStatus.yxUid || "",
488
- organization_id: authStatus.orgId || "",
489
- organization_name: authStatus.orgName || "",
490
- user_type: authStatus.userType || "personal_standard",
491
- security_oauth_token: accessToken,
492
- refresh_token: authStatus.refreshToken || "",
493
- };
494
- const cipher = crypto.createCipheriv("aes-128-cbc", temporaryKey, temporaryKey);
495
- const info = Buffer.concat([
496
- cipher.update(Buffer.from(JSON.stringify(identity), "utf8")),
497
- cipher.final(),
498
- ]).toString("base64");
499
- const payload = Buffer.from(JSON.stringify({
500
- version: "v1",
501
- requestId: randomUUID(),
502
- info,
503
- cosyVersion: QODER_COSY_VERSION,
504
- ideVersion: "",
505
- }), "utf8").toString("base64");
506
- const cosyDate = String(Math.floor(nowMs / 1000));
507
- const signature = crypto
508
- .createHash("md5")
509
- .update(`${payload}\n${cosyKey}\n${cosyDate}\n\n/api/v2/activity`, "utf8")
510
- .digest("hex");
511
- const machineId = randomUUID();
512
- return {
513
- "cosy-data-policy": "agree",
514
- "cosy-machinetype": "5",
515
- "cosy-clienttype": "5",
516
- "cosy-date": cosyDate,
517
- "cosy-user": userId,
518
- "cosy-key": cosyKey,
519
- "cache-control": "no-cache",
520
- "cosy-business-product": "cli",
521
- "cosy-business-type": "agent",
522
- "cosy-scene": "assistant",
523
- accept: "application/json",
524
- authorization: `Bearer COSY.${payload}.${signature}`,
525
- "accept-encoding": "identity",
526
- "cosy-version": QODER_COSY_VERSION,
527
- "cosy-machineid": machineId,
528
- "cosy-machinetoken": machineId,
529
- "login-version": "v2",
530
- "user-agent": "Go-http-client/2.0",
531
- };
532
- }
533
-
534
- async function fetchQoderActivity(authStatus, fetchImpl = fetch, options = {}) {
535
- const activityUrl = options.activityUrl || QODER_ACTIVITY_URL;
536
- const response = await fetchImpl(activityUrl, {
537
- method: "GET",
538
- headers: buildQoderActivityHeaders(authStatus, options),
539
- });
540
- if (response.status === 401 || response.status === 403) {
541
- throw new Error("Qoder activity session expired.");
542
- }
543
- if (!response.ok) {
544
- throw new Error(`Qoder activity API returned HTTP ${response.status}.`);
545
- }
546
- return normalizeQoderActivityResponse(await response.json(), options);
547
- }
548
-
549
- function qoderRequestHeaders(cookieHeader, site) {
550
- return {
551
- Cookie: cookieHeader,
552
- Accept: "application/json, text/plain, */*",
553
- "Accept-Language": "en-US,en;q=0.9",
554
- "User-Agent": QODER_USER_AGENT,
555
- Origin: site.origin,
556
- Referer: `${site.origin}/account/usage`,
557
- "X-Requested-With": "XMLHttpRequest",
558
- "Bx-V": "2.5.35",
559
- };
560
- }
561
-
562
- async function fetchQoderUsage(cookieHeader, site, fetchImpl) {
563
- const response = await fetchImpl(site.usageUrl, {
564
- method: "GET",
565
- headers: qoderRequestHeaders(cookieHeader, site),
566
- });
567
- if (response.status === 401 || response.status === 403) {
568
- const error = new Error("Qoder login expired. Sign in at qoder.com again.");
569
- error.code = "AUTH_EXPIRED";
570
- throw error;
571
- }
572
- if (!response.ok) {
573
- throw new Error(`Qoder usage API returned HTTP ${response.status}.`);
574
- }
575
- return normalizeQoderUsageResponse(await response.json());
576
- }
577
-
578
- function listRecentQoderRendererLogs(logRoot, maxFiles = 12) {
579
- if (!fs.existsSync(logRoot)) return [];
580
- const files = [];
581
- const stack = [{ dir: logRoot, depth: 0 }];
582
- while (stack.length > 0 && files.length < 2000) {
583
- const current = stack.pop();
584
- let entries;
585
- try {
586
- entries = fs.readdirSync(current.dir, { withFileTypes: true });
587
- } catch (_error) {
588
- continue;
589
- }
590
- for (const entry of entries) {
591
- const full = path.join(current.dir, entry.name);
592
- if (entry.isDirectory() && current.depth < 4) {
593
- stack.push({ dir: full, depth: current.depth + 1 });
594
- } else if (entry.isFile() && entry.name === "renderer.log") {
595
- let mtimeMs = 0;
596
- try {
597
- mtimeMs = fs.statSync(full).mtimeMs;
598
- } catch (_error) {}
599
- files.push({ full, mtimeMs });
600
- }
601
- }
602
- }
603
- return files
604
- .sort((a, b) => b.mtimeMs - a.mtimeMs)
605
- .slice(0, maxFiles)
606
- .map((entry) => entry.full);
607
- }
608
-
609
- function parseQoderQuotaLog(text) {
610
- if (typeof text !== "string" || !text) return null;
611
- const matches = Array.from(text.matchAll(
612
- /userType=([^,\s]+)[\s\S]*?isQuotaExceeded=(true|false)[\s\S]*?userQuota(?:=|\s+)used=([0-9.]+),\s*total=([0-9.]+),\s*remaining=([0-9.]+),\s*percentage=([0-9.]+),\s*unit=([^,\s]+)/g,
613
- ));
614
- const match = matches.at(-1);
615
- if (!match) return null;
616
- const quotaExceeded = match[2] === "true";
617
- const used = Number(match[3]);
618
- const total = Number(match[4]);
619
- const remaining = Number(match[5]);
620
- const percentage = Number(match[6]);
621
- if (![used, total, remaining, percentage].every(Number.isFinite)) return null;
622
- return {
623
- configured: true,
624
- error: null,
625
- plan_label: match[1],
626
- quota_exceeded: quotaExceeded,
627
- primary_window: {
628
- used_percent: total === 0
629
- ? 0
630
- : quotaExceeded
631
- ? 100
632
- : Math.max(0, Math.min(100, percentage)),
633
- reset_at: null,
634
- used_credits: used,
635
- limit_credits: total,
636
- remaining_credits: remaining,
637
- unit: match[7],
638
- },
639
- source: "local-log",
640
- };
641
- }
642
-
643
- function readQoderLocalQuota({
644
- home = os.homedir(),
645
- platform = process.platform,
646
- env = process.env,
647
- appDir = "Qoder",
648
- envPrefix = "QODER",
649
- } = {}) {
650
- const logRootKey = `${envPrefix}_LOG_ROOT`;
651
- const homeKey = `${envPrefix}_HOME`;
652
- const explicitLogRoot =
653
- typeof env[logRootKey] === "string" && env[logRootKey].trim()
654
- ? path.resolve(env[logRootKey].trim())
655
- : null;
656
- const configuredRoot =
657
- typeof env[homeKey] === "string" && env[homeKey].trim()
658
- ? path.resolve(env[homeKey].trim())
659
- : null;
660
- const logRoot = explicitLogRoot || (configuredRoot
661
- ? path.join(configuredRoot, "logs")
662
- : platform === "darwin"
663
- ? path.join(home, "Library", "Application Support", appDir, "logs")
664
- : platform === "win32"
665
- ? path.join(env.APPDATA || path.join(home, "AppData", "Roaming"), appDir, "logs")
666
- : path.join(home, ".config", appDir, "logs"));
667
- for (const logPath of listRecentQoderRendererLogs(logRoot)) {
668
- try {
669
- const fd = fs.openSync(logPath, "r");
670
- try {
671
- const stat = fs.fstatSync(fd);
672
- const length = Math.min(stat.size, 512 * 1024);
673
- const buffer = Buffer.alloc(length);
674
- fs.readSync(fd, buffer, 0, length, Math.max(0, stat.size - length));
675
- const parsed = parseQoderQuotaLog(buffer.toString("utf8"));
676
- if (parsed) return parsed;
677
- } finally {
678
- fs.closeSync(fd);
679
- }
680
- } catch (_error) {}
681
- }
682
- return null;
683
- }
684
-
685
- function siteFromEnv(value) {
686
- const normalized = String(value || "").trim().toLowerCase();
687
- return normalized === "cn" || normalized === "china" || normalized.includes(".cn")
688
- ? QODER_SITES.china
689
- : QODER_SITES.international;
690
- }
691
-
692
- async function fetchQoderLimits({
693
- home = os.homedir(),
694
- env = process.env,
695
- platform = process.platform,
696
- appDir = "Qoder",
697
- envPrefix = "QODER",
698
- site = QODER_SITES.international,
699
- sitePinned = false,
700
- cacheNamespace,
701
- fetchImpl = fetch,
702
- rpcRequest = qoderRpcRequest,
703
- nowMs = Date.now(),
704
- cliLimitsRequest,
705
- } = {}) {
706
- let rpcUsage = null;
707
- let rpcAuth = null;
708
- let activityWindow = null;
709
- let activitySource = null;
710
- const rpcOptions = { home, env, platform, appDir, envPrefix };
711
- // Qoder's shared client accepts only one reliable request at a time. Parallel
712
- // connections intermittently time out even while the desktop app is running.
713
- try {
714
- rpcUsage = normalizeQoderRpcUsage(await rpcRequest("credit/usage", {}, rpcOptions));
715
- } catch (_error) {}
716
- try {
717
- const authResult = await rpcRequest("auth/status", {}, rpcOptions);
718
- if (authResult && typeof authResult === "object") rpcAuth = authResult;
719
- } catch (_error) {}
720
- if (rpcAuth) {
721
- try {
722
- activityWindow = await fetchQoderActivity(rpcAuth, fetchImpl, { nowMs, activityUrl: site.activityUrl });
723
- if (activityWindow) {
724
- activitySource = "provider-api";
725
- writeQoderActivityCache(activityWindow, { home, nowMs, namespace: cacheNamespace });
726
- }
727
- } catch (_error) {}
728
- }
729
- // Qoder's activity endpoint occasionally succeeds with an empty activities
730
- // array while the promotion is still active. Treat that as a transient
731
- // omission, not an authoritative deletion: an activity carries its own
732
- // expiry, so the last observed window remains valid until reset_at.
733
- if (!activityWindow) {
734
- activityWindow = readQoderActivityCache({ home, nowMs, namespace: cacheNamespace });
735
- if (activityWindow) activitySource = "disk-cache";
736
- }
737
- if (rpcUsage) {
738
- if (!rpcUsage.plan_label && typeof rpcAuth?.userType === "string") {
739
- rpcUsage.plan_label = rpcAuth.userType;
740
- }
741
- if (activityWindow) rpcUsage.secondary_window = activityWindow;
742
- rpcUsage.source = activityWindow
743
- ? `local-ipc+${activitySource === "disk-cache" ? "cached-activity" : "provider-api"}`
744
- : "local-ipc";
745
- writeQoderLimitsCache(rpcUsage, { home, nowMs, namespace: cacheNamespace });
746
- return rpcUsage;
747
- }
748
-
749
- let cliError = null;
750
- if (cliLimitsRequest) {
751
- try {
752
- const cliUsage = await cliLimitsRequest({ home, env, fetchImpl, normalizeRpcUsage: normalizeQoderRpcUsage });
753
- if (cliUsage) {
754
- if (activityWindow) cliUsage.secondary_window = activityWindow;
755
- writeQoderLimitsCache(cliUsage, { home, nowMs, namespace: cacheNamespace });
756
- return cliUsage;
757
- }
758
- } catch (error) {
759
- cliError = error;
760
- }
761
- }
762
-
763
- // Once native sources are unavailable, prefer a bounded disk snapshot before
764
- // the manual-cookie or local-log fallback.
765
- const cachedLimits = readQoderLimitsCache({ home, nowMs, namespace: cacheNamespace });
766
- if (cachedLimits) {
767
- if (activityWindow) cachedLimits.secondary_window = activityWindow;
768
- return cachedLimits;
769
- }
770
-
771
- // Manual-cookie fallback reads an envPrefix-specific key: QODER_COOKIE for
772
- // the international flow, QODER_CN_COOKIE for the CN flow — the two installs
773
- // hold different sessions and must never share a cookie.
774
- const cookieKey = `${envPrefix}_COOKIE`;
775
- const manualCookie = typeof env[cookieKey] === "string" ? env[cookieKey].trim() : "";
776
- // QODER_SITE is an international-flow knob. A pinned site (the CN fetch)
777
- // must never be overridden by it — the CN flow always targets china.
778
- const manualSite = sitePinned ? site : env.QODER_SITE ? siteFromEnv(env.QODER_SITE) : site;
779
- const sessions = manualCookie
780
- ? [{
781
- cookieHeader: manualCookie,
782
- site: manualSite,
783
- sourceLabel: cookieKey,
784
- }]
785
- : [];
786
-
787
- let lastError = cliError;
788
- for (const session of sessions) {
789
- try {
790
- const result = await fetchQoderUsage(session.cookieHeader, session.site, fetchImpl);
791
- // Qoder 1.18 can return an all-zero active plan with usage_percentage=0
792
- // while the desktop client separately marks the account quota-exceeded.
793
- // Preserve that status as metadata, but match Qoder's Credits UI by
794
- // rendering an empty 0/0 bucket as 0%, not a full red 100% bar.
795
- const local = result.primary_window?.limit_credits === 0
796
- ? readQoderLocalQuota({ home, platform, env, appDir, envPrefix })
797
- : null;
798
- if (local) {
799
- result.quota_exceeded = local.quota_exceeded === true;
800
- result.primary_window.reset_at = null;
801
- result.source = "provider-api+local-log";
802
- result.plan_label = local.plan_label || null;
803
- }
804
- if (activityWindow) {
805
- result.secondary_window = activityWindow;
806
- result.source += activitySource === "disk-cache" ? "+cached-activity" : "+activity";
807
- }
808
- const liveResult = {
809
- ...result,
810
- cookie_source: session.sourceLabel,
811
- site: session.site.id,
812
- };
813
- writeQoderLimitsCache(liveResult, { home, nowMs, namespace: cacheNamespace });
814
- return liveResult;
815
- } catch (error) {
816
- lastError = error;
817
- }
818
- }
819
-
820
- const local = readQoderLocalQuota({ home, platform, env, appDir, envPrefix });
821
- if (local) {
822
- if (activityWindow) {
823
- local.secondary_window = activityWindow;
824
- local.source += activitySource === "disk-cache" ? "+cached-activity" : "+activity";
825
- }
826
- writeQoderLimitsCache(local, { home, nowMs, namespace: cacheNamespace });
827
- return local;
828
- }
829
- if (activityWindow) {
830
- return {
831
- configured: true,
832
- error: null,
833
- plan_label: typeof rpcAuth?.userType === "string" ? rpcAuth.userType : null,
834
- primary_window: null,
835
- secondary_window: activityWindow,
836
- source: activitySource === "disk-cache" ? "cached-activity" : "local-ipc+provider-api",
837
- };
838
- }
839
- if (lastError) {
840
- return {
841
- configured: true,
842
- error: lastError.message || "Qoder usage fetch failed.",
843
- auth_action_required: lastError.code === "AUTH_EXPIRED" ? "reauth" : undefined,
844
- };
845
- }
846
- return { configured: false };
847
- }
848
-
849
- // CN has its own CLI credentials, legacy desktop root and cache namespace.
850
- function fetchQoderCnLimits(opts = {}) {
851
- return fetchQoderLimits({
852
- ...opts,
853
- appDir: "QoderCN",
854
- envPrefix: "QODER_CN",
855
- site: QODER_SITES.china,
856
- sitePinned: true,
857
- cacheNamespace: "cn",
858
- cliLimitsRequest: fetchQoderCnCliLimits,
859
- });
860
- }
861
-
862
- module.exports = {
863
- QODER_SITES,
864
- normalizeQoderUsageResponse,
865
- normalizeQoderRpcUsage,
866
- normalizeQoderActivityResponse,
867
- qoderRequestHeaders,
868
- fetchQoderUsage,
869
- qoderRpcRequest,
870
- buildQoderActivityHeaders,
871
- fetchQoderActivity,
872
- readQoderActivityCache,
873
- writeQoderActivityCache,
874
- readQoderLimitsCache,
875
- writeQoderLimitsCache,
876
- parseQoderQuotaLog,
877
- readQoderLocalQuota,
878
- fetchQoderLimits,
879
- fetchQoderCnLimits,
880
- };
1
+ "use strict";
2
+
3
+ const crypto = require("node:crypto");
4
+ const fs = require("node:fs");
5
+ const net = require("node:net");
6
+ const os = require("node:os");
7
+ const path = require("node:path");
8
+ const { fetchQoderCnCliLimits } = require("./qoder-cn-cli-limits");
9
+
10
+ const QODER_SITES = {
11
+ international: {
12
+ id: "international",
13
+ origin: "https://qoder.com",
14
+ usageUrl: "https://qoder.com/api/v2/me/usages/big_model_credits",
15
+ activityUrl: "https://openapi.qoder.sh/algo/api/v2/activity",
16
+ domains: new Set(["qoder.com", "www.qoder.com"]),
17
+ },
18
+ china: {
19
+ id: "china",
20
+ origin: "https://qoder.cn",
21
+ usageUrl: "https://qoder.cn/api/v2/me/usages/big_model_credits",
22
+ activityUrl: "https://openapi.qoder.com.cn/algo/api/v2/activity",
23
+ domains: new Set(["qoder.cn", "www.qoder.cn", "qoder.com.cn", "www.qoder.com.cn"]),
24
+ },
25
+ };
26
+
27
+ const QODER_USER_AGENT =
28
+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) " +
29
+ "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/143.0.0.0 Safari/537.36";
30
+
31
+ // Qoder 1.18 serves promotional call buckets (including Ultimate Free Calls)
32
+ // from its OpenAPI activity endpoint. The request uses the same COSY envelope
33
+ // as Qoder CLI 1.0.22. Authentication comes from Qoder's already-running local
34
+ // service over JSON-RPC; Token Usage never persists or logs those credentials.
35
+ const QODER_ACTIVITY_URL = "https://openapi.qoder.sh/algo/api/v2/activity";
36
+ const QODER_ULTIMATE_ACTIVITY_ID = "ultimate_200_free_invoke";
37
+ const QODER_COSY_VERSION = "1.0.22";
38
+ const QODER_ACTIVITY_CACHE_FILE = "qoder-activity-cache.json";
39
+ const QODER_ACTIVITY_CACHE_MAX_AGE_MS = 24 * 60 * 60 * 1000;
40
+ const QODER_LIMITS_CACHE_FILE = "qoder-usage-limits-cache.json";
41
+ const QODER_LIMITS_CACHE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
42
+ const QODER_LIMITS_CACHE_UNKNOWN_RESET_TTL_MS = 12 * 60 * 60 * 1000;
43
+ const QODER_SERVER_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
44
+ MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDA8iMH5c02LilrsERw9t6Pv5Nc
45
+ 4k6Pz1EaDicBMpdpxKduSZu5OANqUq8er4GM95omAGIOPOh+Nx0spthYA2BqGz+l
46
+ 6HRkPJ7S236FZz73In/KVuLnwI8JJ2CbuJap8kvheCCZpmAWpb/cPx/3Vr/J6I17
47
+ XcW+ML9FoCI6AOvOzwIDAQAB
48
+ -----END PUBLIC KEY-----`;
49
+
50
+ function finiteNumber(value, field) {
51
+ const number = Number(value);
52
+ if (!Number.isFinite(number)) {
53
+ throw new Error(`Qoder usage response is missing ${field}.`);
54
+ }
55
+ return number;
56
+ }
57
+
58
+ function firstDefined(object, camel, snake) {
59
+ return object?.[camel] ?? object?.[snake];
60
+ }
61
+
62
+ function normalizeResetAt(value) {
63
+ if (value === null || value === undefined || value === "") return null;
64
+ if (typeof value === "number" || /^\d+(?:\.\d+)?$/.test(String(value).trim())) {
65
+ const raw = Number(value);
66
+ if (!Number.isFinite(raw)) return null;
67
+ const milliseconds = raw > 10_000_000_000 ? raw : raw * 1000;
68
+ const date = new Date(milliseconds);
69
+ return Number.isFinite(date.getTime()) ? date.toISOString() : null;
70
+ }
71
+ const timestamp = Date.parse(String(value));
72
+ return Number.isFinite(timestamp) ? new Date(timestamp).toISOString() : null;
73
+ }
74
+
75
+ function quotaSummary(container) {
76
+ return firstDefined(container, "quotaSummary", "quota_summary") || null;
77
+ }
78
+
79
+ function normalizeQuotaSummary(summary) {
80
+ if (!summary || typeof summary !== "object") {
81
+ throw new Error("Qoder usage response is missing totalQuota.quotaSummary.");
82
+ }
83
+ const used = finiteNumber(firstDefined(summary, "usedValue", "used_value"), "usedValue");
84
+ const total = finiteNumber(firstDefined(summary, "limitValue", "limit_value"), "limitValue");
85
+ const rawRemaining = firstDefined(summary, "remainingValue", "remaining_value");
86
+ const remaining = rawRemaining === null || rawRemaining === undefined
87
+ ? Math.max(0, total - used)
88
+ : finiteNumber(rawRemaining, "remainingValue");
89
+ const rawPercentage = firstDefined(summary, "usagePercentage", "usage_percentage");
90
+ const providedPercentage = rawPercentage === null || rawPercentage === undefined
91
+ ? null
92
+ : finiteNumber(rawPercentage, "usagePercentage");
93
+
94
+ if (used < 0 || total < 0 || remaining < 0) {
95
+ throw new Error("Qoder quota values must be nonnegative.");
96
+ }
97
+ if (total === 0 && (used !== 0 || remaining !== 0)) {
98
+ throw new Error("Qoder zero total quota must have zero usage and remaining.");
99
+ }
100
+ const usagePercentage = providedPercentage ?? (total > 0 ? (used / total) * 100 : 100);
101
+ return {
102
+ used,
103
+ total,
104
+ remaining,
105
+ usagePercentage: Math.max(0, Math.min(100, usagePercentage)),
106
+ unit: typeof summary.unit === "string" && summary.unit.trim() ? summary.unit.trim() : null,
107
+ };
108
+ }
109
+
110
+ function normalizeQoderUsageResponse(response) {
111
+ if (!response || typeof response !== "object") {
112
+ throw new Error("Qoder usage response is not an object.");
113
+ }
114
+ const totalContainer = firstDefined(response, "totalQuota", "total_quota");
115
+ const sharedContainer = firstDefined(response, "sharedQuota", "shared_quota");
116
+ const base = normalizeQuotaSummary(quotaSummary(totalContainer));
117
+ const sharedSummary = quotaSummary(sharedContainer);
118
+ const shared = sharedSummary ? normalizeQuotaSummary(sharedSummary) : null;
119
+
120
+ const used = base.used + (shared?.used || 0);
121
+ const total = base.total + (shared?.total || 0);
122
+ const remaining = base.remaining + (shared?.remaining || 0);
123
+ const usedPercent = shared
124
+ ? total > 0
125
+ ? (used / total) * 100
126
+ : 100
127
+ : base.usagePercentage;
128
+
129
+ return {
130
+ configured: true,
131
+ error: null,
132
+ primary_window: {
133
+ used_percent: Math.max(0, Math.min(100, usedPercent)),
134
+ reset_at: normalizeResetAt(firstDefined(response, "nextResetAt", "next_reset_at")),
135
+ used_credits: used,
136
+ limit_credits: total,
137
+ remaining_credits: remaining,
138
+ unit: base.unit || shared?.unit || null,
139
+ },
140
+ source: "provider-api",
141
+ };
142
+ }
143
+
144
+ function qoderDataRoot({
145
+ home = os.homedir(),
146
+ env = process.env,
147
+ platform = process.platform,
148
+ appDir = "Qoder",
149
+ envPrefix = "QODER",
150
+ } = {}) {
151
+ const homeKey = `${envPrefix}_HOME`;
152
+ if (typeof env[homeKey] === "string" && env[homeKey].trim()) {
153
+ return path.resolve(env[homeKey].trim());
154
+ }
155
+ if (platform === "darwin") {
156
+ return path.join(home, "Library", "Application Support", appDir);
157
+ }
158
+ if (platform === "win32") {
159
+ return path.join(env.APPDATA || path.join(home, "AppData", "Roaming"), appDir);
160
+ }
161
+ return path.join(home, ".config", appDir);
162
+ }
163
+
164
+ function qoderRpcRequest(method, params = {}, {
165
+ home = os.homedir(),
166
+ env = process.env,
167
+ platform = process.platform,
168
+ appDir = "Qoder",
169
+ envPrefix = "QODER",
170
+ timeoutMs = 1500,
171
+ netModule = net,
172
+ } = {}) {
173
+ return new Promise((resolve, reject) => {
174
+ const infoPath = path.join(qoderDataRoot({ home, env, platform, appDir, envPrefix }), "SharedClientCache", ".info.json");
175
+ let info;
176
+ try {
177
+ info = JSON.parse(fs.readFileSync(infoPath, "utf8"));
178
+ } catch (_error) {
179
+ reject(new Error("Qoder local service is not running."));
180
+ return;
181
+ }
182
+ const socketPath = typeof info?.ipcServerPath === "string" ? info.ipcServerPath.trim() : "";
183
+ if (!socketPath) {
184
+ reject(new Error("Qoder local service endpoint is unavailable."));
185
+ return;
186
+ }
187
+
188
+ let settled = false;
189
+ let buffer = Buffer.alloc(0);
190
+ const socket = netModule.createConnection(socketPath);
191
+ const timer = setTimeout(() => finish(new Error("Qoder local service request timed out.")), timeoutMs);
192
+
193
+ function finish(error, value) {
194
+ if (settled) return;
195
+ settled = true;
196
+ clearTimeout(timer);
197
+ socket.destroy();
198
+ if (error) reject(error);
199
+ else resolve(value);
200
+ }
201
+
202
+ socket.on("connect", () => {
203
+ const body = Buffer.from(JSON.stringify({
204
+ jsonrpc: "2.0",
205
+ id: 1,
206
+ method,
207
+ params,
208
+ }));
209
+ socket.write(`Content-Length: ${body.length}\r\n\r\n`);
210
+ socket.write(body);
211
+ });
212
+ socket.on("error", (error) => finish(error));
213
+ socket.on("data", (chunk) => {
214
+ buffer = Buffer.concat([buffer, chunk]);
215
+ const headerEnd = buffer.indexOf("\r\n\r\n");
216
+ if (headerEnd < 0) return;
217
+ const match = /Content-Length:\s*(\d+)/i.exec(buffer.subarray(0, headerEnd).toString("ascii"));
218
+ if (!match) {
219
+ finish(new Error("Qoder local service returned an invalid response."));
220
+ return;
221
+ }
222
+ const bodyLength = Number(match[1]);
223
+ const bodyStart = headerEnd + 4;
224
+ if (!Number.isFinite(bodyLength) || bodyLength < 0 || bodyLength > 4 * 1024 * 1024) {
225
+ finish(new Error("Qoder local service response is too large."));
226
+ return;
227
+ }
228
+ if (buffer.length < bodyStart + bodyLength) return;
229
+ try {
230
+ const message = JSON.parse(buffer.subarray(bodyStart, bodyStart + bodyLength).toString("utf8"));
231
+ if (message.error) {
232
+ finish(new Error(message.error.message || "Qoder local service request failed."));
233
+ } else {
234
+ finish(null, message.result);
235
+ }
236
+ } catch (_error) {
237
+ finish(new Error("Qoder local service returned invalid JSON."));
238
+ }
239
+ });
240
+ });
241
+ }
242
+
243
+ function normalizeQoderAddOnQuota(quota) {
244
+ if (quota == null) return null;
245
+ const used = Number(quota.used);
246
+ const total = Number(quota.total);
247
+ const remaining = quota.remaining == null ? Math.max(0, total - used) : Number(quota.remaining);
248
+ if (quota.used == null || quota.total == null
249
+ || ![used, total, remaining].every(Number.isFinite) || Math.min(used, total, remaining) < 0
250
+ || (total === 0 && (used !== 0 || remaining !== 0))) {
251
+ throw new Error("Qoder add-on quota values are invalid.");
252
+ }
253
+ return {
254
+ used_percent: total > 0 ? Math.min(100, (used / total) * 100) : 0,
255
+ // The official addOnQuota has no renewal date. Plan expiry does not apply.
256
+ reset_at: null,
257
+ used_credits: used,
258
+ limit_credits: total,
259
+ remaining_credits: remaining,
260
+ unit: typeof quota.unit === "string" && quota.unit.trim() ? quota.unit.trim() : "credits",
261
+ };
262
+ }
263
+
264
+ function normalizeQoderRpcUsage(response) {
265
+ if (!response || typeof response !== "object") return null;
266
+ const quota = response.userQuota;
267
+ // Qoder CN CLI 1.1.71 renders userQuota and addOnQuota as separate buckets.
268
+ // Only its account-level total_remaining adds them together.
269
+ const addOnWindow = normalizeQoderAddOnQuota(response.addOnQuota);
270
+ if ((!quota || typeof quota !== "object") && !addOnWindow) return null;
271
+ const used = quota ? finiteNumber(quota.used, "userQuota.used") : 0;
272
+ const total = quota ? finiteNumber(quota.total, "userQuota.total") : 0;
273
+ const remaining = quota ? finiteNumber(quota.remaining, "userQuota.remaining") : 0;
274
+ const reportedPercent = Number(response.totalUsagePercentage ?? quota?.percentage);
275
+ const usedPercent = total === 0
276
+ ? 0
277
+ : addOnWindow
278
+ ? (used / total) * 100
279
+ : response.isQuotaExceeded === true
280
+ ? 100
281
+ : Number.isFinite(reportedPercent)
282
+ ? reportedPercent
283
+ : (used / total) * 100;
284
+ const normalizedExpiry = normalizeResetAt(response.expiresAt);
285
+ const expiryMs = normalizedExpiry ? Date.parse(normalizedExpiry) : NaN;
286
+ return {
287
+ configured: true,
288
+ error: null,
289
+ plan_label: typeof response.userType === "string" ? response.userType : null,
290
+ quota_exceeded: response.isQuotaExceeded === true,
291
+ primary_window: quota ? {
292
+ used_percent: Math.max(0, Math.min(100, usedPercent)),
293
+ // Qoder uses 9999-12-31 as a no-expiry sentinel for Free accounts.
294
+ reset_at: Number.isFinite(expiryMs) && expiryMs < Date.UTC(2100, 0, 1)
295
+ ? normalizedExpiry
296
+ : null,
297
+ used_credits: used,
298
+ limit_credits: total,
299
+ remaining_credits: remaining,
300
+ unit: typeof quota.unit === "string" && quota.unit.trim() ? quota.unit.trim() : "credits",
301
+ } : null,
302
+ ...(addOnWindow ? { tertiary_window: addOnWindow } : {}),
303
+ source: "local-ipc",
304
+ };
305
+ }
306
+
307
+ function normalizeQoderActivityResponse(response, { nowMs = Date.now() } = {}) {
308
+ if (!response || typeof response !== "object") {
309
+ throw new Error("Qoder activity response is not an object.");
310
+ }
311
+ if (response.code !== undefined && Number(response.code) !== 0) {
312
+ throw new Error(`Qoder activity API returned ${response.msg || `code ${response.code}`}.`);
313
+ }
314
+ const activities = Array.isArray(response.data?.activities) ? response.data.activities : [];
315
+ const activity = activities.find((entry) => {
316
+ if (!entry || entry.activityId !== QODER_ULTIMATE_ACTIVITY_ID || entry.eligible === false) return false;
317
+ if (String(entry.tagStyle || "").toUpperCase() === "EXPIRED") return false;
318
+ const endAt = Number(entry.activityEndAt);
319
+ return !Number.isFinite(endAt) || endAt <= 0 || endAt > nowMs;
320
+ });
321
+ if (!activity) return null;
322
+ const used = finiteNumber(activity.used, "activity.used");
323
+ const total = finiteNumber(activity.limit, "activity.limit");
324
+ const rawRemaining = Number(activity.remaining);
325
+ const remaining = Number.isFinite(rawRemaining) ? rawRemaining : Math.max(0, total - used);
326
+ if (used < 0 || total <= 0 || remaining < 0) {
327
+ throw new Error("Qoder activity quota values are invalid.");
328
+ }
329
+ return {
330
+ used_percent: Math.max(0, Math.min(100, (used / total) * 100)),
331
+ reset_at: normalizeResetAt(activity.activityEndAt),
332
+ used_credits: used,
333
+ limit_credits: total,
334
+ remaining_credits: remaining,
335
+ unit: "calls",
336
+ activity_id: QODER_ULTIMATE_ACTIVITY_ID,
337
+ };
338
+ }
339
+
340
+ function qoderActivityCachePath({ home = os.homedir(), namespace } = {}) {
341
+ const file = namespace
342
+ ? `qoder-${namespace}-activity-cache.json`
343
+ : QODER_ACTIVITY_CACHE_FILE;
344
+ return path.join(home, ".tokenusage", "tracker", file);
345
+ }
346
+
347
+ function readQoderActivityCache({
348
+ home = os.homedir(),
349
+ nowMs = Date.now(),
350
+ namespace,
351
+ maxAgeMs = QODER_ACTIVITY_CACHE_MAX_AGE_MS,
352
+ } = {}) {
353
+ try {
354
+ const parsed = JSON.parse(fs.readFileSync(qoderActivityCachePath({ home, namespace }), "utf8"));
355
+ const window = parsed?.activity_window;
356
+ const cachedAtMs = Date.parse(parsed?.cached_at || "");
357
+ if (!window || !Number.isFinite(cachedAtMs) || cachedAtMs > nowMs + 60_000) return null;
358
+ const resetAtMs = Date.parse(window.reset_at || "");
359
+ if (Number.isFinite(resetAtMs)) {
360
+ if (resetAtMs <= nowMs) return null;
361
+ } else if (nowMs - cachedAtMs > maxAgeMs) {
362
+ return null;
363
+ }
364
+ const used = Number(window.used_credits);
365
+ const total = Number(window.limit_credits);
366
+ const remaining = Number(window.remaining_credits);
367
+ if (!Number.isFinite(used) || !Number.isFinite(total) || !Number.isFinite(remaining)
368
+ || used < 0 || total <= 0 || remaining < 0) return null;
369
+ return window;
370
+ } catch (_error) {
371
+ return null;
372
+ }
373
+ }
374
+
375
+ function writeQoderActivityCache(window, {
376
+ home = os.homedir(),
377
+ nowMs = Date.now(),
378
+ namespace,
379
+ } = {}) {
380
+ if (!window) return;
381
+ const cachePath = qoderActivityCachePath({ home, namespace });
382
+ const payload = {
383
+ activity_window: window,
384
+ cached_at: new Date(nowMs).toISOString(),
385
+ };
386
+ try {
387
+ fs.mkdirSync(path.dirname(cachePath), { recursive: true });
388
+ const tmpPath = `${cachePath}.${process.pid}.tmp`;
389
+ fs.writeFileSync(tmpPath, JSON.stringify(payload, null, 2), { encoding: "utf8", mode: 0o600 });
390
+ fs.renameSync(tmpPath, cachePath);
391
+ } catch (_error) {}
392
+ }
393
+
394
+ function qoderLimitsCachePath({ home = os.homedir(), namespace } = {}) {
395
+ const file = namespace
396
+ ? `qoder-${namespace}-usage-limits-cache.json`
397
+ : QODER_LIMITS_CACHE_FILE;
398
+ return path.join(home, ".tokenusage", "tracker", file);
399
+ }
400
+
401
+ function qoderCachedWindow(window, { cachedAtMs, nowMs } = {}) {
402
+ if (!window || typeof window !== "object") return null;
403
+ const resetAtMs = Date.parse(window.reset_at || "");
404
+ if (Number.isFinite(resetAtMs)) return resetAtMs > nowMs ? window : null;
405
+ return nowMs - cachedAtMs <= QODER_LIMITS_CACHE_UNKNOWN_RESET_TTL_MS ? window : null;
406
+ }
407
+
408
+ function readQoderLimitsCache({
409
+ home = os.homedir(),
410
+ nowMs = Date.now(),
411
+ namespace,
412
+ } = {}) {
413
+ try {
414
+ const raw = JSON.parse(fs.readFileSync(qoderLimitsCachePath({ home, namespace }), "utf8"))?.qoder;
415
+ const cachedAtMs = Date.parse(raw?.cached_at || "");
416
+ if (!Number.isFinite(cachedAtMs) || cachedAtMs > nowMs + 60_000) return null;
417
+ const primaryWindow = qoderCachedWindow(raw.primary_window, { cachedAtMs, nowMs });
418
+ const secondaryWindow = qoderCachedWindow(raw.secondary_window, { cachedAtMs, nowMs });
419
+ const tertiaryWindow = qoderCachedWindow(raw.tertiary_window, { cachedAtMs, nowMs });
420
+ if (!primaryWindow && !secondaryWindow && !tertiaryWindow) return null;
421
+ const hasUnexpiredDatedWindow = [primaryWindow, secondaryWindow, tertiaryWindow]
422
+ .some((window) => Number.isFinite(Date.parse(window?.reset_at || "")));
423
+ if (nowMs - cachedAtMs > QODER_LIMITS_CACHE_MAX_AGE_MS && !hasUnexpiredDatedWindow) {
424
+ return null;
425
+ }
426
+ return {
427
+ configured: true,
428
+ error: null,
429
+ plan_label: typeof raw.plan_label === "string" ? raw.plan_label : null,
430
+ quota_exceeded: raw.quota_exceeded === true,
431
+ primary_window: primaryWindow,
432
+ secondary_window: secondaryWindow,
433
+ ...(tertiaryWindow ? { tertiary_window: tertiaryWindow } : {}),
434
+ cached: true,
435
+ stale: true,
436
+ cached_at: raw.cached_at,
437
+ source: "disk-cache",
438
+ };
439
+ } catch (_error) {
440
+ return null;
441
+ }
442
+ }
443
+
444
+ function writeQoderLimitsCache(limits, {
445
+ home = os.homedir(),
446
+ nowMs = Date.now(),
447
+ namespace,
448
+ } = {}) {
449
+ if (!limits?.configured || limits.error || (!limits.primary_window && !limits.secondary_window && !limits.tertiary_window)) return;
450
+ const cachePath = qoderLimitsCachePath({ home, namespace });
451
+ const payload = {
452
+ qoder: {
453
+ plan_label: limits.plan_label || null,
454
+ quota_exceeded: limits.quota_exceeded === true,
455
+ primary_window: limits.primary_window || null,
456
+ secondary_window: limits.secondary_window || null,
457
+ ...(limits.tertiary_window ? { tertiary_window: limits.tertiary_window } : {}),
458
+ cached_at: new Date(nowMs).toISOString(),
459
+ },
460
+ };
461
+ try {
462
+ fs.mkdirSync(path.dirname(cachePath), { recursive: true });
463
+ const tmpPath = `${cachePath}.${process.pid}.tmp`;
464
+ fs.writeFileSync(tmpPath, JSON.stringify(payload, null, 2), { encoding: "utf8", mode: 0o600 });
465
+ fs.renameSync(tmpPath, cachePath);
466
+ } catch (_error) {}
467
+ }
468
+
469
+ function buildQoderActivityHeaders(authStatus, {
470
+ nowMs = Date.now(),
471
+ randomUUID = crypto.randomUUID,
472
+ } = {}) {
473
+ const userId = String(authStatus?.id || authStatus?.accountId || "").trim();
474
+ const accessToken = String(authStatus?.token || "").trim();
475
+ if (!userId || !accessToken) {
476
+ throw new Error("Qoder local session is missing activity credentials.");
477
+ }
478
+ const temporaryKey = Buffer.from(randomUUID().replace(/-/g, "").slice(0, 16), "ascii");
479
+ const cosyKey = crypto.publicEncrypt(
480
+ { key: QODER_SERVER_PUBLIC_KEY, padding: crypto.constants.RSA_PKCS1_PADDING },
481
+ temporaryKey,
482
+ ).toString("base64");
483
+ const identity = {
484
+ name: authStatus.name || "",
485
+ aid: userId,
486
+ uid: userId,
487
+ yx_uid: authStatus.yxUid || "",
488
+ organization_id: authStatus.orgId || "",
489
+ organization_name: authStatus.orgName || "",
490
+ user_type: authStatus.userType || "personal_standard",
491
+ security_oauth_token: accessToken,
492
+ refresh_token: authStatus.refreshToken || "",
493
+ };
494
+ const cipher = crypto.createCipheriv("aes-128-cbc", temporaryKey, temporaryKey);
495
+ const info = Buffer.concat([
496
+ cipher.update(Buffer.from(JSON.stringify(identity), "utf8")),
497
+ cipher.final(),
498
+ ]).toString("base64");
499
+ const payload = Buffer.from(JSON.stringify({
500
+ version: "v1",
501
+ requestId: randomUUID(),
502
+ info,
503
+ cosyVersion: QODER_COSY_VERSION,
504
+ ideVersion: "",
505
+ }), "utf8").toString("base64");
506
+ const cosyDate = String(Math.floor(nowMs / 1000));
507
+ const signature = crypto
508
+ .createHash("md5")
509
+ .update(`${payload}\n${cosyKey}\n${cosyDate}\n\n/api/v2/activity`, "utf8")
510
+ .digest("hex");
511
+ const machineId = randomUUID();
512
+ return {
513
+ "cosy-data-policy": "agree",
514
+ "cosy-machinetype": "5",
515
+ "cosy-clienttype": "5",
516
+ "cosy-date": cosyDate,
517
+ "cosy-user": userId,
518
+ "cosy-key": cosyKey,
519
+ "cache-control": "no-cache",
520
+ "cosy-business-product": "cli",
521
+ "cosy-business-type": "agent",
522
+ "cosy-scene": "assistant",
523
+ accept: "application/json",
524
+ authorization: `Bearer COSY.${payload}.${signature}`,
525
+ "accept-encoding": "identity",
526
+ "cosy-version": QODER_COSY_VERSION,
527
+ "cosy-machineid": machineId,
528
+ "cosy-machinetoken": machineId,
529
+ "login-version": "v2",
530
+ "user-agent": "Go-http-client/2.0",
531
+ };
532
+ }
533
+
534
+ async function fetchQoderActivity(authStatus, fetchImpl = fetch, options = {}) {
535
+ const activityUrl = options.activityUrl || QODER_ACTIVITY_URL;
536
+ const response = await fetchImpl(activityUrl, {
537
+ method: "GET",
538
+ headers: buildQoderActivityHeaders(authStatus, options),
539
+ });
540
+ if (response.status === 401 || response.status === 403) {
541
+ throw new Error("Qoder activity session expired.");
542
+ }
543
+ if (!response.ok) {
544
+ throw new Error(`Qoder activity API returned HTTP ${response.status}.`);
545
+ }
546
+ return normalizeQoderActivityResponse(await response.json(), options);
547
+ }
548
+
549
+ function qoderRequestHeaders(cookieHeader, site) {
550
+ return {
551
+ Cookie: cookieHeader,
552
+ Accept: "application/json, text/plain, */*",
553
+ "Accept-Language": "en-US,en;q=0.9",
554
+ "User-Agent": QODER_USER_AGENT,
555
+ Origin: site.origin,
556
+ Referer: `${site.origin}/account/usage`,
557
+ "X-Requested-With": "XMLHttpRequest",
558
+ "Bx-V": "2.5.35",
559
+ };
560
+ }
561
+
562
+ async function fetchQoderUsage(cookieHeader, site, fetchImpl) {
563
+ const response = await fetchImpl(site.usageUrl, {
564
+ method: "GET",
565
+ headers: qoderRequestHeaders(cookieHeader, site),
566
+ });
567
+ if (response.status === 401 || response.status === 403) {
568
+ const error = new Error("Qoder login expired. Sign in at qoder.com again.");
569
+ error.code = "AUTH_EXPIRED";
570
+ throw error;
571
+ }
572
+ if (!response.ok) {
573
+ throw new Error(`Qoder usage API returned HTTP ${response.status}.`);
574
+ }
575
+ return normalizeQoderUsageResponse(await response.json());
576
+ }
577
+
578
+ function listRecentQoderRendererLogs(logRoot, maxFiles = 12) {
579
+ if (!fs.existsSync(logRoot)) return [];
580
+ const files = [];
581
+ const stack = [{ dir: logRoot, depth: 0 }];
582
+ while (stack.length > 0 && files.length < 2000) {
583
+ const current = stack.pop();
584
+ let entries;
585
+ try {
586
+ entries = fs.readdirSync(current.dir, { withFileTypes: true });
587
+ } catch (_error) {
588
+ continue;
589
+ }
590
+ for (const entry of entries) {
591
+ const full = path.join(current.dir, entry.name);
592
+ if (entry.isDirectory() && current.depth < 4) {
593
+ stack.push({ dir: full, depth: current.depth + 1 });
594
+ } else if (entry.isFile() && entry.name === "renderer.log") {
595
+ let mtimeMs = 0;
596
+ try {
597
+ mtimeMs = fs.statSync(full).mtimeMs;
598
+ } catch (_error) {}
599
+ files.push({ full, mtimeMs });
600
+ }
601
+ }
602
+ }
603
+ return files
604
+ .sort((a, b) => b.mtimeMs - a.mtimeMs)
605
+ .slice(0, maxFiles)
606
+ .map((entry) => entry.full);
607
+ }
608
+
609
+ function parseQoderQuotaLog(text) {
610
+ if (typeof text !== "string" || !text) return null;
611
+ const matches = Array.from(text.matchAll(
612
+ /userType=([^,\s]+)[\s\S]*?isQuotaExceeded=(true|false)[\s\S]*?userQuota(?:=|\s+)used=([0-9.]+),\s*total=([0-9.]+),\s*remaining=([0-9.]+),\s*percentage=([0-9.]+),\s*unit=([^,\s]+)/g,
613
+ ));
614
+ const match = matches.at(-1);
615
+ if (!match) return null;
616
+ const quotaExceeded = match[2] === "true";
617
+ const used = Number(match[3]);
618
+ const total = Number(match[4]);
619
+ const remaining = Number(match[5]);
620
+ const percentage = Number(match[6]);
621
+ if (![used, total, remaining, percentage].every(Number.isFinite)) return null;
622
+ return {
623
+ configured: true,
624
+ error: null,
625
+ plan_label: match[1],
626
+ quota_exceeded: quotaExceeded,
627
+ primary_window: {
628
+ used_percent: total === 0
629
+ ? 0
630
+ : quotaExceeded
631
+ ? 100
632
+ : Math.max(0, Math.min(100, percentage)),
633
+ reset_at: null,
634
+ used_credits: used,
635
+ limit_credits: total,
636
+ remaining_credits: remaining,
637
+ unit: match[7],
638
+ },
639
+ source: "local-log",
640
+ };
641
+ }
642
+
643
+ function readQoderLocalQuota({
644
+ home = os.homedir(),
645
+ platform = process.platform,
646
+ env = process.env,
647
+ appDir = "Qoder",
648
+ envPrefix = "QODER",
649
+ } = {}) {
650
+ const logRootKey = `${envPrefix}_LOG_ROOT`;
651
+ const homeKey = `${envPrefix}_HOME`;
652
+ const explicitLogRoot =
653
+ typeof env[logRootKey] === "string" && env[logRootKey].trim()
654
+ ? path.resolve(env[logRootKey].trim())
655
+ : null;
656
+ const configuredRoot =
657
+ typeof env[homeKey] === "string" && env[homeKey].trim()
658
+ ? path.resolve(env[homeKey].trim())
659
+ : null;
660
+ const logRoot = explicitLogRoot || (configuredRoot
661
+ ? path.join(configuredRoot, "logs")
662
+ : platform === "darwin"
663
+ ? path.join(home, "Library", "Application Support", appDir, "logs")
664
+ : platform === "win32"
665
+ ? path.join(env.APPDATA || path.join(home, "AppData", "Roaming"), appDir, "logs")
666
+ : path.join(home, ".config", appDir, "logs"));
667
+ for (const logPath of listRecentQoderRendererLogs(logRoot)) {
668
+ try {
669
+ const fd = fs.openSync(logPath, "r");
670
+ try {
671
+ const stat = fs.fstatSync(fd);
672
+ const length = Math.min(stat.size, 512 * 1024);
673
+ const buffer = Buffer.alloc(length);
674
+ fs.readSync(fd, buffer, 0, length, Math.max(0, stat.size - length));
675
+ const parsed = parseQoderQuotaLog(buffer.toString("utf8"));
676
+ if (parsed) return parsed;
677
+ } finally {
678
+ fs.closeSync(fd);
679
+ }
680
+ } catch (_error) {}
681
+ }
682
+ return null;
683
+ }
684
+
685
+ function siteFromEnv(value) {
686
+ const normalized = String(value || "").trim().toLowerCase();
687
+ return normalized === "cn" || normalized === "china" || normalized.includes(".cn")
688
+ ? QODER_SITES.china
689
+ : QODER_SITES.international;
690
+ }
691
+
692
+ async function fetchQoderLimits({
693
+ home = os.homedir(),
694
+ env = process.env,
695
+ platform = process.platform,
696
+ appDir = "Qoder",
697
+ envPrefix = "QODER",
698
+ site = QODER_SITES.international,
699
+ sitePinned = false,
700
+ cacheNamespace,
701
+ fetchImpl = fetch,
702
+ rpcRequest = qoderRpcRequest,
703
+ nowMs = Date.now(),
704
+ cliLimitsRequest,
705
+ } = {}) {
706
+ let rpcUsage = null;
707
+ let rpcAuth = null;
708
+ let activityWindow = null;
709
+ let activitySource = null;
710
+ const rpcOptions = { home, env, platform, appDir, envPrefix };
711
+ // Qoder's shared client accepts only one reliable request at a time. Parallel
712
+ // connections intermittently time out even while the desktop app is running.
713
+ try {
714
+ rpcUsage = normalizeQoderRpcUsage(await rpcRequest("credit/usage", {}, rpcOptions));
715
+ } catch (_error) {}
716
+ try {
717
+ const authResult = await rpcRequest("auth/status", {}, rpcOptions);
718
+ if (authResult && typeof authResult === "object") rpcAuth = authResult;
719
+ } catch (_error) {}
720
+ if (rpcAuth) {
721
+ try {
722
+ activityWindow = await fetchQoderActivity(rpcAuth, fetchImpl, { nowMs, activityUrl: site.activityUrl });
723
+ if (activityWindow) {
724
+ activitySource = "provider-api";
725
+ writeQoderActivityCache(activityWindow, { home, nowMs, namespace: cacheNamespace });
726
+ }
727
+ } catch (_error) {}
728
+ }
729
+ // Qoder's activity endpoint occasionally succeeds with an empty activities
730
+ // array while the promotion is still active. Treat that as a transient
731
+ // omission, not an authoritative deletion: an activity carries its own
732
+ // expiry, so the last observed window remains valid until reset_at.
733
+ if (!activityWindow) {
734
+ activityWindow = readQoderActivityCache({ home, nowMs, namespace: cacheNamespace });
735
+ if (activityWindow) activitySource = "disk-cache";
736
+ }
737
+ if (rpcUsage) {
738
+ if (!rpcUsage.plan_label && typeof rpcAuth?.userType === "string") {
739
+ rpcUsage.plan_label = rpcAuth.userType;
740
+ }
741
+ if (activityWindow) rpcUsage.secondary_window = activityWindow;
742
+ rpcUsage.source = activityWindow
743
+ ? `local-ipc+${activitySource === "disk-cache" ? "cached-activity" : "provider-api"}`
744
+ : "local-ipc";
745
+ writeQoderLimitsCache(rpcUsage, { home, nowMs, namespace: cacheNamespace });
746
+ return rpcUsage;
747
+ }
748
+
749
+ let cliError = null;
750
+ if (cliLimitsRequest) {
751
+ try {
752
+ const cliUsage = await cliLimitsRequest({ home, env, fetchImpl, normalizeRpcUsage: normalizeQoderRpcUsage });
753
+ if (cliUsage) {
754
+ if (activityWindow) cliUsage.secondary_window = activityWindow;
755
+ writeQoderLimitsCache(cliUsage, { home, nowMs, namespace: cacheNamespace });
756
+ return cliUsage;
757
+ }
758
+ } catch (error) {
759
+ cliError = error;
760
+ }
761
+ }
762
+
763
+ // Once native sources are unavailable, prefer a bounded disk snapshot before
764
+ // the manual-cookie or local-log fallback.
765
+ const cachedLimits = readQoderLimitsCache({ home, nowMs, namespace: cacheNamespace });
766
+ if (cachedLimits) {
767
+ if (activityWindow) cachedLimits.secondary_window = activityWindow;
768
+ return cachedLimits;
769
+ }
770
+
771
+ // Manual-cookie fallback reads an envPrefix-specific key: QODER_COOKIE for
772
+ // the international flow, QODER_CN_COOKIE for the CN flow — the two installs
773
+ // hold different sessions and must never share a cookie.
774
+ const cookieKey = `${envPrefix}_COOKIE`;
775
+ const manualCookie = typeof env[cookieKey] === "string" ? env[cookieKey].trim() : "";
776
+ // QODER_SITE is an international-flow knob. A pinned site (the CN fetch)
777
+ // must never be overridden by it — the CN flow always targets china.
778
+ const manualSite = sitePinned ? site : env.QODER_SITE ? siteFromEnv(env.QODER_SITE) : site;
779
+ const sessions = manualCookie
780
+ ? [{
781
+ cookieHeader: manualCookie,
782
+ site: manualSite,
783
+ sourceLabel: cookieKey,
784
+ }]
785
+ : [];
786
+
787
+ let lastError = cliError;
788
+ for (const session of sessions) {
789
+ try {
790
+ const result = await fetchQoderUsage(session.cookieHeader, session.site, fetchImpl);
791
+ // Qoder 1.18 can return an all-zero active plan with usage_percentage=0
792
+ // while the desktop client separately marks the account quota-exceeded.
793
+ // Preserve that status as metadata, but match Qoder's Credits UI by
794
+ // rendering an empty 0/0 bucket as 0%, not a full red 100% bar.
795
+ const local = result.primary_window?.limit_credits === 0
796
+ ? readQoderLocalQuota({ home, platform, env, appDir, envPrefix })
797
+ : null;
798
+ if (local) {
799
+ result.quota_exceeded = local.quota_exceeded === true;
800
+ result.primary_window.reset_at = null;
801
+ result.source = "provider-api+local-log";
802
+ result.plan_label = local.plan_label || null;
803
+ }
804
+ if (activityWindow) {
805
+ result.secondary_window = activityWindow;
806
+ result.source += activitySource === "disk-cache" ? "+cached-activity" : "+activity";
807
+ }
808
+ const liveResult = {
809
+ ...result,
810
+ cookie_source: session.sourceLabel,
811
+ site: session.site.id,
812
+ };
813
+ writeQoderLimitsCache(liveResult, { home, nowMs, namespace: cacheNamespace });
814
+ return liveResult;
815
+ } catch (error) {
816
+ lastError = error;
817
+ }
818
+ }
819
+
820
+ const local = readQoderLocalQuota({ home, platform, env, appDir, envPrefix });
821
+ if (local) {
822
+ if (activityWindow) {
823
+ local.secondary_window = activityWindow;
824
+ local.source += activitySource === "disk-cache" ? "+cached-activity" : "+activity";
825
+ }
826
+ writeQoderLimitsCache(local, { home, nowMs, namespace: cacheNamespace });
827
+ return local;
828
+ }
829
+ if (activityWindow) {
830
+ return {
831
+ configured: true,
832
+ error: null,
833
+ plan_label: typeof rpcAuth?.userType === "string" ? rpcAuth.userType : null,
834
+ primary_window: null,
835
+ secondary_window: activityWindow,
836
+ source: activitySource === "disk-cache" ? "cached-activity" : "local-ipc+provider-api",
837
+ };
838
+ }
839
+ if (lastError) {
840
+ return {
841
+ configured: true,
842
+ error: lastError.message || "Qoder usage fetch failed.",
843
+ auth_action_required: lastError.code === "AUTH_EXPIRED" ? "reauth" : undefined,
844
+ };
845
+ }
846
+ return { configured: false };
847
+ }
848
+
849
+ // CN has its own CLI credentials, legacy desktop root and cache namespace.
850
+ function fetchQoderCnLimits(opts = {}) {
851
+ return fetchQoderLimits({
852
+ ...opts,
853
+ appDir: "QoderCN",
854
+ envPrefix: "QODER_CN",
855
+ site: QODER_SITES.china,
856
+ sitePinned: true,
857
+ cacheNamespace: "cn",
858
+ cliLimitsRequest: fetchQoderCnCliLimits,
859
+ });
860
+ }
861
+
862
+ module.exports = {
863
+ QODER_SITES,
864
+ normalizeQoderUsageResponse,
865
+ normalizeQoderRpcUsage,
866
+ normalizeQoderActivityResponse,
867
+ qoderRequestHeaders,
868
+ fetchQoderUsage,
869
+ qoderRpcRequest,
870
+ buildQoderActivityHeaders,
871
+ fetchQoderActivity,
872
+ readQoderActivityCache,
873
+ writeQoderActivityCache,
874
+ readQoderLimitsCache,
875
+ writeQoderLimitsCache,
876
+ parseQoderQuotaLog,
877
+ readQoderLocalQuota,
878
+ fetchQoderLimits,
879
+ fetchQoderCnLimits,
880
+ };