@gtrabanco/pi-nan-provider 1.5.2 → 1.5.4

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.
@@ -39,6 +39,7 @@ import type {
39
39
  import { providerAttributionEnabled, stripProviderAttribution } from "./attribution.ts";
40
40
  import { withContextOverflowClassification } from "./context-overflow-classifier.ts";
41
41
  import { withReasoningOnlyStreamGuard } from "./reasoning-only-stream-guard.ts";
42
+ import { createCacheAnomalyFileSink, withCacheAnomalyCapture, type CacheAnomalySink } from "./cache-anomaly.ts";
42
43
  import { NAN_IMAGE_API, baselineImageModels, createNanImagesApi } from "./images.ts";
43
44
  import {
44
45
  baselineModels,
@@ -71,6 +72,8 @@ export interface NanCompatibleProviderOptions {
71
72
  timeoutMs?: number;
72
73
  /** Injectable for tests; defaults to global fetch. */
73
74
  fetchImpl?: typeof fetch;
75
+ /** Sink for the issue #35 cache-anomaly evidence; defaults to the agent-dir JSONL file. */
76
+ cacheAnomalySink?: CacheAnomalySink;
74
77
  }
75
78
 
76
79
  /**
@@ -116,6 +119,19 @@ function modelSupportsUsageInStreaming(model: unknown): boolean {
116
119
  return isObject(compat) && compat.supportsUsageInStreaming === true;
117
120
  }
118
121
 
122
+ /**
123
+ * Whether the model's effective compat sends the `max_completion_tokens`
124
+ * request field instead of the classic `max_tokens` (issue #34). The model
125
+ * object here is pi-ai's post-registry view — baseline catalog, live-merge
126
+ * refresh, `models.json` override and the #19 stale-store overlay all flow
127
+ * through `compat`, so this reads the value the user actually runs with.
128
+ */
129
+ function modelSendsMaxCompletionTokens(model: unknown): boolean {
130
+ if (!isObject(model)) return false;
131
+ const compat = model.compat;
132
+ return isObject(compat) && compat.maxTokensField === "max_completion_tokens";
133
+ }
134
+
119
135
  export function wrapApiForStrictSanitization(api: ProviderStreams): ProviderStreams {
120
136
  const withSanitizer = <TOptions extends object | undefined>(options: TOptions): TOptions => {
121
137
  const userOnPayload = isObject(options) ? (options.onPayload as unknown) : undefined;
@@ -124,6 +140,7 @@ export function wrapApiForStrictSanitization(api: ProviderStreams): ProviderStre
124
140
  onPayload: async (payload: unknown, model: unknown) => {
125
141
  const sanitized = sanitizeOpenAICompatPayload(payload, {
126
142
  preserveStreamOptions: modelSupportsUsageInStreaming(model),
143
+ preserveMaxCompletionTokens: modelSendsMaxCompletionTokens(model),
127
144
  });
128
145
  if (typeof userOnPayload === "function") {
129
146
  const userResult = await (userOnPayload as (p: unknown, m: unknown) => unknown)(sanitized, model);
@@ -284,8 +301,14 @@ export async function createNanCompatibleProvider(
284
301
  // middle → guard (marker detection), innermost → sanitizer (payload).
285
302
  // The guard's onProviderStreamEvent hook sees the raw response chunks
286
303
  // (NOT onPayload, which only receives the outgoing request params).
287
- api: withContextOverflowClassification(
288
- withReasoningOnlyStreamGuard(wrapApiForStrictSanitization(apiFactory())),
304
+ // Outermost: cache-anomaly evidence capture (issue #35). It only adds
305
+ // observation hooks (onResponse for `cf-ray`, onProviderStreamEvent for
306
+ // the raw id/created pair) and never rewrites the stream.
307
+ api: withCacheAnomalyCapture(
308
+ withContextOverflowClassification(
309
+ withReasoningOnlyStreamGuard(wrapApiForStrictSanitization(apiFactory())),
310
+ ),
311
+ { sink: options.cacheAnomalySink ?? createCacheAnomalyFileSink() },
289
312
  ),
290
313
  }),
291
314
  overlayMap,
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
 
package/src/zip.ts ADDED
@@ -0,0 +1,114 @@
1
+ /**
2
+ * Minimal deterministic ZIP writer (store method, no compression).
3
+ *
4
+ * `/nan-debug --emit` must produce a shareable archive that is reproducible
5
+ * byte-for-byte from the same inputs (issue #35 S15). `Bun.Archive` is
6
+ * Bun-only, and this package also runs under Node, so the container is built
7
+ * here with `node:buffer` only: sorted entries, fixed 1980-01-01 timestamps,
8
+ * stored (uncompressed) payloads and the UTF-8 name flag. That also keeps the
9
+ * output readable with any unzip tool.
10
+ */
11
+
12
+ import { Buffer } from "node:buffer";
13
+
14
+ const LOCAL_FILE_HEADER = 0x04034b50;
15
+ const CENTRAL_DIRECTORY_HEADER = 0x02014b50;
16
+ const END_OF_CENTRAL_DIRECTORY = 0x06054b50;
17
+ const VERSION_NEEDED = 20;
18
+ const UTF8_FLAG = 0x0800;
19
+ const STORED_METHOD = 0;
20
+ /** 1980-01-01 00:00:00, the DOS epoch: fixed for reproducible archives. */
21
+ const DOS_TIME = 0;
22
+ const DOS_DATE = 0x0021;
23
+
24
+ const CRC_TABLE: Uint32Array = (() => {
25
+ const table = new Uint32Array(256);
26
+ for (let n = 0; n < 256; n++) {
27
+ let c = n;
28
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
29
+ table[n] = c >>> 0;
30
+ }
31
+ return table;
32
+ })();
33
+
34
+ /** CRC-32 (IEEE 802.3), as required by the ZIP container. */
35
+ export function crc32(data: Uint8Array): number {
36
+ let crc = 0xffffffff;
37
+ for (let i = 0; i < data.length; i++) {
38
+ crc = CRC_TABLE[(crc ^ data[i]!) & 0xff]! ^ (crc >>> 8);
39
+ }
40
+ return (crc ^ 0xffffffff) >>> 0;
41
+ }
42
+
43
+ export interface ZipEntry {
44
+ name: string;
45
+ data: Uint8Array | string;
46
+ }
47
+
48
+ /**
49
+ * Build a store-method zip from the given entries. Entries are sorted by name
50
+ * so the output does not depend on object/insertion order.
51
+ */
52
+ export function createZip(entries: readonly ZipEntry[]): Buffer {
53
+ const sorted = [...entries].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
54
+ const locals: Buffer[] = [];
55
+ const centrals: Buffer[] = [];
56
+ let offset = 0;
57
+
58
+ for (const entry of sorted) {
59
+ const name = Buffer.from(entry.name, "utf8");
60
+ const data = typeof entry.data === "string" ? Buffer.from(entry.data, "utf8") : Buffer.from(entry.data);
61
+ const crc = crc32(data);
62
+
63
+ const local = Buffer.alloc(30 + name.length);
64
+ local.writeUInt32LE(LOCAL_FILE_HEADER, 0);
65
+ local.writeUInt16LE(VERSION_NEEDED, 4);
66
+ local.writeUInt16LE(UTF8_FLAG, 6);
67
+ local.writeUInt16LE(STORED_METHOD, 8);
68
+ local.writeUInt16LE(DOS_TIME, 10);
69
+ local.writeUInt16LE(DOS_DATE, 12);
70
+ local.writeUInt32LE(crc, 14);
71
+ local.writeUInt32LE(data.length, 18);
72
+ local.writeUInt32LE(data.length, 22);
73
+ local.writeUInt16LE(name.length, 26);
74
+ local.writeUInt16LE(0, 28);
75
+ name.copy(local, 30);
76
+ locals.push(local, data);
77
+
78
+ const central = Buffer.alloc(46 + name.length);
79
+ central.writeUInt32LE(CENTRAL_DIRECTORY_HEADER, 0);
80
+ central.writeUInt16LE(VERSION_NEEDED, 4);
81
+ central.writeUInt16LE(VERSION_NEEDED, 6);
82
+ central.writeUInt16LE(UTF8_FLAG, 8);
83
+ central.writeUInt16LE(STORED_METHOD, 10);
84
+ central.writeUInt16LE(DOS_TIME, 12);
85
+ central.writeUInt16LE(DOS_DATE, 14);
86
+ central.writeUInt32LE(crc, 16);
87
+ central.writeUInt32LE(data.length, 20);
88
+ central.writeUInt32LE(data.length, 24);
89
+ central.writeUInt16LE(name.length, 28);
90
+ central.writeUInt16LE(0, 30);
91
+ central.writeUInt16LE(0, 32);
92
+ central.writeUInt16LE(0, 34);
93
+ central.writeUInt16LE(0, 36);
94
+ central.writeUInt32LE(0, 38);
95
+ central.writeUInt32LE(offset, 42);
96
+ name.copy(central, 46);
97
+ centrals.push(central);
98
+
99
+ offset += local.length + data.length;
100
+ }
101
+
102
+ const centralDirectory = Buffer.concat(centrals);
103
+ const end = Buffer.alloc(22);
104
+ end.writeUInt32LE(END_OF_CENTRAL_DIRECTORY, 0);
105
+ end.writeUInt16LE(0, 4);
106
+ end.writeUInt16LE(0, 6);
107
+ end.writeUInt16LE(sorted.length, 8);
108
+ end.writeUInt16LE(sorted.length, 10);
109
+ end.writeUInt32LE(centralDirectory.length, 12);
110
+ end.writeUInt32LE(offset, 16);
111
+ end.writeUInt16LE(0, 20);
112
+
113
+ return Buffer.concat([...locals, centralDirectory, end]);
114
+ }