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,1172 +1,1172 @@
1
- const fs = require("node:fs");
2
- const crypto = require("node:crypto");
3
- const os = require("node:os");
4
- const path = require("node:path");
5
- const { fetchZcodeResetCredits } = require("./zcode-reset-credits");
6
-
7
- const DEFAULT_BILLING_BASE_URL = "https://zcode.z.ai/api/v1/zcode-plan";
8
- const DEFAULT_ZAI_MONITOR_BASE_URL = "https://api.z.ai";
9
- const DEFAULT_BIGMODEL_MONITOR_BASE_URL = "https://bigmodel.cn";
10
- const ZCODE_MONITOR_QUOTA_PATH = "/api/monitor/usage/quota/limit";
11
- const DEFAULT_ZCODE_APP_VERSION = "3.2.5";
12
- const DEFAULT_ZCODE_LOG_FALLBACK_MAX_AGE_MS = 6 * 60 * 60 * 1000;
13
-
14
- function resolveZcodeHome({ home, env = process.env } = {}) {
15
- if (typeof env.TOKENUSAGE_ZCODE_HOME === "string" && env.TOKENUSAGE_ZCODE_HOME.trim()) {
16
- return path.resolve(env.TOKENUSAGE_ZCODE_HOME.trim());
17
- }
18
- if (typeof env.ZCODE_HOME === "string" && env.ZCODE_HOME.trim()) {
19
- return path.resolve(env.ZCODE_HOME.trim());
20
- }
21
- return path.join(home || os.homedir(), ".zcode");
22
- }
23
-
24
- function resolveZcodeBillingBaseUrl(env = process.env) {
25
- const explicit =
26
- typeof env.TOKENUSAGE_ZCODE_BILLING_BASE_URL === "string"
27
- ? env.TOKENUSAGE_ZCODE_BILLING_BASE_URL.trim()
28
- : "";
29
- if (explicit) return explicit.replace(/\/$/, "");
30
- return DEFAULT_BILLING_BASE_URL;
31
- }
32
-
33
- function parsePositiveInteger(value, fallback) {
34
- const n = Number(value);
35
- return Number.isFinite(n) && n >= 0 ? n : fallback;
36
- }
37
-
38
- function readZcodeAppVersionFromPlist(plistPath) {
39
- try {
40
- if (!fs.existsSync(plistPath)) return null;
41
- const text = fs.readFileSync(plistPath, "utf8");
42
- const keyIndex = text.indexOf("<key>CFBundleShortVersionString</key>");
43
- if (keyIndex < 0) return null;
44
- const match = text.slice(keyIndex).match(/<string>([^<]+)<\/string>/);
45
- const version = typeof match?.[1] === "string" ? match[1].trim() : "";
46
- return version || null;
47
- } catch (_error) {
48
- return null;
49
- }
50
- }
51
-
52
- function resolveZcodeAppVersion({ home, env = process.env } = {}) {
53
- const explicit =
54
- typeof env.TOKENUSAGE_ZCODE_APP_VERSION === "string"
55
- ? env.TOKENUSAGE_ZCODE_APP_VERSION.trim()
56
- : "";
57
- if (explicit) return explicit;
58
-
59
- const appPath =
60
- typeof env.TOKENUSAGE_ZCODE_APP_PATH === "string" && env.TOKENUSAGE_ZCODE_APP_PATH.trim()
61
- ? env.TOKENUSAGE_ZCODE_APP_PATH.trim()
62
- : null;
63
- const candidates = appPath
64
- ? [path.join(appPath, "Contents", "Info.plist")]
65
- : [
66
- "/Applications/ZCode.app/Contents/Info.plist",
67
- path.join(home || os.homedir(), "Applications", "ZCode.app", "Contents", "Info.plist"),
68
- ];
69
- for (const plistPath of candidates) {
70
- const version = readZcodeAppVersionFromPlist(plistPath);
71
- if (version) return version;
72
- }
73
- // The API currently rejects balance requests without app_version. The value is
74
- // not used for local accounting, so keep a conservative fallback for CLI-only installs.
75
- return DEFAULT_ZCODE_APP_VERSION;
76
- }
77
-
78
- /** True when any ZCode layout is present: legacy v2/config.json, 3.14+ credentials, or the CLI db. */
79
- function isZcodeInstalled({ home, env } = {}) {
80
- const zcodeHome = resolveZcodeHome({ home, env });
81
- const configPath = path.join(zcodeHome, "v2", "config.json");
82
- if (fs.existsSync(configPath)) return true;
83
- // ZCode 3.14+ no longer writes v2/config.json; a signed-in desktop app still keeps credentials.
84
- if (fs.existsSync(path.join(zcodeHome, "v2", "credentials.json"))) return true;
85
- const dbPath = path.join(zcodeHome, "cli", "db", "db.sqlite");
86
- return fs.existsSync(dbPath);
87
- }
88
-
89
- function loadZcodeProviderAvailability({ home, env } = {}) {
90
- const zcodeHome = resolveZcodeHome({ home, env });
91
- const cachePath = path.join(zcodeHome, "v2", "coding-plan-cache.json");
92
- if (!fs.existsSync(cachePath)) return {};
93
- try {
94
- const cache = JSON.parse(fs.readFileSync(cachePath, "utf8"));
95
- const items = cache?.entryStatus?.items;
96
- return items && typeof items === "object" ? items : {};
97
- } catch (_error) {
98
- return {};
99
- }
100
- }
101
-
102
- /**
103
- * Decode routing identifiers from a complete team selection for the given family.
104
- * Returns null for personal, malformed, or legacy project-only selections.
105
- * @returns {{ organizationId: string, projectId: string } | null}
106
- */
107
- function parseZcodeTeamContext(selection, family) {
108
- if (family !== "bigmodel" && family !== "zai") return null;
109
- const prefix = `team-plan:builtin:${family}-coding-plan:`;
110
- if (!selection.startsWith(prefix)) return null;
111
- const parts = selection.slice(prefix.length).split(":");
112
- // ZCode 3.10.x stores product:organization:project. Older project-only
113
- // selections do not identify an organization, so do not guess its scope.
114
- if (parts.length !== 3) return null;
115
- try {
116
- const [productId, organizationId, projectId] = parts.map((part) => decodeURIComponent(part.trim()).trim());
117
- if (!productId || !organizationId || !projectId) return null;
118
- return { organizationId, projectId };
119
- } catch (_error) {
120
- return null;
121
- }
122
- }
123
-
124
- /**
125
- * Read selected plans in active-family order, retaining each plan's team scope.
126
- * Only the provider key and decoded organization/project identifiers are retained.
127
- */
128
- function loadZcodeSelectedPlans({ home, env } = {}) {
129
- const zcodeHome = resolveZcodeHome({ home, env });
130
- const settingPath = path.join(zcodeHome, "v2", "setting.json");
131
- if (!fs.existsSync(settingPath)) return [];
132
- try {
133
- const setting = JSON.parse(fs.readFileSync(settingPath, "utf8"));
134
- const selected = setting?.modelProviderFamilySelectedKeys;
135
- const domain = typeof setting?.providerFamilyDomain === "string" ? setting.providerFamilyDomain : "";
136
- if (!selected || typeof selected !== "object") {
137
- return loadZcodeConnectionSelectedPlans(setting?.providerFamilyConnectionSelections, domain);
138
- }
139
- const domains = [domain, ...Object.keys(selected)].filter(Boolean);
140
- const out = [];
141
- for (const key of domains) {
142
- const raw = typeof selected[key] === "string" ? selected[key].trim() : "";
143
- const match = raw.match(/builtin:(?:bigmodel|zai)-(?:start|coding)-plan/);
144
- if (!match || out.some((plan) => plan.providerKey === match[0])) continue;
145
- out.push({ providerKey: match[0], teamContext: parseZcodeTeamContext(raw, key) });
146
- }
147
- return out;
148
- } catch (_error) {
149
- return [];
150
- }
151
- }
152
-
153
- /**
154
- * ZCode 3.14+ records the chosen plan per family as `providerFamilyConnectionSelections`
155
- * (`{ zai: { kind: "individual-coding-plan" } }`) instead of `modelProviderFamilySelectedKeys`.
156
- * Team scope for these selections lives on the account credential, not here.
157
- */
158
- function loadZcodeConnectionSelectedPlans(selections, domain) {
159
- if (!selections || typeof selections !== "object") return [];
160
- const families = [domain, ...Object.keys(selections)].filter((family) => family === "bigmodel" || family === "zai");
161
- const out = [];
162
- for (const family of families) {
163
- const kind = typeof selections[family]?.kind === "string" ? selections[family].kind : "";
164
- const planKind = /coding-plan$/.test(kind) ? "coding" : kind === "start-plan" ? "start" : null;
165
- if (!planKind) continue;
166
- const providerKey = `builtin:${family}-${planKind}-plan`;
167
- if (out.some((plan) => plan.providerKey === providerKey)) continue;
168
- out.push({ providerKey, teamContext: null });
169
- }
170
- return out;
171
- }
172
-
173
- /** Return the ordered provider keys without exposing the internal team context. */
174
- function loadZcodeSelectedPlanProviderKeys(options = {}) {
175
- return loadZcodeSelectedPlans(options).map((plan) => plan.providerKey);
176
- }
177
-
178
- function resolveZcodeCredentialsPath({ home, env } = {}) {
179
- return path.join(resolveZcodeHome({ home, env }), "v2", "credentials.json");
180
- }
181
-
182
- function createZcodeCredentialSecret({ home, env = process.env } = {}) {
183
- if (typeof env.ZCODE_CREDENTIAL_SECRET === "string" && env.ZCODE_CREDENTIAL_SECRET) {
184
- return env.ZCODE_CREDENTIAL_SECRET;
185
- }
186
- let username = "";
187
- try {
188
- username = os.userInfo().username || "";
189
- } catch (_error) {
190
- username = "";
191
- }
192
- return `zcode-credential-fallback:${process.platform}:${home || os.homedir()}:${username}`;
193
- }
194
-
195
- function decryptZcodeCredentialValue(value, { home, env } = {}) {
196
- if (typeof value !== "string") return null;
197
- if (!value.startsWith("enc:v1:")) return value;
198
- const encoded = value.slice("enc:v1:".length);
199
- const parts = encoded.split(".");
200
- if (parts.length !== 3) return null;
201
- try {
202
- const [ivPart, tagPart, encryptedPart] = parts;
203
- const iv = Buffer.from(ivPart, "base64url");
204
- const encrypted = Buffer.from(encryptedPart, "base64url");
205
- const tag = Buffer.from(tagPart, "base64url");
206
- const key = crypto.createHash("sha256").update(createZcodeCredentialSecret({ home, env })).digest();
207
- const decipher = crypto.createDecipheriv("aes-256-gcm", key, iv);
208
- decipher.setAuthTag(tag);
209
- return Buffer.concat([decipher.update(encrypted), decipher.final()]).toString("utf8");
210
- } catch (_error) {
211
- return null;
212
- }
213
- }
214
-
215
- function loadZcodeCredentials({ home, env } = {}) {
216
- const credentialsPath = resolveZcodeCredentialsPath({ home, env });
217
- if (!fs.existsSync(credentialsPath)) return {};
218
- try {
219
- const raw = JSON.parse(fs.readFileSync(credentialsPath, "utf8"));
220
- return raw && typeof raw === "object" ? raw : {};
221
- } catch (_error) {
222
- return {};
223
- }
224
- }
225
-
226
- function loadZcodeCredential(name, { home, env } = {}) {
227
- const credentials = loadZcodeCredentials({ home, env });
228
- const decrypted = decryptZcodeCredentialValue(credentials?.[name], { home, env });
229
- return typeof decrypted === "string" && decrypted.trim() ? decrypted.trim() : "";
230
- }
231
-
232
- function loadZcodeActiveProvider({ home, env } = {}) {
233
- return loadZcodeCredential("oauth:active_provider", { home, env });
234
- }
235
-
236
- function resolveZcodeCredentialAuth(providerKey, { home, env } = {}) {
237
- const activeProvider = loadZcodeActiveProvider({ home, env });
238
- if (
239
- (providerKey === "builtin:zai-start-plan" && activeProvider === "zai") ||
240
- (providerKey === "builtin:bigmodel-start-plan" && activeProvider === "bigmodel")
241
- ) {
242
- return loadZcodeCredential("zcodejwttoken", { home, env });
243
- }
244
- return "";
245
- }
246
-
247
- /**
248
- * Map a ZCode 3.14+ per-account key name onto the built-in coding-plan provider it serves:
249
- * account-provider:coding-plan:account:<family>-individual-coding-plan:account:<id>:api-key
250
- * account-provider:team:<providerId>:<productId>:<orgId>:<projectId>:account:<id>:api-key
251
- * Team segments are URI-encoded by ZCode. Start-plan balances use the zcodejwttoken instead.
252
- * @returns {{ providerKey: string, accountId: string, teamContext: { organizationId: string, projectId: string } | null } | null}
253
- */
254
- function parseZcodeAccountProviderCredentialName(name) {
255
- const match = typeof name === "string" ? name.match(/^account-provider:(.+):account:([^:]+):api-key$/) : null;
256
- if (!match) return null;
257
- const scope = match[1];
258
- const accountId = match[2];
259
- const individual = scope.match(/^coding-plan:account:(bigmodel|zai)-individual-coding-plan$/);
260
- if (individual) return { providerKey: `builtin:${individual[1]}-coding-plan`, accountId, teamContext: null };
261
- if (!scope.startsWith("team:")) return null;
262
- const parts = scope.slice("team:".length).split(":");
263
- if (parts.length !== 4) return null;
264
- try {
265
- const [providerId, productId, organizationId, projectId] = parts.map((part) => decodeURIComponent(part).trim());
266
- const team = providerId.match(/^account:(bigmodel|zai)-team-coding-plan$/);
267
- if (!team || !productId || !organizationId || !projectId) return null;
268
- return { providerKey: `builtin:${team[1]}-coding-plan`, accountId, teamContext: { organizationId, projectId } };
269
- } catch (_error) {
270
- return null;
271
- }
272
- }
273
-
274
- /** Region ("bigmodel" | "zai") a built-in plan provider belongs to. */
275
- function zcodeProviderFamily(providerKey) {
276
- return providerKey === "builtin:zai-coding-plan" || providerKey === "builtin:zai-start-plan" ? "zai" : "bigmodel";
277
- }
278
-
279
- /**
280
- * Region whose plan should be served first. The model settings' domain is the
281
- * region the user actually picked, so it wins; the OAuth login region only
282
- * backs installs that never recorded a domain (API-key-only setups).
283
- */
284
- function loadZcodeActiveRegion({ home, env } = {}) {
285
- try {
286
- const settingPath = path.join(resolveZcodeHome({ home, env }), "v2", "setting.json");
287
- if (fs.existsSync(settingPath)) {
288
- const setting = JSON.parse(fs.readFileSync(settingPath, "utf8"));
289
- const domain = typeof setting?.providerFamilyDomain === "string" ? setting.providerFamilyDomain.trim() : "";
290
- if (domain === "bigmodel" || domain === "zai") return domain;
291
- }
292
- } catch (_error) {
293
- // Fall through to the login region below.
294
- }
295
- const active = loadZcodeActiveProvider({ home, env });
296
- return active === "bigmodel" || active === "zai" ? active : "";
297
- }
298
-
299
- /**
300
- * Account id of the signed-in login for a region, from `oauth:<family>:user_info`.
301
- * Reset cards and Start Plan grants are personal to this login, so their
302
- * credentials may only ride along with quota keys that provably share it.
303
- */
304
- function loadZcodeLoginAccountId(family, { home, env } = {}) {
305
- const raw = loadZcodeCredential(`oauth:${family}:user_info`, { home, env });
306
- try {
307
- const id = JSON.parse(raw)?.id;
308
- return typeof id === "string" && id.trim() ? id.trim() : null;
309
- } catch (_error) {
310
- return null;
311
- }
312
- }
313
-
314
- /** Collect decrypted per-account coding-plan keys, grouped by built-in provider key. */
315
- function loadZcodeAccountProviderAuths({ home, env } = {}) {
316
- const credentials = loadZcodeCredentials({ home, env });
317
- const out = {};
318
- for (const name of Object.keys(credentials)) {
319
- const parsed = parseZcodeAccountProviderCredentialName(name);
320
- if (!parsed) continue;
321
- const decrypted = decryptZcodeCredentialValue(credentials[name], { home, env });
322
- const apiKey = typeof decrypted === "string" ? decrypted.trim() : "";
323
- if (!apiKey) continue;
324
- (out[parsed.providerKey] ||= []).push({ apiKey, accountId: parsed.accountId, teamContext: parsed.teamContext });
325
- }
326
- return out;
327
- }
328
-
329
- function isZcodeBuiltinPlanProvider(providerKey) {
330
- return /^builtin:(bigmodel|zai)-(start|coding)-plan$/.test(providerKey);
331
- }
332
-
333
- function isZcodeCodingPlanProvider(providerKey) {
334
- return /^builtin:(bigmodel|zai)-coding-plan$/.test(providerKey);
335
- }
336
-
337
- function isZcodeStartPlanProvider(providerKey) {
338
- return /^builtin:(bigmodel|zai)-start-plan$/.test(providerKey);
339
- }
340
-
341
- function readEnvString(env, names) {
342
- for (const name of names) {
343
- const value = typeof env?.[name] === "string" ? env[name].trim() : "";
344
- if (value) return value;
345
- }
346
- return "";
347
- }
348
-
349
- function resolveZcodeProviderBillingBaseUrl(providerKey, provider, env = process.env) {
350
- const explicit = resolveZcodeBillingBaseUrl(env);
351
- if (explicit !== DEFAULT_BILLING_BASE_URL) return explicit;
352
- if (isZcodeStartPlanProvider(providerKey)) return DEFAULT_BILLING_BASE_URL;
353
- const baseUrl = typeof provider?.options?.baseURL === "string" ? provider.options.baseURL.trim() : "";
354
- if (/\/zcode-plan\/anthropic\/?$/i.test(baseUrl)) return baseUrl.replace(/\/anthropic\/?$/i, "");
355
- return null;
356
- }
357
-
358
- function normalizeUrlOrigin(value) {
359
- try {
360
- const url = new URL(value);
361
- return url.origin.replace(/\/$/, "");
362
- } catch (_error) {
363
- return null;
364
- }
365
- }
366
-
367
- function resolveZcodeProviderQuotaUrl(providerKey, provider, env = process.env) {
368
- if (!isZcodeCodingPlanProvider(providerKey)) return null;
369
- const explicit = readEnvString(env, ["TOKENUSAGE_ZCODE_MONITOR_QUOTA_URL"]);
370
- if (explicit) return explicit;
371
-
372
- const baseUrl = typeof provider?.options?.baseURL === "string" ? provider.options.baseURL.trim() : "";
373
- const baseOrigin = normalizeUrlOrigin(baseUrl);
374
- const isZai = providerKey === "builtin:zai-coding-plan";
375
- const origin = isZai
376
- ? readEnvString(env, [
377
- "TOKENUSAGE_ZCODE_ZAI_MONITOR_BASE_URL",
378
- "ZAI_BUSINESS_BASE_URL",
379
- "ZAI_PRODUCTION_BUSINESS_BASE_URL",
380
- ]) || (baseOrigin && /(^|\.)api\.z\.ai$/i.test(new URL(baseOrigin).hostname) ? baseOrigin : DEFAULT_ZAI_MONITOR_BASE_URL)
381
- : readEnvString(env, [
382
- "TOKENUSAGE_ZCODE_BIGMODEL_MONITOR_BASE_URL",
383
- "BIGMODEL_API_BASE_URL",
384
- "BIGMODEL_PRODUCTION_API_BASE_URL",
385
- ]) || DEFAULT_BIGMODEL_MONITOR_BASE_URL;
386
- return `${origin.replace(/\/$/, "")}${ZCODE_MONITOR_QUOTA_PATH}`;
387
- }
388
-
389
- /**
390
- * Build quota/billing candidates from enabled providers and their existing keys.
391
- * Coding plans precede promotional Start Plan grants, and within each plan kind
392
- * the active region's providers come first so switching regions never keeps
393
- * serving the previously saved other-region plan. Selected plans take
394
- * precedence; team scope stays attached to its own provider. ZCode 3.14+
395
- * dropped v2/config.json: there, candidates come from credentials.json
396
- * alone (the active family's zcodejwttoken for start plans, per-account coding-plan keys).
397
- */
398
- function loadZcodeAuthCandidates({ home, env } = {}) {
399
- const zcodeHome = resolveZcodeHome({ home, env });
400
- const configPath = path.join(zcodeHome, "v2", "config.json");
401
- const hasConfig = fs.existsSync(configPath);
402
- try {
403
- const config = hasConfig ? JSON.parse(fs.readFileSync(configPath, "utf8")) : {};
404
- if (!config || typeof config !== "object") return [];
405
- const providers = config.provider || {};
406
- // Per-account keys are a 3.14+ concept; a legacy config.json stays the only
407
- // quota-key source there. The account keys are still read in mixed layouts
408
- // (config.json + newer credentials.json) purely to prove key ownership.
409
- const accountAuths = loadZcodeAccountProviderAuths({ home, env });
410
- const accountAuthsAsKeys = hasConfig ? {} : accountAuths;
411
- const defaultCandidates = [
412
- "builtin:bigmodel-start-plan",
413
- "builtin:zai-start-plan",
414
- "builtin:bigmodel-coding-plan",
415
- "builtin:zai-coding-plan",
416
- ];
417
- const availability = loadZcodeProviderAvailability({ home, env });
418
- const hasAvailability = Object.keys(availability).length > 0;
419
- const selectedPlans = loadZcodeSelectedPlans({ home, env });
420
- const selectedCandidates = selectedPlans.map((plan) => plan.providerKey)
421
- .filter((key) => defaultCandidates.includes(key));
422
- const availableCandidates = defaultCandidates.filter((key) => availability?.[key]?.status === "available");
423
- const activeFamily = loadZcodeActiveRegion({ home, env });
424
- const regionRank = (key) => activeFamily && zcodeProviderFamily(key) === activeFamily ? 0 : 1;
425
- const candidates = [
426
- ...selectedCandidates,
427
- ...availableCandidates,
428
- ...defaultCandidates,
429
- ].filter((key, index, all) => all.indexOf(key) === index)
430
- .sort((a, b) =>
431
- (Number(isZcodeCodingPlanProvider(b)) - Number(isZcodeCodingPlanProvider(a)))
432
- || (regionRank(a) - regionRank(b)));
433
- const auths = [];
434
- for (const key of candidates) {
435
- const configured = providers[key];
436
- const provider = configured && typeof configured === "object" ? configured : null;
437
- if (provider?.enabled === false) continue;
438
- if (hasAvailability && availability?.[key]?.status && availability[key].status !== "available") continue;
439
- const apiKey = typeof provider?.options?.apiKey === "string" ? provider.options.apiKey.trim() : "";
440
- const billingBaseUrl = resolveZcodeProviderBillingBaseUrl(key, provider, env);
441
- const quotaUrl = resolveZcodeProviderQuotaUrl(key, provider, env);
442
- const teamContext = selectedPlans.find((plan) => plan.providerKey === key)?.teamContext;
443
- // Legacy layouts only trust the shared JWT for providers config.json still lists.
444
- const credentialApiKey = provider || !hasConfig ? resolveZcodeCredentialAuth(key, { home, env }) : "";
445
- // A config.json key that byte-equals a per-account credential inherits
446
- // that credential's account identity, so ownership stays provable for
447
- // keys the ZCode app wrote into config.json for the current login.
448
- const owningAccount = Object.values(accountAuths).flat()
449
- .find((entry) => entry.apiKey === apiKey) || null;
450
- // Leftover keys from previously signed-in accounts stay as fallbacks but
451
- // never outrank the current login's key, so the primary window cannot
452
- // show account A's quota while login-scoped extras show account B's.
453
- const family = zcodeProviderFamily(key);
454
- const loginAccountId = loadZcodeLoginAccountId(family, { home, env });
455
- const accountEntries = (accountAuthsAsKeys[key] || [])
456
- .slice()
457
- .sort((a, b) => (loginAccountId
458
- ? Number(a.accountId !== loginAccountId) - Number(b.accountId !== loginAccountId)
459
- : 0))
460
- .map((entry) => ({
461
- apiKey: entry.apiKey,
462
- authSource: "credential:account-provider",
463
- teamContext: entry.teamContext,
464
- accountId: entry.accountId,
465
- }));
466
- const authEntries = [
467
- credentialApiKey ? { apiKey: credentialApiKey, authSource: "credential:zcodejwttoken", teamContext } : null,
468
- ...accountEntries,
469
- apiKey ? {
470
- apiKey,
471
- authSource: "provider:config",
472
- teamContext,
473
- ...(owningAccount ? { accountId: owningAccount.accountId } : {}),
474
- } : null,
475
- ].filter(Boolean);
476
- const seenKeys = new Set();
477
- for (const entry of authEntries) {
478
- if ((!billingBaseUrl && !quotaUrl) || seenKeys.has(entry.apiKey)) continue;
479
- seenKeys.add(entry.apiKey);
480
- auths.push({
481
- apiKey: entry.apiKey,
482
- auth_source: entry.authSource,
483
- providerKey: key,
484
- planKind: isZcodeCodingPlanProvider(key) ? "coding-plan" : "start-plan",
485
- baseUrl: provider?.options?.baseURL || null,
486
- billingBaseUrl,
487
- quotaUrl,
488
- ...(entry.teamContext ? { teamContext: entry.teamContext } : {}),
489
- ...(entry.accountId ? { accountId: entry.accountId } : {}),
490
- availability: availability?.[key]?.status || null,
491
- });
492
- }
493
- }
494
- return auths;
495
- } catch (_error) {
496
- return [];
497
- }
498
- }
499
-
500
- function loadZcodeApiKey({ home, env } = {}) {
501
- return loadZcodeAuthCandidates({ home, env })[0] || null;
502
- }
503
-
504
- /** Client-identification headers ZCode sends to its own billing host, including X-Device-Mid when known. */
505
- function buildZcodeSourceHeaders({ home, env } = {}) {
506
- const headers = {
507
- "User-Agent": `ZCode/${resolveZcodeAppVersion({ home, env })}`,
508
- "HTTP-Referer": "https://zcode.z.ai/",
509
- "X-ZCode-App-Version": resolveZcodeAppVersion({ home, env }),
510
- "X-Platform": process.platform,
511
- "X-Release-Channel": "stable",
512
- "X-Client-Language": Intl.DateTimeFormat().resolvedOptions().locale || "en-US",
513
- "X-Client-Timezone": Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC",
514
- "X-Os-Category": process.platform,
515
- "X-Os-Version": os.release(),
516
- };
517
- const deviceMid = loadZcodeTelemetryDeviceMid({ home, env })
518
- || loadZcodeCredential("zcodefeedbackclientid", { home, env });
519
- if (deviceMid) headers["X-Device-Mid"] = deviceMid;
520
- return headers;
521
- }
522
-
523
- /**
524
- * ZCode 3.14+ keeps the device id in v2/telemetry-state.json, and billing/balance
525
- * rejects requests without X-Device-Mid as `code=3001 parameter error`.
526
- * @returns {string} the device id, or "" when absent or not header-safe
527
- */
528
- function loadZcodeTelemetryDeviceMid({ home, env } = {}) {
529
- const statePath = path.join(resolveZcodeHome({ home, env }), "v2", "telemetry-state.json");
530
- if (!fs.existsSync(statePath)) return "";
531
- try {
532
- const state = JSON.parse(fs.readFileSync(statePath, "utf8"));
533
- const deviceMid = typeof state?.deviceMid === "string" ? state.deviceMid.trim() : "";
534
- return /^[\x20-\x7e]+$/.test(deviceMid) ? deviceMid : "";
535
- } catch (_error) {
536
- return "";
537
- }
538
- }
539
-
540
- function zcodeValNumber(value) {
541
- if (value == null) return null;
542
- const n = Number(value);
543
- return Number.isFinite(n) ? n : null;
544
- }
545
-
546
- function zcodeTsToIso(value) {
547
- if (typeof value === "number" && Number.isFinite(value) && value > 0) {
548
- return new Date(value * 1000).toISOString();
549
- }
550
- return null;
551
- }
552
-
553
- function clampPercent(value) {
554
- if (value === null || value === undefined || value === "") return null;
555
- const n = Number(value);
556
- if (!Number.isFinite(n)) return null;
557
- if (n <= 0) return 0;
558
- if (n >= 100) return 100;
559
- return n;
560
- }
561
-
562
- function buildWindow({ usedPercent, resetAt }) {
563
- const pct = clampPercent(usedPercent);
564
- if (pct === null) return null;
565
- return {
566
- used_percent: pct,
567
- reset_at: typeof resetAt === "string" && resetAt ? resetAt : null,
568
- };
569
- }
570
-
571
- // Z.ai coding-plan ids look like "zcode-v3-start-plan-0615". The raw id reads
572
- // terribly as a plan label, so extract just the human tier ("Start"/"Lite"/
573
- // "Pro"/"Max"); fall back to null (→ bare "ZCode") when no known tier matches.
574
- function deriveZcodePlanLabel(planId) {
575
- if (typeof planId !== "string" || !planId) return null;
576
- const m = planId.toLowerCase().match(/\b(lite|start|pro|max|team|enterprise)\b/);
577
- if (!m) return null;
578
- return m[1].charAt(0).toUpperCase() + m[1].slice(1);
579
- }
580
-
581
- /**
582
- * Normalize a start-plan billing/balance payload into labelled buckets plus the
583
- * primary/secondary/tertiary windows (daily allowances first, promotional grants after).
584
- */
585
- function normalizeZcodeBalanceResponse(body) {
586
- const data = body?.data;
587
- if (!data || typeof data !== "object") {
588
- throw new Error("Could not parse ZCode balance: missing data");
589
- }
590
-
591
- const balances = Array.isArray(data.balances) ? data.balances : [];
592
- if (!balances.length) {
593
- return {
594
- server_time: zcodeValNumber(data.server_time),
595
- plan_kind: "start-plan",
596
- plan_id: null,
597
- plan_label: null,
598
- buckets: [],
599
- primary_window: null,
600
- secondary_window: null,
601
- tertiary_window: null,
602
- };
603
- }
604
-
605
- const serverTime = zcodeValNumber(data.server_time);
606
- // Promotional grants ("free eggs", weekend builds) arrive as extra plans whose
607
- // entitlements are one-time; index them so each bucket can say where it came from.
608
- const plans = Array.isArray(data.plans) ? data.plans : [];
609
- const hasPlans = plans.length > 0;
610
- const planByUserPlanId = new Map();
611
- const periodByEntitlementId = new Map();
612
- for (const plan of plans) {
613
- if (typeof plan?.user_plan_id === "string") planByUserPlanId.set(plan.user_plan_id, plan);
614
- for (const ent of Array.isArray(plan?.entitlements) ? plan.entitlements : []) {
615
- if (typeof ent?.entitlement_id === "string" && typeof ent?.period === "string") {
616
- periodByEntitlementId.set(ent.entitlement_id, ent.period);
617
- }
618
- }
619
- }
620
- const buckets = balances.map((b) => {
621
- const total = zcodeValNumber(b.total_units);
622
- const used = zcodeValNumber(b.used_units);
623
- const remaining = zcodeValNumber(b.remaining_units);
624
- const periodEnd = zcodeValNumber(b.period_end) || zcodeValNumber(b.expires_at);
625
- const resetAt = zcodeTsToIso(periodEnd);
626
- const usedPercent =
627
- total != null && total > 0 && used != null ? (used / total) * 100 : null;
628
-
629
- const showName = typeof b.show_name === "string" ? b.show_name : "";
630
- const entitlementId = typeof b.entitlement_id === "string" ? b.entitlement_id : "";
631
- const plan = planByUserPlanId.get(b.user_plan_id) || null;
632
- const period = periodByEntitlementId.get(entitlementId) || null;
633
- const oneTime = period === "one_time";
634
- const planName = typeof plan?.name === "string" && plan.name.trim() ? plan.name.trim() : null;
635
-
636
- return {
637
- show_name: showName,
638
- label: oneTime && planName ? `${showName} · ${planName}` : showName,
639
- entitlement_id: entitlementId,
640
- plan_id: typeof b.plan_id === "string" ? b.plan_id : null,
641
- plan_name: planName,
642
- period,
643
- priority: zcodeValNumber(b.priority),
644
- total_units: total,
645
- used_units: used,
646
- remaining_units: remaining,
647
- window: buildWindow({ usedPercent, resetAt }),
648
- };
649
- });
650
-
651
- // Recurring (daily) allowances first so the primary/secondary windows keep meaning
652
- // "today's main models"; one-time promotional grants follow. Within each group, ZCode's
653
- // own bucket priority (flagship model first), then larger totals.
654
- const sorted = buckets.slice().sort((a, b) => {
655
- const aOneTime = a.period === "one_time" ? 1 : 0;
656
- const bOneTime = b.period === "one_time" ? 1 : 0;
657
- if (aOneTime !== bOneTime) return aOneTime - bOneTime;
658
- if (hasPlans && a.priority != null && b.priority != null && a.priority !== b.priority) return b.priority - a.priority;
659
- const aTotal = a.total_units || 0;
660
- const bTotal = b.total_units || 0;
661
- return bTotal - aTotal;
662
- });
663
-
664
- const planId = sorted[0]?.plan_id || (typeof balances[0]?.plan_id === "string" ? balances[0].plan_id : null);
665
- return {
666
- server_time: serverTime,
667
- plan_kind: "start-plan",
668
- plan_id: planId,
669
- plan_label: deriveZcodePlanLabel(planId),
670
- buckets: sorted,
671
- primary_window: sorted[0]?.window || null,
672
- secondary_window: sorted[1]?.window || null,
673
- tertiary_window: sorted[2]?.window || null,
674
- };
675
- }
676
-
677
- async function fetchZcodeBilling(apiKey, { fetchImpl = fetch, baseUrl, env, home, signal } = {}) {
678
- const root = (baseUrl || resolveZcodeBillingBaseUrl(env)).replace(/\/$/, "");
679
- const url = new URL(`${root}/billing/balance`);
680
- const appVersion = resolveZcodeAppVersion({ home, env });
681
- if (appVersion) url.searchParams.set("app_version", appVersion);
682
- const headers = {
683
- Authorization: `Bearer ${apiKey}`,
684
- Accept: "application/json",
685
- };
686
- if (url.origin === new URL(DEFAULT_BILLING_BASE_URL).origin) {
687
- Object.assign(headers, buildZcodeSourceHeaders({ home, env }));
688
- }
689
- const res = await fetchImpl(url.toString(), {
690
- method: "GET",
691
- headers,
692
- signal,
693
- });
694
- if (res.status === 401 || res.status === 403) {
695
- throw new Error("Not authenticated with ZCode. Run `zcode` in Terminal to log in.");
696
- }
697
- if (!res.ok) {
698
- let detail = "";
699
- try {
700
- const body = await res.json();
701
- if (body && typeof body === "object") {
702
- const code = body.code != null ? ` code=${body.code}` : "";
703
- const msg = body.msg ? ` msg=${body.msg}` : "";
704
- detail = `${code}${msg}`;
705
- }
706
- } catch (_error) {
707
- detail = "";
708
- }
709
- throw new Error(`ZCode billing API returned ${res.status}${detail}`);
710
- }
711
- return res.json();
712
- }
713
-
714
- /**
715
- * Read the signed-in login's Start Plan grants (bonus buckets) from billing/balance.
716
- * Read-only; a timed-out request aborts its connection so the optional read
717
- * never drags on the primary quota windows.
718
- */
719
- async function fetchZcodeStartPlanGrants({ zcodeToken, fetchImpl = fetch, env, home, timeoutMs = 2000 } = {}) {
720
- const controller = new AbortController();
721
- let timer;
722
- try {
723
- return await Promise.race([
724
- (async () => {
725
- const body = await fetchZcodeBilling(zcodeToken, {
726
- fetchImpl,
727
- baseUrl: resolveZcodeBillingBaseUrl(env),
728
- env,
729
- home,
730
- signal: controller.signal,
731
- });
732
- // An HTTP 200 with a nonzero business code and empty data must surface
733
- // as a failed read, not silently pose as "no grants".
734
- if (body && typeof body.code === "number" && body.code !== 0) {
735
- throw new Error(`ZCode start plan grants API error: code=${body.code} msg=${body?.msg || "unknown"}`);
736
- }
737
- return normalizeZcodeBalanceResponse(body);
738
- })(),
739
- new Promise((_, reject) => {
740
- timer = setTimeout(() => {
741
- controller.abort();
742
- reject(new Error("ZCode start plan grants request timed out"));
743
- }, timeoutMs);
744
- }),
745
- ]);
746
- } finally {
747
- clearTimeout(timer);
748
- }
749
- }
750
-
751
- /**
752
- * Fetch quota using the existing provider key and optional team routing metadata.
753
- * Organization/project IDs select the subscription at the resolved provider URL;
754
- * they do not choose the destination or include the contents of the settings file.
755
- */
756
- async function fetchZcodeCodingPlanQuota(apiKey, { fetchImpl = fetch, quotaUrl, teamContext } = {}) {
757
- const headers = {
758
- authorization: apiKey,
759
- Accept: "application/json",
760
- };
761
- if (teamContext?.organizationId && teamContext?.projectId) {
762
- const url = new URL(quotaUrl);
763
- url.searchParams.set("type", "2");
764
- quotaUrl = url.toString();
765
- headers["bigmodel-organization"] = teamContext.organizationId;
766
- headers["bigmodel-project"] = teamContext.projectId;
767
- }
768
- const res = await fetchImpl(quotaUrl, {
769
- method: "GET",
770
- headers,
771
- });
772
- if (res.status === 401 || res.status === 403) {
773
- throw new Error("Not authenticated with ZCode coding plan. Run `zcode` in Terminal to log in.");
774
- }
775
- let body = null;
776
- try {
777
- body = await res.json();
778
- } catch (_error) {
779
- body = null;
780
- }
781
- if (!res.ok) {
782
- const code = body?.code != null ? ` code=${body.code}` : "";
783
- const msg = body?.msg || body?.message ? ` msg=${body.msg || body.message}` : "";
784
- throw new Error(`ZCode coding plan API returned ${res.status}${code}${msg}`);
785
- }
786
- return body;
787
- }
788
-
789
- function quotaTimestampToIso(value) {
790
- if (typeof value === "string" && value.trim()) {
791
- const parsed = new Date(value.trim());
792
- return Number.isNaN(parsed.getTime()) ? null : parsed.toISOString();
793
- }
794
- const n = zcodeValNumber(value);
795
- if (n == null || n <= 0) return null;
796
- return new Date(n > 10_000_000_000 ? n : n * 1000).toISOString();
797
- }
798
-
799
- function findZcodeQuotaLimit(limits, type, unit, number = null) {
800
- if (!Array.isArray(limits)) return null;
801
- return (
802
- limits.find((limit) => {
803
- if (!limit || typeof limit !== "object") return false;
804
- if (limit.type !== type) return false;
805
- if (zcodeValNumber(limit.unit) !== unit) return false;
806
- if (number == null) return true;
807
- return zcodeValNumber(limit.number) === number;
808
- }) || null
809
- );
810
- }
811
-
812
- // ZCode 3.3.x coding-plan quota rows expose `percentage` as already-used %
813
- // (0–100). `unit`/`number` identify the window (5h / weekly / tools), not a
814
- // token total — deriving used% from usage/number turns an unused TIME_LIMIT
815
- // (usage=100, number=1, percentage=0) into a false 100% bar.
816
- function normalizeZcodeQuotaLimit(limit, { showName } = {}) {
817
- if (!limit || typeof limit !== "object") return null;
818
- const total = zcodeValNumber(limit.number);
819
- const used = zcodeValNumber(limit.usage) ?? zcodeValNumber(limit.currentValue);
820
- const remaining = zcodeValNumber(limit.remaining);
821
- const rawPercentage = zcodeValNumber(limit.percentage);
822
- let usedPercent = null;
823
- if (rawPercentage != null) {
824
- usedPercent = rawPercentage;
825
- } else if (total != null && total > 0 && used != null) {
826
- usedPercent = (used / total) * 100;
827
- } else if (total != null && total > 0 && remaining != null && remaining <= total) {
828
- usedPercent = ((total - remaining) / total) * 100;
829
- }
830
-
831
- const detail = Array.isArray(limit.usageDetails) ? limit.usageDetails.find((item) => item && typeof item === "object") : null;
832
- const resolvedShowName =
833
- (typeof showName === "string" && showName.trim())
834
- || (typeof detail?.displayName === "string" && detail.displayName.trim())
835
- || (typeof detail?.modelCode === "string" && detail.modelCode.trim())
836
- || (typeof limit.type === "string" && limit.type.trim())
837
- || "Coding plan";
838
-
839
- return {
840
- show_name: resolvedShowName,
841
- entitlement_id: typeof limit.type === "string" ? limit.type : "",
842
- total_units: rawPercentage != null ? null : total,
843
- used_units: rawPercentage != null ? null : used,
844
- remaining_units: rawPercentage != null ? null : remaining,
845
- window: buildWindow({ usedPercent, resetAt: quotaTimestampToIso(limit.nextResetTime) }),
846
- };
847
- }
848
-
849
- function normalizeZcodeCodingPlanQuotaResponse(body) {
850
- const code = typeof body?.code === "number" ? body.code : null;
851
- if (code !== null && code !== 0 && code !== 200) {
852
- throw new Error(`ZCode coding plan API error: code=${code} msg=${body?.msg || body?.message || "unknown"}`);
853
- }
854
- if (body?.success === false) {
855
- throw new Error(`ZCode coding plan API error: msg=${body?.msg || body?.message || "unknown"}`);
856
- }
857
- const data = body?.data;
858
- if (!data || typeof data !== "object") {
859
- throw new Error("Could not parse ZCode coding plan quota: missing data");
860
- }
861
- const limits = Array.isArray(data.limits) ? data.limits : [];
862
- // Match ZCode's own sidebar: TOKENS_LIMIT(unit=3,number=5)=5h,
863
- // TOKENS_LIMIT(unit=6)=weekly, TIME_LIMIT(unit=5,number=1)=tool calls.
864
- const fiveHourLimit = findZcodeQuotaLimit(limits, "TOKENS_LIMIT", 3, 5);
865
- const weeklyLimit = findZcodeQuotaLimit(limits, "TOKENS_LIMIT", 6);
866
- const toolsLimit = findZcodeQuotaLimit(limits, "TIME_LIMIT", 5, 1);
867
- const hasNamedWindows = Boolean(fiveHourLimit || weeklyLimit || toolsLimit);
868
-
869
- let buckets;
870
- if (hasNamedWindows) {
871
- buckets = [
872
- fiveHourLimit ? normalizeZcodeQuotaLimit(fiveHourLimit, { showName: "5h" }) : null,
873
- weeklyLimit ? normalizeZcodeQuotaLimit(weeklyLimit, { showName: "Weekly" }) : null,
874
- toolsLimit ? normalizeZcodeQuotaLimit(toolsLimit, { showName: "Tools" }) : null,
875
- ].filter((bucket) => bucket?.window);
876
- } else {
877
- buckets = limits.map((limit) => normalizeZcodeQuotaLimit(limit)).filter((bucket) => bucket?.window);
878
- buckets.sort((a, b) => (b.total_units || 0) - (a.total_units || 0));
879
- }
880
-
881
- const level = typeof data.level === "string" && data.level.trim() ? data.level.trim() : null;
882
- return {
883
- server_time: null,
884
- plan_kind: "coding-plan",
885
- plan_id: level,
886
- plan_label: level ? deriveZcodePlanLabel(level) || level : "Coding",
887
- buckets,
888
- primary_window: buckets[0]?.window || null,
889
- secondary_window: buckets[1]?.window || null,
890
- tertiary_window: buckets[2]?.window || null,
891
- };
892
- }
893
-
894
- function parseZcodeLogTimestamp(line) {
895
- const match = line.match(/^\[(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})\.(\d{3})\]/);
896
- if (!match) return null;
897
- const [, year, month, day, hour, minute, second, ms] = match;
898
- const timestamp = new Date(
899
- Number(year),
900
- Number(month) - 1,
901
- Number(day),
902
- Number(hour),
903
- Number(minute),
904
- Number(second),
905
- Number(ms),
906
- );
907
- const time = timestamp.getTime();
908
- return Number.isFinite(time) ? time : null;
909
- }
910
-
911
- function formatZcodeLogDate(date) {
912
- const y = date.getFullYear();
913
- const m = String(date.getMonth() + 1).padStart(2, "0");
914
- const d = String(date.getDate()).padStart(2, "0");
915
- return `${y}-${m}-${d}`;
916
- }
917
-
918
- function recentZcodeLogPaths({ home, env, nowMs = Date.now() } = {}) {
919
- const logsDir = path.join(resolveZcodeHome({ home, env }), "v2", "logs");
920
- const today = new Date(nowMs);
921
- const yesterday = new Date(nowMs - 24 * 60 * 60 * 1000);
922
- return [today, yesterday].map((d) => path.join(logsDir, `${formatZcodeLogDate(d)}.log`));
923
- }
924
-
925
- function extractZcodeBalanceLogRecord(line) {
926
- if (!line.includes("[usage-stats] billing/balance 请求完成")) return null;
927
- const jsonStart = line.indexOf("{");
928
- if (jsonStart < 0) return null;
929
- try {
930
- const entry = JSON.parse(line.slice(jsonStart));
931
- const body = entry?.payload;
932
- if (!entry?.success || entry?.code !== 0 || !body || body?.code !== 0) return null;
933
- if (!Array.isArray(body?.data?.balances) || body.data.balances.length === 0) return null;
934
- const timestampMs = parseZcodeLogTimestamp(line);
935
- if (timestampMs == null) return null;
936
- return {
937
- body,
938
- providerKey: typeof entry.providerId === "string" ? entry.providerId : null,
939
- timestampMs,
940
- log_timestamp: new Date(timestampMs).toISOString(),
941
- };
942
- } catch (_error) {
943
- return null;
944
- }
945
- }
946
-
947
- function loadLatestZcodeBalanceFromLogs({
948
- home,
949
- env = process.env,
950
- providerKeys = [],
951
- nowMs = Date.now(),
952
- requireProviderMatch = false,
953
- } = {}) {
954
- if (env.TOKENUSAGE_ZCODE_DISABLE_LOG_FALLBACK === "1") return null;
955
- const maxAgeMs = parsePositiveInteger(env.TOKENUSAGE_ZCODE_LOG_MAX_AGE_MS, DEFAULT_ZCODE_LOG_FALLBACK_MAX_AGE_MS);
956
- const preferredProviders = new Set(providerKeys.filter(Boolean));
957
- let preferred = null;
958
- let fallback = null;
959
- for (const logPath of recentZcodeLogPaths({ home, env, nowMs })) {
960
- if (!fs.existsSync(logPath)) continue;
961
- let text = "";
962
- try {
963
- text = fs.readFileSync(logPath, "utf8");
964
- } catch (_error) {
965
- continue;
966
- }
967
- const lines = text.split(/\r?\n/);
968
- for (let i = lines.length - 1; i >= 0; i -= 1) {
969
- const record = extractZcodeBalanceLogRecord(lines[i]);
970
- if (!record) continue;
971
- const ageMs = nowMs - record.timestampMs;
972
- if (ageMs < 0 || ageMs > maxAgeMs) continue;
973
- if (!fallback || record.timestampMs > fallback.timestampMs) fallback = record;
974
- if (preferredProviders.has(record.providerKey) && (!preferred || record.timestampMs > preferred.timestampMs)) {
975
- preferred = record;
976
- }
977
- }
978
- }
979
- if (preferred) return preferred;
980
- return requireProviderMatch && preferredProviders.size > 0 ? null : fallback;
981
- }
982
-
983
- function zcodeLogFallbackResult(logRecord, errors = []) {
984
- if (!logRecord) return null;
985
- return {
986
- configured: true,
987
- error: null,
988
- source: "zcode-log",
989
- provider_key: logRecord.providerKey,
990
- log_timestamp: logRecord.log_timestamp,
991
- provider_errors: errors,
992
- ...normalizeZcodeBalanceResponse(logRecord.body),
993
- };
994
- }
995
-
996
- /**
997
- * Login tokens for reset cards / Start Plan grants, or null when the quota key
998
- * cannot be proven to belong to the signed-in login. Both extras are personal
999
- * to the current login. Any key carrying an account id (per-account
1000
- * credentials, or config.json keys that byte-equal one) must match the login's
1001
- * id. Once a login identity exists, an unprovable key (a config.json key no
1002
- * account credential vouches for — e.g. left over from a switched account)
1003
- * never merges its quota with this login's cards. When the login identity
1004
- * itself is unreadable (user_info missing or unparseable) nothing can prove
1005
- * the key belongs to the signed-in account either, so the extras are skipped
1006
- * and only the main plan quota stays.
1007
- */
1008
- function loadZcodeLoginScopedTokens(family, auth, { home, env } = {}) {
1009
- if (loadZcodeActiveProvider({ home, env }) !== family) return null;
1010
- const loginAccountId = loadZcodeLoginAccountId(family, { home, env });
1011
- if (!loginAccountId) return null;
1012
- if (auth.accountId) {
1013
- if (auth.accountId !== loginAccountId) return null;
1014
- } else if (auth.auth_source === "credential:account-provider" || auth.auth_source === "provider:config") {
1015
- return null;
1016
- }
1017
- const zcodeToken = loadZcodeCredential("zcodejwttoken", { home, env });
1018
- if (!zcodeToken) return null;
1019
- const codingPlanToken = loadZcodeCredential(`oauth:${family}:access_token`, { home, env });
1020
- return { zcodeToken, codingPlanToken };
1021
- }
1022
-
1023
- /**
1024
- * Return normalized quota windows, trying eligible providers and recent billing logs.
1025
- * Credentials and internal team routing identifiers are omitted from the result.
1026
- */
1027
- async function fetchZcodeLimits({ home, env, fetchImpl = fetch, nowMs = Date.now(), providerTimeoutMs } = {}) {
1028
- const startedAt = Date.now();
1029
- if (!isZcodeInstalled({ home, env })) {
1030
- return { configured: false };
1031
- }
1032
- const authCandidates = loadZcodeAuthCandidates({ home, env });
1033
- if (!authCandidates.length) {
1034
- const logFallback = loadLatestZcodeBalanceFromLogs({ home, env, nowMs });
1035
- if (logFallback) return zcodeLogFallbackResult(logFallback, []);
1036
- return { configured: false };
1037
- }
1038
- const errors = [];
1039
- let emptySuccess = null;
1040
- for (const auth of authCandidates) {
1041
- try {
1042
- const body = auth.planKind === "coding-plan"
1043
- ? await fetchZcodeCodingPlanQuota(auth.apiKey, {
1044
- fetchImpl,
1045
- quotaUrl: auth.quotaUrl,
1046
- teamContext: auth.teamContext,
1047
- })
1048
- : await fetchZcodeBilling(auth.apiKey, {
1049
- fetchImpl,
1050
- baseUrl: auth.billingBaseUrl,
1051
- env,
1052
- home,
1053
- });
1054
- const normalized = auth.planKind === "coding-plan"
1055
- ? normalizeZcodeCodingPlanQuotaResponse(body)
1056
- : normalizeZcodeBalanceResponse(body);
1057
- if (auth.planKind !== "coding-plan") {
1058
- const apiCode = typeof body?.code === "number" ? body.code : null;
1059
- if (apiCode !== null && apiCode !== 0) {
1060
- throw new Error(`ZCode billing API error: code=${apiCode} msg=${body?.msg || "unknown"}`);
1061
- }
1062
- }
1063
- const result = {
1064
- configured: true,
1065
- error: null,
1066
- provider_key: auth.providerKey,
1067
- ...normalized,
1068
- };
1069
- if (Array.isArray(normalized.buckets) && normalized.buckets.length === 0 && authCandidates.length > 1) {
1070
- emptySuccess = emptySuccess || result;
1071
- continue;
1072
- }
1073
- if (auth.planKind === "coding-plan") {
1074
- const family = zcodeProviderFamily(auth.providerKey);
1075
- const tokens = loadZcodeLoginScopedTokens(family, auth, { home, env });
1076
- if (tokens) {
1077
- const remainingMs = providerTimeoutMs > 0 ? providerTimeoutMs - (Date.now() - startedAt) - 100 : 4000;
1078
- if (remainingMs <= 0) {
1079
- result.reset_credits = { error: "ZCode reset credits: provider time budget exhausted" };
1080
- result.start_plan = { configured: true, error: "ZCode start plan grants: provider time budget exhausted" };
1081
- } else {
1082
- const timeoutMs = Math.min(2000, remainingMs);
1083
- // Reset cards additionally need the region's login token; without
1084
- // it the status endpoint cannot identify a coding plan, so the
1085
- // inventory stays absent instead of surfacing a blocking error.
1086
- await Promise.all([
1087
- (tokens.codingPlanToken
1088
- ? fetchZcodeResetCredits({
1089
- zcodeToken: tokens.zcodeToken,
1090
- codingPlanToken: tokens.codingPlanToken,
1091
- teamContext: auth.teamContext,
1092
- fetchImpl,
1093
- nowMs,
1094
- timeoutMs,
1095
- })
1096
- : Promise.resolve(null)
1097
- ).then(
1098
- (value) => {
1099
- if (value) result.reset_credits = value;
1100
- },
1101
- (reason) => {
1102
- result.reset_credits = { error: reason?.message || "Could not read ZCode reset credits" };
1103
- },
1104
- ),
1105
- fetchZcodeStartPlanGrants({
1106
- zcodeToken: tokens.zcodeToken,
1107
- fetchImpl,
1108
- env,
1109
- home,
1110
- timeoutMs,
1111
- }).then(
1112
- (value) => {
1113
- // No grants on the login → no section, instead of an empty card.
1114
- if (Array.isArray(value.buckets) && value.buckets.length) {
1115
- result.start_plan = { configured: true, error: null, ...value };
1116
- }
1117
- },
1118
- (reason) => {
1119
- result.start_plan = {
1120
- configured: true,
1121
- error: reason?.message || "Could not read ZCode start plan grants",
1122
- };
1123
- },
1124
- ),
1125
- ]);
1126
- }
1127
- }
1128
- }
1129
- return result;
1130
- } catch (error) {
1131
- errors.push(`${auth.providerKey}: ${error?.message || "Unknown error"}`);
1132
- }
1133
- }
1134
- if (emptySuccess) return emptySuccess;
1135
- const logFallback = loadLatestZcodeBalanceFromLogs({
1136
- home,
1137
- env,
1138
- providerKeys: authCandidates.map((auth) => auth.providerKey),
1139
- nowMs,
1140
- requireProviderMatch: authCandidates.some((auth) => auth.planKind === "coding-plan"),
1141
- });
1142
- if (logFallback) return zcodeLogFallbackResult(logFallback, errors);
1143
- return {
1144
- configured: true,
1145
- error: errors[0] || "Unknown error",
1146
- provider_errors: errors,
1147
- };
1148
- }
1149
-
1150
- module.exports = {
1151
- resolveZcodeHome,
1152
- resolveZcodeBillingBaseUrl,
1153
- resolveZcodeAppVersion,
1154
- isZcodeInstalled,
1155
- loadZcodeProviderAvailability,
1156
- loadZcodeSelectedPlanProviderKeys,
1157
- loadZcodeCredential,
1158
- loadZcodeLoginAccountId,
1159
- zcodeProviderFamily,
1160
- loadLatestZcodeBalanceFromLogs,
1161
- resolveZcodeProviderBillingBaseUrl,
1162
- resolveZcodeProviderQuotaUrl,
1163
- loadZcodeAuthCandidates,
1164
- loadZcodeApiKey,
1165
- deriveZcodePlanLabel,
1166
- normalizeZcodeBalanceResponse,
1167
- normalizeZcodeCodingPlanQuotaResponse,
1168
- fetchZcodeBilling,
1169
- fetchZcodeCodingPlanQuota,
1170
- fetchZcodeStartPlanGrants,
1171
- fetchZcodeLimits,
1172
- };
1
+ const fs = require("node:fs");
2
+ const crypto = require("node:crypto");
3
+ const os = require("node:os");
4
+ const path = require("node:path");
5
+ const { fetchZcodeResetCredits } = require("./zcode-reset-credits");
6
+
7
+ const DEFAULT_BILLING_BASE_URL = "https://zcode.z.ai/api/v1/zcode-plan";
8
+ const DEFAULT_ZAI_MONITOR_BASE_URL = "https://api.z.ai";
9
+ const DEFAULT_BIGMODEL_MONITOR_BASE_URL = "https://bigmodel.cn";
10
+ const ZCODE_MONITOR_QUOTA_PATH = "/api/monitor/usage/quota/limit";
11
+ const DEFAULT_ZCODE_APP_VERSION = "3.2.5";
12
+ const DEFAULT_ZCODE_LOG_FALLBACK_MAX_AGE_MS = 6 * 60 * 60 * 1000;
13
+
14
+ function resolveZcodeHome({ home, env = process.env } = {}) {
15
+ if (typeof env.TOKENUSAGE_ZCODE_HOME === "string" && env.TOKENUSAGE_ZCODE_HOME.trim()) {
16
+ return path.resolve(env.TOKENUSAGE_ZCODE_HOME.trim());
17
+ }
18
+ if (typeof env.ZCODE_HOME === "string" && env.ZCODE_HOME.trim()) {
19
+ return path.resolve(env.ZCODE_HOME.trim());
20
+ }
21
+ return path.join(home || os.homedir(), ".zcode");
22
+ }
23
+
24
+ function resolveZcodeBillingBaseUrl(env = process.env) {
25
+ const explicit =
26
+ typeof env.TOKENUSAGE_ZCODE_BILLING_BASE_URL === "string"
27
+ ? env.TOKENUSAGE_ZCODE_BILLING_BASE_URL.trim()
28
+ : "";
29
+ if (explicit) return explicit.replace(/\/$/, "");
30
+ return DEFAULT_BILLING_BASE_URL;
31
+ }
32
+
33
+ function parsePositiveInteger(value, fallback) {
34
+ const n = Number(value);
35
+ return Number.isFinite(n) && n >= 0 ? n : fallback;
36
+ }
37
+
38
+ function readZcodeAppVersionFromPlist(plistPath) {
39
+ try {
40
+ if (!fs.existsSync(plistPath)) return null;
41
+ const text = fs.readFileSync(plistPath, "utf8");
42
+ const keyIndex = text.indexOf("<key>CFBundleShortVersionString</key>");
43
+ if (keyIndex < 0) return null;
44
+ const match = text.slice(keyIndex).match(/<string>([^<]+)<\/string>/);
45
+ const version = typeof match?.[1] === "string" ? match[1].trim() : "";
46
+ return version || null;
47
+ } catch (_error) {
48
+ return null;
49
+ }
50
+ }
51
+
52
+ function resolveZcodeAppVersion({ home, env = process.env } = {}) {
53
+ const explicit =
54
+ typeof env.TOKENUSAGE_ZCODE_APP_VERSION === "string"
55
+ ? env.TOKENUSAGE_ZCODE_APP_VERSION.trim()
56
+ : "";
57
+ if (explicit) return explicit;
58
+
59
+ const appPath =
60
+ typeof env.TOKENUSAGE_ZCODE_APP_PATH === "string" && env.TOKENUSAGE_ZCODE_APP_PATH.trim()
61
+ ? env.TOKENUSAGE_ZCODE_APP_PATH.trim()
62
+ : null;
63
+ const candidates = appPath
64
+ ? [path.join(appPath, "Contents", "Info.plist")]
65
+ : [
66
+ "/Applications/ZCode.app/Contents/Info.plist",
67
+ path.join(home || os.homedir(), "Applications", "ZCode.app", "Contents", "Info.plist"),
68
+ ];
69
+ for (const plistPath of candidates) {
70
+ const version = readZcodeAppVersionFromPlist(plistPath);
71
+ if (version) return version;
72
+ }
73
+ // The API currently rejects balance requests without app_version. The value is
74
+ // not used for local accounting, so keep a conservative fallback for CLI-only installs.
75
+ return DEFAULT_ZCODE_APP_VERSION;
76
+ }
77
+
78
+ /** True when any ZCode layout is present: legacy v2/config.json, 3.14+ credentials, or the CLI db. */
79
+ function isZcodeInstalled({ home, env } = {}) {
80
+ const zcodeHome = resolveZcodeHome({ home, env });
81
+ const configPath = path.join(zcodeHome, "v2", "config.json");
82
+ if (fs.existsSync(configPath)) return true;
83
+ // ZCode 3.14+ no longer writes v2/config.json; a signed-in desktop app still keeps credentials.
84
+ if (fs.existsSync(path.join(zcodeHome, "v2", "credentials.json"))) return true;
85
+ const dbPath = path.join(zcodeHome, "cli", "db", "db.sqlite");
86
+ return fs.existsSync(dbPath);
87
+ }
88
+
89
+ function loadZcodeProviderAvailability({ home, env } = {}) {
90
+ const zcodeHome = resolveZcodeHome({ home, env });
91
+ const cachePath = path.join(zcodeHome, "v2", "coding-plan-cache.json");
92
+ if (!fs.existsSync(cachePath)) return {};
93
+ try {
94
+ const cache = JSON.parse(fs.readFileSync(cachePath, "utf8"));
95
+ const items = cache?.entryStatus?.items;
96
+ return items && typeof items === "object" ? items : {};
97
+ } catch (_error) {
98
+ return {};
99
+ }
100
+ }
101
+
102
+ /**
103
+ * Decode routing identifiers from a complete team selection for the given family.
104
+ * Returns null for personal, malformed, or legacy project-only selections.
105
+ * @returns {{ organizationId: string, projectId: string } | null}
106
+ */
107
+ function parseZcodeTeamContext(selection, family) {
108
+ if (family !== "bigmodel" && family !== "zai") return null;
109
+ const prefix = `team-plan:builtin:${family}-coding-plan:`;
110
+ if (!selection.startsWith(prefix)) return null;
111
+ const parts = selection.slice(prefix.length).split(":");
112
+ // ZCode 3.10.x stores product:organization:project. Older project-only
113
+ // selections do not identify an organization, so do not guess its scope.
114
+ if (parts.length !== 3) return null;
115
+ try {
116
+ const [productId, organizationId, projectId] = parts.map((part) => decodeURIComponent(part.trim()).trim());
117
+ if (!productId || !organizationId || !projectId) return null;
118
+ return { organizationId, projectId };
119
+ } catch (_error) {
120
+ return null;
121
+ }
122
+ }
123
+
124
+ /**
125
+ * Read selected plans in active-family order, retaining each plan's team scope.
126
+ * Only the provider key and decoded organization/project identifiers are retained.
127
+ */
128
+ function loadZcodeSelectedPlans({ home, env } = {}) {
129
+ const zcodeHome = resolveZcodeHome({ home, env });
130
+ const settingPath = path.join(zcodeHome, "v2", "setting.json");
131
+ if (!fs.existsSync(settingPath)) return [];
132
+ try {
133
+ const setting = JSON.parse(fs.readFileSync(settingPath, "utf8"));
134
+ const selected = setting?.modelProviderFamilySelectedKeys;
135
+ const domain = typeof setting?.providerFamilyDomain === "string" ? setting.providerFamilyDomain : "";
136
+ if (!selected || typeof selected !== "object") {
137
+ return loadZcodeConnectionSelectedPlans(setting?.providerFamilyConnectionSelections, domain);
138
+ }
139
+ const domains = [domain, ...Object.keys(selected)].filter(Boolean);
140
+ const out = [];
141
+ for (const key of domains) {
142
+ const raw = typeof selected[key] === "string" ? selected[key].trim() : "";
143
+ const match = raw.match(/builtin:(?:bigmodel|zai)-(?:start|coding)-plan/);
144
+ if (!match || out.some((plan) => plan.providerKey === match[0])) continue;
145
+ out.push({ providerKey: match[0], teamContext: parseZcodeTeamContext(raw, key) });
146
+ }
147
+ return out;
148
+ } catch (_error) {
149
+ return [];
150
+ }
151
+ }
152
+
153
+ /**
154
+ * ZCode 3.14+ records the chosen plan per family as `providerFamilyConnectionSelections`
155
+ * (`{ zai: { kind: "individual-coding-plan" } }`) instead of `modelProviderFamilySelectedKeys`.
156
+ * Team scope for these selections lives on the account credential, not here.
157
+ */
158
+ function loadZcodeConnectionSelectedPlans(selections, domain) {
159
+ if (!selections || typeof selections !== "object") return [];
160
+ const families = [domain, ...Object.keys(selections)].filter((family) => family === "bigmodel" || family === "zai");
161
+ const out = [];
162
+ for (const family of families) {
163
+ const kind = typeof selections[family]?.kind === "string" ? selections[family].kind : "";
164
+ const planKind = /coding-plan$/.test(kind) ? "coding" : kind === "start-plan" ? "start" : null;
165
+ if (!planKind) continue;
166
+ const providerKey = `builtin:${family}-${planKind}-plan`;
167
+ if (out.some((plan) => plan.providerKey === providerKey)) continue;
168
+ out.push({ providerKey, teamContext: null });
169
+ }
170
+ return out;
171
+ }
172
+
173
+ /** Return the ordered provider keys without exposing the internal team context. */
174
+ function loadZcodeSelectedPlanProviderKeys(options = {}) {
175
+ return loadZcodeSelectedPlans(options).map((plan) => plan.providerKey);
176
+ }
177
+
178
+ function resolveZcodeCredentialsPath({ home, env } = {}) {
179
+ return path.join(resolveZcodeHome({ home, env }), "v2", "credentials.json");
180
+ }
181
+
182
+ function createZcodeCredentialSecret({ home, env = process.env } = {}) {
183
+ if (typeof env.ZCODE_CREDENTIAL_SECRET === "string" && env.ZCODE_CREDENTIAL_SECRET) {
184
+ return env.ZCODE_CREDENTIAL_SECRET;
185
+ }
186
+ let username = "";
187
+ try {
188
+ username = os.userInfo().username || "";
189
+ } catch (_error) {
190
+ username = "";
191
+ }
192
+ return `zcode-credential-fallback:${process.platform}:${home || os.homedir()}:${username}`;
193
+ }
194
+
195
+ function decryptZcodeCredentialValue(value, { home, env } = {}) {
196
+ if (typeof value !== "string") return null;
197
+ if (!value.startsWith("enc:v1:")) return value;
198
+ const encoded = value.slice("enc:v1:".length);
199
+ const parts = encoded.split(".");
200
+ if (parts.length !== 3) return null;
201
+ try {
202
+ const [ivPart, tagPart, encryptedPart] = parts;
203
+ const iv = Buffer.from(ivPart, "base64url");
204
+ const encrypted = Buffer.from(encryptedPart, "base64url");
205
+ const tag = Buffer.from(tagPart, "base64url");
206
+ const key = crypto.createHash("sha256").update(createZcodeCredentialSecret({ home, env })).digest();
207
+ const decipher = crypto.createDecipheriv("aes-256-gcm", key, iv);
208
+ decipher.setAuthTag(tag);
209
+ return Buffer.concat([decipher.update(encrypted), decipher.final()]).toString("utf8");
210
+ } catch (_error) {
211
+ return null;
212
+ }
213
+ }
214
+
215
+ function loadZcodeCredentials({ home, env } = {}) {
216
+ const credentialsPath = resolveZcodeCredentialsPath({ home, env });
217
+ if (!fs.existsSync(credentialsPath)) return {};
218
+ try {
219
+ const raw = JSON.parse(fs.readFileSync(credentialsPath, "utf8"));
220
+ return raw && typeof raw === "object" ? raw : {};
221
+ } catch (_error) {
222
+ return {};
223
+ }
224
+ }
225
+
226
+ function loadZcodeCredential(name, { home, env } = {}) {
227
+ const credentials = loadZcodeCredentials({ home, env });
228
+ const decrypted = decryptZcodeCredentialValue(credentials?.[name], { home, env });
229
+ return typeof decrypted === "string" && decrypted.trim() ? decrypted.trim() : "";
230
+ }
231
+
232
+ function loadZcodeActiveProvider({ home, env } = {}) {
233
+ return loadZcodeCredential("oauth:active_provider", { home, env });
234
+ }
235
+
236
+ function resolveZcodeCredentialAuth(providerKey, { home, env } = {}) {
237
+ const activeProvider = loadZcodeActiveProvider({ home, env });
238
+ if (
239
+ (providerKey === "builtin:zai-start-plan" && activeProvider === "zai") ||
240
+ (providerKey === "builtin:bigmodel-start-plan" && activeProvider === "bigmodel")
241
+ ) {
242
+ return loadZcodeCredential("zcodejwttoken", { home, env });
243
+ }
244
+ return "";
245
+ }
246
+
247
+ /**
248
+ * Map a ZCode 3.14+ per-account key name onto the built-in coding-plan provider it serves:
249
+ * account-provider:coding-plan:account:<family>-individual-coding-plan:account:<id>:api-key
250
+ * account-provider:team:<providerId>:<productId>:<orgId>:<projectId>:account:<id>:api-key
251
+ * Team segments are URI-encoded by ZCode. Start-plan balances use the zcodejwttoken instead.
252
+ * @returns {{ providerKey: string, accountId: string, teamContext: { organizationId: string, projectId: string } | null } | null}
253
+ */
254
+ function parseZcodeAccountProviderCredentialName(name) {
255
+ const match = typeof name === "string" ? name.match(/^account-provider:(.+):account:([^:]+):api-key$/) : null;
256
+ if (!match) return null;
257
+ const scope = match[1];
258
+ const accountId = match[2];
259
+ const individual = scope.match(/^coding-plan:account:(bigmodel|zai)-individual-coding-plan$/);
260
+ if (individual) return { providerKey: `builtin:${individual[1]}-coding-plan`, accountId, teamContext: null };
261
+ if (!scope.startsWith("team:")) return null;
262
+ const parts = scope.slice("team:".length).split(":");
263
+ if (parts.length !== 4) return null;
264
+ try {
265
+ const [providerId, productId, organizationId, projectId] = parts.map((part) => decodeURIComponent(part).trim());
266
+ const team = providerId.match(/^account:(bigmodel|zai)-team-coding-plan$/);
267
+ if (!team || !productId || !organizationId || !projectId) return null;
268
+ return { providerKey: `builtin:${team[1]}-coding-plan`, accountId, teamContext: { organizationId, projectId } };
269
+ } catch (_error) {
270
+ return null;
271
+ }
272
+ }
273
+
274
+ /** Region ("bigmodel" | "zai") a built-in plan provider belongs to. */
275
+ function zcodeProviderFamily(providerKey) {
276
+ return providerKey === "builtin:zai-coding-plan" || providerKey === "builtin:zai-start-plan" ? "zai" : "bigmodel";
277
+ }
278
+
279
+ /**
280
+ * Region whose plan should be served first. The model settings' domain is the
281
+ * region the user actually picked, so it wins; the OAuth login region only
282
+ * backs installs that never recorded a domain (API-key-only setups).
283
+ */
284
+ function loadZcodeActiveRegion({ home, env } = {}) {
285
+ try {
286
+ const settingPath = path.join(resolveZcodeHome({ home, env }), "v2", "setting.json");
287
+ if (fs.existsSync(settingPath)) {
288
+ const setting = JSON.parse(fs.readFileSync(settingPath, "utf8"));
289
+ const domain = typeof setting?.providerFamilyDomain === "string" ? setting.providerFamilyDomain.trim() : "";
290
+ if (domain === "bigmodel" || domain === "zai") return domain;
291
+ }
292
+ } catch (_error) {
293
+ // Fall through to the login region below.
294
+ }
295
+ const active = loadZcodeActiveProvider({ home, env });
296
+ return active === "bigmodel" || active === "zai" ? active : "";
297
+ }
298
+
299
+ /**
300
+ * Account id of the signed-in login for a region, from `oauth:<family>:user_info`.
301
+ * Reset cards and Start Plan grants are personal to this login, so their
302
+ * credentials may only ride along with quota keys that provably share it.
303
+ */
304
+ function loadZcodeLoginAccountId(family, { home, env } = {}) {
305
+ const raw = loadZcodeCredential(`oauth:${family}:user_info`, { home, env });
306
+ try {
307
+ const id = JSON.parse(raw)?.id;
308
+ return typeof id === "string" && id.trim() ? id.trim() : null;
309
+ } catch (_error) {
310
+ return null;
311
+ }
312
+ }
313
+
314
+ /** Collect decrypted per-account coding-plan keys, grouped by built-in provider key. */
315
+ function loadZcodeAccountProviderAuths({ home, env } = {}) {
316
+ const credentials = loadZcodeCredentials({ home, env });
317
+ const out = {};
318
+ for (const name of Object.keys(credentials)) {
319
+ const parsed = parseZcodeAccountProviderCredentialName(name);
320
+ if (!parsed) continue;
321
+ const decrypted = decryptZcodeCredentialValue(credentials[name], { home, env });
322
+ const apiKey = typeof decrypted === "string" ? decrypted.trim() : "";
323
+ if (!apiKey) continue;
324
+ (out[parsed.providerKey] ||= []).push({ apiKey, accountId: parsed.accountId, teamContext: parsed.teamContext });
325
+ }
326
+ return out;
327
+ }
328
+
329
+ function isZcodeBuiltinPlanProvider(providerKey) {
330
+ return /^builtin:(bigmodel|zai)-(start|coding)-plan$/.test(providerKey);
331
+ }
332
+
333
+ function isZcodeCodingPlanProvider(providerKey) {
334
+ return /^builtin:(bigmodel|zai)-coding-plan$/.test(providerKey);
335
+ }
336
+
337
+ function isZcodeStartPlanProvider(providerKey) {
338
+ return /^builtin:(bigmodel|zai)-start-plan$/.test(providerKey);
339
+ }
340
+
341
+ function readEnvString(env, names) {
342
+ for (const name of names) {
343
+ const value = typeof env?.[name] === "string" ? env[name].trim() : "";
344
+ if (value) return value;
345
+ }
346
+ return "";
347
+ }
348
+
349
+ function resolveZcodeProviderBillingBaseUrl(providerKey, provider, env = process.env) {
350
+ const explicit = resolveZcodeBillingBaseUrl(env);
351
+ if (explicit !== DEFAULT_BILLING_BASE_URL) return explicit;
352
+ if (isZcodeStartPlanProvider(providerKey)) return DEFAULT_BILLING_BASE_URL;
353
+ const baseUrl = typeof provider?.options?.baseURL === "string" ? provider.options.baseURL.trim() : "";
354
+ if (/\/zcode-plan\/anthropic\/?$/i.test(baseUrl)) return baseUrl.replace(/\/anthropic\/?$/i, "");
355
+ return null;
356
+ }
357
+
358
+ function normalizeUrlOrigin(value) {
359
+ try {
360
+ const url = new URL(value);
361
+ return url.origin.replace(/\/$/, "");
362
+ } catch (_error) {
363
+ return null;
364
+ }
365
+ }
366
+
367
+ function resolveZcodeProviderQuotaUrl(providerKey, provider, env = process.env) {
368
+ if (!isZcodeCodingPlanProvider(providerKey)) return null;
369
+ const explicit = readEnvString(env, ["TOKENUSAGE_ZCODE_MONITOR_QUOTA_URL"]);
370
+ if (explicit) return explicit;
371
+
372
+ const baseUrl = typeof provider?.options?.baseURL === "string" ? provider.options.baseURL.trim() : "";
373
+ const baseOrigin = normalizeUrlOrigin(baseUrl);
374
+ const isZai = providerKey === "builtin:zai-coding-plan";
375
+ const origin = isZai
376
+ ? readEnvString(env, [
377
+ "TOKENUSAGE_ZCODE_ZAI_MONITOR_BASE_URL",
378
+ "ZAI_BUSINESS_BASE_URL",
379
+ "ZAI_PRODUCTION_BUSINESS_BASE_URL",
380
+ ]) || (baseOrigin && /(^|\.)api\.z\.ai$/i.test(new URL(baseOrigin).hostname) ? baseOrigin : DEFAULT_ZAI_MONITOR_BASE_URL)
381
+ : readEnvString(env, [
382
+ "TOKENUSAGE_ZCODE_BIGMODEL_MONITOR_BASE_URL",
383
+ "BIGMODEL_API_BASE_URL",
384
+ "BIGMODEL_PRODUCTION_API_BASE_URL",
385
+ ]) || DEFAULT_BIGMODEL_MONITOR_BASE_URL;
386
+ return `${origin.replace(/\/$/, "")}${ZCODE_MONITOR_QUOTA_PATH}`;
387
+ }
388
+
389
+ /**
390
+ * Build quota/billing candidates from enabled providers and their existing keys.
391
+ * Coding plans precede promotional Start Plan grants, and within each plan kind
392
+ * the active region's providers come first so switching regions never keeps
393
+ * serving the previously saved other-region plan. Selected plans take
394
+ * precedence; team scope stays attached to its own provider. ZCode 3.14+
395
+ * dropped v2/config.json: there, candidates come from credentials.json
396
+ * alone (the active family's zcodejwttoken for start plans, per-account coding-plan keys).
397
+ */
398
+ function loadZcodeAuthCandidates({ home, env } = {}) {
399
+ const zcodeHome = resolveZcodeHome({ home, env });
400
+ const configPath = path.join(zcodeHome, "v2", "config.json");
401
+ const hasConfig = fs.existsSync(configPath);
402
+ try {
403
+ const config = hasConfig ? JSON.parse(fs.readFileSync(configPath, "utf8")) : {};
404
+ if (!config || typeof config !== "object") return [];
405
+ const providers = config.provider || {};
406
+ // Per-account keys are a 3.14+ concept; a legacy config.json stays the only
407
+ // quota-key source there. The account keys are still read in mixed layouts
408
+ // (config.json + newer credentials.json) purely to prove key ownership.
409
+ const accountAuths = loadZcodeAccountProviderAuths({ home, env });
410
+ const accountAuthsAsKeys = hasConfig ? {} : accountAuths;
411
+ const defaultCandidates = [
412
+ "builtin:bigmodel-start-plan",
413
+ "builtin:zai-start-plan",
414
+ "builtin:bigmodel-coding-plan",
415
+ "builtin:zai-coding-plan",
416
+ ];
417
+ const availability = loadZcodeProviderAvailability({ home, env });
418
+ const hasAvailability = Object.keys(availability).length > 0;
419
+ const selectedPlans = loadZcodeSelectedPlans({ home, env });
420
+ const selectedCandidates = selectedPlans.map((plan) => plan.providerKey)
421
+ .filter((key) => defaultCandidates.includes(key));
422
+ const availableCandidates = defaultCandidates.filter((key) => availability?.[key]?.status === "available");
423
+ const activeFamily = loadZcodeActiveRegion({ home, env });
424
+ const regionRank = (key) => activeFamily && zcodeProviderFamily(key) === activeFamily ? 0 : 1;
425
+ const candidates = [
426
+ ...selectedCandidates,
427
+ ...availableCandidates,
428
+ ...defaultCandidates,
429
+ ].filter((key, index, all) => all.indexOf(key) === index)
430
+ .sort((a, b) =>
431
+ (Number(isZcodeCodingPlanProvider(b)) - Number(isZcodeCodingPlanProvider(a)))
432
+ || (regionRank(a) - regionRank(b)));
433
+ const auths = [];
434
+ for (const key of candidates) {
435
+ const configured = providers[key];
436
+ const provider = configured && typeof configured === "object" ? configured : null;
437
+ if (provider?.enabled === false) continue;
438
+ if (hasAvailability && availability?.[key]?.status && availability[key].status !== "available") continue;
439
+ const apiKey = typeof provider?.options?.apiKey === "string" ? provider.options.apiKey.trim() : "";
440
+ const billingBaseUrl = resolveZcodeProviderBillingBaseUrl(key, provider, env);
441
+ const quotaUrl = resolveZcodeProviderQuotaUrl(key, provider, env);
442
+ const teamContext = selectedPlans.find((plan) => plan.providerKey === key)?.teamContext;
443
+ // Legacy layouts only trust the shared JWT for providers config.json still lists.
444
+ const credentialApiKey = provider || !hasConfig ? resolveZcodeCredentialAuth(key, { home, env }) : "";
445
+ // A config.json key that byte-equals a per-account credential inherits
446
+ // that credential's account identity, so ownership stays provable for
447
+ // keys the ZCode app wrote into config.json for the current login.
448
+ const owningAccount = Object.values(accountAuths).flat()
449
+ .find((entry) => entry.apiKey === apiKey) || null;
450
+ // Leftover keys from previously signed-in accounts stay as fallbacks but
451
+ // never outrank the current login's key, so the primary window cannot
452
+ // show account A's quota while login-scoped extras show account B's.
453
+ const family = zcodeProviderFamily(key);
454
+ const loginAccountId = loadZcodeLoginAccountId(family, { home, env });
455
+ const accountEntries = (accountAuthsAsKeys[key] || [])
456
+ .slice()
457
+ .sort((a, b) => (loginAccountId
458
+ ? Number(a.accountId !== loginAccountId) - Number(b.accountId !== loginAccountId)
459
+ : 0))
460
+ .map((entry) => ({
461
+ apiKey: entry.apiKey,
462
+ authSource: "credential:account-provider",
463
+ teamContext: entry.teamContext,
464
+ accountId: entry.accountId,
465
+ }));
466
+ const authEntries = [
467
+ credentialApiKey ? { apiKey: credentialApiKey, authSource: "credential:zcodejwttoken", teamContext } : null,
468
+ ...accountEntries,
469
+ apiKey ? {
470
+ apiKey,
471
+ authSource: "provider:config",
472
+ teamContext,
473
+ ...(owningAccount ? { accountId: owningAccount.accountId } : {}),
474
+ } : null,
475
+ ].filter(Boolean);
476
+ const seenKeys = new Set();
477
+ for (const entry of authEntries) {
478
+ if ((!billingBaseUrl && !quotaUrl) || seenKeys.has(entry.apiKey)) continue;
479
+ seenKeys.add(entry.apiKey);
480
+ auths.push({
481
+ apiKey: entry.apiKey,
482
+ auth_source: entry.authSource,
483
+ providerKey: key,
484
+ planKind: isZcodeCodingPlanProvider(key) ? "coding-plan" : "start-plan",
485
+ baseUrl: provider?.options?.baseURL || null,
486
+ billingBaseUrl,
487
+ quotaUrl,
488
+ ...(entry.teamContext ? { teamContext: entry.teamContext } : {}),
489
+ ...(entry.accountId ? { accountId: entry.accountId } : {}),
490
+ availability: availability?.[key]?.status || null,
491
+ });
492
+ }
493
+ }
494
+ return auths;
495
+ } catch (_error) {
496
+ return [];
497
+ }
498
+ }
499
+
500
+ function loadZcodeApiKey({ home, env } = {}) {
501
+ return loadZcodeAuthCandidates({ home, env })[0] || null;
502
+ }
503
+
504
+ /** Client-identification headers ZCode sends to its own billing host, including X-Device-Mid when known. */
505
+ function buildZcodeSourceHeaders({ home, env } = {}) {
506
+ const headers = {
507
+ "User-Agent": `ZCode/${resolveZcodeAppVersion({ home, env })}`,
508
+ "HTTP-Referer": "https://zcode.z.ai/",
509
+ "X-ZCode-App-Version": resolveZcodeAppVersion({ home, env }),
510
+ "X-Platform": process.platform,
511
+ "X-Release-Channel": "stable",
512
+ "X-Client-Language": Intl.DateTimeFormat().resolvedOptions().locale || "en-US",
513
+ "X-Client-Timezone": Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC",
514
+ "X-Os-Category": process.platform,
515
+ "X-Os-Version": os.release(),
516
+ };
517
+ const deviceMid = loadZcodeTelemetryDeviceMid({ home, env })
518
+ || loadZcodeCredential("zcodefeedbackclientid", { home, env });
519
+ if (deviceMid) headers["X-Device-Mid"] = deviceMid;
520
+ return headers;
521
+ }
522
+
523
+ /**
524
+ * ZCode 3.14+ keeps the device id in v2/telemetry-state.json, and billing/balance
525
+ * rejects requests without X-Device-Mid as `code=3001 parameter error`.
526
+ * @returns {string} the device id, or "" when absent or not header-safe
527
+ */
528
+ function loadZcodeTelemetryDeviceMid({ home, env } = {}) {
529
+ const statePath = path.join(resolveZcodeHome({ home, env }), "v2", "telemetry-state.json");
530
+ if (!fs.existsSync(statePath)) return "";
531
+ try {
532
+ const state = JSON.parse(fs.readFileSync(statePath, "utf8"));
533
+ const deviceMid = typeof state?.deviceMid === "string" ? state.deviceMid.trim() : "";
534
+ return /^[\x20-\x7e]+$/.test(deviceMid) ? deviceMid : "";
535
+ } catch (_error) {
536
+ return "";
537
+ }
538
+ }
539
+
540
+ function zcodeValNumber(value) {
541
+ if (value == null) return null;
542
+ const n = Number(value);
543
+ return Number.isFinite(n) ? n : null;
544
+ }
545
+
546
+ function zcodeTsToIso(value) {
547
+ if (typeof value === "number" && Number.isFinite(value) && value > 0) {
548
+ return new Date(value * 1000).toISOString();
549
+ }
550
+ return null;
551
+ }
552
+
553
+ function clampPercent(value) {
554
+ if (value === null || value === undefined || value === "") return null;
555
+ const n = Number(value);
556
+ if (!Number.isFinite(n)) return null;
557
+ if (n <= 0) return 0;
558
+ if (n >= 100) return 100;
559
+ return n;
560
+ }
561
+
562
+ function buildWindow({ usedPercent, resetAt }) {
563
+ const pct = clampPercent(usedPercent);
564
+ if (pct === null) return null;
565
+ return {
566
+ used_percent: pct,
567
+ reset_at: typeof resetAt === "string" && resetAt ? resetAt : null,
568
+ };
569
+ }
570
+
571
+ // Z.ai coding-plan ids look like "zcode-v3-start-plan-0615". The raw id reads
572
+ // terribly as a plan label, so extract just the human tier ("Start"/"Lite"/
573
+ // "Pro"/"Max"); fall back to null (→ bare "ZCode") when no known tier matches.
574
+ function deriveZcodePlanLabel(planId) {
575
+ if (typeof planId !== "string" || !planId) return null;
576
+ const m = planId.toLowerCase().match(/\b(lite|start|pro|max|team|enterprise)\b/);
577
+ if (!m) return null;
578
+ return m[1].charAt(0).toUpperCase() + m[1].slice(1);
579
+ }
580
+
581
+ /**
582
+ * Normalize a start-plan billing/balance payload into labelled buckets plus the
583
+ * primary/secondary/tertiary windows (daily allowances first, promotional grants after).
584
+ */
585
+ function normalizeZcodeBalanceResponse(body) {
586
+ const data = body?.data;
587
+ if (!data || typeof data !== "object") {
588
+ throw new Error("Could not parse ZCode balance: missing data");
589
+ }
590
+
591
+ const balances = Array.isArray(data.balances) ? data.balances : [];
592
+ if (!balances.length) {
593
+ return {
594
+ server_time: zcodeValNumber(data.server_time),
595
+ plan_kind: "start-plan",
596
+ plan_id: null,
597
+ plan_label: null,
598
+ buckets: [],
599
+ primary_window: null,
600
+ secondary_window: null,
601
+ tertiary_window: null,
602
+ };
603
+ }
604
+
605
+ const serverTime = zcodeValNumber(data.server_time);
606
+ // Promotional grants ("free eggs", weekend builds) arrive as extra plans whose
607
+ // entitlements are one-time; index them so each bucket can say where it came from.
608
+ const plans = Array.isArray(data.plans) ? data.plans : [];
609
+ const hasPlans = plans.length > 0;
610
+ const planByUserPlanId = new Map();
611
+ const periodByEntitlementId = new Map();
612
+ for (const plan of plans) {
613
+ if (typeof plan?.user_plan_id === "string") planByUserPlanId.set(plan.user_plan_id, plan);
614
+ for (const ent of Array.isArray(plan?.entitlements) ? plan.entitlements : []) {
615
+ if (typeof ent?.entitlement_id === "string" && typeof ent?.period === "string") {
616
+ periodByEntitlementId.set(ent.entitlement_id, ent.period);
617
+ }
618
+ }
619
+ }
620
+ const buckets = balances.map((b) => {
621
+ const total = zcodeValNumber(b.total_units);
622
+ const used = zcodeValNumber(b.used_units);
623
+ const remaining = zcodeValNumber(b.remaining_units);
624
+ const periodEnd = zcodeValNumber(b.period_end) || zcodeValNumber(b.expires_at);
625
+ const resetAt = zcodeTsToIso(periodEnd);
626
+ const usedPercent =
627
+ total != null && total > 0 && used != null ? (used / total) * 100 : null;
628
+
629
+ const showName = typeof b.show_name === "string" ? b.show_name : "";
630
+ const entitlementId = typeof b.entitlement_id === "string" ? b.entitlement_id : "";
631
+ const plan = planByUserPlanId.get(b.user_plan_id) || null;
632
+ const period = periodByEntitlementId.get(entitlementId) || null;
633
+ const oneTime = period === "one_time";
634
+ const planName = typeof plan?.name === "string" && plan.name.trim() ? plan.name.trim() : null;
635
+
636
+ return {
637
+ show_name: showName,
638
+ label: oneTime && planName ? `${showName} · ${planName}` : showName,
639
+ entitlement_id: entitlementId,
640
+ plan_id: typeof b.plan_id === "string" ? b.plan_id : null,
641
+ plan_name: planName,
642
+ period,
643
+ priority: zcodeValNumber(b.priority),
644
+ total_units: total,
645
+ used_units: used,
646
+ remaining_units: remaining,
647
+ window: buildWindow({ usedPercent, resetAt }),
648
+ };
649
+ });
650
+
651
+ // Recurring (daily) allowances first so the primary/secondary windows keep meaning
652
+ // "today's main models"; one-time promotional grants follow. Within each group, ZCode's
653
+ // own bucket priority (flagship model first), then larger totals.
654
+ const sorted = buckets.slice().sort((a, b) => {
655
+ const aOneTime = a.period === "one_time" ? 1 : 0;
656
+ const bOneTime = b.period === "one_time" ? 1 : 0;
657
+ if (aOneTime !== bOneTime) return aOneTime - bOneTime;
658
+ if (hasPlans && a.priority != null && b.priority != null && a.priority !== b.priority) return b.priority - a.priority;
659
+ const aTotal = a.total_units || 0;
660
+ const bTotal = b.total_units || 0;
661
+ return bTotal - aTotal;
662
+ });
663
+
664
+ const planId = sorted[0]?.plan_id || (typeof balances[0]?.plan_id === "string" ? balances[0].plan_id : null);
665
+ return {
666
+ server_time: serverTime,
667
+ plan_kind: "start-plan",
668
+ plan_id: planId,
669
+ plan_label: deriveZcodePlanLabel(planId),
670
+ buckets: sorted,
671
+ primary_window: sorted[0]?.window || null,
672
+ secondary_window: sorted[1]?.window || null,
673
+ tertiary_window: sorted[2]?.window || null,
674
+ };
675
+ }
676
+
677
+ async function fetchZcodeBilling(apiKey, { fetchImpl = fetch, baseUrl, env, home, signal } = {}) {
678
+ const root = (baseUrl || resolveZcodeBillingBaseUrl(env)).replace(/\/$/, "");
679
+ const url = new URL(`${root}/billing/balance`);
680
+ const appVersion = resolveZcodeAppVersion({ home, env });
681
+ if (appVersion) url.searchParams.set("app_version", appVersion);
682
+ const headers = {
683
+ Authorization: `Bearer ${apiKey}`,
684
+ Accept: "application/json",
685
+ };
686
+ if (url.origin === new URL(DEFAULT_BILLING_BASE_URL).origin) {
687
+ Object.assign(headers, buildZcodeSourceHeaders({ home, env }));
688
+ }
689
+ const res = await fetchImpl(url.toString(), {
690
+ method: "GET",
691
+ headers,
692
+ signal,
693
+ });
694
+ if (res.status === 401 || res.status === 403) {
695
+ throw new Error("Not authenticated with ZCode. Run `zcode` in Terminal to log in.");
696
+ }
697
+ if (!res.ok) {
698
+ let detail = "";
699
+ try {
700
+ const body = await res.json();
701
+ if (body && typeof body === "object") {
702
+ const code = body.code != null ? ` code=${body.code}` : "";
703
+ const msg = body.msg ? ` msg=${body.msg}` : "";
704
+ detail = `${code}${msg}`;
705
+ }
706
+ } catch (_error) {
707
+ detail = "";
708
+ }
709
+ throw new Error(`ZCode billing API returned ${res.status}${detail}`);
710
+ }
711
+ return res.json();
712
+ }
713
+
714
+ /**
715
+ * Read the signed-in login's Start Plan grants (bonus buckets) from billing/balance.
716
+ * Read-only; a timed-out request aborts its connection so the optional read
717
+ * never drags on the primary quota windows.
718
+ */
719
+ async function fetchZcodeStartPlanGrants({ zcodeToken, fetchImpl = fetch, env, home, timeoutMs = 2000 } = {}) {
720
+ const controller = new AbortController();
721
+ let timer;
722
+ try {
723
+ return await Promise.race([
724
+ (async () => {
725
+ const body = await fetchZcodeBilling(zcodeToken, {
726
+ fetchImpl,
727
+ baseUrl: resolveZcodeBillingBaseUrl(env),
728
+ env,
729
+ home,
730
+ signal: controller.signal,
731
+ });
732
+ // An HTTP 200 with a nonzero business code and empty data must surface
733
+ // as a failed read, not silently pose as "no grants".
734
+ if (body && typeof body.code === "number" && body.code !== 0) {
735
+ throw new Error(`ZCode start plan grants API error: code=${body.code} msg=${body?.msg || "unknown"}`);
736
+ }
737
+ return normalizeZcodeBalanceResponse(body);
738
+ })(),
739
+ new Promise((_, reject) => {
740
+ timer = setTimeout(() => {
741
+ controller.abort();
742
+ reject(new Error("ZCode start plan grants request timed out"));
743
+ }, timeoutMs);
744
+ }),
745
+ ]);
746
+ } finally {
747
+ clearTimeout(timer);
748
+ }
749
+ }
750
+
751
+ /**
752
+ * Fetch quota using the existing provider key and optional team routing metadata.
753
+ * Organization/project IDs select the subscription at the resolved provider URL;
754
+ * they do not choose the destination or include the contents of the settings file.
755
+ */
756
+ async function fetchZcodeCodingPlanQuota(apiKey, { fetchImpl = fetch, quotaUrl, teamContext } = {}) {
757
+ const headers = {
758
+ authorization: apiKey,
759
+ Accept: "application/json",
760
+ };
761
+ if (teamContext?.organizationId && teamContext?.projectId) {
762
+ const url = new URL(quotaUrl);
763
+ url.searchParams.set("type", "2");
764
+ quotaUrl = url.toString();
765
+ headers["bigmodel-organization"] = teamContext.organizationId;
766
+ headers["bigmodel-project"] = teamContext.projectId;
767
+ }
768
+ const res = await fetchImpl(quotaUrl, {
769
+ method: "GET",
770
+ headers,
771
+ });
772
+ if (res.status === 401 || res.status === 403) {
773
+ throw new Error("Not authenticated with ZCode coding plan. Run `zcode` in Terminal to log in.");
774
+ }
775
+ let body = null;
776
+ try {
777
+ body = await res.json();
778
+ } catch (_error) {
779
+ body = null;
780
+ }
781
+ if (!res.ok) {
782
+ const code = body?.code != null ? ` code=${body.code}` : "";
783
+ const msg = body?.msg || body?.message ? ` msg=${body.msg || body.message}` : "";
784
+ throw new Error(`ZCode coding plan API returned ${res.status}${code}${msg}`);
785
+ }
786
+ return body;
787
+ }
788
+
789
+ function quotaTimestampToIso(value) {
790
+ if (typeof value === "string" && value.trim()) {
791
+ const parsed = new Date(value.trim());
792
+ return Number.isNaN(parsed.getTime()) ? null : parsed.toISOString();
793
+ }
794
+ const n = zcodeValNumber(value);
795
+ if (n == null || n <= 0) return null;
796
+ return new Date(n > 10_000_000_000 ? n : n * 1000).toISOString();
797
+ }
798
+
799
+ function findZcodeQuotaLimit(limits, type, unit, number = null) {
800
+ if (!Array.isArray(limits)) return null;
801
+ return (
802
+ limits.find((limit) => {
803
+ if (!limit || typeof limit !== "object") return false;
804
+ if (limit.type !== type) return false;
805
+ if (zcodeValNumber(limit.unit) !== unit) return false;
806
+ if (number == null) return true;
807
+ return zcodeValNumber(limit.number) === number;
808
+ }) || null
809
+ );
810
+ }
811
+
812
+ // ZCode 3.3.x coding-plan quota rows expose `percentage` as already-used %
813
+ // (0–100). `unit`/`number` identify the window (5h / weekly / tools), not a
814
+ // token total — deriving used% from usage/number turns an unused TIME_LIMIT
815
+ // (usage=100, number=1, percentage=0) into a false 100% bar.
816
+ function normalizeZcodeQuotaLimit(limit, { showName } = {}) {
817
+ if (!limit || typeof limit !== "object") return null;
818
+ const total = zcodeValNumber(limit.number);
819
+ const used = zcodeValNumber(limit.usage) ?? zcodeValNumber(limit.currentValue);
820
+ const remaining = zcodeValNumber(limit.remaining);
821
+ const rawPercentage = zcodeValNumber(limit.percentage);
822
+ let usedPercent = null;
823
+ if (rawPercentage != null) {
824
+ usedPercent = rawPercentage;
825
+ } else if (total != null && total > 0 && used != null) {
826
+ usedPercent = (used / total) * 100;
827
+ } else if (total != null && total > 0 && remaining != null && remaining <= total) {
828
+ usedPercent = ((total - remaining) / total) * 100;
829
+ }
830
+
831
+ const detail = Array.isArray(limit.usageDetails) ? limit.usageDetails.find((item) => item && typeof item === "object") : null;
832
+ const resolvedShowName =
833
+ (typeof showName === "string" && showName.trim())
834
+ || (typeof detail?.displayName === "string" && detail.displayName.trim())
835
+ || (typeof detail?.modelCode === "string" && detail.modelCode.trim())
836
+ || (typeof limit.type === "string" && limit.type.trim())
837
+ || "Coding plan";
838
+
839
+ return {
840
+ show_name: resolvedShowName,
841
+ entitlement_id: typeof limit.type === "string" ? limit.type : "",
842
+ total_units: rawPercentage != null ? null : total,
843
+ used_units: rawPercentage != null ? null : used,
844
+ remaining_units: rawPercentage != null ? null : remaining,
845
+ window: buildWindow({ usedPercent, resetAt: quotaTimestampToIso(limit.nextResetTime) }),
846
+ };
847
+ }
848
+
849
+ function normalizeZcodeCodingPlanQuotaResponse(body) {
850
+ const code = typeof body?.code === "number" ? body.code : null;
851
+ if (code !== null && code !== 0 && code !== 200) {
852
+ throw new Error(`ZCode coding plan API error: code=${code} msg=${body?.msg || body?.message || "unknown"}`);
853
+ }
854
+ if (body?.success === false) {
855
+ throw new Error(`ZCode coding plan API error: msg=${body?.msg || body?.message || "unknown"}`);
856
+ }
857
+ const data = body?.data;
858
+ if (!data || typeof data !== "object") {
859
+ throw new Error("Could not parse ZCode coding plan quota: missing data");
860
+ }
861
+ const limits = Array.isArray(data.limits) ? data.limits : [];
862
+ // Match ZCode's own sidebar: TOKENS_LIMIT(unit=3,number=5)=5h,
863
+ // TOKENS_LIMIT(unit=6)=weekly, TIME_LIMIT(unit=5,number=1)=tool calls.
864
+ const fiveHourLimit = findZcodeQuotaLimit(limits, "TOKENS_LIMIT", 3, 5);
865
+ const weeklyLimit = findZcodeQuotaLimit(limits, "TOKENS_LIMIT", 6);
866
+ const toolsLimit = findZcodeQuotaLimit(limits, "TIME_LIMIT", 5, 1);
867
+ const hasNamedWindows = Boolean(fiveHourLimit || weeklyLimit || toolsLimit);
868
+
869
+ let buckets;
870
+ if (hasNamedWindows) {
871
+ buckets = [
872
+ fiveHourLimit ? normalizeZcodeQuotaLimit(fiveHourLimit, { showName: "5h" }) : null,
873
+ weeklyLimit ? normalizeZcodeQuotaLimit(weeklyLimit, { showName: "Weekly" }) : null,
874
+ toolsLimit ? normalizeZcodeQuotaLimit(toolsLimit, { showName: "Tools" }) : null,
875
+ ].filter((bucket) => bucket?.window);
876
+ } else {
877
+ buckets = limits.map((limit) => normalizeZcodeQuotaLimit(limit)).filter((bucket) => bucket?.window);
878
+ buckets.sort((a, b) => (b.total_units || 0) - (a.total_units || 0));
879
+ }
880
+
881
+ const level = typeof data.level === "string" && data.level.trim() ? data.level.trim() : null;
882
+ return {
883
+ server_time: null,
884
+ plan_kind: "coding-plan",
885
+ plan_id: level,
886
+ plan_label: level ? deriveZcodePlanLabel(level) || level : "Coding",
887
+ buckets,
888
+ primary_window: buckets[0]?.window || null,
889
+ secondary_window: buckets[1]?.window || null,
890
+ tertiary_window: buckets[2]?.window || null,
891
+ };
892
+ }
893
+
894
+ function parseZcodeLogTimestamp(line) {
895
+ const match = line.match(/^\[(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})\.(\d{3})\]/);
896
+ if (!match) return null;
897
+ const [, year, month, day, hour, minute, second, ms] = match;
898
+ const timestamp = new Date(
899
+ Number(year),
900
+ Number(month) - 1,
901
+ Number(day),
902
+ Number(hour),
903
+ Number(minute),
904
+ Number(second),
905
+ Number(ms),
906
+ );
907
+ const time = timestamp.getTime();
908
+ return Number.isFinite(time) ? time : null;
909
+ }
910
+
911
+ function formatZcodeLogDate(date) {
912
+ const y = date.getFullYear();
913
+ const m = String(date.getMonth() + 1).padStart(2, "0");
914
+ const d = String(date.getDate()).padStart(2, "0");
915
+ return `${y}-${m}-${d}`;
916
+ }
917
+
918
+ function recentZcodeLogPaths({ home, env, nowMs = Date.now() } = {}) {
919
+ const logsDir = path.join(resolveZcodeHome({ home, env }), "v2", "logs");
920
+ const today = new Date(nowMs);
921
+ const yesterday = new Date(nowMs - 24 * 60 * 60 * 1000);
922
+ return [today, yesterday].map((d) => path.join(logsDir, `${formatZcodeLogDate(d)}.log`));
923
+ }
924
+
925
+ function extractZcodeBalanceLogRecord(line) {
926
+ if (!line.includes("[usage-stats] billing/balance 请求完成")) return null;
927
+ const jsonStart = line.indexOf("{");
928
+ if (jsonStart < 0) return null;
929
+ try {
930
+ const entry = JSON.parse(line.slice(jsonStart));
931
+ const body = entry?.payload;
932
+ if (!entry?.success || entry?.code !== 0 || !body || body?.code !== 0) return null;
933
+ if (!Array.isArray(body?.data?.balances) || body.data.balances.length === 0) return null;
934
+ const timestampMs = parseZcodeLogTimestamp(line);
935
+ if (timestampMs == null) return null;
936
+ return {
937
+ body,
938
+ providerKey: typeof entry.providerId === "string" ? entry.providerId : null,
939
+ timestampMs,
940
+ log_timestamp: new Date(timestampMs).toISOString(),
941
+ };
942
+ } catch (_error) {
943
+ return null;
944
+ }
945
+ }
946
+
947
+ function loadLatestZcodeBalanceFromLogs({
948
+ home,
949
+ env = process.env,
950
+ providerKeys = [],
951
+ nowMs = Date.now(),
952
+ requireProviderMatch = false,
953
+ } = {}) {
954
+ if (env.TOKENUSAGE_ZCODE_DISABLE_LOG_FALLBACK === "1") return null;
955
+ const maxAgeMs = parsePositiveInteger(env.TOKENUSAGE_ZCODE_LOG_MAX_AGE_MS, DEFAULT_ZCODE_LOG_FALLBACK_MAX_AGE_MS);
956
+ const preferredProviders = new Set(providerKeys.filter(Boolean));
957
+ let preferred = null;
958
+ let fallback = null;
959
+ for (const logPath of recentZcodeLogPaths({ home, env, nowMs })) {
960
+ if (!fs.existsSync(logPath)) continue;
961
+ let text = "";
962
+ try {
963
+ text = fs.readFileSync(logPath, "utf8");
964
+ } catch (_error) {
965
+ continue;
966
+ }
967
+ const lines = text.split(/\r?\n/);
968
+ for (let i = lines.length - 1; i >= 0; i -= 1) {
969
+ const record = extractZcodeBalanceLogRecord(lines[i]);
970
+ if (!record) continue;
971
+ const ageMs = nowMs - record.timestampMs;
972
+ if (ageMs < 0 || ageMs > maxAgeMs) continue;
973
+ if (!fallback || record.timestampMs > fallback.timestampMs) fallback = record;
974
+ if (preferredProviders.has(record.providerKey) && (!preferred || record.timestampMs > preferred.timestampMs)) {
975
+ preferred = record;
976
+ }
977
+ }
978
+ }
979
+ if (preferred) return preferred;
980
+ return requireProviderMatch && preferredProviders.size > 0 ? null : fallback;
981
+ }
982
+
983
+ function zcodeLogFallbackResult(logRecord, errors = []) {
984
+ if (!logRecord) return null;
985
+ return {
986
+ configured: true,
987
+ error: null,
988
+ source: "zcode-log",
989
+ provider_key: logRecord.providerKey,
990
+ log_timestamp: logRecord.log_timestamp,
991
+ provider_errors: errors,
992
+ ...normalizeZcodeBalanceResponse(logRecord.body),
993
+ };
994
+ }
995
+
996
+ /**
997
+ * Login tokens for reset cards / Start Plan grants, or null when the quota key
998
+ * cannot be proven to belong to the signed-in login. Both extras are personal
999
+ * to the current login. Any key carrying an account id (per-account
1000
+ * credentials, or config.json keys that byte-equal one) must match the login's
1001
+ * id. Once a login identity exists, an unprovable key (a config.json key no
1002
+ * account credential vouches for — e.g. left over from a switched account)
1003
+ * never merges its quota with this login's cards. When the login identity
1004
+ * itself is unreadable (user_info missing or unparseable) nothing can prove
1005
+ * the key belongs to the signed-in account either, so the extras are skipped
1006
+ * and only the main plan quota stays.
1007
+ */
1008
+ function loadZcodeLoginScopedTokens(family, auth, { home, env } = {}) {
1009
+ if (loadZcodeActiveProvider({ home, env }) !== family) return null;
1010
+ const loginAccountId = loadZcodeLoginAccountId(family, { home, env });
1011
+ if (!loginAccountId) return null;
1012
+ if (auth.accountId) {
1013
+ if (auth.accountId !== loginAccountId) return null;
1014
+ } else if (auth.auth_source === "credential:account-provider" || auth.auth_source === "provider:config") {
1015
+ return null;
1016
+ }
1017
+ const zcodeToken = loadZcodeCredential("zcodejwttoken", { home, env });
1018
+ if (!zcodeToken) return null;
1019
+ const codingPlanToken = loadZcodeCredential(`oauth:${family}:access_token`, { home, env });
1020
+ return { zcodeToken, codingPlanToken };
1021
+ }
1022
+
1023
+ /**
1024
+ * Return normalized quota windows, trying eligible providers and recent billing logs.
1025
+ * Credentials and internal team routing identifiers are omitted from the result.
1026
+ */
1027
+ async function fetchZcodeLimits({ home, env, fetchImpl = fetch, nowMs = Date.now(), providerTimeoutMs } = {}) {
1028
+ const startedAt = Date.now();
1029
+ if (!isZcodeInstalled({ home, env })) {
1030
+ return { configured: false };
1031
+ }
1032
+ const authCandidates = loadZcodeAuthCandidates({ home, env });
1033
+ if (!authCandidates.length) {
1034
+ const logFallback = loadLatestZcodeBalanceFromLogs({ home, env, nowMs });
1035
+ if (logFallback) return zcodeLogFallbackResult(logFallback, []);
1036
+ return { configured: false };
1037
+ }
1038
+ const errors = [];
1039
+ let emptySuccess = null;
1040
+ for (const auth of authCandidates) {
1041
+ try {
1042
+ const body = auth.planKind === "coding-plan"
1043
+ ? await fetchZcodeCodingPlanQuota(auth.apiKey, {
1044
+ fetchImpl,
1045
+ quotaUrl: auth.quotaUrl,
1046
+ teamContext: auth.teamContext,
1047
+ })
1048
+ : await fetchZcodeBilling(auth.apiKey, {
1049
+ fetchImpl,
1050
+ baseUrl: auth.billingBaseUrl,
1051
+ env,
1052
+ home,
1053
+ });
1054
+ const normalized = auth.planKind === "coding-plan"
1055
+ ? normalizeZcodeCodingPlanQuotaResponse(body)
1056
+ : normalizeZcodeBalanceResponse(body);
1057
+ if (auth.planKind !== "coding-plan") {
1058
+ const apiCode = typeof body?.code === "number" ? body.code : null;
1059
+ if (apiCode !== null && apiCode !== 0) {
1060
+ throw new Error(`ZCode billing API error: code=${apiCode} msg=${body?.msg || "unknown"}`);
1061
+ }
1062
+ }
1063
+ const result = {
1064
+ configured: true,
1065
+ error: null,
1066
+ provider_key: auth.providerKey,
1067
+ ...normalized,
1068
+ };
1069
+ if (Array.isArray(normalized.buckets) && normalized.buckets.length === 0 && authCandidates.length > 1) {
1070
+ emptySuccess = emptySuccess || result;
1071
+ continue;
1072
+ }
1073
+ if (auth.planKind === "coding-plan") {
1074
+ const family = zcodeProviderFamily(auth.providerKey);
1075
+ const tokens = loadZcodeLoginScopedTokens(family, auth, { home, env });
1076
+ if (tokens) {
1077
+ const remainingMs = providerTimeoutMs > 0 ? providerTimeoutMs - (Date.now() - startedAt) - 100 : 4000;
1078
+ if (remainingMs <= 0) {
1079
+ result.reset_credits = { error: "ZCode reset credits: provider time budget exhausted" };
1080
+ result.start_plan = { configured: true, error: "ZCode start plan grants: provider time budget exhausted" };
1081
+ } else {
1082
+ const timeoutMs = Math.min(2000, remainingMs);
1083
+ // Reset cards additionally need the region's login token; without
1084
+ // it the status endpoint cannot identify a coding plan, so the
1085
+ // inventory stays absent instead of surfacing a blocking error.
1086
+ await Promise.all([
1087
+ (tokens.codingPlanToken
1088
+ ? fetchZcodeResetCredits({
1089
+ zcodeToken: tokens.zcodeToken,
1090
+ codingPlanToken: tokens.codingPlanToken,
1091
+ teamContext: auth.teamContext,
1092
+ fetchImpl,
1093
+ nowMs,
1094
+ timeoutMs,
1095
+ })
1096
+ : Promise.resolve(null)
1097
+ ).then(
1098
+ (value) => {
1099
+ if (value) result.reset_credits = value;
1100
+ },
1101
+ (reason) => {
1102
+ result.reset_credits = { error: reason?.message || "Could not read ZCode reset credits" };
1103
+ },
1104
+ ),
1105
+ fetchZcodeStartPlanGrants({
1106
+ zcodeToken: tokens.zcodeToken,
1107
+ fetchImpl,
1108
+ env,
1109
+ home,
1110
+ timeoutMs,
1111
+ }).then(
1112
+ (value) => {
1113
+ // No grants on the login → no section, instead of an empty card.
1114
+ if (Array.isArray(value.buckets) && value.buckets.length) {
1115
+ result.start_plan = { configured: true, error: null, ...value };
1116
+ }
1117
+ },
1118
+ (reason) => {
1119
+ result.start_plan = {
1120
+ configured: true,
1121
+ error: reason?.message || "Could not read ZCode start plan grants",
1122
+ };
1123
+ },
1124
+ ),
1125
+ ]);
1126
+ }
1127
+ }
1128
+ }
1129
+ return result;
1130
+ } catch (error) {
1131
+ errors.push(`${auth.providerKey}: ${error?.message || "Unknown error"}`);
1132
+ }
1133
+ }
1134
+ if (emptySuccess) return emptySuccess;
1135
+ const logFallback = loadLatestZcodeBalanceFromLogs({
1136
+ home,
1137
+ env,
1138
+ providerKeys: authCandidates.map((auth) => auth.providerKey),
1139
+ nowMs,
1140
+ requireProviderMatch: authCandidates.some((auth) => auth.planKind === "coding-plan"),
1141
+ });
1142
+ if (logFallback) return zcodeLogFallbackResult(logFallback, errors);
1143
+ return {
1144
+ configured: true,
1145
+ error: errors[0] || "Unknown error",
1146
+ provider_errors: errors,
1147
+ };
1148
+ }
1149
+
1150
+ module.exports = {
1151
+ resolveZcodeHome,
1152
+ resolveZcodeBillingBaseUrl,
1153
+ resolveZcodeAppVersion,
1154
+ isZcodeInstalled,
1155
+ loadZcodeProviderAvailability,
1156
+ loadZcodeSelectedPlanProviderKeys,
1157
+ loadZcodeCredential,
1158
+ loadZcodeLoginAccountId,
1159
+ zcodeProviderFamily,
1160
+ loadLatestZcodeBalanceFromLogs,
1161
+ resolveZcodeProviderBillingBaseUrl,
1162
+ resolveZcodeProviderQuotaUrl,
1163
+ loadZcodeAuthCandidates,
1164
+ loadZcodeApiKey,
1165
+ deriveZcodePlanLabel,
1166
+ normalizeZcodeBalanceResponse,
1167
+ normalizeZcodeCodingPlanQuotaResponse,
1168
+ fetchZcodeBilling,
1169
+ fetchZcodeCodingPlanQuota,
1170
+ fetchZcodeStartPlanGrants,
1171
+ fetchZcodeLimits,
1172
+ };