@narumitw/pi-usage 0.57.0 → 0.59.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/README.md +118 -2
- package/dist/index.ts +1247 -240
- package/dist/index.ts.map +4 -4
- package/package.json +8 -1
- package/src/codex-fast-runtime.ts +34 -26
- package/src/format.ts +189 -3
- package/src/index.ts +20 -0
- package/src/providers/baseten.ts +55 -0
- package/src/providers/fireworks.ts +198 -0
- package/src/providers/minimax.ts +264 -0
- package/src/providers/moonshot.ts +64 -0
- package/src/providers/vercel-ai-gateway.ts +43 -0
- package/src/query.ts +355 -9
- package/src/settings.ts +16 -1
- package/src/types.ts +44 -0
- package/src/usage-settings-ui.ts +125 -33
- package/src/usage.ts +55 -23
|
@@ -0,0 +1,264 @@
|
|
|
1
|
+
import { sanitizeDisplayText } from "../core.js";
|
|
2
|
+
import type { MiniMaxUsagePayload, UsageBucket, UsageMetric, UsageReport } from "../types.js";
|
|
3
|
+
|
|
4
|
+
export type MiniMaxProviderId = "minimax" | "minimax-cn";
|
|
5
|
+
export type MiniMaxUsageKind = "token-plan" | "account-balance";
|
|
6
|
+
|
|
7
|
+
const PROVIDERS = {
|
|
8
|
+
minimax: { name: "MiniMax", currency: "USD" },
|
|
9
|
+
"minimax-cn": { name: "MiniMax CN", currency: "CNY" },
|
|
10
|
+
} as const;
|
|
11
|
+
const DECIMAL_AMOUNT = /^-?(?:0|[1-9]\d*)(?:\.\d+)?$/u;
|
|
12
|
+
const PERCENT_TOLERANCE = 1;
|
|
13
|
+
|
|
14
|
+
export function miniMaxUsageKind(apiKey: string): MiniMaxUsageKind {
|
|
15
|
+
return apiKey.startsWith("sk-api-") ? "account-balance" : "token-plan";
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function normalizeMiniMaxUsagePayload(
|
|
19
|
+
providerId: MiniMaxProviderId,
|
|
20
|
+
kind: MiniMaxUsageKind,
|
|
21
|
+
payload: MiniMaxUsagePayload,
|
|
22
|
+
capturedAt: number,
|
|
23
|
+
): UsageReport {
|
|
24
|
+
return kind === "account-balance"
|
|
25
|
+
? normalizeBalance(providerId, payload, capturedAt)
|
|
26
|
+
: normalizeTokenPlan(providerId, payload, capturedAt);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function normalizeBalance(
|
|
30
|
+
providerId: MiniMaxProviderId,
|
|
31
|
+
payload: MiniMaxUsagePayload,
|
|
32
|
+
capturedAt: number,
|
|
33
|
+
): UsageReport {
|
|
34
|
+
assertSuccess(payload);
|
|
35
|
+
const provider = PROVIDERS[providerId];
|
|
36
|
+
const metrics: UsageMetric[] = [
|
|
37
|
+
balanceMetric(
|
|
38
|
+
"available-balance",
|
|
39
|
+
"Available balance",
|
|
40
|
+
payload.available_amount,
|
|
41
|
+
provider.currency,
|
|
42
|
+
),
|
|
43
|
+
balanceMetric("cash-balance", "Cash balance", payload.cash_balance, provider.currency, true),
|
|
44
|
+
balanceMetric("voucher-balance", "Voucher balance", payload.voucher_balance, provider.currency),
|
|
45
|
+
balanceMetric("credit-balance", "Credit balance", payload.credit_balance, provider.currency),
|
|
46
|
+
balanceMetric("owed-amount", "Owed amount", payload.owed_amount, provider.currency),
|
|
47
|
+
];
|
|
48
|
+
return {
|
|
49
|
+
providerId,
|
|
50
|
+
providerName: provider.name,
|
|
51
|
+
capturedAt,
|
|
52
|
+
source: "minimax-account-balance",
|
|
53
|
+
semantics: { kind: "api-key", label: "MiniMax pay-as-you-go account balance" },
|
|
54
|
+
buckets: [],
|
|
55
|
+
metrics,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function normalizeTokenPlan(
|
|
60
|
+
providerId: MiniMaxProviderId,
|
|
61
|
+
payload: MiniMaxUsagePayload,
|
|
62
|
+
capturedAt: number,
|
|
63
|
+
): UsageReport {
|
|
64
|
+
assertSuccess(payload);
|
|
65
|
+
if (!Array.isArray(payload.model_remains) || payload.model_remains.length === 0) {
|
|
66
|
+
throw new Error("MiniMax Token Plan returned no quota rows.");
|
|
67
|
+
}
|
|
68
|
+
const provider = PROVIDERS[providerId];
|
|
69
|
+
const buckets: UsageBucket[] = [];
|
|
70
|
+
const groups = new Set<string>();
|
|
71
|
+
for (const [index, raw] of payload.model_remains.entries()) {
|
|
72
|
+
const row = asObject(raw);
|
|
73
|
+
if (!row) throw new Error("MiniMax Token Plan quota row was not an object.");
|
|
74
|
+
const groupLabel = safeLabel(row.model_name, `Quota ${index + 1}`);
|
|
75
|
+
const groupId = uniqueGroupId(groupLabel, index, groups);
|
|
76
|
+
buckets.push(
|
|
77
|
+
normalizeWindow(row, {
|
|
78
|
+
id: `${groupId}:interval`,
|
|
79
|
+
label: "Rolling window",
|
|
80
|
+
groupId,
|
|
81
|
+
groupLabel,
|
|
82
|
+
countField: "current_interval_usage_count",
|
|
83
|
+
totalField: "current_interval_total_count",
|
|
84
|
+
percentField: "current_interval_remaining_percent",
|
|
85
|
+
statusField: "current_interval_status",
|
|
86
|
+
startField: "start_time",
|
|
87
|
+
endField: "end_time",
|
|
88
|
+
}),
|
|
89
|
+
normalizeWindow(row, {
|
|
90
|
+
id: `${groupId}:weekly`,
|
|
91
|
+
label: "Weekly window",
|
|
92
|
+
groupId,
|
|
93
|
+
groupLabel,
|
|
94
|
+
countField: "current_weekly_usage_count",
|
|
95
|
+
totalField: "current_weekly_total_count",
|
|
96
|
+
percentField: "current_weekly_remaining_percent",
|
|
97
|
+
statusField: "current_weekly_status",
|
|
98
|
+
startField: "weekly_start_time",
|
|
99
|
+
endField: "weekly_end_time",
|
|
100
|
+
boostPermille: row.weekly_boost_permille,
|
|
101
|
+
}),
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
return {
|
|
105
|
+
providerId,
|
|
106
|
+
providerName: provider.name,
|
|
107
|
+
capturedAt,
|
|
108
|
+
source: "minimax-token-plan",
|
|
109
|
+
semantics: { kind: "consumer-subscription", label: "MiniMax Token Plan quota" },
|
|
110
|
+
buckets,
|
|
111
|
+
metrics: [],
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
type WindowFields = {
|
|
116
|
+
id: string;
|
|
117
|
+
label: string;
|
|
118
|
+
groupId: string;
|
|
119
|
+
groupLabel: string;
|
|
120
|
+
countField: string;
|
|
121
|
+
totalField: string;
|
|
122
|
+
percentField: string;
|
|
123
|
+
statusField: string;
|
|
124
|
+
startField: string;
|
|
125
|
+
endField: string;
|
|
126
|
+
boostPermille?: unknown;
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
function normalizeWindow(row: Record<string, unknown>, fields: WindowFields): UsageBucket {
|
|
130
|
+
const status = optionalInteger(row[fields.statusField], fields.statusField);
|
|
131
|
+
if (status !== undefined && ![1, 2, 3].includes(status)) {
|
|
132
|
+
throw new Error(`MiniMax Token Plan ${fields.label} status was unsupported.`);
|
|
133
|
+
}
|
|
134
|
+
const percent = optionalPercent(row[fields.percentField], fields.percentField);
|
|
135
|
+
validateBoost(fields.boostPermille);
|
|
136
|
+
const start = timestamp(row[fields.startField], fields.startField);
|
|
137
|
+
const end = timestamp(row[fields.endField], fields.endField);
|
|
138
|
+
if (end < start) throw new Error(`MiniMax Token Plan ${fields.label} timestamps were reversed.`);
|
|
139
|
+
const resetsAt = Math.floor(end / 1_000);
|
|
140
|
+
const windowMinutes = Math.max(1, Math.round((end - start) / 60_000));
|
|
141
|
+
if (status === 3) {
|
|
142
|
+
return {
|
|
143
|
+
id: fields.id,
|
|
144
|
+
label: fields.label,
|
|
145
|
+
groupId: fields.groupId,
|
|
146
|
+
groupLabel: fields.groupLabel,
|
|
147
|
+
remaining: 100,
|
|
148
|
+
unit: "percent",
|
|
149
|
+
period: "unlimited",
|
|
150
|
+
windowMinutes,
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
const total = nonnegativeInteger(row[fields.totalField], fields.totalField);
|
|
154
|
+
const count = nonnegativeInteger(row[fields.countField], fields.countField);
|
|
155
|
+
const resolved = resolveQuotaCounts(count, total, percent);
|
|
156
|
+
if (!resolved) throw new Error(`MiniMax Token Plan ${fields.label} counts were inconsistent.`);
|
|
157
|
+
return {
|
|
158
|
+
id: fields.id,
|
|
159
|
+
label: fields.label,
|
|
160
|
+
groupId: fields.groupId,
|
|
161
|
+
groupLabel: fields.groupLabel,
|
|
162
|
+
...resolved,
|
|
163
|
+
unit: "count",
|
|
164
|
+
windowMinutes,
|
|
165
|
+
resetsAt,
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function resolveQuotaCounts(
|
|
170
|
+
reportedCount: number,
|
|
171
|
+
total: number,
|
|
172
|
+
remainingPercent: number | undefined,
|
|
173
|
+
): Pick<UsageBucket, "used" | "remaining" | "limit"> | undefined {
|
|
174
|
+
if (total <= 0 || reportedCount > total) return undefined;
|
|
175
|
+
let remaining = reportedCount;
|
|
176
|
+
if (remainingPercent !== undefined) {
|
|
177
|
+
const asRemaining = (reportedCount / total) * 100;
|
|
178
|
+
const asUsed = ((total - reportedCount) / total) * 100;
|
|
179
|
+
const remainingDistance = Math.abs(asRemaining - remainingPercent);
|
|
180
|
+
const usedDistance = Math.abs(asUsed - remainingPercent);
|
|
181
|
+
if (Math.min(remainingDistance, usedDistance) > PERCENT_TOLERANCE) return undefined;
|
|
182
|
+
if (usedDistance < remainingDistance) remaining = total - reportedCount;
|
|
183
|
+
}
|
|
184
|
+
return { used: total - remaining, remaining, limit: total };
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function assertSuccess(payload: MiniMaxUsagePayload): void {
|
|
188
|
+
const base = asObject(payload.base_resp);
|
|
189
|
+
if (base?.status_code !== 0) {
|
|
190
|
+
throw new Error("MiniMax usage response did not report success.");
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function balanceMetric(
|
|
195
|
+
id: string,
|
|
196
|
+
label: string,
|
|
197
|
+
value: unknown,
|
|
198
|
+
currency: "CNY" | "USD",
|
|
199
|
+
allowNegative = false,
|
|
200
|
+
): UsageMetric {
|
|
201
|
+
if (
|
|
202
|
+
typeof value !== "string" ||
|
|
203
|
+
value.length > 64 ||
|
|
204
|
+
!DECIMAL_AMOUNT.test(value) ||
|
|
205
|
+
(!allowNegative && value.startsWith("-"))
|
|
206
|
+
) {
|
|
207
|
+
throw new Error(`MiniMax ${label.toLowerCase()} was not a valid amount.`);
|
|
208
|
+
}
|
|
209
|
+
return { id, label, value, unit: "currency", currency };
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
function asObject(value: unknown): Record<string, unknown> | undefined {
|
|
213
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
214
|
+
return value as Record<string, unknown>;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function safeLabel(value: unknown, fallback: string): string {
|
|
218
|
+
if (typeof value !== "string") throw new Error("MiniMax Token Plan model name was not a string.");
|
|
219
|
+
return sanitizeDisplayText(value, 80) || fallback;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
function uniqueGroupId(label: string, index: number, groups: Set<string>): string {
|
|
223
|
+
const base =
|
|
224
|
+
label
|
|
225
|
+
.toLowerCase()
|
|
226
|
+
.replace(/[^a-z0-9]+/gu, "-")
|
|
227
|
+
.replace(/^-|-$/gu, "") || "quota";
|
|
228
|
+
const id = groups.has(base) ? `${base}-${index + 1}` : base;
|
|
229
|
+
groups.add(id);
|
|
230
|
+
return id;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
function nonnegativeInteger(value: unknown, field: string): number {
|
|
234
|
+
if (!Number.isSafeInteger(value) || (value as number) < 0) {
|
|
235
|
+
throw new Error(`MiniMax Token Plan ${field} was not a nonnegative safe integer.`);
|
|
236
|
+
}
|
|
237
|
+
return value as number;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
function optionalInteger(value: unknown, field: string): number | undefined {
|
|
241
|
+
if (value === undefined || value === null) return undefined;
|
|
242
|
+
return nonnegativeInteger(value, field);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
function optionalPercent(value: unknown, field: string): number | undefined {
|
|
246
|
+
if (value === undefined || value === null) return undefined;
|
|
247
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 100) {
|
|
248
|
+
throw new Error(`MiniMax Token Plan ${field} was not a percentage.`);
|
|
249
|
+
}
|
|
250
|
+
return value;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function validateBoost(boost: unknown): void {
|
|
254
|
+
if (boost === undefined || boost === null) return;
|
|
255
|
+
const permille = nonnegativeInteger(boost, "weekly_boost_permille");
|
|
256
|
+
if (permille > 10_000) throw new Error("MiniMax Token Plan weekly boost was unreasonable.");
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
function timestamp(value: unknown, field: string): number {
|
|
260
|
+
if (!Number.isSafeInteger(value) || (value as number) <= 0) {
|
|
261
|
+
throw new Error(`MiniMax Token Plan ${field} was not a valid timestamp.`);
|
|
262
|
+
}
|
|
263
|
+
return value as number;
|
|
264
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import type { MoonshotBalancePayload, UsageMetric, UsageReport } from "../types.js";
|
|
2
|
+
|
|
3
|
+
export type MoonshotProviderId = "moonshotai" | "moonshotai-cn";
|
|
4
|
+
|
|
5
|
+
const PROVIDERS = {
|
|
6
|
+
moonshotai: { name: "Moonshot AI", currency: "USD" },
|
|
7
|
+
"moonshotai-cn": { name: "Moonshot AI CN", currency: "CNY" },
|
|
8
|
+
} as const;
|
|
9
|
+
|
|
10
|
+
export function normalizeMoonshotBalancePayload(
|
|
11
|
+
providerId: MoonshotProviderId,
|
|
12
|
+
payload: MoonshotBalancePayload,
|
|
13
|
+
capturedAt: number,
|
|
14
|
+
): UsageReport {
|
|
15
|
+
if (payload.code !== 0 || payload.status !== true) {
|
|
16
|
+
throw new Error("Moonshot AI balance response did not report success.");
|
|
17
|
+
}
|
|
18
|
+
const data = asObject(payload.data);
|
|
19
|
+
if (!data) throw new Error("Moonshot AI balance response data was not an object.");
|
|
20
|
+
const provider = PROVIDERS[providerId];
|
|
21
|
+
const available = amount(data.available_balance, "available balance", false);
|
|
22
|
+
const voucher = amount(data.voucher_balance, "voucher balance", false);
|
|
23
|
+
const cash = amount(data.cash_balance, "cash balance", true);
|
|
24
|
+
const metrics: UsageMetric[] = [
|
|
25
|
+
currencyMetric("available-balance", "Available balance", available, provider.currency),
|
|
26
|
+
currencyMetric("voucher-balance", "Voucher balance", voucher, provider.currency),
|
|
27
|
+
currencyMetric("cash-balance", "Cash balance", cash, provider.currency),
|
|
28
|
+
];
|
|
29
|
+
return {
|
|
30
|
+
providerId,
|
|
31
|
+
providerName: provider.name,
|
|
32
|
+
capturedAt,
|
|
33
|
+
source: "moonshot-balance",
|
|
34
|
+
semantics: { kind: "api-key", label: "Moonshot API account balance" },
|
|
35
|
+
buckets: [],
|
|
36
|
+
metrics,
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function currencyMetric(
|
|
41
|
+
id: string,
|
|
42
|
+
label: string,
|
|
43
|
+
value: string,
|
|
44
|
+
currency: "CNY" | "USD",
|
|
45
|
+
): UsageMetric {
|
|
46
|
+
return { id, label, value, unit: "currency", currency };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function asObject(value: unknown): Record<string, unknown> | undefined {
|
|
50
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
51
|
+
return value as Record<string, unknown>;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function amount(value: unknown, label: string, allowNegative: boolean): string {
|
|
55
|
+
if (
|
|
56
|
+
typeof value !== "number" ||
|
|
57
|
+
!Number.isFinite(value) ||
|
|
58
|
+
(!allowNegative && value < 0) ||
|
|
59
|
+
Math.abs(value) > Number.MAX_SAFE_INTEGER
|
|
60
|
+
) {
|
|
61
|
+
throw new Error(`Moonshot AI ${label} was not a valid amount.`);
|
|
62
|
+
}
|
|
63
|
+
return String(value);
|
|
64
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import type { UsageMetric, UsageReport, VercelAIGatewayCreditsPayload } from "../types.js";
|
|
2
|
+
|
|
3
|
+
const DECIMAL_AMOUNT = /^(?:0|[1-9]\d*)(?:\.\d+)?$/u;
|
|
4
|
+
|
|
5
|
+
export function normalizeVercelAIGatewayCreditsPayload(
|
|
6
|
+
payload: VercelAIGatewayCreditsPayload,
|
|
7
|
+
capturedAt: number,
|
|
8
|
+
): UsageReport {
|
|
9
|
+
const balance = decimalAmount(payload.balance, "balance");
|
|
10
|
+
const totalUsed = decimalAmount(payload.total_used, "total used");
|
|
11
|
+
const metrics: UsageMetric[] = [
|
|
12
|
+
{
|
|
13
|
+
id: "credit-balance",
|
|
14
|
+
label: "Credit balance",
|
|
15
|
+
value: balance,
|
|
16
|
+
unit: "currency",
|
|
17
|
+
currency: "USD",
|
|
18
|
+
},
|
|
19
|
+
{
|
|
20
|
+
id: "lifetime-spend",
|
|
21
|
+
label: "Lifetime spend",
|
|
22
|
+
value: totalUsed,
|
|
23
|
+
unit: "currency",
|
|
24
|
+
currency: "USD",
|
|
25
|
+
},
|
|
26
|
+
];
|
|
27
|
+
return {
|
|
28
|
+
providerId: "vercel-ai-gateway",
|
|
29
|
+
providerName: "Vercel AI Gateway",
|
|
30
|
+
capturedAt,
|
|
31
|
+
source: "vercel-ai-gateway-credits",
|
|
32
|
+
semantics: { kind: "api-key", label: "AI Gateway credits and lifetime spend" },
|
|
33
|
+
buckets: [],
|
|
34
|
+
metrics,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function decimalAmount(value: unknown, label: string): string {
|
|
39
|
+
if (typeof value !== "string" || value.length > 64 || !DECIMAL_AMOUNT.test(value)) {
|
|
40
|
+
throw new Error(`Vercel AI Gateway ${label} was not a valid nonnegative amount.`);
|
|
41
|
+
}
|
|
42
|
+
return value;
|
|
43
|
+
}
|