magpie-blaze-api 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +113 -2
- package/index.mjs +53 -0
- package/opencode.mjs +3 -0
- package/opencode2.mjs +634 -0
- package/package.json +60 -4
- package/src/constants.mjs +157 -0
- package/src/fetch.mjs +126 -0
- package/src/models.mjs +354 -0
- package/src/plugin.mjs +331 -0
- package/src/usage.mjs +337 -0
package/src/plugin.mjs
ADDED
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import {
|
|
3
|
+
BLAZE_ICON_DATA_URI,
|
|
4
|
+
DEFAULT_BASE_URL,
|
|
5
|
+
PROVIDER_ID,
|
|
6
|
+
PROVIDER_NAME,
|
|
7
|
+
SDK,
|
|
8
|
+
} from "./constants.mjs";
|
|
9
|
+
import { createBlazeFetch, sanitizeProviderRouting } from "./fetch.mjs";
|
|
10
|
+
import {
|
|
11
|
+
buildConfigModels,
|
|
12
|
+
fetchBlazeModels,
|
|
13
|
+
normalizeBaseURL,
|
|
14
|
+
} from "./models.mjs";
|
|
15
|
+
import { fetchBlazeUsage } from "./usage.mjs";
|
|
16
|
+
|
|
17
|
+
function extractApiKey(auth) {
|
|
18
|
+
if (!auth || typeof auth !== "object") return "";
|
|
19
|
+
const raw = auth.type === "oauth" ? (auth.access ?? auth.key) : (auth.key ?? auth.access);
|
|
20
|
+
return typeof raw === "string" ? raw.trim() : "";
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function maskKey(key) {
|
|
24
|
+
const s = String(key || "").trim();
|
|
25
|
+
if (s.length <= 10) return `${s.slice(0, 4)}…`;
|
|
26
|
+
return `${s.slice(0, 8)}…${s.slice(-4)}`;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function fingerprint(key) {
|
|
30
|
+
return createHash("sha256").update(String(key || "")).digest("hex").slice(0, 16);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function effectiveOptions(auth, provider, pluginOpts, defaultBaseURL) {
|
|
34
|
+
const meta = auth?.metadata && typeof auth.metadata === "object" ? auth.metadata : {};
|
|
35
|
+
const provOpts = provider?.options && typeof provider.options === "object" ? provider.options : {};
|
|
36
|
+
|
|
37
|
+
let baseURL = defaultBaseURL;
|
|
38
|
+
const rawBase = meta.baseURL || pluginOpts.baseURL || provOpts.baseURL;
|
|
39
|
+
if (rawBase) {
|
|
40
|
+
try {
|
|
41
|
+
baseURL = normalizeBaseURL(rawBase);
|
|
42
|
+
} catch {
|
|
43
|
+
baseURL = defaultBaseURL;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const scope = ["all", "available", "free"].includes(meta.scope)
|
|
48
|
+
? meta.scope
|
|
49
|
+
: ["all", "available", "free"].includes(pluginOpts.scope)
|
|
50
|
+
? pluginOpts.scope
|
|
51
|
+
: "available";
|
|
52
|
+
|
|
53
|
+
const protocol =
|
|
54
|
+
pluginOpts.protocol === "chat" || meta.protocol === "chat" ? "chat" : "auto";
|
|
55
|
+
|
|
56
|
+
const providerRouting = sanitizeProviderRouting(
|
|
57
|
+
String(meta.providerRouting ?? pluginOpts.providerRouting ?? ""),
|
|
58
|
+
);
|
|
59
|
+
|
|
60
|
+
return {
|
|
61
|
+
baseURL,
|
|
62
|
+
scope,
|
|
63
|
+
protocol,
|
|
64
|
+
providerRouting,
|
|
65
|
+
includeSearchModels: pluginOpts.includeSearchModels !== false,
|
|
66
|
+
includeTokV2: pluginOpts.includeTokV2 !== false,
|
|
67
|
+
includeFree: pluginOpts.includeFree !== false,
|
|
68
|
+
includeUnavailable: Boolean(pluginOpts.includeUnavailable),
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export async function BlazeApiPlugin(input = {}, options = {}) {
|
|
73
|
+
const mergedOpts = {
|
|
74
|
+
...(input?.magpie?.options && typeof input.magpie.options === "object"
|
|
75
|
+
? input.magpie.options
|
|
76
|
+
: {}),
|
|
77
|
+
...(options && typeof options === "object" ? options : {}),
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
const defaultBaseURL = normalizeBaseURL(mergedOpts.baseURL || DEFAULT_BASE_URL);
|
|
81
|
+
const fetchImpl = mergedOpts.fetchImpl ?? fetch;
|
|
82
|
+
const now = mergedOpts.now ?? Date.now;
|
|
83
|
+
const accountCaches = new Map();
|
|
84
|
+
|
|
85
|
+
const rememberModels = (cacheKey, models) => {
|
|
86
|
+
accountCaches.delete(cacheKey);
|
|
87
|
+
accountCaches.set(cacheKey, models);
|
|
88
|
+
if (accountCaches.size > 32) {
|
|
89
|
+
accountCaches.delete(accountCaches.keys().next().value);
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
return {
|
|
94
|
+
async config(cfg) {
|
|
95
|
+
cfg.provider ??= {};
|
|
96
|
+
cfg.provider[PROVIDER_ID] ??= {
|
|
97
|
+
name: PROVIDER_NAME,
|
|
98
|
+
npm: SDK.chat,
|
|
99
|
+
api: defaultBaseURL,
|
|
100
|
+
models: buildConfigModels(defaultBaseURL, mergedOpts),
|
|
101
|
+
};
|
|
102
|
+
},
|
|
103
|
+
|
|
104
|
+
auth: {
|
|
105
|
+
provider: PROVIDER_ID,
|
|
106
|
+
icon: BLAZE_ICON_DATA_URI,
|
|
107
|
+
methods: [
|
|
108
|
+
{
|
|
109
|
+
type: "api",
|
|
110
|
+
label: "BlazeAPI Key",
|
|
111
|
+
placeholder: "blaze-…",
|
|
112
|
+
},
|
|
113
|
+
{
|
|
114
|
+
type: "api",
|
|
115
|
+
label: "BlazeAPI Key (verify & configure)",
|
|
116
|
+
prompts: [
|
|
117
|
+
{
|
|
118
|
+
type: "password",
|
|
119
|
+
key: "apiKey",
|
|
120
|
+
message: "BlazeAPI API key",
|
|
121
|
+
placeholder: "blaze-…",
|
|
122
|
+
validate: (v) => (v && v.trim() ? undefined : "API key is required"),
|
|
123
|
+
},
|
|
124
|
+
{
|
|
125
|
+
type: "select",
|
|
126
|
+
key: "scope",
|
|
127
|
+
message: "Model catalog scope",
|
|
128
|
+
options: [
|
|
129
|
+
{
|
|
130
|
+
label: "Available for account (recommended)",
|
|
131
|
+
value: "available",
|
|
132
|
+
hint: "Only models your current balance/plan can call; paid models appear when you top up",
|
|
133
|
+
},
|
|
134
|
+
{
|
|
135
|
+
label: "All chat models",
|
|
136
|
+
value: "all",
|
|
137
|
+
hint: "Full catalog including PAYG models even with $0 balance",
|
|
138
|
+
},
|
|
139
|
+
{
|
|
140
|
+
label: "Free models only",
|
|
141
|
+
value: "free",
|
|
142
|
+
hint: "Only free/* models",
|
|
143
|
+
},
|
|
144
|
+
],
|
|
145
|
+
},
|
|
146
|
+
{
|
|
147
|
+
type: "text",
|
|
148
|
+
key: "baseURL",
|
|
149
|
+
message: "Custom Base URL (optional — leave empty for default)",
|
|
150
|
+
placeholder: DEFAULT_BASE_URL,
|
|
151
|
+
required: false,
|
|
152
|
+
validate: (v) => {
|
|
153
|
+
if (!v || !v.trim()) return undefined;
|
|
154
|
+
try {
|
|
155
|
+
normalizeBaseURL(v);
|
|
156
|
+
return undefined;
|
|
157
|
+
} catch (err) {
|
|
158
|
+
return err.message;
|
|
159
|
+
}
|
|
160
|
+
},
|
|
161
|
+
},
|
|
162
|
+
],
|
|
163
|
+
async authorize(inputs, extra) {
|
|
164
|
+
const obj =
|
|
165
|
+
inputs && typeof inputs === "object" && !Array.isArray(inputs)
|
|
166
|
+
? inputs
|
|
167
|
+
: {};
|
|
168
|
+
const apiKey = String(
|
|
169
|
+
(typeof inputs === "string" ? inputs : obj.apiKey ?? obj.key ?? obj.token) || "",
|
|
170
|
+
).trim();
|
|
171
|
+
if (!apiKey) {
|
|
172
|
+
return { type: "failed", error: "BlazeAPI API key is required." };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
let customBaseURL;
|
|
176
|
+
const rawBase = String(obj.baseURL || "").trim();
|
|
177
|
+
if (rawBase) {
|
|
178
|
+
try {
|
|
179
|
+
customBaseURL = normalizeBaseURL(rawBase);
|
|
180
|
+
} catch (err) {
|
|
181
|
+
return { type: "failed", error: err.message };
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
const targetBase = customBaseURL || defaultBaseURL;
|
|
186
|
+
const defaultScope = ["all", "available", "free"].includes(mergedOpts.scope)
|
|
187
|
+
? mergedOpts.scope
|
|
188
|
+
: "available";
|
|
189
|
+
const scope = ["all", "available", "free"].includes(obj.scope)
|
|
190
|
+
? obj.scope
|
|
191
|
+
: defaultScope;
|
|
192
|
+
|
|
193
|
+
const usage = await fetchBlazeUsage({
|
|
194
|
+
baseURL: targetBase,
|
|
195
|
+
apiKey,
|
|
196
|
+
fetchImpl,
|
|
197
|
+
signal: extra?.signal,
|
|
198
|
+
now,
|
|
199
|
+
});
|
|
200
|
+
|
|
201
|
+
if (usage.signIn === "expired") {
|
|
202
|
+
return {
|
|
203
|
+
type: "failed",
|
|
204
|
+
error: usage.error || "Invalid BlazeAPI API key.",
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
let plan = usage.plan;
|
|
209
|
+
let user = usage.user;
|
|
210
|
+
|
|
211
|
+
if (usage.error) {
|
|
212
|
+
// Fallback check via /models in case a custom proxy omits /usage.
|
|
213
|
+
try {
|
|
214
|
+
await fetchBlazeModels({
|
|
215
|
+
baseURL: targetBase,
|
|
216
|
+
apiKey,
|
|
217
|
+
fetchImpl,
|
|
218
|
+
signal: extra?.signal,
|
|
219
|
+
opts: { ...mergedOpts, scope },
|
|
220
|
+
});
|
|
221
|
+
} catch (err) {
|
|
222
|
+
return {
|
|
223
|
+
type: "failed",
|
|
224
|
+
error: err?.message || usage.error,
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const accountId =
|
|
230
|
+
user || (plan ? `${plan} (${maskKey(apiKey)})` : maskKey(apiKey));
|
|
231
|
+
const metadata = {};
|
|
232
|
+
if (scope !== "available" || (obj.scope && obj.scope !== defaultScope)) {
|
|
233
|
+
metadata.scope = scope;
|
|
234
|
+
}
|
|
235
|
+
if (customBaseURL && customBaseURL !== DEFAULT_BASE_URL) {
|
|
236
|
+
metadata.baseURL = customBaseURL;
|
|
237
|
+
}
|
|
238
|
+
if (plan) metadata.plan = plan;
|
|
239
|
+
if (user && user.includes("@")) metadata.email = user;
|
|
240
|
+
|
|
241
|
+
return {
|
|
242
|
+
type: "success",
|
|
243
|
+
key: apiKey,
|
|
244
|
+
accountId,
|
|
245
|
+
uid: fingerprint(apiKey),
|
|
246
|
+
account: accountId,
|
|
247
|
+
...(user && user.includes("@") ? { email: user } : {}),
|
|
248
|
+
metadata,
|
|
249
|
+
};
|
|
250
|
+
},
|
|
251
|
+
},
|
|
252
|
+
],
|
|
253
|
+
|
|
254
|
+
async loader(getAuth, provider) {
|
|
255
|
+
const auth = await getAuth();
|
|
256
|
+
const apiKey = extractApiKey(auth);
|
|
257
|
+
if (!apiKey) return {};
|
|
258
|
+
const acc = effectiveOptions(auth, provider, mergedOpts, defaultBaseURL);
|
|
259
|
+
return {
|
|
260
|
+
baseURL: acc.baseURL,
|
|
261
|
+
apiKey,
|
|
262
|
+
fetch: createBlazeFetch({
|
|
263
|
+
apiKey,
|
|
264
|
+
providerRouting: acc.providerRouting,
|
|
265
|
+
fetchImpl,
|
|
266
|
+
}),
|
|
267
|
+
};
|
|
268
|
+
},
|
|
269
|
+
|
|
270
|
+
async usage(getAuth, provider) {
|
|
271
|
+
const auth = await getAuth();
|
|
272
|
+
const apiKey = extractApiKey(auth);
|
|
273
|
+
if (!apiKey) {
|
|
274
|
+
return {
|
|
275
|
+
error: "Not signed in to BlazeAPI",
|
|
276
|
+
signIn: "expired",
|
|
277
|
+
windows: [],
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
const acc = effectiveOptions(auth, provider, mergedOpts, defaultBaseURL);
|
|
281
|
+
return fetchBlazeUsage({
|
|
282
|
+
baseURL: acc.baseURL,
|
|
283
|
+
apiKey,
|
|
284
|
+
fetchImpl,
|
|
285
|
+
now,
|
|
286
|
+
});
|
|
287
|
+
},
|
|
288
|
+
},
|
|
289
|
+
|
|
290
|
+
provider: {
|
|
291
|
+
id: PROVIDER_ID,
|
|
292
|
+
async models(provider, { auth } = {}) {
|
|
293
|
+
if (!auth) return provider.models;
|
|
294
|
+
const apiKey = extractApiKey(auth);
|
|
295
|
+
if (!apiKey) return provider.models;
|
|
296
|
+
|
|
297
|
+
const acc = effectiveOptions(auth, provider, mergedOpts, defaultBaseURL);
|
|
298
|
+
const cacheKey = `${acc.baseURL}\0${acc.scope}\0${acc.protocol}\0${acc.providerRouting}\0${acc.includeSearchModels}\0${acc.includeTokV2}\0${acc.includeFree}\0${acc.includeUnavailable}\0${fingerprint(apiKey)}`;
|
|
299
|
+
|
|
300
|
+
try {
|
|
301
|
+
const { models } = await fetchBlazeModels({
|
|
302
|
+
baseURL: acc.baseURL,
|
|
303
|
+
apiKey,
|
|
304
|
+
fetchImpl,
|
|
305
|
+
opts: acc,
|
|
306
|
+
});
|
|
307
|
+
if (Object.keys(models).length > 0) {
|
|
308
|
+
rememberModels(cacheKey, models);
|
|
309
|
+
return models;
|
|
310
|
+
}
|
|
311
|
+
const cached = accountCaches.get(cacheKey);
|
|
312
|
+
if (cached) {
|
|
313
|
+
const fallback = { ...cached };
|
|
314
|
+
fallback[Symbol.for("magpie.fellBack")] = true;
|
|
315
|
+
return fallback;
|
|
316
|
+
}
|
|
317
|
+
return provider.models;
|
|
318
|
+
} catch (err) {
|
|
319
|
+
if (err?.signIn === "expired") throw err;
|
|
320
|
+
const cached = accountCaches.get(cacheKey);
|
|
321
|
+
if (cached) {
|
|
322
|
+
const fallback = { ...cached };
|
|
323
|
+
fallback[Symbol.for("magpie.fellBack")] = true;
|
|
324
|
+
return fallback;
|
|
325
|
+
}
|
|
326
|
+
return provider.models;
|
|
327
|
+
}
|
|
328
|
+
},
|
|
329
|
+
},
|
|
330
|
+
};
|
|
331
|
+
}
|
package/src/usage.mjs
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
import { DEFAULT_BASE_URL } from "./constants.mjs";
|
|
2
|
+
import { classifyAuthError } from "./fetch.mjs";
|
|
3
|
+
|
|
4
|
+
const DAY_MS = 24 * 60 * 60 * 1000;
|
|
5
|
+
const DAY_S = 86_400;
|
|
6
|
+
|
|
7
|
+
export function nextUtcMidnight(now = Date.now()) {
|
|
8
|
+
return new Date((Math.floor(now / DAY_MS) + 1) * DAY_MS).toISOString();
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function num(v) {
|
|
12
|
+
if (typeof v === "number" && Number.isFinite(v)) return v;
|
|
13
|
+
if (typeof v === "string" && v.trim() && Number.isFinite(Number(v))) {
|
|
14
|
+
return Number(v);
|
|
15
|
+
}
|
|
16
|
+
return undefined;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function str(v) {
|
|
20
|
+
return typeof v === "string" && v.trim() ? v.trim() : undefined;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function formatUsd(amount) {
|
|
24
|
+
if (amount > 0 && amount < 0.01) return `$${amount.toFixed(4)}`;
|
|
25
|
+
return `$${amount.toFixed(2)}`;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function formatCompact(n) {
|
|
29
|
+
if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(2).replace(/\.?0+$/, "")}M`;
|
|
30
|
+
if (n >= 1_000) return `${(n / 1_000).toFixed(1).replace(/\.0$/, "")}k`;
|
|
31
|
+
return String(Math.round(n));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function formatPlan(rawPlan, balanceUsd) {
|
|
35
|
+
const s = str(rawPlan);
|
|
36
|
+
if (!s) {
|
|
37
|
+
return balanceUsd !== undefined && balanceUsd > 0 ? "PAYG" : undefined;
|
|
38
|
+
}
|
|
39
|
+
const lower = s.toLowerCase();
|
|
40
|
+
if (lower === "free" && balanceUsd !== undefined && balanceUsd > 0) {
|
|
41
|
+
return "PAYG";
|
|
42
|
+
}
|
|
43
|
+
return s.charAt(0).toUpperCase() + s.slice(1);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function readErrorMessage(res) {
|
|
47
|
+
const text = await res.text().catch(() => "");
|
|
48
|
+
if (!text) return "";
|
|
49
|
+
try {
|
|
50
|
+
const parsed = JSON.parse(text);
|
|
51
|
+
const msg = parsed?.error?.message ?? parsed?.message ?? parsed?.error;
|
|
52
|
+
if (typeof msg === "string" && msg.trim()) return msg.trim().slice(0, 300);
|
|
53
|
+
} catch {
|
|
54
|
+
// Plain-text error
|
|
55
|
+
}
|
|
56
|
+
return text.trim().slice(0, 300);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function parseUsagePayload(raw, now = Date.now()) {
|
|
60
|
+
const root = raw && typeof raw === "object" && !Array.isArray(raw) ? raw : {};
|
|
61
|
+
const u = root.data && typeof root.data === "object" && !Array.isArray(root.data) ? root.data : root;
|
|
62
|
+
|
|
63
|
+
const quotas = u.quotas && typeof u.quotas === "object" && !Array.isArray(u.quotas) ? u.quotas : {};
|
|
64
|
+
|
|
65
|
+
const balanceUsd = num(
|
|
66
|
+
u.balance_usd ??
|
|
67
|
+
u.balanceUsd ??
|
|
68
|
+
u.payg_balance_usd ??
|
|
69
|
+
u.paygBalanceUsd ??
|
|
70
|
+
u.balance ??
|
|
71
|
+
quotas.payg?.remaining_usd,
|
|
72
|
+
);
|
|
73
|
+
const rawPlan =
|
|
74
|
+
typeof u.plan === "object" && u.plan !== null
|
|
75
|
+
? (u.plan.name ?? u.plan.id ?? u.plan.tier)
|
|
76
|
+
: (u.plan ?? u.plan_name ?? u.planName ?? u.tier);
|
|
77
|
+
const plan = formatPlan(rawPlan, balanceUsd);
|
|
78
|
+
const user = str(u.email ?? u.user ?? u.username ?? u.account_id ?? u.accountId ?? u.key_name ?? u.keyName);
|
|
79
|
+
const until = str(u.plan_expires_at ?? u.planExpiresAt ?? u.until ?? u.expires_at ?? u.expiresAt);
|
|
80
|
+
|
|
81
|
+
const windows = [];
|
|
82
|
+
|
|
83
|
+
const tokensUsed = num(
|
|
84
|
+
u.tokens_used_today ??
|
|
85
|
+
u.tokensUsedToday ??
|
|
86
|
+
u.daily_tokens_used ??
|
|
87
|
+
u.dailyTokensUsed ??
|
|
88
|
+
u.tokens_used ??
|
|
89
|
+
u.tokensUsed ??
|
|
90
|
+
u.used_tokens ??
|
|
91
|
+
u.used ??
|
|
92
|
+
quotas.token_plan?.used,
|
|
93
|
+
);
|
|
94
|
+
const tokenLimit = num(
|
|
95
|
+
u.effective_token_limit ??
|
|
96
|
+
u.effectiveTokenLimit ??
|
|
97
|
+
u.token_limit ??
|
|
98
|
+
u.tokenLimit ??
|
|
99
|
+
u.daily_limit ??
|
|
100
|
+
u.dailyLimit ??
|
|
101
|
+
u.daily_token_limit ??
|
|
102
|
+
u.dailyTokenLimit ??
|
|
103
|
+
u.limit ??
|
|
104
|
+
quotas.token_plan?.limit,
|
|
105
|
+
);
|
|
106
|
+
const unlimited = Boolean(u.unlimited);
|
|
107
|
+
const resetsAt = str(u.resets_at ?? u.resetsAt) ?? nextUtcMidnight(now);
|
|
108
|
+
const hasPaygBalance = balanceUsd !== undefined && balanceUsd > 0;
|
|
109
|
+
|
|
110
|
+
if (!unlimited && tokenLimit !== undefined && tokenLimit > 0) {
|
|
111
|
+
const win = {
|
|
112
|
+
name: "Daily tokens",
|
|
113
|
+
limit: tokenLimit,
|
|
114
|
+
unit: "tokens",
|
|
115
|
+
span: DAY_S,
|
|
116
|
+
resetsAt,
|
|
117
|
+
};
|
|
118
|
+
if (tokensUsed !== undefined && tokensUsed >= 0) {
|
|
119
|
+
win.amount = tokensUsed;
|
|
120
|
+
} else {
|
|
121
|
+
win.display = `${formatCompact(tokenLimit)} tokens / day`;
|
|
122
|
+
}
|
|
123
|
+
if (hasPaygBalance) win.aside = true;
|
|
124
|
+
windows.push(win);
|
|
125
|
+
} else if (unlimited && tokensUsed !== undefined && tokensUsed >= 0) {
|
|
126
|
+
windows.push({
|
|
127
|
+
name: "Daily tokens",
|
|
128
|
+
display: `${formatCompact(tokensUsed)} used today · unlimited`,
|
|
129
|
+
span: DAY_S,
|
|
130
|
+
resetsAt,
|
|
131
|
+
aside: true,
|
|
132
|
+
});
|
|
133
|
+
} else if (tokensUsed !== undefined && tokensUsed > 0) {
|
|
134
|
+
windows.push({
|
|
135
|
+
name: "Daily tokens",
|
|
136
|
+
display: `${formatCompact(tokensUsed)} used today`,
|
|
137
|
+
span: DAY_S,
|
|
138
|
+
resetsAt,
|
|
139
|
+
aside: true,
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const rpmLimit = num(u.rpm ?? u.rpm_limit ?? u.rpmLimit);
|
|
144
|
+
const rpmUsed = num(u.rpm_used ?? u.rpmUsed);
|
|
145
|
+
if (rpmLimit !== undefined && rpmLimit > 0 && rpmUsed !== undefined && rpmUsed >= 0) {
|
|
146
|
+
windows.push({
|
|
147
|
+
name: "Rate limit",
|
|
148
|
+
amount: rpmUsed,
|
|
149
|
+
limit: rpmLimit,
|
|
150
|
+
unit: "req/min",
|
|
151
|
+
span: 60,
|
|
152
|
+
aside: true,
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const vaultTokens = num(
|
|
157
|
+
u.vault_tokens ??
|
|
158
|
+
u.vaultTokens ??
|
|
159
|
+
u.vault_balance ??
|
|
160
|
+
u.vaultBalance ??
|
|
161
|
+
u.bank_tokens ??
|
|
162
|
+
u.bankTokens ??
|
|
163
|
+
u.token_vault?.balance ??
|
|
164
|
+
quotas.vault?.balance,
|
|
165
|
+
);
|
|
166
|
+
if (vaultTokens !== undefined && vaultTokens > 0) {
|
|
167
|
+
windows.push({
|
|
168
|
+
name: "Token vault",
|
|
169
|
+
balance: vaultTokens,
|
|
170
|
+
unit: "tokens",
|
|
171
|
+
aside: true,
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const bonusTokens = num(
|
|
176
|
+
u.tok_bonus_tokens ??
|
|
177
|
+
u.tokBonusTokens ??
|
|
178
|
+
u.bonus_tokens ??
|
|
179
|
+
u.bonusTokens ??
|
|
180
|
+
quotas.bonus?.balance,
|
|
181
|
+
);
|
|
182
|
+
if (bonusTokens !== undefined && bonusTokens > 0) {
|
|
183
|
+
windows.push({
|
|
184
|
+
name: "Bonus tokens",
|
|
185
|
+
balance: bonusTokens,
|
|
186
|
+
unit: "tokens",
|
|
187
|
+
aside: true,
|
|
188
|
+
});
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
const tokensV2 = num(
|
|
192
|
+
u.tok_v2_tokens ??
|
|
193
|
+
u.tokV2Tokens ??
|
|
194
|
+
u.tokens_v2_balance ??
|
|
195
|
+
u.tokensV2Balance ??
|
|
196
|
+
u.tokv2_balance ??
|
|
197
|
+
u.tokv2Balance ??
|
|
198
|
+
u.tokens_v2?.balance ??
|
|
199
|
+
u.tokv2?.balance ??
|
|
200
|
+
quotas.tokv2?.remaining,
|
|
201
|
+
);
|
|
202
|
+
const tokv2Used = num(quotas.tokv2?.used);
|
|
203
|
+
const tokv2Limit = num(quotas.tokv2?.limit);
|
|
204
|
+
if (tokv2Limit !== undefined && tokv2Limit > 0 && tokv2Used !== undefined && tokv2Used >= 0) {
|
|
205
|
+
windows.push({
|
|
206
|
+
name: "Tokens V2",
|
|
207
|
+
amount: tokv2Used,
|
|
208
|
+
limit: tokv2Limit,
|
|
209
|
+
unit: "tokens",
|
|
210
|
+
aside: true,
|
|
211
|
+
});
|
|
212
|
+
} else if (tokensV2 !== undefined && tokensV2 > 0) {
|
|
213
|
+
windows.push({
|
|
214
|
+
name: "Tokens V2",
|
|
215
|
+
balance: tokensV2,
|
|
216
|
+
unit: "tokens",
|
|
217
|
+
aside: true,
|
|
218
|
+
});
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
const directCredits = num(u.credits_balance ?? u.creditsBalance ?? quotas.credits?.remaining);
|
|
222
|
+
const requestCredits = num(u.request_credits ?? u.requestCredits);
|
|
223
|
+
const planCredits = num(u.plan_credits ?? u.planCredits);
|
|
224
|
+
const credits =
|
|
225
|
+
directCredits !== undefined && directCredits > 0
|
|
226
|
+
? directCredits
|
|
227
|
+
: (requestCredits !== undefined && requestCredits > 0 ? requestCredits : 0) +
|
|
228
|
+
(planCredits !== undefined && planCredits > 0 ? planCredits : 0);
|
|
229
|
+
const creditsUsed = num(quotas.credits?.used);
|
|
230
|
+
const creditsLimit = num(quotas.credits?.limit);
|
|
231
|
+
if (creditsLimit !== undefined && creditsLimit > 0 && creditsUsed !== undefined && creditsUsed >= 0) {
|
|
232
|
+
windows.push({
|
|
233
|
+
name: "Credits",
|
|
234
|
+
amount: creditsUsed,
|
|
235
|
+
limit: creditsLimit,
|
|
236
|
+
unit: "credits",
|
|
237
|
+
aside: true,
|
|
238
|
+
});
|
|
239
|
+
} else if (credits > 0) {
|
|
240
|
+
windows.push({
|
|
241
|
+
name: "Credits",
|
|
242
|
+
balance: credits,
|
|
243
|
+
unit: "credits",
|
|
244
|
+
aside: true,
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
const result = {
|
|
249
|
+
windows,
|
|
250
|
+
signIn: "kept",
|
|
251
|
+
};
|
|
252
|
+
if (plan) result.plan = plan;
|
|
253
|
+
if (user) result.user = user;
|
|
254
|
+
if (until) result.until = until;
|
|
255
|
+
if (balanceUsd !== undefined && balanceUsd >= 0) {
|
|
256
|
+
result.balance = formatUsd(balanceUsd);
|
|
257
|
+
}
|
|
258
|
+
return result;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
export async function fetchBlazeUsage({
|
|
262
|
+
baseURL = DEFAULT_BASE_URL,
|
|
263
|
+
apiKey,
|
|
264
|
+
fetchImpl = fetch,
|
|
265
|
+
signal,
|
|
266
|
+
now = Date.now,
|
|
267
|
+
} = {}) {
|
|
268
|
+
if (!apiKey) {
|
|
269
|
+
return {
|
|
270
|
+
error: "Missing BlazeAPI key",
|
|
271
|
+
signIn: "expired",
|
|
272
|
+
windows: [],
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
const timeout = AbortSignal.timeout(15_000);
|
|
277
|
+
const combinedSignal = signal ? AbortSignal.any([signal, timeout]) : timeout;
|
|
278
|
+
|
|
279
|
+
let res;
|
|
280
|
+
try {
|
|
281
|
+
res = await fetchImpl(`${baseURL}/usage`, {
|
|
282
|
+
method: "GET",
|
|
283
|
+
headers: {
|
|
284
|
+
Authorization: `Bearer ${apiKey}`,
|
|
285
|
+
Accept: "application/json",
|
|
286
|
+
},
|
|
287
|
+
signal: combinedSignal,
|
|
288
|
+
redirect: "error",
|
|
289
|
+
});
|
|
290
|
+
} catch (err) {
|
|
291
|
+
return {
|
|
292
|
+
error: `Could not reach BlazeAPI: ${err?.message || String(err)}`,
|
|
293
|
+
windows: [],
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
if (res.status === 401 || res.status === 403) {
|
|
298
|
+
const rawText = await res.text().catch(() => "");
|
|
299
|
+
const signIn = classifyAuthError(res.status, rawText);
|
|
300
|
+
let msg = rawText.trim().slice(0, 300);
|
|
301
|
+
if (rawText) {
|
|
302
|
+
try {
|
|
303
|
+
const parsed = JSON.parse(rawText);
|
|
304
|
+
const extracted = parsed?.error?.message ?? parsed?.message ?? parsed?.error;
|
|
305
|
+
if (typeof extracted === "string" && extracted.trim()) msg = extracted.trim().slice(0, 300);
|
|
306
|
+
} catch {}
|
|
307
|
+
}
|
|
308
|
+
return {
|
|
309
|
+
error:
|
|
310
|
+
msg ||
|
|
311
|
+
(signIn === "expired"
|
|
312
|
+
? "Invalid or expired BlazeAPI key"
|
|
313
|
+
: `BlazeAPI answered HTTP ${res.status}`),
|
|
314
|
+
signIn,
|
|
315
|
+
windows: [],
|
|
316
|
+
};
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
if (!res.ok) {
|
|
320
|
+
const msg = await readErrorMessage(res);
|
|
321
|
+
return {
|
|
322
|
+
error: `BlazeAPI answered HTTP ${res.status}${msg ? `: ${msg}` : ""}`,
|
|
323
|
+
signIn: "kept",
|
|
324
|
+
windows: [],
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
try {
|
|
329
|
+
const payload = await res.json();
|
|
330
|
+
return parseUsagePayload(payload, typeof now === "function" ? now() : now);
|
|
331
|
+
} catch (err) {
|
|
332
|
+
return {
|
|
333
|
+
error: `Invalid BlazeAPI usage response: ${err?.message || String(err)}`,
|
|
334
|
+
windows: [],
|
|
335
|
+
};
|
|
336
|
+
}
|
|
337
|
+
}
|