tokenusage-cli 0.1.0

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 (125) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/LICENSE +22 -0
  3. package/README.md +94 -0
  4. package/THIRD_PARTY_NOTICES.md +140 -0
  5. package/bin/tokenusage.js +69 -0
  6. package/package.json +59 -0
  7. package/src/cli.js +134 -0
  8. package/src/commands/device-login.js +205 -0
  9. package/src/commands/diagnostics.js +38 -0
  10. package/src/commands/doctor.js +110 -0
  11. package/src/commands/init.js +2436 -0
  12. package/src/commands/sessions.js +29 -0
  13. package/src/commands/status.js +1747 -0
  14. package/src/commands/sync.js +7934 -0
  15. package/src/commands/uninstall.js +312 -0
  16. package/src/lib/account-usage-dedup.js +267 -0
  17. package/src/lib/antigravity-paths.js +48 -0
  18. package/src/lib/ark-agent-plan-limits.js +438 -0
  19. package/src/lib/ark-coding-plan-limits.js +537 -0
  20. package/src/lib/async-queue-reader.js +138 -0
  21. package/src/lib/atomic-json.js +27 -0
  22. package/src/lib/bearer-token.js +11 -0
  23. package/src/lib/categorizer-utils.js +232 -0
  24. package/src/lib/claude-categorizer.js +1343 -0
  25. package/src/lib/claude-config.js +279 -0
  26. package/src/lib/claude-user-identity.js +56 -0
  27. package/src/lib/cli-ui.js +179 -0
  28. package/src/lib/cloud-account.js +541 -0
  29. package/src/lib/cloud-device-token.js +141 -0
  30. package/src/lib/cloud-sync-prefs.js +14 -0
  31. package/src/lib/cloud-usage-reset.js +115 -0
  32. package/src/lib/codex-config.js +595 -0
  33. package/src/lib/codex-context-breakdown.js +806 -0
  34. package/src/lib/codex-model-attribution.js +128 -0
  35. package/src/lib/codex-rollout-parser.js +1471 -0
  36. package/src/lib/codex-service-tier.js +49 -0
  37. package/src/lib/codex-token-refresh.js +140 -0
  38. package/src/lib/codex-token-usage.js +195 -0
  39. package/src/lib/codex-usage-record.js +195 -0
  40. package/src/lib/command-runner.js +313 -0
  41. package/src/lib/commandcode-limits.js +317 -0
  42. package/src/lib/context-health.js +124 -0
  43. package/src/lib/cursor-config.js +605 -0
  44. package/src/lib/cursor-store.js +1918 -0
  45. package/src/lib/debug-flags.js +7 -0
  46. package/src/lib/devin-limits.js +249 -0
  47. package/src/lib/devin-usage.js +212 -0
  48. package/src/lib/diagnostics.js +383 -0
  49. package/src/lib/doctor.js +385 -0
  50. package/src/lib/dumate.js +95 -0
  51. package/src/lib/fs.js +455 -0
  52. package/src/lib/function-url.js +14 -0
  53. package/src/lib/gemini-config.js +291 -0
  54. package/src/lib/git-outcomes.js +243 -0
  55. package/src/lib/grok-context-breakdown.js +890 -0
  56. package/src/lib/grok-hook.js +360 -0
  57. package/src/lib/grok-limits.js +865 -0
  58. package/src/lib/grok-usage.js +98 -0
  59. package/src/lib/heatmap-compact.js +114 -0
  60. package/src/lib/ingest-sanitize.js +41 -0
  61. package/src/lib/init-flow.js +42 -0
  62. package/src/lib/install-resolver.js +170 -0
  63. package/src/lib/jsonl-lines.js +134 -0
  64. package/src/lib/kimi-model-repair.js +173 -0
  65. package/src/lib/kimi-profile.js +61 -0
  66. package/src/lib/kimi-session.js +216 -0
  67. package/src/lib/local-api.js +3588 -0
  68. package/src/lib/machine-id.js +238 -0
  69. package/src/lib/multi-install-parser.js +113 -0
  70. package/src/lib/notify-command.js +38 -0
  71. package/src/lib/omp-hook.js +589 -0
  72. package/src/lib/openclaw-cli.js +104 -0
  73. package/src/lib/openclaw-hook.js +375 -0
  74. package/src/lib/openclaw-session-plugin.js +560 -0
  75. package/src/lib/opencode-config.js +121 -0
  76. package/src/lib/opencode-go-limits.js +807 -0
  77. package/src/lib/outcomes-engine.js +253 -0
  78. package/src/lib/passive-mode.js +219 -0
  79. package/src/lib/pet-packages.js +722 -0
  80. package/src/lib/pricing/curated-overrides.json +822 -0
  81. package/src/lib/pricing/index.js +379 -0
  82. package/src/lib/pricing/litellm-fetcher.js +172 -0
  83. package/src/lib/pricing/matcher.js +456 -0
  84. package/src/lib/pricing/seed-snapshot.json +1 -0
  85. package/src/lib/progress.js +76 -0
  86. package/src/lib/project-usage-purge.js +117 -0
  87. package/src/lib/prompt.js +24 -0
  88. package/src/lib/provider-status.js +104 -0
  89. package/src/lib/proxy-env.js +489 -0
  90. package/src/lib/proxy-settings.js +163 -0
  91. package/src/lib/qoder-cn-cli-limits.js +119 -0
  92. package/src/lib/qoder-limits.js +880 -0
  93. package/src/lib/quiet-warnings.js +26 -0
  94. package/src/lib/rollout.js +25966 -0
  95. package/src/lib/runtime-config.js +259 -0
  96. package/src/lib/scan-roots.js +277 -0
  97. package/src/lib/sentry.js +231 -0
  98. package/src/lib/session-analytics.js +2972 -0
  99. package/src/lib/session-performance.js +237 -0
  100. package/src/lib/session-upload.js +379 -0
  101. package/src/lib/skill-usage.js +267 -0
  102. package/src/lib/skills-manager.js +1591 -0
  103. package/src/lib/source-metadata.js +48 -0
  104. package/src/lib/sqlite-reader.js +215 -0
  105. package/src/lib/star-cta.js +73 -0
  106. package/src/lib/subscription-manager.js +293 -0
  107. package/src/lib/subscriptions.js +508 -0
  108. package/src/lib/telemetry.js +193 -0
  109. package/src/lib/tracker-paths.js +16 -0
  110. package/src/lib/trae-cn-config.js +548 -0
  111. package/src/lib/trae-db.js +127 -0
  112. package/src/lib/trae-snapshot.js +230 -0
  113. package/src/lib/trae-sqlite.js +143 -0
  114. package/src/lib/trae-usage.js +121 -0
  115. package/src/lib/upload-queue.js +134 -0
  116. package/src/lib/upload-throttle.js +171 -0
  117. package/src/lib/usage-limits.js +4552 -0
  118. package/src/lib/wrapped-aggregator.js +236 -0
  119. package/src/lib/wsl-probe.js +281 -0
  120. package/src/lib/zcode-limits.js +1172 -0
  121. package/src/lib/zcode-reset-credits.js +66 -0
  122. package/test/cli-smoke.test.js +53 -0
  123. package/test/ingest-sanitize.test.js +162 -0
  124. package/test/quiet-warnings.test.js +53 -0
  125. package/test/session-upload.test.js +427 -0
