tokenusage-cli 0.5.4 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +52 -0
- package/README.md +7 -6
- package/package.json +1 -1
- package/src/cli.js +44 -5
- package/src/commands/device-login.js +16 -17
- package/src/commands/diagnostics.js +16 -16
- package/src/commands/doctor.js +14 -11
- package/src/commands/pause.js +34 -3
- package/src/commands/project-profiles.js +97 -0
- package/src/commands/sessions.js +18 -30
- package/src/commands/status.js +22 -16
- package/src/commands/sync.js +117 -3614
- package/src/commands/uninstall.js +10 -9
- package/src/commands/upload.js +18 -12
- package/src/lib/ark-agent-plan-limits.js +4 -13
- package/src/lib/ark-coding-plan-limits.js +4 -13
- package/src/lib/cli-flags.js +109 -0
- package/src/lib/commandcode-limits.js +11 -38
- package/src/lib/doctor.js +91 -1
- package/src/lib/fs.js +10 -0
- package/src/lib/grok-limits.js +5 -18
- package/src/lib/limits-core.js +64 -0
- package/src/lib/qoder-limits.js +4 -13
- package/src/lib/queue-backup.js +24 -0
- package/src/lib/queue-drain.js +388 -0
- package/src/lib/usage-limits.js +22 -29
- package/src/lib/workbuddy-ipc.js +191 -0
- package/src/lib/workbuddy-limits.js +656 -0
- package/src/lib/zcode-limits.js +5 -18
- package/src/repairs/claude.js +442 -0
- package/src/repairs/codebuddy.js +246 -0
- package/src/repairs/codex.js +1023 -0
- package/src/repairs/droid.js +266 -0
- package/src/repairs/grok.js +352 -0
- package/src/repairs/legacy-migrations.js +135 -0
- package/src/repairs/mimo.js +161 -0
- package/src/repairs/workbuddy.js +209 -0
- package/src/repairs/zcode.js +647 -0
|
@@ -0,0 +1,656 @@
|
|
|
1
|
+
// WorkBuddy subscription-plan quota.
|
|
2
|
+
//
|
|
3
|
+
// The desktop app already reads this from its billing meter. China
|
|
4
|
+
// (WorkBuddy, ~/.workbuddy) and international (WorkBuddy AI, ~/.workbuddy-ai)
|
|
5
|
+
// share the path shape and differ by host:
|
|
6
|
+
//
|
|
7
|
+
// POST {origin}/billing/meter/get-user-resource-summary
|
|
8
|
+
// POST {origin}/billing/meter/get-user-resource-paid-packages
|
|
9
|
+
// POST {origin}/billing/meter/get-user-resource-free-packages
|
|
10
|
+
//
|
|
11
|
+
// Prefer each edition's wbipc/endpoint.json -> wb.request/http.fetch proxy.
|
|
12
|
+
// WorkBuddy adds its own credentials, including encrypted desktop sessions.
|
|
13
|
+
// Legacy plaintext credentials remain a fallback when no local IPC exists.
|
|
14
|
+
//
|
|
15
|
+
// Only two windows are returned, mirroring the desktop app's own split:
|
|
16
|
+
// the subscription plan package (the row the app calls 套餐基础积分, with that
|
|
17
|
+
// package's cycle end as the reset) and one pooled resource-package window
|
|
18
|
+
// for every non-plan credit group (套餐赠送积分 / 购买积分 / 平台奖励积分).
|
|
19
|
+
// Display names are English regardless of the backend's localized names.
|
|
20
|
+
|
|
21
|
+
const fs = require("node:fs");
|
|
22
|
+
const path = require("node:path");
|
|
23
|
+
const { resolveWorkbuddyHome } = require("./rollout");
|
|
24
|
+
const { UNAVAILABLE, readWorkbuddyIpcDiscovery, openWorkbuddyIpc } = require("./workbuddy-ipc");
|
|
25
|
+
|
|
26
|
+
const PLAN_PRIORITY = Object.freeze({
|
|
27
|
+
TCACA_code_027_0FCGVA6vSa: 4, // flagship
|
|
28
|
+
TCACA_code_026_BaESVICNoi: 3, // advanced
|
|
29
|
+
TCACA_code_002_AkiJS3ZHF5: 2, // pro monthly
|
|
30
|
+
TCACA_code_005_maRGyrHhw1: 2, // pro monthly plus
|
|
31
|
+
TCACA_code_003_FAnt7lcmRT: 2, // pro yearly
|
|
32
|
+
TCACA_code_023_4xbGhMrE6q: 1, // youth
|
|
33
|
+
TCACA_code_035_ArVxJcGDsm: 0, // international monthly
|
|
34
|
+
TCACA_code_039_KRcQj7wUat: 0, // trial monthly
|
|
35
|
+
TCACA_code_040_mi9rCYg46x: 0, // trial yearly
|
|
36
|
+
TCACA_code_008_cfWoLwvjU4: 0, // China monthly trial
|
|
37
|
+
});
|
|
38
|
+
|
|
39
|
+
// Verbatim English edition labels from WorkBuddy Desktop 5.8.3's
|
|
40
|
+
// renderer/assets/edition-config-BLwrE-d8.js (getEditionConfigMap), with the
|
|
41
|
+
// package -> edition mapping in common-DRZ6FwkK.js (resolveEditionFromResources).
|
|
42
|
+
// These are official UI fallbacks, not English names supplied by the CN API.
|
|
43
|
+
const PLAN_LABELS = Object.freeze({
|
|
44
|
+
TCACA_code_027_0FCGVA6vSa: "Ultimate",
|
|
45
|
+
TCACA_code_026_BaESVICNoi: "Advanced",
|
|
46
|
+
TCACA_code_002_AkiJS3ZHF5: "STANDARD",
|
|
47
|
+
TCACA_code_005_maRGyrHhw1: "STANDARD",
|
|
48
|
+
TCACA_code_003_FAnt7lcmRT: "STANDARD",
|
|
49
|
+
TCACA_code_023_4xbGhMrE6q: "Youth",
|
|
50
|
+
TCACA_code_035_ArVxJcGDsm: "Free",
|
|
51
|
+
TCACA_code_039_KRcQj7wUat: "STANDARD TRIAL",
|
|
52
|
+
TCACA_code_040_mi9rCYg46x: "STANDARD TRIAL",
|
|
53
|
+
TCACA_code_008_cfWoLwvjU4: "Free",
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
// Platform reward credits. Never selected, even when the summary names one
|
|
57
|
+
// as a subscription package.
|
|
58
|
+
const REWARD_CODES = new Set([
|
|
59
|
+
"TCACA_code_001_PqouKr6QWV", // free, not the plan
|
|
60
|
+
"TCACA_code_006_DbXS0lrypC", // gift
|
|
61
|
+
"TCACA_code_007_nzdH5h4Nl0", // activity / 官方活动
|
|
62
|
+
"TCACA_code_009_0XmEQc2xOf", // extra credit package
|
|
63
|
+
"TCACA_code_028_NtpWi0jzXs", // bonus
|
|
64
|
+
"TCACA_code_029_6wCGEWquYy",
|
|
65
|
+
"TCACA_code_030_BjSt89qTvr",
|
|
66
|
+
"TCACA_code_036_lupO5WgNdG", // international extra
|
|
67
|
+
"TCACA_code_037_WxOD3MpI2o", // international bonus
|
|
68
|
+
"TCACA_code_038_OhvqZtiPKr", // extra
|
|
69
|
+
]);
|
|
70
|
+
|
|
71
|
+
const VARIANTS = Object.freeze({
|
|
72
|
+
workbuddy: {
|
|
73
|
+
id: "workbuddy",
|
|
74
|
+
source: "workbuddy",
|
|
75
|
+
envToken: "WORKBUDDY_ACCESS_TOKEN",
|
|
76
|
+
defaultOrigin: "https://www.workbuddy.cn",
|
|
77
|
+
allowedHostSuffixes: ["workbuddy.cn", "copilot.tencent.com", "wb.tencentbuddy.com"],
|
|
78
|
+
authFileNames: ["workbuddy-desktop.info"],
|
|
79
|
+
brand: "WorkBuddy",
|
|
80
|
+
},
|
|
81
|
+
workbuddyAi: {
|
|
82
|
+
id: "workbuddyAi",
|
|
83
|
+
source: "workbuddy-ai",
|
|
84
|
+
envToken: "WORKBUDDY_AI_ACCESS_TOKEN",
|
|
85
|
+
defaultOrigin: "https://www.workbuddy.ai",
|
|
86
|
+
allowedHostSuffixes: ["workbuddy.ai"],
|
|
87
|
+
authFileNames: ["workbuddy-ai.info", "workbuddy-desktop.info"],
|
|
88
|
+
brand: "WorkBuddy AI",
|
|
89
|
+
},
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
function isNonEmptyString(value) {
|
|
93
|
+
return typeof value === "string" && value.trim().length > 0;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function hostOf(value) {
|
|
97
|
+
if (!isNonEmptyString(value)) return "";
|
|
98
|
+
const trimmed = value.trim();
|
|
99
|
+
try {
|
|
100
|
+
const withScheme = /^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`;
|
|
101
|
+
return new URL(withScheme).hostname.toLowerCase();
|
|
102
|
+
} catch {
|
|
103
|
+
return "";
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function hostAllowed(hostname, suffixes) {
|
|
108
|
+
if (!hostname) return false;
|
|
109
|
+
return suffixes.some((suffix) => hostname === suffix || hostname.endsWith(`.${suffix}`));
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function originAllowed(origin, variant) {
|
|
113
|
+
return hostAllowed(hostOf(origin), variant.allowedHostSuffixes);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function toCount(value) {
|
|
117
|
+
if (typeof value === "number" && Number.isFinite(value) && value >= 0) return value;
|
|
118
|
+
if (typeof value === "string" && value.trim() && Number.isFinite(Number(value))) {
|
|
119
|
+
const n = Number(value);
|
|
120
|
+
return n >= 0 ? n : null;
|
|
121
|
+
}
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function firstCount(row, keys) {
|
|
126
|
+
for (const key of keys) {
|
|
127
|
+
const n = toCount(row?.[key]);
|
|
128
|
+
if (n !== null) return n;
|
|
129
|
+
}
|
|
130
|
+
return null;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function firstString(row, keys) {
|
|
134
|
+
for (const key of keys) {
|
|
135
|
+
if (isNonEmptyString(row?.[key])) return row[key].trim();
|
|
136
|
+
}
|
|
137
|
+
return "";
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function normalizeResetAt(value) {
|
|
141
|
+
if (value === null || value === undefined || value === "") return null;
|
|
142
|
+
if (typeof value === "number" && Number.isFinite(value) && value > 0) {
|
|
143
|
+
const ms = value > 10_000_000_000 ? value : value * 1000;
|
|
144
|
+
const date = new Date(ms);
|
|
145
|
+
return Number.isFinite(date.getTime()) ? date.toISOString() : null;
|
|
146
|
+
}
|
|
147
|
+
const text = String(value).trim();
|
|
148
|
+
if (!text) return null;
|
|
149
|
+
// "2026-10-31 23:59:59" is the cycle boundary the app shows. Without a
|
|
150
|
+
// zone, Date parses the T form as local time, matching the desktop app.
|
|
151
|
+
const normalized = /^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/.test(text)
|
|
152
|
+
? text.replace(" ", "T")
|
|
153
|
+
: text;
|
|
154
|
+
const parsed = Date.parse(normalized);
|
|
155
|
+
return Number.isFinite(parsed) ? new Date(parsed).toISOString() : null;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
function clampPercent(value) {
|
|
159
|
+
if (!Number.isFinite(value)) return null;
|
|
160
|
+
if (value <= 0) return 0;
|
|
161
|
+
if (value >= 100) return 100;
|
|
162
|
+
return value;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
function normalizePackageRow(row) {
|
|
166
|
+
if (!row || typeof row !== "object") return null;
|
|
167
|
+
const code = firstString(row, ["PackageCode", "packageCode", "package_code"]);
|
|
168
|
+
if (!code) return null;
|
|
169
|
+
const total = firstCount(row, [
|
|
170
|
+
"CycleTotalCapacity",
|
|
171
|
+
"cycleTotal",
|
|
172
|
+
"CycleCapacitySizePrecise",
|
|
173
|
+
"total",
|
|
174
|
+
]);
|
|
175
|
+
const remain = firstCount(row, [
|
|
176
|
+
"CycleRemainCapacity",
|
|
177
|
+
"cycleRemain",
|
|
178
|
+
"CycleCapacityRemainPrecise",
|
|
179
|
+
"left",
|
|
180
|
+
]);
|
|
181
|
+
const used = firstCount(row, ["CycleUsedCapacity", "cycleUsed", "used"]);
|
|
182
|
+
return {
|
|
183
|
+
code,
|
|
184
|
+
name: firstString(row, ["PackageName", "packageName", "name"]),
|
|
185
|
+
total,
|
|
186
|
+
remain,
|
|
187
|
+
used,
|
|
188
|
+
cycleEnd: firstString(row, ["CycleEndTime", "cycleEnd", "cycle_end"])
|
|
189
|
+
|| firstString(row, ["DeductionEndTime", "expireAt"]),
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function unwrapBillingBody(payload) {
|
|
194
|
+
if (!payload || typeof payload !== "object") return null;
|
|
195
|
+
const code = payload.code ?? payload.Code;
|
|
196
|
+
if (code !== undefined && code !== 0 && code !== "0") return null;
|
|
197
|
+
const data = payload.data ?? payload.Data;
|
|
198
|
+
if (data && typeof data === "object") return data;
|
|
199
|
+
return payload;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function collectPackageRows(payload) {
|
|
203
|
+
const data = unwrapBillingBody(payload);
|
|
204
|
+
if (!data) return [];
|
|
205
|
+
const lists = [];
|
|
206
|
+
for (const key of ["Packages", "packages", "Accounts", "accounts", "Resources", "resources"]) {
|
|
207
|
+
if (Array.isArray(data[key])) lists.push(data[key]);
|
|
208
|
+
}
|
|
209
|
+
if (Array.isArray(data)) lists.push(data);
|
|
210
|
+
const rows = [];
|
|
211
|
+
for (const list of lists) {
|
|
212
|
+
for (const item of list) {
|
|
213
|
+
const row = normalizePackageRow(item);
|
|
214
|
+
if (row) rows.push(row);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
return rows;
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function readSubscriptionIdentity(payload) {
|
|
221
|
+
const data = unwrapBillingBody(payload);
|
|
222
|
+
if (!data) return { code: "", name: "" };
|
|
223
|
+
return {
|
|
224
|
+
code: firstString(data, ["SubscriptionPackageCode", "subscriptionPackageCode"]),
|
|
225
|
+
name: firstString(data, ["SubscriptionPackageName", "subscriptionPackageName"]),
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
function mergePackageRows(rows) {
|
|
230
|
+
const byCode = new Map();
|
|
231
|
+
for (const row of rows) {
|
|
232
|
+
const prev = byCode.get(row.code);
|
|
233
|
+
if (!prev) {
|
|
234
|
+
byCode.set(row.code, { ...row });
|
|
235
|
+
continue;
|
|
236
|
+
}
|
|
237
|
+
byCode.set(row.code, {
|
|
238
|
+
code: row.code,
|
|
239
|
+
name: row.name || prev.name,
|
|
240
|
+
total: row.total ?? prev.total,
|
|
241
|
+
remain: row.remain ?? prev.remain,
|
|
242
|
+
used: row.used ?? prev.used,
|
|
243
|
+
cycleEnd: row.cycleEnd || prev.cycleEnd,
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
return [...byCode.values()];
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
function isRewardCode(code) {
|
|
250
|
+
return REWARD_CODES.has(code);
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function isSelectablePlan(row, subscriptionPackageCode) {
|
|
254
|
+
if (!row || isRewardCode(row.code)) return false;
|
|
255
|
+
if (Object.prototype.hasOwnProperty.call(PLAN_PRIORITY, row.code)) return true;
|
|
256
|
+
return Boolean(subscriptionPackageCode) && row.code === subscriptionPackageCode;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function planScore(row) {
|
|
260
|
+
const priority = PLAN_PRIORITY[row.code] ?? 0;
|
|
261
|
+
const live = row.total > 0 && row.remain > 0 ? 1 : 0;
|
|
262
|
+
const total = Number.isFinite(row.total) ? row.total : 0;
|
|
263
|
+
return priority * 1_000_000_000 + live * 1_000_000 + total;
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
function planWindow(row) {
|
|
267
|
+
const total = row.total;
|
|
268
|
+
const remain = row.remain;
|
|
269
|
+
const used = row.used ?? (total !== null && remain !== null ? Math.max(0, total - remain) : null);
|
|
270
|
+
if (total === null || total <= 0 || used === null) return null;
|
|
271
|
+
const usedPercent = clampPercent((used / total) * 100);
|
|
272
|
+
if (usedPercent === null) return null;
|
|
273
|
+
return {
|
|
274
|
+
used_percent: usedPercent,
|
|
275
|
+
reset_at: normalizeResetAt(row.cycleEnd),
|
|
276
|
+
used_credits: used,
|
|
277
|
+
limit_credits: total,
|
|
278
|
+
remaining_credits: remain ?? Math.max(0, total - used),
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
// Legacy merge for the pre-split unified row. The local app now publishes
|
|
283
|
+
// both editions side by side; cloud mirrors of this module still merge.
|
|
284
|
+
function selectWorkbuddyLimits(china, international) {
|
|
285
|
+
const editions = [china, international].filter(Boolean);
|
|
286
|
+
const usable = (value) => value.configured === true && !value.error;
|
|
287
|
+
return editions.find((value) => usable(value) && value.primary_window)
|
|
288
|
+
|| editions.find(usable)
|
|
289
|
+
|| editions.find((value) => value.configured === true)
|
|
290
|
+
|| { configured: false };
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// Pick the one subscription-plan package. Reward rows are ignored here — they
|
|
294
|
+
// feed the resource-pool window instead. When several plan packages exist, the
|
|
295
|
+
// highest tier that still has credit wins, matching the desktop app's
|
|
296
|
+
// pickActivePlanBase.
|
|
297
|
+
function selectWorkbuddyPlanQuota(rows, identity = {}, variantId = "workbuddy") {
|
|
298
|
+
const merged = mergePackageRows(rows.filter(Boolean));
|
|
299
|
+
const subscriptionPackageCode = identity.code || "";
|
|
300
|
+
const candidates = merged.filter((row) => isSelectablePlan(row, subscriptionPackageCode));
|
|
301
|
+
if (candidates.length === 0) return null;
|
|
302
|
+
candidates.sort((a, b) => planScore(b) - planScore(a));
|
|
303
|
+
const chosen = candidates[0];
|
|
304
|
+
const window = planWindow(chosen);
|
|
305
|
+
if (!window) return null;
|
|
306
|
+
const planLabel = englishPlanLabel(chosen, identity, variantId);
|
|
307
|
+
return {
|
|
308
|
+
plan_label: planLabel || null,
|
|
309
|
+
primary_window: window,
|
|
310
|
+
package_code: chosen.code,
|
|
311
|
+
};
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
// The desktop app's billing meter splits an account into CreditGroups:
|
|
315
|
+
// plan_base (套餐基础积分) plus the non-plan pools plan_bonus (套餐赠送积分),
|
|
316
|
+
// addon (购买积分) and benefit (平台奖励积分). The app shows those pools as
|
|
317
|
+
// resource packages on top of the plan, so mirror that split: one window for
|
|
318
|
+
// the plan cycle, one pooled window for everything else. Groups the summary
|
|
319
|
+
// does not quantify are ignored; a pool with no credit at all stays null so
|
|
320
|
+
// the UI drops it like a missing window.
|
|
321
|
+
function collectResourceGroups(summary) {
|
|
322
|
+
const data = unwrapBillingBody(summary);
|
|
323
|
+
if (!data) return null;
|
|
324
|
+
const groups = [
|
|
325
|
+
data.CreditGroups,
|
|
326
|
+
data.creditGroups,
|
|
327
|
+
data.credit_groups,
|
|
328
|
+
].find(Array.isArray);
|
|
329
|
+
if (groups) {
|
|
330
|
+
const pool = { total: 0, used: 0, remain: 0, remainDerived: 0, seen: false, usedSeen: false, remainSeen: false };
|
|
331
|
+
for (const group of groups) {
|
|
332
|
+
if (!group || typeof group !== "object") continue;
|
|
333
|
+
const kind = firstString(group, ["Kind", "kind"]);
|
|
334
|
+
if (kind && kind.toLowerCase() === "plan_base") continue;
|
|
335
|
+
const total = firstCount(group, ["CycleTotalCapacity", "total"]);
|
|
336
|
+
const used = firstCount(group, ["CycleUsedCapacity", "used"]);
|
|
337
|
+
const remain = firstCount(group, ["CycleRemainCapacity", "remain"]);
|
|
338
|
+
if (total === null && used === null && remain === null) continue;
|
|
339
|
+
pool.seen = true;
|
|
340
|
+
// A group that omits its usage is still counted: derive it from the
|
|
341
|
+
// capacity identity, the way planWindow does for the plan row.
|
|
342
|
+
const knownUsed = used ?? (total !== null && remain !== null ? Math.max(0, total - remain) : null);
|
|
343
|
+
pool.usedSeen = pool.usedSeen || knownUsed !== null;
|
|
344
|
+
pool.remainSeen = pool.remainSeen || remain !== null;
|
|
345
|
+
pool.total += total ?? 0;
|
|
346
|
+
pool.used += knownUsed ?? 0;
|
|
347
|
+
if (remain === null) pool.remainDerived += Math.max(0, (total ?? 0) - (used ?? 0));
|
|
348
|
+
else pool.remain += remain;
|
|
349
|
+
}
|
|
350
|
+
return pool.seen ? pool : null;
|
|
351
|
+
}
|
|
352
|
+
// Older summaries predate CreditGroups. Their package rows carry the same
|
|
353
|
+
// pools one row per package — every row that cannot be the subscription
|
|
354
|
+
// plan is resource credit.
|
|
355
|
+
const identity = readSubscriptionIdentity(summary);
|
|
356
|
+
const rows = collectPackageRows(summary)
|
|
357
|
+
.filter((row) => !isSelectablePlan(row, identity.code));
|
|
358
|
+
if (rows.length === 0) return null;
|
|
359
|
+
const derivedUsed = (row) =>
|
|
360
|
+
row.used ?? (row.total !== null && row.remain !== null ? Math.max(0, row.total - row.remain) : null);
|
|
361
|
+
return {
|
|
362
|
+
total: rows.reduce((sum, row) => sum + (row.total ?? 0), 0),
|
|
363
|
+
used: rows.reduce((sum, row) => sum + (derivedUsed(row) ?? 0), 0),
|
|
364
|
+
remain: rows.reduce((sum, row) => sum + (row.remain ?? 0), 0),
|
|
365
|
+
remainDerived: rows.reduce(
|
|
366
|
+
(sum, row) => sum + (row.remain === null ? Math.max(0, (row.total ?? 0) - (row.used ?? 0)) : 0),
|
|
367
|
+
0,
|
|
368
|
+
),
|
|
369
|
+
seen: true,
|
|
370
|
+
usedSeen: rows.some((row) => derivedUsed(row) !== null),
|
|
371
|
+
remainSeen: rows.some((row) => row.remain !== null),
|
|
372
|
+
};
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
// Resource credits have no shared cycle: benefit and add-on packages carry
|
|
376
|
+
// their own grants, so the pooled window has no reset. An empty pool (0/0)
|
|
377
|
+
// yields no window instead of a full or zeroed bar.
|
|
378
|
+
function resourceWindow(pool) {
|
|
379
|
+
if (!pool || !(pool.total > 0) || !Number.isFinite(pool.total)) return null;
|
|
380
|
+
// No group reported either side of the meter: usage is unknowable, not
|
|
381
|
+
// zero — hide the pool instead of rendering a full bar.
|
|
382
|
+
if (!pool.usedSeen && !pool.remainSeen) return null;
|
|
383
|
+
const used = pool.usedSeen || pool.used > 0
|
|
384
|
+
? pool.used
|
|
385
|
+
: Math.max(0, pool.total - (pool.remain + pool.remainDerived));
|
|
386
|
+
const usedPercent = clampPercent((used / pool.total) * 100);
|
|
387
|
+
if (usedPercent === null) return null;
|
|
388
|
+
const remaining = pool.remainSeen
|
|
389
|
+
? pool.remain + pool.remainDerived
|
|
390
|
+
: Math.max(0, pool.total - used);
|
|
391
|
+
if (!Number.isFinite(remaining)) return null;
|
|
392
|
+
return {
|
|
393
|
+
used_percent: usedPercent,
|
|
394
|
+
reset_at: null,
|
|
395
|
+
used_credits: used,
|
|
396
|
+
limit_credits: pool.total,
|
|
397
|
+
remaining_credits: remaining,
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
function englishPlanLabel(row, identity, variantId) {
|
|
402
|
+
// An actual English subscription/package name takes precedence over the
|
|
403
|
+
// client's edition fallback. Unknown localized tiers stay unnamed.
|
|
404
|
+
for (const name of [identity.name, row.name]) {
|
|
405
|
+
if (typeof name === "string" && /^[\x20-\x7e]+$/.test(name.trim())
|
|
406
|
+
&& /[a-z]/i.test(name) && !/^TCACA_code_/i.test(name.trim())) return name.trim();
|
|
407
|
+
}
|
|
408
|
+
const known = PLAN_LABELS[row.code];
|
|
409
|
+
if (variantId === "workbuddyAi") {
|
|
410
|
+
if (known === "STANDARD") return "Pro";
|
|
411
|
+
if (known === "STANDARD TRIAL") return "Pro-Trial";
|
|
412
|
+
}
|
|
413
|
+
return known || null;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
function variantById(id) {
|
|
417
|
+
return VARIANTS[id] || null;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
function directoryExists(dir) {
|
|
421
|
+
if (!dir) return false;
|
|
422
|
+
try {
|
|
423
|
+
return fs.statSync(dir).isDirectory();
|
|
424
|
+
} catch {
|
|
425
|
+
return false;
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
function authSearchDirs(env, workbuddyHome) {
|
|
430
|
+
const home = isNonEmptyString(env?.HOME) ? env.HOME.trim() : "";
|
|
431
|
+
const dirs = [];
|
|
432
|
+
if (home && process.platform === "darwin") {
|
|
433
|
+
dirs.push(path.join(home, "Library", "Application Support", "CodeBuddyExtension", "Data", "Public", "auth"));
|
|
434
|
+
} else if (process.platform === "win32") {
|
|
435
|
+
const appData = isNonEmptyString(env?.APPDATA) ? env.APPDATA.trim() : (home ? path.join(home, "AppData", "Roaming") : "");
|
|
436
|
+
if (appData) dirs.push(path.join(appData, "CodeBuddyExtension", "Data", "Public", "auth"));
|
|
437
|
+
} else if (home) {
|
|
438
|
+
dirs.push(path.join(home, ".config", "CodeBuddyExtension", "Data", "Public", "auth"));
|
|
439
|
+
}
|
|
440
|
+
if (workbuddyHome) dirs.push(path.join(workbuddyHome, "auth"));
|
|
441
|
+
return dirs;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
function readAuthFile(filePath) {
|
|
445
|
+
let parsed;
|
|
446
|
+
try {
|
|
447
|
+
parsed = JSON.parse(fs.readFileSync(filePath, "utf8"));
|
|
448
|
+
} catch {
|
|
449
|
+
return null;
|
|
450
|
+
}
|
|
451
|
+
const auth = parsed?.auth;
|
|
452
|
+
if (!auth || typeof auth !== "object") return null;
|
|
453
|
+
const domain = isNonEmptyString(auth.domain) ? auth.domain.trim() : "";
|
|
454
|
+
const token = auth.accessToken;
|
|
455
|
+
if (isNonEmptyString(token)) return { token: token.trim(), domain, encrypted: false };
|
|
456
|
+
if (token && typeof token === "object" && token.$wbEncrypted === 1) {
|
|
457
|
+
return { token: null, domain, encrypted: true };
|
|
458
|
+
}
|
|
459
|
+
return { token: null, domain, encrypted: false };
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
function resolveSession(variant, { env, authFiles, workbuddyHome }) {
|
|
463
|
+
const files = Array.isArray(authFiles)
|
|
464
|
+
? authFiles
|
|
465
|
+
: authSearchDirs(env, workbuddyHome).flatMap((dir) => variant.authFileNames.map((name) => path.join(dir, name)));
|
|
466
|
+
let encryptedForVariant = false;
|
|
467
|
+
for (const filePath of files) {
|
|
468
|
+
if (!filePath) continue;
|
|
469
|
+
const session = readAuthFile(filePath);
|
|
470
|
+
if (!session) continue;
|
|
471
|
+
if (!hostAllowed(hostOf(session.domain), variant.allowedHostSuffixes)) continue;
|
|
472
|
+
if (session.token) return { token: session.token, encrypted: false, matched: true };
|
|
473
|
+
if (session.encrypted) encryptedForVariant = true;
|
|
474
|
+
}
|
|
475
|
+
return { token: null, encrypted: encryptedForVariant, matched: encryptedForVariant };
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
function readProductEndpoint(workbuddyHome) {
|
|
479
|
+
if (!workbuddyHome) return "";
|
|
480
|
+
const storage = path.join(workbuddyHome, "storage");
|
|
481
|
+
const found = [];
|
|
482
|
+
const walk = (dir, depth) => {
|
|
483
|
+
if (depth > 5 || found.length > 4) return;
|
|
484
|
+
let entries;
|
|
485
|
+
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
|
|
486
|
+
for (const entry of entries) {
|
|
487
|
+
if (found.length > 4) return;
|
|
488
|
+
const full = path.join(dir, entry.name);
|
|
489
|
+
if (entry.isDirectory()) walk(full, depth + 1);
|
|
490
|
+
else if (entry.name === "wb-product-config.json") found.push(full);
|
|
491
|
+
}
|
|
492
|
+
};
|
|
493
|
+
walk(storage, 0);
|
|
494
|
+
for (const filePath of found) {
|
|
495
|
+
try {
|
|
496
|
+
const parsed = JSON.parse(fs.readFileSync(filePath, "utf8"));
|
|
497
|
+
const data = parsed?.["product-config-snapshot"]?.data;
|
|
498
|
+
if (isNonEmptyString(data?.endpoint)) return data.endpoint.trim();
|
|
499
|
+
} catch {
|
|
500
|
+
// The next snapshot may still be readable.
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
return "";
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
function resolveOrigin(variant, { origin, workbuddyHome }) {
|
|
507
|
+
if (isNonEmptyString(origin) && originAllowed(origin, variant)) {
|
|
508
|
+
return origin.trim().replace(/\/+$/, "");
|
|
509
|
+
}
|
|
510
|
+
const configured = readProductEndpoint(workbuddyHome);
|
|
511
|
+
if (configured && originAllowed(configured, variant)) return configured.replace(/\/+$/, "");
|
|
512
|
+
return variant.defaultOrigin;
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
function resolveToken(variant, env) {
|
|
516
|
+
const fromEnv = env && typeof env === "object" ? env[variant.envToken] : null;
|
|
517
|
+
return isNonEmptyString(fromEnv) ? fromEnv.trim() : "";
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
async function postBilling(fetchImpl, url, token, body = {}, signal) {
|
|
521
|
+
const response = await fetchImpl(url, {
|
|
522
|
+
method: "POST",
|
|
523
|
+
headers: {
|
|
524
|
+
Accept: "application/json",
|
|
525
|
+
"Content-Type": "application/json",
|
|
526
|
+
Authorization: `Bearer ${token}`,
|
|
527
|
+
},
|
|
528
|
+
body: JSON.stringify(body),
|
|
529
|
+
signal,
|
|
530
|
+
});
|
|
531
|
+
if (response.status === 401 || response.status === 403) {
|
|
532
|
+
const error = new Error(`${VARIANTS.workbuddy.brand} sign-in expired.`);
|
|
533
|
+
error.code = "AUTH_EXPIRED";
|
|
534
|
+
throw error;
|
|
535
|
+
}
|
|
536
|
+
if (!response.ok) {
|
|
537
|
+
throw new Error(`WorkBuddy quota request failed (${response.status}).`);
|
|
538
|
+
}
|
|
539
|
+
return response.json();
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
async function fetchPlanQuota(post, variantId) {
|
|
543
|
+
const prefix = "/billing/meter/";
|
|
544
|
+
const summary = await post(`${prefix}get-user-resource-summary`, {});
|
|
545
|
+
if (!unwrapBillingBody(summary)) throw new Error("WorkBuddy quota request was rejected.");
|
|
546
|
+
const identity = readSubscriptionIdentity(summary);
|
|
547
|
+
const planCodes = [...new Set([...Object.keys(PLAN_PRIORITY),
|
|
548
|
+
...(identity.code && !isRewardCode(identity.code) ? [identity.code] : [])])];
|
|
549
|
+
const packageRows = await Promise.all(["paid", "free"].map(async (kind) => {
|
|
550
|
+
const rows = [];
|
|
551
|
+
for (let page = 1; page <= 10; page++) {
|
|
552
|
+
const payload = await post(`${prefix}get-user-resource-${kind}-packages`, {
|
|
553
|
+
PageNumber: page, PageSize: 100, PackageCodes: planCodes,
|
|
554
|
+
Status: [0, 3], ...(kind === "paid" ? { NeedRenewInfo: true } : {}),
|
|
555
|
+
});
|
|
556
|
+
const data = unwrapBillingBody(payload);
|
|
557
|
+
if (!data) throw new Error("WorkBuddy quota request was rejected.");
|
|
558
|
+
rows.push(...collectPackageRows(payload));
|
|
559
|
+
const count = Array.isArray(data.Accounts) ? data.Accounts.length : 0;
|
|
560
|
+
if (count < 100 || (Number(data.TotalCount) > 0 && page * 100 >= Number(data.TotalCount))) return rows;
|
|
561
|
+
}
|
|
562
|
+
throw new Error("WorkBuddy quota package list was incomplete.");
|
|
563
|
+
}));
|
|
564
|
+
const quota = selectWorkbuddyPlanQuota([
|
|
565
|
+
...collectPackageRows(summary), ...packageRows.flat(),
|
|
566
|
+
], identity, variantId);
|
|
567
|
+
return {
|
|
568
|
+
configured: true, error: null,
|
|
569
|
+
plan_label: quota?.plan_label || englishPlanLabel({ code: identity.code }, identity, variantId),
|
|
570
|
+
primary_window: quota?.primary_window || null,
|
|
571
|
+
secondary_window: resourceWindow(collectResourceGroups(summary)),
|
|
572
|
+
};
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
function scopedEnv(env, home) {
|
|
576
|
+
const next = { ...(env || {}) };
|
|
577
|
+
// An explicit home is the whole lookup root. Tests pass a temp directory
|
|
578
|
+
// while process.env.HOME still points at the developer, and a China
|
|
579
|
+
// session must not leak into that lookup.
|
|
580
|
+
if (isNonEmptyString(home)) {
|
|
581
|
+
next.HOME = home.trim();
|
|
582
|
+
if (next.USERPROFILE) next.USERPROFILE = home.trim();
|
|
583
|
+
}
|
|
584
|
+
return next;
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
async function fetchVariant(variantId, opts = {}) {
|
|
588
|
+
const variant = variantById(variantId);
|
|
589
|
+
if (!variant) return { configured: false };
|
|
590
|
+
const env = scopedEnv(opts.env || process.env, opts.home);
|
|
591
|
+
const workbuddyHome = opts.workbuddyHome || resolveWorkbuddyHome(env, variant.source);
|
|
592
|
+
const installed = directoryExists(workbuddyHome);
|
|
593
|
+
const discovery = readWorkbuddyIpcDiscovery(workbuddyHome);
|
|
594
|
+
if (discovery) {
|
|
595
|
+
// Discovery is edition-local. Never fall back to the other edition's
|
|
596
|
+
// socket or allow an explicitly redirected product to be mislabelled.
|
|
597
|
+
const productEndpoint = readProductEndpoint(workbuddyHome);
|
|
598
|
+
if (productEndpoint && !originAllowed(productEndpoint, variant)) {
|
|
599
|
+
throw new Error("WorkBuddy quota host does not match this edition.");
|
|
600
|
+
}
|
|
601
|
+
const client = await openWorkbuddyIpc({
|
|
602
|
+
discovery, signal: opts.signal, timeoutMs: opts.timeoutMs, connectImpl: opts.connectImpl,
|
|
603
|
+
});
|
|
604
|
+
try {
|
|
605
|
+
return { ...await fetchPlanQuota((apiPath, body) => client.postBilling(apiPath, body), variantId), source: "ipc" };
|
|
606
|
+
} finally {
|
|
607
|
+
client.close();
|
|
608
|
+
}
|
|
609
|
+
}
|
|
610
|
+
const explicitToken = resolveToken(variant, env);
|
|
611
|
+
const session = explicitToken
|
|
612
|
+
? { token: explicitToken, encrypted: false, matched: true }
|
|
613
|
+
: resolveSession(variant, { env, authFiles: opts.authFiles, workbuddyHome });
|
|
614
|
+
if (!session.token) {
|
|
615
|
+
if (session.encrypted || installed) return { configured: true, error: UNAVAILABLE };
|
|
616
|
+
if (!installed) return { configured: false };
|
|
617
|
+
return { configured: false };
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
const fetchImpl = opts.fetchImpl || fetch;
|
|
621
|
+
// An explicit origin is the caller's host. Otherwise use this edition's
|
|
622
|
+
// own product-config endpoint, and never the other edition's default.
|
|
623
|
+
const origin = resolveOrigin(variant, {
|
|
624
|
+
origin: opts.origin,
|
|
625
|
+
workbuddyHome: opts.origin ? null : workbuddyHome,
|
|
626
|
+
});
|
|
627
|
+
if (!originAllowed(origin, variant)) {
|
|
628
|
+
throw new Error("WorkBuddy quota host does not match this edition.");
|
|
629
|
+
}
|
|
630
|
+
return { ...await fetchPlanQuota((apiPath, body) => postBilling(fetchImpl,
|
|
631
|
+
`${origin}${apiPath}`, session.token, body, opts.signal), variantId), source: "api" };
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
function fetchWorkbuddyLimits(opts) {
|
|
635
|
+
return fetchVariant("workbuddy", opts);
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
function fetchWorkbuddyAiLimits(opts) {
|
|
639
|
+
return fetchVariant("workbuddyAi", opts);
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
module.exports = {
|
|
643
|
+
PLAN_PRIORITY,
|
|
644
|
+
REWARD_CODES,
|
|
645
|
+
VARIANTS,
|
|
646
|
+
selectWorkbuddyPlanQuota,
|
|
647
|
+
selectWorkbuddyLimits,
|
|
648
|
+
collectPackageRows,
|
|
649
|
+
collectResourceGroups,
|
|
650
|
+
resourceWindow,
|
|
651
|
+
readSubscriptionIdentity,
|
|
652
|
+
originAllowed,
|
|
653
|
+
hostAllowed,
|
|
654
|
+
fetchWorkbuddyLimits,
|
|
655
|
+
fetchWorkbuddyAiLimits,
|
|
656
|
+
};
|
package/src/lib/zcode-limits.js
CHANGED
|
@@ -4,6 +4,11 @@ const os = require("node:os");
|
|
|
4
4
|
const path = require("node:path");
|
|
5
5
|
const { fetchZcodeResetCredits } = require("./zcode-reset-credits");
|
|
6
6
|
|
|
7
|
+
const {
|
|
8
|
+
clampPercent,
|
|
9
|
+
buildWindow,
|
|
10
|
+
} = require("./limits-core");
|
|
11
|
+
|
|
7
12
|
const DEFAULT_BILLING_BASE_URL = "https://zcode.z.ai/api/v1/zcode-plan";
|
|
8
13
|
const DEFAULT_ZAI_MONITOR_BASE_URL = "https://api.z.ai";
|
|
9
14
|
const DEFAULT_BIGMODEL_MONITOR_BASE_URL = "https://bigmodel.cn";
|
|
@@ -550,24 +555,6 @@ function zcodeTsToIso(value) {
|
|
|
550
555
|
return null;
|
|
551
556
|
}
|
|
552
557
|
|
|
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
558
|
// Z.ai coding-plan ids look like "zcode-v3-start-plan-0615". The raw id reads
|
|
572
559
|
// terribly as a plan label, so extract just the human tier ("Start"/"Lite"/
|
|
573
560
|
// "Pro"/"Max"); fall back to null (→ bare "ZCode") when no known tier matches.
|