@gtrabanco/pi-nan-provider 1.5.3 → 1.5.5

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/src/usage.ts CHANGED
@@ -62,16 +62,24 @@ export const MODEL_QUOTAS: readonly ModelQuota[] = [
62
62
  export interface UsageModelTotals {
63
63
  model: string;
64
64
  prompt_tokens: number;
65
+ /** Cached input tokens (part of `prompt_tokens`, not added to `total_tokens`). 2026-11-11 onward. */
66
+ cached_tokens: number;
65
67
  completion_tokens: number;
66
68
  total_tokens: number;
67
69
  api_requests: number;
70
+ /** Credits billed on this model in the window, one decimal. 2026-11-10 onward. */
71
+ credits: number;
68
72
  }
69
73
 
70
74
  export interface UsageTotals {
71
75
  prompt_tokens: number;
76
+ /** Cached input tokens (part of `prompt_tokens`, not added to `total_tokens`). 2026-11-11 onward. */
77
+ cached_tokens: number;
72
78
  completion_tokens: number;
73
79
  total_tokens: number;
74
80
  api_requests: number;
81
+ /** Credits billed in the window, one decimal. 2026-11-10 onward. */
82
+ credits: number;
75
83
  by_model: UsageModelTotals[];
76
84
  }
77
85
 
@@ -80,9 +88,29 @@ export interface UsageAllTime {
80
88
  completion_tokens: number;
81
89
  total_tokens: number;
82
90
  api_requests: number;
91
+ /** When the all-time summary was last computed, ISO 8601 UTC. */
83
92
  cached_at: string | null;
84
93
  }
85
94
 
95
+ export interface UsageCredits {
96
+ /** Start of the current billing period (UTC). */
97
+ period_start: string;
98
+ /** End of the current billing period (UTC), when the allowance renews. */
99
+ period_end: string;
100
+ /** Credits included in your plan for this period. */
101
+ allowance: number;
102
+ /** Credits used from the allowance this period. */
103
+ used: number;
104
+ /** Credits left in the allowance this period. Pack credits are not included. */
105
+ remaining: number;
106
+ /** Credits left in your purchased packs, used once the allowance runs out. */
107
+ pack_credits: number;
108
+ /** When your pack credits expire, or `null` without pack credits. */
109
+ pack_expires_at: string | null;
110
+ /** `true` while your subscription is not active (e.g. failed payment). */
111
+ frozen: boolean;
112
+ }
113
+
86
114
  export interface UsageReport {
87
115
  object: "usage.report";
88
116
  /** First day of the window actually served (after clamping). */
@@ -92,9 +120,12 @@ export interface UsageReport {
92
120
  /** Daily (date, model) rows — paginated; unused here (totals cover the window). */
93
121
  data: unknown[];
94
122
  totals: UsageTotals;
123
+ /** Lifetime usage, always present. */
95
124
  all_time: UsageAllTime;
96
125
  has_more: boolean;
97
126
  next_cursor: string | null;
127
+ /** Current billing period credits, or `null` if not billed in credits. */
128
+ credits: UsageCredits | null;
98
129
  }
99
130
 
100
131
  export interface UsageFetchError {
@@ -218,24 +249,7 @@ export function formatCount(n: number): string {
218
249
  return String(Math.trunc(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
219
250
  }
220
251
 
221
- function progressBar(percentage: number, width = 20): string {
222
- const clamped = Math.min(Math.max(percentage, 0), 100);
223
- const filled = Math.round((clamped / 100) * width);
224
- const empty = width - filled;
225
- return `[${"█".repeat(filled)}${"░".repeat(empty)}]`;
226
- }
227
252
 
228
- /**
229
- * `api_requests` comes back as 0 for some models that do have usage (live
230
- * probe 2026-09-27: qwen3.8-flash 796M tokens / 0 requests, while the window
231
- * total still sums the other models exactly). Reporting a bare "0 requests"
232
- * next to real consumption would read as a bug in this command, so say what
233
- * the endpoint actually reported.
234
- */
235
- function requestsSuffix(tokens: number, requests: number): string {
236
- if (tokens > 0 && requests === 0) return "requests not reported";
237
- return `${formatCount(requests)} requests`;
238
- }
239
253
 
240
254
  // ── Message builders ──────────────────────────────────────────────────────
241
255
 
@@ -263,87 +277,84 @@ export function buildStaticMessage(now = new Date()): string {
263
277
  return lines.join("\n");
264
278
  }
265
279
 
266
- /** Usage report merged with the documented caps. */
280
+ /** Format a credit value — integer or one decimal. */
281
+ function formatCredits(value: number): string {
282
+ return Number.isInteger(value) ? String(value) : `${value}`;
283
+ }
284
+
285
+ /** Credits progress bar: fills based on percentage, width N. */
286
+ function creditsBar(pct: number, width = 20): string {
287
+ const clamped = Math.min(Math.max(pct, 0), 100);
288
+ const filled = Math.round((clamped / 100) * width);
289
+ const empty = width - filled;
290
+ return `[${"█".repeat(filled)}${"░".repeat(empty)}]`;
291
+ }
292
+
293
+ /** Format a model's usage row: "model · X.XM in / YM cached / Z.ZM out · W (cr)" */
294
+ function modelRow(m: UsageModelTotals): string {
295
+ const inM = (m.prompt_tokens / 1_000_000).toFixed(1);
296
+ const cacheM = (m.cached_tokens / 1_000_000).toFixed(1);
297
+ const outM = (m.completion_tokens / 1_000_000).toFixed(1);
298
+ const cr = formatCredits(m.credits ?? 0);
299
+ return ` ${m.model} · ${inM}M in / ${cacheM}M cached / ${outM}M out · ${cr} (cr)`;
300
+ }
301
+
302
+ /** Usage report with credits-first layout. */
267
303
  export function buildUsageMessage(report: UsageReport, now = new Date()): string {
268
- const start = report.start_date;
269
- const end = report.end_date;
270
- const days = daysBetween(start, end);
271
304
  const totals = report.totals;
272
305
  const byModel = totals?.by_model ?? [];
273
- const totalTokens = totals?.total_tokens ?? 0;
274
- const totalRequests = totals?.api_requests ?? 0;
306
+ const credits = report.credits;
307
+
308
+ const lines: string[] = [];
309
+
310
+ // ── Credits banner ────────────────────────────────────────────────────
311
+ lines.push("💳 Credits");
312
+ if (credits) {
313
+ const total = credits.allowance;
314
+ const used = credits.used;
315
+ const remaining = credits.remaining;
316
+ const pct = total > 0 ? (used / total) * 100 : 0;
317
+ const packInfo = credits.pack_credits > 0
318
+ ? ` · packs: ${formatCredits(credits.pack_credits)} cr${credits.pack_expires_at ? ` (exp ${credits.pack_expires_at.slice(0, 10)})` : ""}`
319
+ : "";
275
320
 
276
- const lines: string[] = [
277
- "📊 NaN Usage",
278
- "",
279
- `🗓️ Window: ${start} → ${end} UTC (${days} day${days === 1 ? "" : "s"})`,
280
- "",
281
- resetLine(now),
282
- "",
283
- ];
321
+ lines.push(` ${creditsBar(pct)} ${pct.toFixed(1)}% used · ${formatCredits(used)} / ${formatCredits(total)} (${formatCredits(remaining)} remaining)${packInfo}`);
322
+ if (credits.frozen) {
323
+ lines.push(" ⚠️ Account frozen (subscription inactive): credit-billed requests are refused");
324
+ }
325
+ lines.push(` Period: ${credits.period_start.slice(0, 10)} → ${credits.period_end.slice(0, 10)} UTC`);
326
+ } else {
327
+ lines.push(" Credits not available for this account");
328
+ }
284
329
 
285
- const usageOf = (model: string): UsageModelTotals | undefined => byModel.find((m) => m.model === model);
330
+ lines.push("");
331
+ lines.push(resetLine(now));
332
+ lines.push("");
286
333
 
287
- if (totalTokens === 0 && totalRequests === 0 && byModel.length === 0) {
288
- lines.push("No usage in this window.");
289
- } else {
290
- const capped = MODEL_QUOTAS.filter((q) => q.monthlyCap > 0);
291
- const uncapped = MODEL_QUOTAS.filter((q) => q.monthlyCap === 0);
292
- const known = new Set(MODEL_QUOTAS.map((q) => q.model));
293
- const others = byModel.filter((m) => !known.has(m.model)).sort((a, b) => b.total_tokens - a.total_tokens);
294
-
295
- lines.push("Models with monthly caps:", "");
296
- for (const quota of capped) {
297
- const usage = usageOf(quota.model);
298
- const used = usage?.total_tokens ?? 0;
299
- const requests = usage?.api_requests ?? 0;
300
- const percentage = (used / quota.monthlyCap) * 100;
301
- const remaining = Math.max(quota.monthlyCap - used, 0);
302
-
303
- lines.push(`${quota.label}:`);
304
- lines.push(` ${progressBar(percentage)} ${percentage.toFixed(1)}% of monthly cap`);
305
- lines.push(
306
- ` Used: ${formatTokens(used)} / ${formatTokens(quota.monthlyCap)} (${formatTokens(remaining)} remaining) · ${requestsSuffix(used, requests)}`,
307
- );
308
- if (quota.rollingWindowCap > 0) {
309
- lines.push(
310
- ` ↳ rolling window: ${formatTokens(quota.rollingWindowCap)} / ${quota.rollingWindowHours}h ` +
311
- "(daily granularity — /usage cannot break it down)",
312
- );
313
- }
314
- lines.push("");
315
- }
334
+ // ── Model usage ───────────────────────────────────────────────────────
335
+ const sorted = byModel
336
+ .filter((m) => m.total_tokens > 0)
337
+ .sort((a, b) => (b.credits ?? 0) - (a.credits ?? 0));
316
338
 
317
- const usedUncapped = uncapped.filter((q) => (usageOf(q.model)?.total_tokens ?? 0) > 0);
318
- if (usedUncapped.length > 0) {
319
- lines.push("Uncapped models:", "");
320
- for (const quota of usedUncapped) {
321
- const usage = usageOf(quota.model)!;
322
- lines.push(`${quota.label}: ${formatTokens(usage.total_tokens)} used · ${requestsSuffix(usage.total_tokens, usage.api_requests)}`);
323
- }
324
- lines.push("");
339
+ if (sorted.length > 0) {
340
+ const totalCredits = totals?.credits ?? 0;
341
+ lines.push("⚡ Usage");
342
+ for (const m of sorted) {
343
+ lines.push(modelRow(m));
325
344
  }
326
-
327
- if (others.length > 0) {
328
- lines.push("Other models (no documented cap):", "");
329
- for (const usage of others) {
330
- lines.push(`${usage.model}: ${formatTokens(usage.total_tokens)} used · ${requestsSuffix(usage.total_tokens, usage.api_requests)}`);
331
- }
332
- lines.push("");
345
+ lines.push("");
346
+ if (totalCredits > 0) {
347
+ lines.push(`Total credits consumed: ${formatCredits(totalCredits)} (cr)`);
333
348
  }
334
349
  }
335
350
 
336
- lines.push(
337
- `Window totals: ${formatTokens(totalTokens)} tokens ` +
338
- `(${formatTokens(totals?.prompt_tokens ?? 0)} prompt / ${formatTokens(totals?.completion_tokens ?? 0)} completion) · ` +
339
- `${formatCount(totalRequests)} requests`,
340
- );
351
+ // ── All time ──────────────────────────────────────────────────────────
341
352
  const allTime = report.all_time;
342
353
  if (allTime) {
343
- const cached = allTime.cached_at ? ` (cached ${allTime.cached_at.slice(0, 10)})` : "";
354
+ const cached = allTime.cached_at ? ` (as of ${allTime.cached_at.slice(0, 10)})` : "";
344
355
  lines.push(`All time: ${formatTokens(allTime.total_tokens)} tokens · ${formatCount(allTime.api_requests)} requests${cached}`);
345
356
  }
346
- lines.push("💡 Source: GET /v1/usage · caps from https://nan.builders/docs/models");
357
+ lines.push("💡 Source: GET /v1/usage");
347
358
  return lines.join("\n");
348
359
  }
349
360