@@ -0,0 +1,16 @@
1
+ const os = require("node:os");
2
+ const path = require("node:path");
3
+
4
+ async function resolveTrackerPaths({ home = os.homedir() } = {}) {
5
+ const rootDir = path.join(home, ".tokenusage");
6
+ return {
7
+ rootDir,
8
+ trackerDir: path.join(rootDir, "tracker"),
9
+ binDir: path.join(rootDir, "bin"),
10
+ cacheDir: path.join(rootDir, "cache"),
11
+ };
12
+ }
13
+
14
+ module.exports = {
15
+ resolveTrackerPaths,
16
+ };
@@ -0,0 +1,548 @@
1
+ "use strict";
2
+
3
+ /**
4
+ * TRAE Work CN (国内版) config + usage fetch. Phase A: macOS + Windows + test-injected
5
+ * paths only. Resolves the CN home, reads the `iCubeAuthInfo://icube.cloudide`
6
+ * blob from User/globalStorage/storage.json (plaintext JSON or Base64 tc v5),
7
+ * and talks to the TRAE CN usage API. JWTs / refresh tokens are never
8
+ * persisted, never logged, and never put into error messages; a
9
+ * present-but-unreadable blob fails closed with a generic error.
10
+ *
11
+ * tc v5 blob: [6-byte magic "tc\x05\x10\x00\x00"][32-byte salt][AES-128-CBC ct]
12
+ * kdf_buf = SHA-512(salt) || (JG xor KG) // 128 bytes
13
+ * kdf_out = SHA-512(kdf_buf) // 64 bytes
14
+ * key = kdf_out[0..16], iv = kdf_out[16..32]
15
+ * plaintext = [SHA-512(json)][json] // integrity prefix stripped
16
+ */
17
+
18
+ const crypto = require("node:crypto");
19
+ const fs = require("node:fs");
20
+ const os = require("node:os");
21
+ const path = require("node:path");
22
+
23
+ const TRAE_CN_HOME_ENV = "TOKENUSAGE_TRAE_CN_HOME";
24
+ // The TRAE CN usage read transmits the locally stored sign-in JWT to TRAE's
25
+ // official endpoint, so it is strictly opt-in: nothing is sent unless the
26
+ // user explicitly sets this flag. Any value other than 1/true keeps it off.
27
+ const TRAE_CN_USAGE_ENV = "TOKENUSAGE_TRAE_CN_USAGE";
28
+
29
+ function isTraeCnUsageEnabled(env = process.env) {
30
+ const value = env ? env[TRAE_CN_USAGE_ENV] : undefined;
31
+ const normalized = typeof value === "string" ? value.trim().toLowerCase() : "";
32
+ return normalized === "1" || normalized === "true";
33
+ }
34
+ const TRAE_CN_APP_DIR = "TRAE SOLO CN";
35
+ const TRAE_CN_AUTH_KEY = "iCubeAuthInfo://icube.cloudide";
36
+
37
+ const TRAE_CN_USAGE_URL = "https://api.trae.cn/trae/api/v1/pay/query_user_usage_group_by_session";
38
+ // usage_type [7] mirrors the constant the official TRAE client sends when its
39
+ // usage page queries this endpoint (observed in the client's outbound
40
+ // requests; the enum is undocumented server-side). Other values unverified.
41
+ const TRAE_CN_USAGE_TYPE = [7];
42
+ const TRAE_CN_USAGE_PAGE_SIZE = 20;
43
+ const TRAE_CN_USAGE_MAX_PAGES = 100;
44
+ const TRAE_CN_USAGE_DELAY_MS = 300;
45
+ const TRAE_CN_USAGE_TIMEOUT_MS = 30 * 1000;
46
+ // Capacity-adaptive window splitting: 30 days halves at most 8 times
47
+ // (finest sub-window ~2.8h, aggregate ceiling ~512k sessions/30d). A window
48
+ // still over capacity at that depth fails closed — never a partial import.
49
+ const TRAE_CN_USAGE_MAX_SPLIT_DEPTH = 8;
50
+
51
+ const TRAE_CN_MAGIC = Buffer.from([0x74, 0x63, 0x05, 0x10, 0x00, 0x00]);
52
+ const TRAE_CN_SALT_LEN = 32;
53
+ const TRAE_CN_HASH_LEN = 64;
54
+ const TRAE_CN_AES_KEY_LEN = 16;
55
+ const TRAE_CN_IV_LEN = 16;
56
+
57
+ // JG / KG — the two halves of the hardcoded (obfuscated) password in the TRAE
58
+ // client's byteCrypto.js (XOR the pair to recover the KDF secret). Failure
59
+ // signature when TRAE ships a new key: readTraeCnAuthFromStorage throws
60
+ // "Trae CN auth payload is malformed", sync skips the source, and
61
+ // `tokenusage status` reports auth "malformed" — re-extract the pair
62
+ // from the updated client to restore decryption.
63
+ const TRAE_CN_JG = Buffer.from([
64
+ 82, 9, 106, 213, 48, 54, 165, 56, 191, 64, 163, 158, 129, 243, 215, 251, 124, 227, 57, 130,
65
+ 155, 47, 255, 135, 52, 142, 67, 68, 196, 222, 233, 203, 84, 123, 148, 50, 166, 194, 35, 61,
66
+ 238, 76, 149, 11, 66, 250, 195, 78, 8, 46, 161, 102, 40, 217, 36, 178, 118, 91, 162, 73,
67
+ 109, 139, 209, 37,
68
+ ]);
69
+ const TRAE_CN_KG = Buffer.from([
70
+ 31, 221, 168, 51, 136, 7, 199, 49, 177, 18, 16, 89, 39, 128, 236, 95, 96, 81, 127, 169, 25,
71
+ 181, 74, 13, 45, 229, 122, 159, 147, 201, 156, 239, 160, 224, 59, 77, 174, 42, 245, 176,
72
+ 200, 235, 187, 60, 131, 83, 153, 97, 23, 43, 4, 126, 186, 119, 214, 38, 225, 105, 20, 99,
73
+ 85, 33, 12, 125,
74
+ ]);
75
+
76
+ // ---------------------------------------------------------------------------
77
+ // Path resolution
78
+ // ---------------------------------------------------------------------------
79
+
80
+ function resolveTraeCnHome({ env = process.env, home = os.homedir(), platform = process.platform } = {}) {
81
+ const override = env[TRAE_CN_HOME_ENV];
82
+ if (typeof override === "string" && override.trim()) {
83
+ return path.resolve(override.trim());
84
+ }
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);
96
+ }
97
+ // No verified CN Work app-data layout on other platforms yet.
98
+ return null;
99
+ }
100
+
101
+ function resolveTraeCnStoragePath(options = {}) {
102
+ const home = resolveTraeCnHome(options);
103
+ return home ? path.join(home, "User", "globalStorage", "storage.json") : null;
104
+ }
105
+
106
+ // ---------------------------------------------------------------------------
107
+ // tc v5 decryption
108
+ // ---------------------------------------------------------------------------
109
+
110
+ function traeCnHardcodedKdfSecret() {
111
+ const secret = Buffer.alloc(64);
112
+ for (let i = 0; i < 64; i++) secret[i] = TRAE_CN_JG[i] ^ TRAE_CN_KG[i];
113
+ return secret;
114
+ }
115
+
116
+ function deriveTraeCnKeyIv(salt) {
117
+ if (!Buffer.isBuffer(salt) || salt.length !== TRAE_CN_SALT_LEN) {
118
+ throw new Error("Trae CN auth salt is malformed.");
119
+ }
120
+ const kdfBuf = Buffer.concat([
121
+ crypto.createHash("sha512").update(salt).digest(),
122
+ traeCnHardcodedKdfSecret(),
123
+ ]);
124
+ // Vendor tc-v5 compatibility KDF, not password storage.
125
+ const kdfOut = crypto.createHash("sha512").update(kdfBuf).digest();
126
+ return {
127
+ key: kdfOut.subarray(0, TRAE_CN_AES_KEY_LEN),
128
+ iv: kdfOut.subarray(TRAE_CN_AES_KEY_LEN, TRAE_CN_AES_KEY_LEN + TRAE_CN_IV_LEN),
129
+ };
130
+ }
131
+
132
+ /** Decrypt a raw tc v5 blob; returns the JSON bytes (integrity prefix stripped). */
133
+ function decryptTraeCnBlob(blob) {
134
+ const minLen = TRAE_CN_MAGIC.length + TRAE_CN_SALT_LEN + 16;
135
+ if (!Buffer.isBuffer(blob) || blob.length < minLen) {
136
+ throw new Error("Trae CN auth blob is too short.");
137
+ }
138
+ if (!blob.subarray(0, TRAE_CN_MAGIC.length).equals(TRAE_CN_MAGIC)) {
139
+ throw new Error("Trae CN auth blob has an unknown format.");
140
+ }
141
+ const salt = blob.subarray(TRAE_CN_MAGIC.length, TRAE_CN_MAGIC.length + TRAE_CN_SALT_LEN);
142
+ const ciphertext = blob.subarray(TRAE_CN_MAGIC.length + TRAE_CN_SALT_LEN);
143
+ if (ciphertext.length % 16 !== 0) {
144
+ throw new Error("Trae CN auth blob is not block-aligned.");
145
+ }
146
+ const { key, iv } = deriveTraeCnKeyIv(salt);
147
+ const decipher = crypto.createDecipheriv("aes-128-cbc", key, iv); // PKCS7 default
148
+ let plaintext;
149
+ try {
150
+ plaintext = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
151
+ } catch (_error) {
152
+ throw new Error("Trae CN auth blob could not be decrypted.");
153
+ }
154
+ if (plaintext.length < TRAE_CN_HASH_LEN) {
155
+ throw new Error("Trae CN auth blob is missing its integrity digest.");
156
+ }
157
+ const expected = plaintext.subarray(0, TRAE_CN_HASH_LEN);
158
+ const data = plaintext.subarray(TRAE_CN_HASH_LEN);
159
+ const actual = crypto.createHash("sha512").update(data).digest();
160
+ if (expected.length !== actual.length || !crypto.timingSafeEqual(expected, actual)) {
161
+ throw new Error("Trae CN auth blob failed its integrity check.");
162
+ }
163
+ return data;
164
+ }
165
+
166
+ /** Decrypt a Base64-encoded tc v5 blob and return the plaintext UTF-8 string. */
167
+ function decryptTraeCnBase64(value) {
168
+ const blob = Buffer.from(String(value).trim(), "base64");
169
+ return decryptTraeCnBlob(blob).toString("utf8");
170
+ }
171
+
172
+ // ---------------------------------------------------------------------------
173
+ // Credential reading
174
+ // ---------------------------------------------------------------------------
175
+
176
+ /**
177
+ * Parse a stored auth value: a plaintext JSON object / JSON string, or a
178
+ * Base64-encoded tc v5 blob. Fails closed with a credential-safe error.
179
+ */
180
+ function parseTraeCnAuthValue(value) {
181
+ if (value && typeof value === "object") {
182
+ return value;
183
+ }
184
+ if (typeof value === "string") {
185
+ const trimmed = value.trim();
186
+ if (!trimmed) {
187
+ throw new Error("Trae CN auth data is empty.");
188
+ }
189
+ if (trimmed.startsWith("{")) {
190
+ let parsed;
191
+ try {
192
+ parsed = JSON.parse(trimmed);
193
+ } catch (_error) {
194
+ throw new Error("Trae CN auth JSON is malformed.");
195
+ }
196
+ if (!parsed || typeof parsed !== "object") {
197
+ throw new Error("Trae CN auth JSON is malformed.");
198
+ }
199
+ return parsed;
200
+ }
201
+ let decrypted;
202
+ try {
203
+ decrypted = decryptTraeCnBase64(trimmed);
204
+ } catch (error) {
205
+ if (error && error.message.startsWith("Trae CN auth")) throw error;
206
+ throw new Error("Trae CN auth payload is malformed.");
207
+ }
208
+ let parsed;
209
+ try {
210
+ parsed = JSON.parse(decrypted);
211
+ } catch (_error) {
212
+ throw new Error("Trae CN auth payload is malformed.");
213
+ }
214
+ if (!parsed || typeof parsed !== "object") {
215
+ throw new Error("Trae CN auth payload is malformed.");
216
+ }
217
+ return parsed;
218
+ }
219
+ throw new Error("Trae CN auth data is missing or malformed.");
220
+ }
221
+
222
+ /**
223
+ * Read + decrypt the auth object from storage.json. Returns null when the
224
+ * file or the auth key is absent (not signed in). Throws a credential-safe
225
+ * error when present data is malformed, and a distinct unreadable error for
226
+ * real IO failures (permission denied, I/O error) - an unreadable storage
227
+ * file must not be reported as "not signed in".
228
+ */
229
+ function readTraeCnAuthFromStorage({ env, home, platform, fsModule = fs } = {}) {
230
+ const storagePath = resolveTraeCnStoragePath({ env, home, platform });
231
+ if (!storagePath) return null;
232
+ let raw;
233
+ try {
234
+ raw = fsModule.readFileSync(storagePath, "utf8");
235
+ } catch (error) {
236
+ // A missing file (or missing path component) simply means the app is not
237
+ // installed / not signed in. Any other failure - EACCES, EISDIR, a real
238
+ // I/O error - fails closed with a generic, credential-safe error. Only a
239
+ // stable machine-readable code is attached, never the OS detail, so
240
+ // storage contents cannot leak through logs or error messages.
241
+ if (error && (error.code === "ENOENT" || error.code === "ENOTDIR")) {
242
+ return null;
243
+ }
244
+ const unreadable = new Error("Trae CN storage.json could not be read.");
245
+ unreadable.code = "TRAE_CN_STORAGE_UNREADABLE";
246
+ throw unreadable;
247
+ }
248
+ let parsed;
249
+ try {
250
+ parsed = JSON.parse(raw);
251
+ } catch (_error) {
252
+ throw new Error("Trae CN storage.json is not valid JSON.");
253
+ }
254
+ const value = parsed && typeof parsed === "object" ? parsed[TRAE_CN_AUTH_KEY] : undefined;
255
+ if (value === undefined || value === null) return null;
256
+ return parseTraeCnAuthValue(value);
257
+ }
258
+
259
+ /** Extract a nonempty JWT from a parsed auth object. */
260
+ function extractTraeCnToken(auth) {
261
+ const token = auth && typeof auth === "object" ? auth.token : undefined;
262
+ if (typeof token === "string" && token.trim()) {
263
+ return token.trim();
264
+ }
265
+ throw new Error("Trae CN auth data has no token.");
266
+ }
267
+
268
+ // ---------------------------------------------------------------------------
269
+ // Usage API
270
+ // ---------------------------------------------------------------------------
271
+
272
+ function usageError(message, { status, apiCode } = {}) {
273
+ const error = new Error(message);
274
+ if (status !== undefined) error.status = status;
275
+ if (apiCode !== undefined) error.apiCode = apiCode;
276
+ if (status === 401 || status === 403) error.code = "AUTH_EXPIRED";
277
+ return error;
278
+ }
279
+
280
+ function assertUsageParams({ start_time, end_time, page_size }) {
281
+ if (!Number.isInteger(start_time) || start_time <= 0) {
282
+ throw new Error("Trae CN usage start_time must be a positive integer epoch second.");
283
+ }
284
+ if (!Number.isInteger(end_time) || end_time <= 0) {
285
+ throw new Error("Trae CN usage end_time must be a positive integer epoch second.");
286
+ }
287
+ if (start_time > end_time) {
288
+ throw new Error("Trae CN usage start_time must not be after end_time.");
289
+ }
290
+ if (!Number.isInteger(page_size) || page_size <= 0 || page_size > TRAE_CN_USAGE_PAGE_SIZE) {
291
+ throw new Error(
292
+ `Trae CN usage page_size must be a positive integer no greater than ${TRAE_CN_USAGE_PAGE_SIZE}.`,
293
+ );
294
+ }
295
+ }
296
+
297
+ /**
298
+ * Fetch one page of TRAE CN usage. Returns { sessions, total, page_num, page_size }
299
+ * where `total` is null when the API omits it. Errors never contain the JWT
300
+ * or the raw request/response body.
301
+ */
302
+ async function fetchTraeCnUsagePage({
303
+ jwt,
304
+ start_time,
305
+ end_time,
306
+ page_num,
307
+ page_size = TRAE_CN_USAGE_PAGE_SIZE,
308
+ fetchImpl = fetch,
309
+ timeoutMs = TRAE_CN_USAGE_TIMEOUT_MS,
310
+ } = {}) {
311
+ if (typeof jwt !== "string" || !jwt.trim()) {
312
+ throw new Error("Trae CN usage request requires a token.");
313
+ }
314
+ if (!Number.isInteger(page_num) || page_num < 1) {
315
+ throw new Error("Trae CN usage page_num must be a positive integer.");
316
+ }
317
+ assertUsageParams({ start_time, end_time, page_size });
318
+ const controller = new AbortController();
319
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
320
+ try {
321
+ let response;
322
+ try {
323
+ // Security note (CodeQL "File data -> outbound network request"):
324
+ // the credential read from TRAE's local storage.json is sent ONLY to
325
+ // TRAE_CN_USAGE_URL, a compile-time constant HTTPS endpoint of the
326
+ // official API - callers cannot redirect the destination (the url
327
+ // parameter is ignored; pinned by the "sends the exact request" test).
328
+ // The whole flow is behind the explicit TOKENUSAGE_TRAE_CN_USAGE
329
+ // opt-in, the JWT is never logged, never written to the queue/cursor
330
+ // state, and never uploaded to the Token Usage cloud (queue rows carry
331
+ // token counters only; transport exceptions are sanitized).
332
+ response = await fetchImpl(TRAE_CN_USAGE_URL, {
333
+ method: "POST",
334
+ headers: {
335
+ "Content-Type": "application/json",
336
+ Authorization: `Cloud-IDE-JWT ${jwt.trim()}`,
337
+ },
338
+ body: JSON.stringify({
339
+ usage_type: TRAE_CN_USAGE_TYPE,
340
+ start_time,
341
+ end_time,
342
+ page_num,
343
+ page_size,
344
+ }),
345
+ signal: controller.signal,
346
+ });
347
+ } catch (_error) {
348
+ throw new Error("Trae CN usage API request failed.");
349
+ }
350
+ if (response.status === 401 || response.status === 403) {
351
+ throw usageError(`Trae CN usage API returned HTTP ${response.status}.`, { status: response.status });
352
+ }
353
+ if (!response.ok) {
354
+ throw usageError(`Trae CN usage API returned HTTP ${response.status}.`, { status: response.status });
355
+ }
356
+ let parsed;
357
+ try {
358
+ parsed = await response.json();
359
+ } catch (_error) {
360
+ throw new Error("Trae CN usage API returned a non-JSON response.");
361
+ }
362
+ const apiCode = parsed?.data?.code ?? parsed?.code;
363
+ if (apiCode !== undefined && Number(apiCode) !== 0) {
364
+ throw usageError(`Trae CN usage API returned error code ${apiCode}.`, {
365
+ status: response.status,
366
+ apiCode: Number(apiCode),
367
+ });
368
+ }
369
+ // Documented wrapper: data.user_usage_group_by_sessions, or the top-level
370
+ // equivalent. Only this module parses the wrapper; token rows/buckets are
371
+ // normalized elsewhere. A body without the session-array wrapper fails
372
+ // closed as a schema error instead of being misread as an empty result;
373
+ // an explicit empty array remains valid.
374
+ const data = parsed?.data && typeof parsed.data === "object" ? parsed.data : parsed;
375
+ if (!Array.isArray(data?.user_usage_group_by_sessions)) {
376
+ throw new Error("Trae CN usage API response is missing the session list.");
377
+ }
378
+ const sessions = data.user_usage_group_by_sessions;
379
+ // The declared total gates pagination termination (sessions.length >=
380
+ // total stops the walk), so a malformed value must fail closed as a
381
+ // schema error - never be coerced into a legal-looking stop condition.
382
+ // A negative, fractional, non-finite, or non-number total (the API
383
+ // speaks JSON numbers; a quoted digit string is a schema anomaly) would
384
+ // otherwise silently truncate the snapshot after page 1 and still look
385
+ // authoritative.
386
+ const rawTotal = data?.total;
387
+ let total = null;
388
+ if (rawTotal !== undefined && rawTotal !== null) {
389
+ if (
390
+ typeof rawTotal !== "number" ||
391
+ !Number.isSafeInteger(rawTotal) ||
392
+ rawTotal < 0
393
+ ) {
394
+ throw new Error("Trae CN usage API returned an invalid total.");
395
+ }
396
+ total = rawTotal;
397
+ }
398
+ return { sessions, total, page_num, page_size };
399
+ } finally {
400
+ clearTimeout(timer);
401
+ }
402
+ }
403
+
404
+ /**
405
+ * Fetch usage across pages serially. Starts at the 1-based page_num, at most
406
+ * maxPages pages, with a delay between pages (pass delayMs = 0 to disable in
407
+ * tests). Stops at the stated total when present, otherwise on an empty page.
408
+ * Throws if maxPages is reached while another page would still be needed.
409
+ */
410
+ async function fetchTraeCnUsage({
411
+ jwt,
412
+ start_time,
413
+ end_time,
414
+ page_num = 1,
415
+ page_size = TRAE_CN_USAGE_PAGE_SIZE,
416
+ fetchImpl = fetch,
417
+ maxPages = TRAE_CN_USAGE_MAX_PAGES,
418
+ delayMs = TRAE_CN_USAGE_DELAY_MS,
419
+ pageFetcher = fetchTraeCnUsagePage,
420
+ } = {}) {
421
+ const sessions = [];
422
+ let total = null;
423
+ let pagesFetched = 0;
424
+ let page = page_num;
425
+ for (;;) {
426
+ if (pagesFetched >= maxPages) {
427
+ // A further page would be needed but the cap prevents it: fail closed
428
+ // rather than return a partial snapshot that looks authoritative. Cap
429
+ // exhaustion is the same over-capacity signal as the declared-total
430
+ // check below (which the API may omit) — tag it identically so window
431
+ // splitting engages either way.
432
+ const error = new Error("Trae CN usage pagination exceeded the maximum page count.");
433
+ error.code = "TRAE_CN_USAGE_CAPACITY_EXCEEDED";
434
+ throw error;
435
+ }
436
+ const result = await pageFetcher({ jwt, start_time, end_time, page_num: page, page_size, fetchImpl });
437
+ pagesFetched += 1;
438
+ total = result.total ?? null;
439
+ if (pagesFetched === 1 && Number.isFinite(total) && total > page_size * maxPages) {
440
+ const error = new Error("Trae CN usage snapshot exceeds the supported capacity.");
441
+ error.code = "TRAE_CN_USAGE_CAPACITY_EXCEEDED";
442
+ throw error;
443
+ }
444
+ if (Array.isArray(result.sessions)) sessions.push(...result.sessions);
445
+ if (result.sessions.length === 0) break;
446
+ if (total !== null && sessions.length >= total) break;
447
+ if (delayMs > 0) await new Promise((resolve) => setTimeout(resolve, delayMs));
448
+ page += 1;
449
+ }
450
+ return { sessions, total, pages_fetched: pagesFetched };
451
+ }
452
+
453
+ /**
454
+ * Capacity-adaptive window fetch. Probing the official API confirmed the
455
+ * start_time/end_time range is closed on both ends ([a,b] and [b,c] both
456
+ * return the row at b) and that a row returned by two overlapping windows is
457
+ * byte-identical (idempotent duplicate, never cumulative). Splitting therefore
458
+ * staggers adjacent sub-windows by one second ([start,mid] + [mid+1,end]) so
459
+ * the union equals the full window exactly; any residual duplicate would be
460
+ * absorbed by the session-level reconciliation. On TRAE_CN_USAGE_CAPACITY_
461
+ * EXCEEDED the window halves recursively up to maxSplitDepth levels; a window
462
+ * still over capacity at the finest allowed granularity re-throws so the
463
+ * caller keeps its fail-closed guarantee.
464
+ */
465
+ async function fetchTraeCnUsageWindowed(options = {}, depth = 0) {
466
+ const { start_time, end_time } = options;
467
+ try {
468
+ return await fetchTraeCnUsage(options);
469
+ } catch (error) {
470
+ if (error?.code !== "TRAE_CN_USAGE_CAPACITY_EXCEEDED") throw error;
471
+ if (end_time - start_time < 1 || depth >= TRAE_CN_USAGE_MAX_SPLIT_DEPTH) throw error;
472
+ const mid = start_time + Math.floor((end_time - start_time) / 2);
473
+ const left = await fetchTraeCnUsageWindowed({ ...options, end_time: mid }, depth + 1);
474
+ const right = await fetchTraeCnUsageWindowed({ ...options, start_time: mid + 1 }, depth + 1);
475
+ const total =
476
+ Number.isFinite(left.total) && Number.isFinite(right.total) ? left.total + right.total : null;
477
+ return {
478
+ sessions: [...left.sessions, ...right.sessions],
479
+ total,
480
+ pages_fetched: left.pages_fetched + right.pages_fetched,
481
+ };
482
+ }
483
+ }
484
+
485
+ /**
486
+ * High-level storage-backed fetch: read the JWT from storage.json, fetch
487
+ * usage, and on a 401/403 re-read + re-decrypt storage.json and retry exactly
488
+ * once. Never persists or logs the JWT / refresh token; no refreshToken flow.
489
+ */
490
+ async function fetchTraeCnUsageWithAuth({
491
+ start_time,
492
+ end_time,
493
+ page_num = 1,
494
+ page_size = TRAE_CN_USAGE_PAGE_SIZE,
495
+ fetchImpl = fetch,
496
+ delayMs = TRAE_CN_USAGE_DELAY_MS,
497
+ maxPages = TRAE_CN_USAGE_MAX_PAGES,
498
+ readAuth = readTraeCnAuthFromStorage,
499
+ usageFetcher = fetchTraeCnUsageWindowed,
500
+ ...storageOptions
501
+ } = {}) {
502
+ let auth = readAuth(storageOptions);
503
+ let jwt = auth ? extractTraeCnToken(auth) : null;
504
+ if (!jwt) {
505
+ throw new Error("Trae CN credentials are not configured.");
506
+ }
507
+ const run = () =>
508
+ usageFetcher({ jwt, start_time, end_time, page_num, page_size, fetchImpl, delayMs, maxPages });
509
+ try {
510
+ return await run();
511
+ } catch (error) {
512
+ const authFailure =
513
+ error?.code === "AUTH_EXPIRED" || error?.status === 401 || error?.status === 403;
514
+ if (!authFailure) throw error;
515
+ // Session may have rotated since the first read; re-read storage once.
516
+ auth = readAuth(storageOptions);
517
+ jwt = auth ? extractTraeCnToken(auth) : null;
518
+ if (!jwt) throw error;
519
+ return await run();
520
+ }
521
+ }
522
+
523
+ module.exports = {
524
+ TRAE_CN_HOME_ENV,
525
+ TRAE_CN_USAGE_ENV,
526
+ isTraeCnUsageEnabled,
527
+ TRAE_CN_APP_DIR,
528
+ TRAE_CN_AUTH_KEY,
529
+ TRAE_CN_USAGE_URL,
530
+ TRAE_CN_USAGE_TYPE,
531
+ TRAE_CN_USAGE_PAGE_SIZE,
532
+ TRAE_CN_USAGE_MAX_PAGES,
533
+ TRAE_CN_USAGE_DELAY_MS,
534
+ TRAE_CN_MAGIC,
535
+ resolveTraeCnHome,
536
+ resolveTraeCnStoragePath,
537
+ traeCnHardcodedKdfSecret,
538
+ deriveTraeCnKeyIv,
539
+ decryptTraeCnBlob,
540
+ decryptTraeCnBase64,
541
+ parseTraeCnAuthValue,
542
+ readTraeCnAuthFromStorage,
543
+ extractTraeCnToken,
544
+ fetchTraeCnUsagePage,
545
+ fetchTraeCnUsage,
546
+ fetchTraeCnUsageWindowed,
547
+ fetchTraeCnUsageWithAuth,
548
+ };
@@ -0,0 +1,127 @@
1
+ const fs = require("node:fs");
2
+ const os = require("node:os");
3
+ const path = require("node:path");
4
+
5
+ const { openTraeSnapshot } = require("./trae-snapshot");
6
+ const { withTraeSqlite } = require("./trae-sqlite");
7
+
8
+ const TOKEN_FIELDS = [
9
+ "prompt_tokens", "prompt_tokens_total", "input_tokens",
10
+ "completion_tokens", "completion_tokens_total", "output_tokens",
11
+ "total_tokens", "cache_read_input_tokens", "cache_creation_input_tokens",
12
+ "reasoning_tokens", "reasoning_output_tokens",
13
+ ];
14
+
15
+ function resolveTraeDbPaths(env = process.env, { platform = process.platform, home = os.homedir() } = {}) {
16
+ const explicit = String(env.TOKENUSAGE_TRAE_DB || "").trim();
17
+ if (explicit) return [path.resolve(explicit)];
18
+ const customHome = String(env.TOKENUSAGE_TRAE_HOME || "").trim();
19
+ const parent = platform === "win32"
20
+ ? env.APPDATA || path.join(home, "AppData", "Roaming")
21
+ : platform === "darwin"
22
+ ? path.join(home, "Library", "Application Support")
23
+ : env.XDG_CONFIG_HOME || path.join(home, ".config");
24
+ const roots = customHome ? [customHome] : [path.join(parent, "Trae"), path.join(parent, "TRAE SOLO")];
25
+ const result = [];
26
+ for (const root of roots) {
27
+ // A decrypted sibling may be an old export. Only an explicit DB override
28
+ // opts into one; normal discovery always reads the current application DB.
29
+ for (const module of ["ai-agent", "ai-chat"]) {
30
+ const candidate = path.resolve(root, "ModularData", module, "database.db");
31
+ let present;
32
+ try { present = fs.statSync(candidate).isFile(); }
33
+ catch (err) {
34
+ // Permission failures must reach the reader's diagnostics, not masquerade
35
+ // as an absent installation and silently drop an entire usage history.
36
+ present = err.code !== "ENOENT" && err.code !== "ENOTDIR";
37
+ }
38
+ if (present) {
39
+ result.push(candidate);
40
+ break;
41
+ }
42
+ }
43
+ }
44
+ return [...new Set(result)];
45
+ }
46
+
47
+ function error(message) {
48
+ return new Error(`Cannot read TRAE usage: ${message}`);
49
+ }
50
+
51
+ async function projectUsage(queryRows) {
52
+ const tables = await queryRows("SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'chat_turn'");
53
+ // history_v2.token_usage can be a context-size snapshot rather than billed
54
+ // usage. Do not synthesize input tokens from those scalar values.
55
+ if (!tables.length) throw error("unsupported database schema: chat_turn table is missing.");
56
+ const columns = new Set((await queryRows("PRAGMA table_info(chat_turn)")).map((row) => row.name));
57
+ if (!columns.has("context") || (!columns.has("created_at") && !columns.has("updated_at"))) {
58
+ throw error("unsupported chat_turn schema.");
59
+ }
60
+ const column = (name, fallback = "NULL") => columns.has(name) ? `"${name}"` : fallback;
61
+ const date = columns.has("created_at") && columns.has("updated_at")
62
+ ? 'COALESCE("created_at", "updated_at")' : column("created_at", column("updated_at"));
63
+ const modelPaths = [
64
+ "persist_user_message_context.model_info.display_model_name",
65
+ "persist_user_message_context.model_info.model_name",
66
+ "persist_user_message_context.model_info.config_name", "model_name", "model",
67
+ "agent_model", "selected_model.name", "selectedModel.name",
68
+ ];
69
+ const model = modelPaths.map((field) => `CASE WHEN json_type(context, '$.${field}') = 'text'
70
+ THEN NULLIF(NULLIF(TRIM(json_extract(context, '$.${field}')), ''), '-') END`);
71
+ const fields = TOKEN_FIELDS.map((field) => `CASE
72
+ WHEN json_type(context, '$.token_usage.${field}') IN ('integer', 'real')
73
+ THEN json_extract(context, '$.token_usage.${field}') END AS "${field}"`);
74
+ const invalidFields = TOKEN_FIELDS.map((field) =>
75
+ `COALESCE(json_type(context, '$.token_usage.${field}') NOT IN ('integer', 'real', 'null'), 0)`);
76
+ // Project inside SQLite: prompts, messages, session titles, fee/account data,
77
+ // and the rest of the context never cross into JS results or cursor state.
78
+ const query = `SELECT CAST(${column("id", "rowid")} AS TEXT) AS id,
79
+ ${column("session_id")} AS session_id, ${column("turn_id")} AS turn_id,
80
+ ${date} AS created_at, ${column("updated_at")} AS updated_at,
81
+ COALESCE(${model.join(", ")}, 'trae-unknown') AS model,
82
+ ${fields.join(", ")}, (${invalidFields.join(" OR ")}) AS invalid_usage
83
+ FROM chat_turn WHERE CASE WHEN json_valid(context)
84
+ THEN json_type(context, '$.token_usage') = 'object' ELSE 0 END`;
85
+ return (await queryRows(query)).map((row) => {
86
+ const usage = {};
87
+ let invalid = Boolean(row.invalid_usage);
88
+ for (const field of TOKEN_FIELDS) {
89
+ const value = row[field];
90
+ if (value == null) continue;
91
+ if (!Number.isSafeInteger(value) || value < 0) invalid = true;
92
+ else usage[field] = value;
93
+ }
94
+ return {
95
+ id: row.id, session_id: row.session_id, turn_id: row.turn_id,
96
+ created_at: row.created_at, updated_at: row.updated_at,
97
+ model: row.model, usage: invalid ? null : usage,
98
+ };
99
+ });
100
+ }
101
+
102
+ async function readTraeUsageRows(dbPath, { env = process.env } = {}) {
103
+ for (let attempt = 0; attempt < 3; attempt++) {
104
+ let snapshot;
105
+ try { snapshot = openTraeSnapshot(dbPath, env); }
106
+ catch (err) {
107
+ // A writer can also change the files while the snapshot opens. Retry
108
+ // that too, and report the specific failure once attempts run out.
109
+ if (err?.transient && attempt < 2) continue;
110
+ throw err;
111
+ }
112
+ try {
113
+ let result;
114
+ try { result = await withTraeSqlite(snapshot, projectUsage); }
115
+ catch (err) {
116
+ // A writer may have changed pages while SQLite was reading. Discard
117
+ // every projected row and retry; never publish a mixed snapshot.
118
+ if (snapshot.isStable()) throw err;
119
+ continue;
120
+ }
121
+ if (snapshot.isStable()) return result;
122
+ } finally { snapshot.close(); }
123
+ }
124
+ throw error("database changed during the read; retry after TRAE finishes its current turn.");
125
+ }
126
+
127
+ module.exports = { resolveTraeDbPaths, readTraeUsageRows };