@gtrabanco/pi-nan-provider 1.5.2 → 1.5.3

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.
@@ -0,0 +1,601 @@
1
+ /**
2
+ * `/nan-debug` — deterministic, redacted NaN evidence collector (issue #35).
3
+ *
4
+ * NaN could not reproduce the prompt-cache anomaly and asked for "modelo y
5
+ * cf-ray de un par de llamadas". This module reads pi's session JSONL (usage,
6
+ * stop reasons, response ids) plus the local cache-anomaly capture
7
+ * (`nan-cache-anomalies.jsonl`, which holds the `cf-ray` pair) and renders a
8
+ * report that can be shared verbatim.
9
+ *
10
+ * Contract (issue #35):
11
+ * - no LLM, no network unless `--window` explicitly asks for `/v1/usage`;
12
+ * - never collect prompt/response content, credentials or raw paths;
13
+ * - session and worktree identifiers are MD5-truncated to 12 chars;
14
+ * - error text is reduced to a fixed class;
15
+ * - the same inputs produce byte-identical zip bytes.
16
+ *
17
+ * The report layout matches the 2026-11-10 anonymized dataset: one aggregated
18
+ * `anonymized_usage.jsonl` row per (date, session, model), plus `turns.jsonl`
19
+ * with the per-turn detail the issue asks for (`response_id`, `created` = null
20
+ * because pi does not persist it, usage, stop reason, error class).
21
+ */
22
+
23
+ import { createHash } from "node:crypto";
24
+ import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
25
+ import { basename, dirname, join } from "node:path";
26
+ import { PI_AI_VERSION } from "@earendil-works/pi-ai";
27
+ import { VERSION as PI_VERSION, getAgentDir } from "@earendil-works/pi-coding-agent";
28
+ import { GENERATED_CATALOG_META } from "../scripts/models.generated.ts";
29
+ import { CACHE_ANOMALY_FILE, defaultCacheAnomalyPath, type CacheAnomalyRecord } from "./cache-anomaly.ts";
30
+ import { fetchUsageReport, rollingWindow, type UsageWindow } from "./usage.ts";
31
+ import { createZip } from "./zip.ts";
32
+
33
+ export const DEFAULT_DEBUG_WINDOW_DAYS = 7;
34
+ export const MAX_DEBUG_WINDOW_DAYS = 90;
35
+ export const NAN_DEBUG_REPORT_DIR = "nan-debug-report";
36
+ export const NAN_DEBUG_ZIP = "nan-debug-report.zip";
37
+
38
+ export const DEBUG_USAGE_LINE =
39
+ "Usage: /nan-debug [topic] [--window N] [--out file] [--emit] — collects a redacted NaN evidence report locally; --emit writes the shareable zip.";
40
+
41
+ export type DebugWindow = UsageWindow;
42
+
43
+ // ── Argument parsing ──────────────────────────────────────────────────────
44
+
45
+ export interface DebugArgs {
46
+ topic?: string;
47
+ windowDays: number;
48
+ /** True when `--window` was given; only then is `/v1/usage` consulted. */
49
+ windowProvided: boolean;
50
+ out?: string;
51
+ emit: boolean;
52
+ }
53
+
54
+ export type ParseDebugArgsResult = { ok: true; args: DebugArgs } | { ok: false; error: string };
55
+
56
+ const TOPIC_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,31}$/;
57
+
58
+ /** Parse `/nan-debug` arguments. Deterministic; no filesystem or clock access. */
59
+ export function parseDebugArgs(input: string): ParseDebugArgsResult {
60
+ const tokens = input.trim().split(/\s+/).filter(Boolean);
61
+ const args: DebugArgs = { windowDays: DEFAULT_DEBUG_WINDOW_DAYS, windowProvided: false, emit: false };
62
+
63
+ for (let i = 0; i < tokens.length; i++) {
64
+ const token = tokens[i]!;
65
+ if (token === "--emit") {
66
+ args.emit = true;
67
+ continue;
68
+ }
69
+ if (token === "--window") {
70
+ const value = tokens[i + 1];
71
+ if (value === undefined) return { ok: false, error: `--window needs a day count (1-${MAX_DEBUG_WINDOW_DAYS}). ${DEBUG_USAGE_LINE}` };
72
+ i += 1;
73
+ if (!/^\d+$/.test(value) || Number(value) < 1 || Number(value) > MAX_DEBUG_WINDOW_DAYS) {
74
+ return { ok: false, error: `Invalid --window "${value}". ${DEBUG_USAGE_LINE}` };
75
+ }
76
+ args.windowDays = Number(value);
77
+ args.windowProvided = true;
78
+ continue;
79
+ }
80
+ if (token === "--out") {
81
+ const value = tokens[i + 1];
82
+ if (value === undefined || value.length === 0) return { ok: false, error: `--out needs a file or directory path. ${DEBUG_USAGE_LINE}` };
83
+ // A flag token here is a missing value, not a path: consuming `--emit` or
84
+ // `--window` as the value would silently drop an explicit option (EV-2026-11-11 A1).
85
+ if (value.startsWith("--")) return { ok: false, error: `--out needs a file or directory path (got "${value}"). ${DEBUG_USAGE_LINE}` };
86
+ i += 1;
87
+ args.out = value;
88
+ continue;
89
+ }
90
+ if (token.startsWith("--")) return { ok: false, error: `Unknown option "${token}". ${DEBUG_USAGE_LINE}` };
91
+ if (args.topic !== undefined) return { ok: false, error: `Unexpected argument "${token}". ${DEBUG_USAGE_LINE}` };
92
+ if (!TOPIC_PATTERN.test(token)) {
93
+ return { ok: false, error: `Invalid topic "${token}" (use 1-32 chars: letters, digits, "_" or "-"). ${DEBUG_USAGE_LINE}` };
94
+ }
95
+ args.topic = token;
96
+ }
97
+
98
+ return { ok: true, args };
99
+ }
100
+
101
+ // ── Error classification ──────────────────────────────────────────────────
102
+
103
+ export type DebugErrorClass = "overflow" | "rate_limited" | "invalid_request" | "transport" | "other";
104
+
105
+ const ERROR_PATTERNS: ReadonlyArray<readonly [DebugErrorClass, RegExp]> = [
106
+ ["overflow", /context (?:overflow|window|length)|prompt is too long|maximum context|too many tokens|exceeds? (?:the )?(?:model'?s )?context|origin_response_timeout|\b524\b/i],
107
+ ["rate_limited", /rate.?limit|too many requests|\b429\b/i],
108
+ ["invalid_request", /invalid request|check your request parameters|\b400\b/i],
109
+ ["transport", /timed? ?out|timeout|aborted|abort|network|fetch failed|econn|etimedout|socket|stream ended|ended without|reasoning-only stream guard/i],
110
+ ];
111
+
112
+ /**
113
+ * Map a raw `errorMessage` to a fixed class. The raw text is never emitted —
114
+ * this is the only thing that reaches the report.
115
+ */
116
+ export function classifyErrorMessage(message: string | undefined): DebugErrorClass | null {
117
+ if (typeof message !== "string" || message.length === 0) return null;
118
+ for (const [kind, pattern] of ERROR_PATTERNS) {
119
+ if (pattern.test(message)) return kind;
120
+ }
121
+ return "other";
122
+ }
123
+
124
+ function isReasoningOnlyStreamError(message: string | undefined): boolean {
125
+ return typeof message === "string" && /reasoning-only stream guard/i.test(message);
126
+ }
127
+
128
+ // ── Report types ──────────────────────────────────────────────────────────
129
+
130
+ export interface DebugUsageRow {
131
+ date: string;
132
+ session_id: string;
133
+ worktree_label: string;
134
+ model: string;
135
+ turns: number;
136
+ total_tokens: number;
137
+ input_tokens: number;
138
+ output_tokens: number;
139
+ cache_read_tokens: number;
140
+ cache_write_tokens: number;
141
+ reasoning_tokens: number;
142
+ avg_tokens_per_turn: number;
143
+ cache_hit_rate_pct: number;
144
+ stop_reason_counts: Record<string, number>;
145
+ anomalies: Array<{ kind: string; detected_at: string }>;
146
+ }
147
+
148
+ export interface DebugTurn {
149
+ date: string;
150
+ session_id: string;
151
+ worktree_label: string;
152
+ turn: number;
153
+ timestamp: string;
154
+ model: string;
155
+ stop_reason: string;
156
+ error: DebugErrorClass | null;
157
+ response_id: string | null;
158
+ created: number | null;
159
+ input: number;
160
+ output: number;
161
+ cache_read: number;
162
+ cache_write: number;
163
+ reasoning: number;
164
+ total: number;
165
+ model_ms: number;
166
+ }
167
+
168
+ export interface DebugCounts {
169
+ sessions: number;
170
+ turns: number;
171
+ models: string[];
172
+ anomalies: {
173
+ duplicateIdCreated: number;
174
+ reasoningOnlyStream: number;
175
+ contextOverflow: number;
176
+ };
177
+ }
178
+
179
+ export interface DebugReport {
180
+ window: DebugWindow;
181
+ topic: string | null;
182
+ generatedAt: string;
183
+ rows: DebugUsageRow[];
184
+ turns: DebugTurn[];
185
+ anomalies: CacheAnomalyRecord[];
186
+ counts: DebugCounts;
187
+ metadata: Record<string, unknown>;
188
+ usageWindow?: unknown;
189
+ }
190
+
191
+ export type FetchUsageWindow = (window: DebugWindow, apiKey: string) => Promise<unknown>;
192
+
193
+ export interface BuildDebugReportOptions {
194
+ agentDir?: string;
195
+ now?: Date;
196
+ windowDays?: number;
197
+ topic?: string;
198
+ /** Only consulted when `includeUsage` is true. */
199
+ apiKey?: string;
200
+ fetchUsage?: FetchUsageWindow;
201
+ includeUsage?: boolean;
202
+ anomalyFile?: string;
203
+ sessionsDir?: string;
204
+ }
205
+
206
+ // ── Helpers ───────────────────────────────────────────────────────────────
207
+
208
+ function md5Short(value: string): string {
209
+ return createHash("md5").update(value).digest("hex").slice(0, 12);
210
+ }
211
+
212
+ function numberOrZero(value: unknown): number {
213
+ return typeof value === "number" && Number.isFinite(value) ? value : 0;
214
+ }
215
+
216
+ function isoDateOf(value: unknown): string | null {
217
+ if (typeof value === "string") {
218
+ const parsed = new Date(value);
219
+ return Number.isNaN(parsed.getTime()) ? null : parsed.toISOString().slice(0, 10);
220
+ }
221
+ if (typeof value === "number" && Number.isFinite(value)) return new Date(value).toISOString().slice(0, 10);
222
+ return null;
223
+ }
224
+
225
+ function formatInt(value: number): string {
226
+ return String(Math.round(value)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
227
+ }
228
+
229
+ function round1(value: number): number {
230
+ return Math.round(value * 10) / 10;
231
+ }
232
+
233
+ function packageVersion(): string {
234
+ try {
235
+ const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")) as { version?: unknown };
236
+ return typeof pkg.version === "string" ? pkg.version : "unknown";
237
+ } catch {
238
+ return "unknown";
239
+ }
240
+ }
241
+
242
+ function listSessionFiles(root: string): string[] {
243
+ if (!existsSync(root)) return [];
244
+ const files: string[] = [];
245
+ const stack = [root];
246
+ while (stack.length > 0) {
247
+ const dir = stack.pop()!;
248
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
249
+ const path = join(dir, entry.name);
250
+ if (entry.isDirectory()) stack.push(path);
251
+ else if (entry.isFile() && entry.name.endsWith(".jsonl")) files.push(path);
252
+ }
253
+ }
254
+ return files.sort();
255
+ }
256
+
257
+ /** Date of a session file: the ISO-timestamp filename prefix, else its mtime. */
258
+ function sessionFileDate(file: string): string {
259
+ const match = /^(\d{4}-\d{2}-\d{2})T/.exec(basename(file));
260
+ if (match) return match[1]!;
261
+ try {
262
+ return statSync(file).mtime.toISOString().slice(0, 10);
263
+ } catch {
264
+ return "1970-01-01";
265
+ }
266
+ }
267
+
268
+ interface SessionHeader {
269
+ cwd?: string;
270
+ }
271
+
272
+ interface RawAssistantEntry {
273
+ timestamp?: unknown;
274
+ message?: Record<string, unknown>;
275
+ }
276
+
277
+ /**
278
+ * Read one session file: its cwd and the assistant turns. Only the fields the
279
+ * report needs are extracted; `message.content` is never touched.
280
+ */
281
+ function readSession(file: string): { cwd: string; turns: Array<{ raw: RawAssistantEntry; message: Record<string, unknown> }> } {
282
+ let text: string;
283
+ try {
284
+ text = readFileSync(file, "utf8");
285
+ } catch {
286
+ return { cwd: "", turns: [] };
287
+ }
288
+ let header: SessionHeader = {};
289
+ const turns: Array<{ raw: RawAssistantEntry; message: Record<string, unknown> }> = [];
290
+ for (const line of text.split("\n")) {
291
+ if (line.trim().length === 0) continue;
292
+ let entry: Record<string, unknown>;
293
+ try {
294
+ entry = JSON.parse(line) as Record<string, unknown>;
295
+ } catch {
296
+ continue;
297
+ }
298
+ if (entry.type === "session") {
299
+ header = entry as SessionHeader;
300
+ continue;
301
+ }
302
+ if (entry.type !== "message") continue;
303
+ const message = entry.message;
304
+ if (typeof message !== "object" || message === null) continue;
305
+ const record = message as Record<string, unknown>;
306
+ if (record.role !== "assistant" || record.provider !== "nan") continue;
307
+ turns.push({ raw: entry as RawAssistantEntry, message: record });
308
+ }
309
+ return { cwd: typeof header.cwd === "string" ? header.cwd : "", turns };
310
+ }
311
+
312
+ function readAnomalies(file: string): CacheAnomalyRecord[] {
313
+ if (!existsSync(file)) return [];
314
+ const records: CacheAnomalyRecord[] = [];
315
+ const text = readFileSync(file, "utf8");
316
+ for (const line of text.split("\n")) {
317
+ if (line.trim().length === 0) continue;
318
+ try {
319
+ const parsed = JSON.parse(line) as CacheAnomalyRecord;
320
+ if (parsed && typeof parsed === "object" && typeof parsed.detected_at === "string") records.push(parsed);
321
+ } catch {
322
+ // A corrupted line must not break the collector.
323
+ }
324
+ }
325
+ return records;
326
+ }
327
+
328
+ function inWindow(date: string, window: DebugWindow): boolean {
329
+ return date >= window.start && date <= window.end;
330
+ }
331
+
332
+ // ── Report building ───────────────────────────────────────────────────────
333
+
334
+ export async function buildDebugReport(options: BuildDebugReportOptions = {}): Promise<DebugReport> {
335
+ const agentDir = options.agentDir ?? getAgentDir();
336
+ const now = options.now ?? new Date();
337
+ const window = rollingWindow(options.windowDays ?? DEFAULT_DEBUG_WINDOW_DAYS, now);
338
+ const sessionsDir = options.sessionsDir ?? join(agentDir, "sessions");
339
+ const anomalyFile = options.anomalyFile ?? (options.agentDir ? join(agentDir, CACHE_ANOMALY_FILE) : defaultCacheAnomalyPath());
340
+
341
+ const anomalies = readAnomalies(anomalyFile).filter((record) => inWindow(record.detected_at.slice(0, 10), window));
342
+
343
+ const turns: DebugTurn[] = [];
344
+ const usages = new Map<string, DebugUsageRow>();
345
+ const worktreeLabels = new Set<string>();
346
+ const sessionIds = new Set<string>();
347
+ const models = new Set<string>();
348
+ let reasoningOnlyCount = 0;
349
+ let contextOverflowCount = 0;
350
+
351
+ for (const file of listSessionFiles(sessionsDir)) {
352
+ const date = sessionFileDate(file);
353
+ if (!inWindow(date, window)) continue;
354
+ const { cwd, turns: rawTurns } = readSession(file);
355
+ if (rawTurns.length === 0) continue;
356
+
357
+ const sessionId = md5Short(file);
358
+ const worktreeLabel = cwd ? md5Short(cwd) : "000000000000";
359
+ sessionIds.add(sessionId);
360
+ worktreeLabels.add(worktreeLabel);
361
+
362
+ rawTurns.forEach(({ raw, message }, index) => {
363
+ const model = typeof message.model === "string" ? message.model : "unknown";
364
+ const usage = (typeof message.usage === "object" && message.usage !== null ? message.usage : {}) as Record<string, unknown>;
365
+ const stopReason = typeof message.stopReason === "string" ? message.stopReason : "unknown";
366
+ const responseId = typeof message.responseId === "string" ? message.responseId : null;
367
+ const errorMessage = typeof message.errorMessage === "string" ? message.errorMessage : undefined;
368
+ const errorClass = classifyErrorMessage(errorMessage);
369
+ if (isReasoningOnlyStreamError(errorMessage)) reasoningOnlyCount += 1;
370
+ if (errorClass === "overflow") contextOverflowCount += 1;
371
+ const timestamp =
372
+ typeof raw.timestamp === "string"
373
+ ? raw.timestamp
374
+ : new Date(numberOrZero(message.timestamp)).toISOString();
375
+ const dateOfTurn = isoDateOf(timestamp) ?? date;
376
+
377
+ models.add(model);
378
+ turns.push({
379
+ date: dateOfTurn,
380
+ session_id: sessionId,
381
+ worktree_label: worktreeLabel,
382
+ turn: index + 1,
383
+ timestamp,
384
+ model,
385
+ stop_reason: stopReason,
386
+ error: errorClass,
387
+ response_id: responseId,
388
+ created: null,
389
+ input: numberOrZero(usage.input),
390
+ output: numberOrZero(usage.output),
391
+ cache_read: numberOrZero(usage.cacheRead),
392
+ cache_write: numberOrZero(usage.cacheWrite),
393
+ reasoning: numberOrZero(usage.reasoning),
394
+ total: numberOrZero(usage.totalTokens),
395
+ model_ms: numberOrZero(message.durationMs),
396
+ });
397
+
398
+ const key = `${dateOfTurn}\u0000${sessionId}\u0000${model}`;
399
+ let row = usages.get(key);
400
+ if (!row) {
401
+ row = {
402
+ date: dateOfTurn,
403
+ session_id: sessionId,
404
+ worktree_label: worktreeLabel,
405
+ model,
406
+ turns: 0,
407
+ total_tokens: 0,
408
+ input_tokens: 0,
409
+ output_tokens: 0,
410
+ cache_read_tokens: 0,
411
+ cache_write_tokens: 0,
412
+ reasoning_tokens: 0,
413
+ avg_tokens_per_turn: 0,
414
+ cache_hit_rate_pct: 0,
415
+ stop_reason_counts: {},
416
+ anomalies: [],
417
+ };
418
+ usages.set(key, row);
419
+ }
420
+ row.turns += 1;
421
+ row.total_tokens += numberOrZero(usage.totalTokens);
422
+ row.input_tokens += numberOrZero(usage.input);
423
+ row.output_tokens += numberOrZero(usage.output);
424
+ row.cache_read_tokens += numberOrZero(usage.cacheRead);
425
+ row.cache_write_tokens += numberOrZero(usage.cacheWrite);
426
+ row.reasoning_tokens += numberOrZero(usage.reasoning);
427
+ row.stop_reason_counts[stopReason] = (row.stop_reason_counts[stopReason] ?? 0) + 1;
428
+ });
429
+ }
430
+
431
+ const rows = [...usages.values()].sort((a, b) =>
432
+ a.date === b.date
433
+ ? a.session_id === b.session_id
434
+ ? a.model.localeCompare(b.model)
435
+ : a.session_id.localeCompare(b.session_id)
436
+ : a.date.localeCompare(b.date),
437
+ );
438
+ for (const row of rows) {
439
+ row.avg_tokens_per_turn = row.turns > 0 ? round1(row.total_tokens / row.turns) : 0;
440
+ const denominator = row.input_tokens + row.cache_read_tokens;
441
+ row.cache_hit_rate_pct = denominator > 0 ? round1((row.cache_read_tokens / denominator) * 100) : 0;
442
+ row.anomalies = anomalies
443
+ .filter((record) => record.model === row.model && record.detected_at.slice(0, 10) === row.date)
444
+ .map((record) => ({ kind: record.kind, detected_at: record.detected_at }));
445
+ }
446
+
447
+ const generatedAt = now.toISOString();
448
+ const versions = { provider: packageVersion(), pi_ai: PI_AI_VERSION, pi: PI_VERSION };
449
+ const metadata: Record<string, unknown> = {
450
+ generated_at: generatedAt,
451
+ topic: options.topic ?? null,
452
+ window,
453
+ versions,
454
+ catalog: {
455
+ source: GENERATED_CATALOG_META.source,
456
+ models_dev_provider: GENERATED_CATALOG_META.modelsDevProvider,
457
+ fetched_at: GENERATED_CATALOG_META.fetchedAt,
458
+ model_count: GENERATED_CATALOG_META.modelCount,
459
+ },
460
+ redaction: {
461
+ session_ids_hashed: sessionIds.size,
462
+ worktree_labels_hashed: worktreeLabels.size,
463
+ prompt_response_bytes: 0,
464
+ credentials: 0,
465
+ },
466
+ };
467
+
468
+ const report: DebugReport = {
469
+ window,
470
+ topic: options.topic ?? null,
471
+ generatedAt,
472
+ rows,
473
+ turns: turns.sort((a, b) =>
474
+ a.timestamp === b.timestamp ? a.session_id.localeCompare(b.session_id) : a.timestamp.localeCompare(b.timestamp),
475
+ ),
476
+ anomalies,
477
+ counts: {
478
+ sessions: sessionIds.size,
479
+ turns: turns.length,
480
+ models: [...models].sort(),
481
+ anomalies: {
482
+ duplicateIdCreated: anomalies.length,
483
+ reasoningOnlyStream: reasoningOnlyCount,
484
+ contextOverflow: contextOverflowCount,
485
+ },
486
+ },
487
+ metadata,
488
+ };
489
+
490
+ if (options.includeUsage && options.fetchUsage) {
491
+ if (!options.apiKey) {
492
+ report.usageWindow = { error: "no API key resolved — usage window skipped" };
493
+ } else {
494
+ try {
495
+ report.usageWindow = await options.fetchUsage(window, options.apiKey);
496
+ } catch (error) {
497
+ report.usageWindow = { error: error instanceof Error ? error.message : String(error) };
498
+ }
499
+ }
500
+ if (report.usageWindow !== undefined) {
501
+ (metadata as Record<string, unknown>).usage_window_included = true;
502
+ }
503
+ }
504
+
505
+ return report;
506
+ }
507
+
508
+ // ── Rendering ─────────────────────────────────────────────────────────────
509
+
510
+ export interface RenderedReport {
511
+ files: Record<string, string>;
512
+ preview: string;
513
+ }
514
+
515
+ function renderReadme(report: DebugReport, versions: Record<string, string>): string {
516
+ return [
517
+ "# nan-debug report",
518
+ "",
519
+ `Generated by \`/nan-debug\` (issue #35) on ${report.generatedAt}. Local-only: nothing was uploaded.`,
520
+ "",
521
+ `Window: ${report.window.start} → ${report.window.end} (${report.window.days}d)`,
522
+ `Topic: ${report.topic ?? "(none)"}`,
523
+ "",
524
+ "## What is collected",
525
+ "",
526
+ "- `anonymized_usage.jsonl` — one aggregated row per date/session/model: token counters, turn count, stop-reason counts, cache-hit rate, anomaly signatures.",
527
+ "- `turns.jsonl` — one row per assistant turn: model, usage counters, stop reason, classified error, response id, `created` (null when the transcript has none), duration.",
528
+ "- `anomalies.jsonl` — duplicate `id`/`created` pairs captured by the provider, with both `cf-ray` values (see issue #35).",
529
+ "- `metadata.json` — versions, catalog provenance, window, redaction counters.",
530
+ "",
531
+ "## What is never collected",
532
+ "",
533
+ "- Prompt or response content.",
534
+ "- Raw file paths or worktree names (MD5 truncated to 12 chars).",
535
+ "- Credentials or auth headers.",
536
+ "",
537
+ "## Versions",
538
+ "",
539
+ `- package: ${versions.provider}`,
540
+ `- pi-ai: ${versions.pi_ai}`,
541
+ `- pi: ${versions.pi}`,
542
+ "",
543
+ ].join("\n");
544
+ }
545
+
546
+ export function renderDebugReport(report: DebugReport): RenderedReport {
547
+ const versions = (report.metadata as { versions: Record<string, string> }).versions;
548
+ const files: Record<string, string> = {
549
+ "README.md": renderReadme(report, versions),
550
+ "anonymized_usage.jsonl": report.rows.map((row) => JSON.stringify(row)).join("\n") + (report.rows.length > 0 ? "\n" : ""),
551
+ "turns.jsonl": report.turns.map((turn) => JSON.stringify(turn)).join("\n") + (report.turns.length > 0 ? "\n" : ""),
552
+ "anomalies.jsonl": report.anomalies.map((record) => JSON.stringify(record)).join("\n") + (report.anomalies.length > 0 ? "\n" : ""),
553
+ "metadata.json": `${JSON.stringify(report.metadata, null, 2)}\n`,
554
+ };
555
+ if (report.usageWindow !== undefined) {
556
+ files["usage_window.json"] = `${JSON.stringify(report.usageWindow, null, 2)}\n`;
557
+ }
558
+
559
+ const perModel = report.counts.models
560
+ .map((model) => {
561
+ const rows = report.rows.filter((row) => row.model === model);
562
+ const turns = rows.reduce((sum, row) => sum + row.turns, 0);
563
+ const tokens = rows.reduce((sum, row) => sum + row.total_tokens, 0);
564
+ return `${model} ${formatInt(turns > 0 ? tokens / turns : 0)}`;
565
+ })
566
+ .join(" · ");
567
+
568
+ const preview = [
569
+ `nan-debug report — ${report.window.start} → ${report.window.end} (window: ${report.window.days}d)`,
570
+ `sessions: ${report.counts.sessions} · turns: ${report.counts.turns} · models: ${report.counts.models.length}`,
571
+ `per-model avg tokens/turn: ${perModel.length > 0 ? perModel : "(none)"}`,
572
+ `anomalies: ${report.counts.anomalies.duplicateIdCreated} duplicate id/created pairs · ${report.counts.anomalies.reasoningOnlyStream} reasoning-only stream · ${report.counts.anomalies.contextOverflow} context overflow`,
573
+ `redaction: ${report.counts.sessions} session ids hashed · ${(report.metadata as { redaction: { worktree_labels_hashed: number } }).redaction.worktree_labels_hashed} paths hashed · 0 prompt/response bytes collected`,
574
+ "→ nothing shared yet. Run with --emit to write nan-debug-report.zip",
575
+ ].join("\n");
576
+
577
+ return { files, preview };
578
+ }
579
+
580
+ export function writeDebugReport(files: Record<string, string>, outDir: string): void {
581
+ mkdirSync(outDir, { recursive: true });
582
+ for (const [name, content] of Object.entries(files)) {
583
+ writeFileSync(join(outDir, name), content);
584
+ }
585
+ }
586
+
587
+ export function writeDebugZip(files: Record<string, string>, zipPath: string): void {
588
+ mkdirSync(dirname(zipPath), { recursive: true });
589
+ const entries = Object.entries(files).map(([name, data]) => ({ name, data }));
590
+ writeFileSync(zipPath, createZip(entries));
591
+ }
592
+
593
+ // ── Live usage (only with --window) ───────────────────────────────────────
594
+
595
+ /** Default `--window` usage source: the same `/nan-usage` endpoint, same key. */
596
+ export async function fetchDebugUsageWindow(window: DebugWindow, apiKey: string): Promise<unknown> {
597
+ const result = await fetchUsageReport({ apiKey, window });
598
+ if (!result.ok) return { error: result.error };
599
+ return result.report;
600
+ }
601
+
package/src/index.ts CHANGED
@@ -30,6 +30,7 @@ import type { Provider } from "@earendil-works/pi-ai";
30
30
  import { configureProviderAttribution } from "./attribution.ts";
31
31
  import { registerNanMcpCommand } from "./commands.ts";
32
32
  import { registerNanUsageCommand } from "./usage.ts";
33
+ import { registerNanDebugCommand } from "./debug-command.ts";
33
34
  import { baselineModels } from "./fetch-models.ts";
34
35
  import { createNanCompatibleProvider, type OpenAICompatibleProviderConfig } from "./provider-factory.ts";
35
36
  import { PROVIDERS } from "./providers.ts";
@@ -160,6 +161,7 @@ export default async function nanProviderExtension(pi: ExtensionAPI): Promise<vo
160
161
  if (typeof pi.registerCommand === "function") {
161
162
  registerNanMcpCommand(pi);
162
163
  registerNanUsageCommand(pi);
164
+ registerNanDebugCommand(pi);
163
165
  }
164
166
  }
165
167
 
@@ -198,6 +198,17 @@ export interface SanitizerOptions {
198
198
  * NaN payload as before.
199
199
  */
200
200
  preserveStreamOptions?: boolean;
201
+ /**
202
+ * Keep `max_completion_tokens` in the payload instead of renaming it to
203
+ * `max_tokens`. Set only when the model's effective `compat.maxTokensField`
204
+ * is `"max_completion_tokens"` (issue #34: NaN confirmed the gateway honors
205
+ * `max_completion_tokens` on `qwen3.8-flash` as the interim bound for the
206
+ * reasoning phase, which `max_tokens` does not bound). When false/absent the
207
+ * documented rename runs — NaN's published OpenAPI schema only documents
208
+ * `max_tokens`, so hand-built payloads and non-overridden models stay on
209
+ * the strict shape.
210
+ */
211
+ preserveMaxCompletionTokens?: boolean;
201
212
  }
202
213
 
203
214
  /**
@@ -243,8 +254,15 @@ export function sanitizeOpenAICompatPayload(payload: unknown, options: Sanitizer
243
254
  // pi-ai would not send it for such a model anyway, and a hand-built payload
244
255
  // must stay schema-strict.
245
256
  if (options.preserveStreamOptions !== true) delete out.stream_options;
246
- // NaN documents `max_tokens`, not `max_completion_tokens`.
247
- if ("max_completion_tokens" in out && !("max_tokens" in out)) {
257
+ // NaN documents `max_tokens`, not `max_completion_tokens` — unless the
258
+ // model's compat declares `max_completion_tokens` (issue #34): the gateway
259
+ // honors it there as the interim reasoning bound, so the rename would undo
260
+ // the catalog's maxTokensField override before the payload leaves pi.
261
+ if (
262
+ "max_completion_tokens" in out &&
263
+ !("max_tokens" in out) &&
264
+ options.preserveMaxCompletionTokens !== true
265
+ ) {
248
266
  out.max_tokens = out.max_completion_tokens;
249
267
  delete out.max_completion_tokens;
250
268
  }