@gtrabanco/pi-nan-provider 1.5.7 → 1.6.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/AGENTS.md +51 -4
- package/README.es.md +38 -12
- package/README.md +34 -11
- package/package.json +3 -3
- package/scripts/models.generated.ts +8 -8
- package/src/cache-anomaly.ts +26 -2
- package/src/debug-command.ts +4 -1
- package/src/debug-report.ts +465 -18
- package/src/provider-factory.ts +9 -2
- package/src/response-rays.ts +140 -0
package/src/debug-report.ts
CHANGED
|
@@ -4,14 +4,19 @@
|
|
|
4
4
|
* NaN could not reproduce the prompt-cache anomaly and asked for "modelo y
|
|
5
5
|
* cf-ray de un par de llamadas". This module reads pi's session JSONL (usage,
|
|
6
6
|
* stop reasons, response ids) plus the local cache-anomaly capture
|
|
7
|
-
* (`nan-cache-anomalies.jsonl`, which holds the `cf-ray` pair) and
|
|
8
|
-
*
|
|
7
|
+
* (`nan-cache-anomalies.jsonl`, which holds the anomaly `cf-ray` pair) and
|
|
8
|
+
* the per-response ray sidecar (`nan-response-rays.jsonl`, issue #35 S11),
|
|
9
|
+
* and renders a report that can be shared verbatim.
|
|
9
10
|
*
|
|
10
|
-
* Contract (issue #35):
|
|
11
|
+
* Contract (issue #35, scoped by PR #44):
|
|
11
12
|
* - no LLM, no network unless `--window` explicitly asks for `/v1/usage`;
|
|
12
|
-
* - never collect prompt/response content,
|
|
13
|
+
* - the redacted root files never collect prompt/response content,
|
|
14
|
+
* credentials or raw paths — `sessions/` is the owner-requested exception
|
|
15
|
+
* (PR #44): raw transcripts with only the `cwd` header MD5-hashed;
|
|
13
16
|
* - session and worktree identifiers are MD5-truncated to 12 chars;
|
|
14
|
-
* - error text is reduced to a fixed class;
|
|
17
|
+
* - error text in rows and the preview is reduced to a fixed class;
|
|
18
|
+
* `errors.jsonl` carries at most 200 characters of the raw message plus
|
|
19
|
+
* an MD5 hash of the full text, which appears nowhere else;
|
|
15
20
|
* - the same inputs produce byte-identical zip bytes.
|
|
16
21
|
*
|
|
17
22
|
* The report layout matches the 2026-11-10 anonymized dataset: one aggregated
|
|
@@ -27,6 +32,7 @@ import { PI_AI_VERSION } from "@earendil-works/pi-ai";
|
|
|
27
32
|
import { VERSION as PI_VERSION, getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
28
33
|
import { GENERATED_CATALOG_META } from "../scripts/models.generated.ts";
|
|
29
34
|
import { CACHE_ANOMALY_FILE, defaultCacheAnomalyPath, type CacheAnomalyRecord } from "./cache-anomaly.ts";
|
|
35
|
+
import { RESPONSE_RAYS_FILE, readResponseRays } from "./response-rays.ts";
|
|
30
36
|
import { fetchUsageReport, rollingWindow, type UsageWindow } from "./usage.ts";
|
|
31
37
|
import { createZip } from "./zip.ts";
|
|
32
38
|
|
|
@@ -36,17 +42,48 @@ export const NAN_DEBUG_REPORT_DIR = "nan-debug-report";
|
|
|
36
42
|
export const NAN_DEBUG_ZIP = "nan-debug-report.zip";
|
|
37
43
|
|
|
38
44
|
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.";
|
|
45
|
+
"Usage: /nan-debug [topic] [--window N] [--interval FLEXIBLE] [--out file] [--emit] — collects a redacted NaN evidence report locally; --emit writes the shareable zip.\n\nIntervals: '5min', '2h', '3d', '1mes', '2026-11-10 - 2026-11-11 17:30', '10:30 - 11:00', '2026-11-10 -', max 90 days, mutually exclusive with --window.";
|
|
40
46
|
|
|
41
|
-
|
|
47
|
+
/** A flexible time window with ISO-capable boundaries (YYYY-MM-DD or full ISO 8601). */
|
|
48
|
+
export interface DebugWindow {
|
|
49
|
+
/** Inclusive start, YYYY-MM-DD or ISO 8601 (lexicographic comparison works). */
|
|
50
|
+
start: string;
|
|
51
|
+
/** Inclusive end, YYYY-MM-DD or ISO 8601. */
|
|
52
|
+
end: string;
|
|
53
|
+
/** Inclusive day count (for back-compat with --window). */
|
|
54
|
+
days: number;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** A relative span in milliseconds (for "5min", "2h", etc.). */
|
|
58
|
+
export interface RelativeSpan {
|
|
59
|
+
kind: "relative";
|
|
60
|
+
/** Span duration in milliseconds. */
|
|
61
|
+
spanMs: number;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** An explicit range (absolute or partial). */
|
|
65
|
+
export interface ExplicitRange {
|
|
66
|
+
kind: "range";
|
|
67
|
+
start: string; // ISO string or null (null = fill from window or now)
|
|
68
|
+
end: string; // ISO string or null
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** A single point-in-time (interpreted as "from this point to now"). */
|
|
72
|
+
export interface SinglePoint {
|
|
73
|
+
kind: "point";
|
|
74
|
+
point: string; // ISO string
|
|
75
|
+
}
|
|
42
76
|
|
|
43
77
|
// ── Argument parsing ──────────────────────────────────────────────────────
|
|
44
78
|
|
|
45
79
|
export interface DebugArgs {
|
|
46
80
|
topic?: string;
|
|
81
|
+
/** Day count for --window (1-90). Not used when interval is provided. */
|
|
47
82
|
windowDays: number;
|
|
48
83
|
/** True when `--window` was given; only then is `/v1/usage` consulted. */
|
|
49
84
|
windowProvided: boolean;
|
|
85
|
+
/** Flexible time interval from --interval (replaces --window when provided). */
|
|
86
|
+
interval?: string;
|
|
50
87
|
out?: string;
|
|
51
88
|
emit: boolean;
|
|
52
89
|
}
|
|
@@ -77,6 +114,32 @@ export function parseDebugArgs(input: string): ParseDebugArgsResult {
|
|
|
77
114
|
args.windowProvided = true;
|
|
78
115
|
continue;
|
|
79
116
|
}
|
|
117
|
+
if (token === "--interval") {
|
|
118
|
+
// The value spans every token up to the next `--` flag: pi passes the
|
|
119
|
+
// command text raw and unquoted (PE-010), so a range like
|
|
120
|
+
// "2026-11-10 - 2026-11-11 17:30" arrives as several whitespace tokens.
|
|
121
|
+
const parts: string[] = [];
|
|
122
|
+
let j = i + 1;
|
|
123
|
+
while (j < tokens.length && !tokens[j]!.startsWith("--")) {
|
|
124
|
+
parts.push(tokens[j]!);
|
|
125
|
+
j += 1;
|
|
126
|
+
}
|
|
127
|
+
if (parts.length === 0) {
|
|
128
|
+
const next = tokens[i + 1];
|
|
129
|
+
return next === undefined
|
|
130
|
+
? { ok: false, error: `--interval needs a time description. ${DEBUG_USAGE_LINE}` }
|
|
131
|
+
: { ok: false, error: `--interval needs a time description (got "${next}"). ${DEBUG_USAGE_LINE}` };
|
|
132
|
+
}
|
|
133
|
+
i = j - 1;
|
|
134
|
+
let value = parts.join(" ");
|
|
135
|
+
// Strip one layer of surrounding quotes (`--interval " - 2026-11-10"`).
|
|
136
|
+
if (value.length > 1 && ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'")))) {
|
|
137
|
+
value = value.slice(1, -1).trim();
|
|
138
|
+
}
|
|
139
|
+
if (value.length === 0) return { ok: false, error: `--interval needs a time description. ${DEBUG_USAGE_LINE}` };
|
|
140
|
+
args.interval = value;
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
80
143
|
if (token === "--out") {
|
|
81
144
|
const value = tokens[i + 1];
|
|
82
145
|
if (value === undefined || value.length === 0) return { ok: false, error: `--out needs a file or directory path. ${DEBUG_USAGE_LINE}` };
|
|
@@ -95,9 +158,241 @@ export function parseDebugArgs(input: string): ParseDebugArgsResult {
|
|
|
95
158
|
args.topic = token;
|
|
96
159
|
}
|
|
97
160
|
|
|
161
|
+
// --window and --interval are mutually exclusive
|
|
162
|
+
if (args.windowProvided && args.interval) {
|
|
163
|
+
return { ok: false, error: `Cannot use --window and --interval together. --window expects a day count; --interval accepts flexible time descriptions. ${DEBUG_USAGE_LINE}` };
|
|
164
|
+
}
|
|
165
|
+
|
|
98
166
|
return { ok: true, args };
|
|
99
167
|
}
|
|
100
168
|
|
|
169
|
+
// ── Flexible time interval parsing ────────────────────────────────────────
|
|
170
|
+
|
|
171
|
+
/** Max allowed span in ms: 90 days. */
|
|
172
|
+
const MAX_INTERVAL_MS = 90 * 86_400_000;
|
|
173
|
+
|
|
174
|
+
const TIME_UNITS: ReadonlyMap<string, number> = new Map([
|
|
175
|
+
["min", 60_000],
|
|
176
|
+
["minute", 60_000],
|
|
177
|
+
["minutes", 60_000],
|
|
178
|
+
["m", 60_000],
|
|
179
|
+
["hour", 3_600_000],
|
|
180
|
+
["hours", 3_600_000],
|
|
181
|
+
["h", 3_600_000],
|
|
182
|
+
["hr", 3_600_000],
|
|
183
|
+
["d", 86_400_000],
|
|
184
|
+
["day", 86_400_000],
|
|
185
|
+
["days", 86_400_000],
|
|
186
|
+
["mes", 30 * 86_400_000],
|
|
187
|
+
["month", 30 * 86_400_000],
|
|
188
|
+
["año", 365 * 86_400_000],
|
|
189
|
+
["year", 365 * 86_400_000],
|
|
190
|
+
]);
|
|
191
|
+
|
|
192
|
+
/** Parse a standalone relative span like "5min", "2h", "3d": null when it is not a relative span, the explicit cap error when it exceeds 90 days. */
|
|
193
|
+
function tryParseRelativeSpan(input?: string): RelativeSpan | { error: string } | null {
|
|
194
|
+
if (!input) return null;
|
|
195
|
+
const match = /^(\d+)\s*(\S+)$/.exec(input.trim());
|
|
196
|
+
if (!match) return null;
|
|
197
|
+
const [, amountStr, unit] = match;
|
|
198
|
+
if (typeof amountStr !== "string" || typeof unit !== "string") return null;
|
|
199
|
+
if (Number(amountStr) <= 0) return null;
|
|
200
|
+
const spanMs = TIME_UNITS.get(unit);
|
|
201
|
+
if (!spanMs) return null;
|
|
202
|
+
const total = Number(amountStr) * spanMs;
|
|
203
|
+
if (total > MAX_INTERVAL_MS) return { error: `Interval too large (max 90 days).` };
|
|
204
|
+
return { kind: "relative" as const, spanMs: total };
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** ISO 8601 date-time regex: YYYY-MM-DD[T ]HH:MM[:SS[.mmm]][Z] */
|
|
208
|
+
const ISO_PARTIAL = /^(\d{4})-(\d{1,2})(?:-(\d{1,2}))?(?:[T ](\d{1,2}):(\d{2})(?::(\d{2}))?(?:\.(\d+))?)?Z?$/;
|
|
209
|
+
|
|
210
|
+
/** Parse a partial ISO string to a Date. Missing components get sensible defaults. */
|
|
211
|
+
function parsePartialISO(value: string): Date | null {
|
|
212
|
+
const m = ISO_PARTIAL.exec(value.trim());
|
|
213
|
+
if (!m) return null;
|
|
214
|
+
const [, yearStr, monthStr, dayStr, hourStr, minStr, secStr, msStr] = m;
|
|
215
|
+
const year = Number(yearStr);
|
|
216
|
+
const month = Number(monthStr);
|
|
217
|
+
if (year < 1900 || year > 9999 || month < 1 || month > 12) return null;
|
|
218
|
+
const day = dayStr ? Number(dayStr) : 1;
|
|
219
|
+
if (day < 1 || day > 31) return null;
|
|
220
|
+
const hour = hourStr ? Number(hourStr) : 0;
|
|
221
|
+
if (hour > 23) return null;
|
|
222
|
+
const min = minStr ? Number(minStr) : 0;
|
|
223
|
+
if (min > 59) return null;
|
|
224
|
+
const sec = secStr ? Number(secStr) : 0;
|
|
225
|
+
if (sec > 59) return null;
|
|
226
|
+
let ms = 0;
|
|
227
|
+
if (msStr) {
|
|
228
|
+
// Pad or truncate to 3 digits
|
|
229
|
+
const padded = (msStr + "000").slice(0, 3);
|
|
230
|
+
ms = Number(padded);
|
|
231
|
+
}
|
|
232
|
+
// Use UTC to avoid timezone confusion
|
|
233
|
+
try {
|
|
234
|
+
return new Date(Date.UTC(year, month - 1, day, hour, min, sec, ms));
|
|
235
|
+
} catch {
|
|
236
|
+
return null;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
/**
|
|
241
|
+
* Build a full ISO 8601 UTC string (always `YYYY-MM-DDTHH:mm:ss.sssZ`) so
|
|
242
|
+
* interval bounds compare lexicographically against day-granular dates once
|
|
243
|
+
* `slice(0, 10)` is applied.
|
|
244
|
+
*/
|
|
245
|
+
function dateToISO(d: Date): string {
|
|
246
|
+
const y = d.getUTCFullYear();
|
|
247
|
+
const m = String(d.getUTCMonth() + 1).padStart(2, "0");
|
|
248
|
+
const day = String(d.getUTCDate()).padStart(2, "0");
|
|
249
|
+
const h = String(d.getUTCHours()).padStart(2, "0");
|
|
250
|
+
const mi = String(d.getUTCMinutes()).padStart(2, "0");
|
|
251
|
+
const s = String(d.getUTCSeconds()).padStart(2, "0");
|
|
252
|
+
return `${y}-${m}-${day}T${h}:${mi}:${s}.${d.getUTCMilliseconds().toString().padStart(3, "0")}Z`;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* Main parser: converts a freeform time description into a DebugWindow.
|
|
257
|
+
* Handles: relative spans, explicit ranges ("2026-11-10 - 2026-11-11 17:30"),
|
|
258
|
+
* single dates, partial times ("10:30 - 11:00"), etc.
|
|
259
|
+
*/
|
|
260
|
+
export function parseFlexibleTime(input: string, now: Date): DebugWindow | { ok: false; error: string } {
|
|
261
|
+
const trimmed = input.trim();
|
|
262
|
+
if (trimmed.length === 0) return { ok: false, error: `--interval requires a time description. ${DEBUG_USAGE_LINE}` };
|
|
263
|
+
|
|
264
|
+
// 1. Try relative span: "5min", "2h", "3d", "1mes"
|
|
265
|
+
const relative = tryParseRelativeSpan(trimmed);
|
|
266
|
+
if (relative) {
|
|
267
|
+
if ("error" in relative) return { ok: false, error: relative.error };
|
|
268
|
+
return {
|
|
269
|
+
start: dateToISO(new Date(now.getTime() - relative.spanMs)),
|
|
270
|
+
end: dateToISO(now),
|
|
271
|
+
days: Math.max(1, Math.round(relative.spanMs / 86_400_000)),
|
|
272
|
+
};
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// 2. Open left: "- <date>" — from the default window's start until <date>
|
|
276
|
+
// (issue #44: "inicio del window hasta 10 nov").
|
|
277
|
+
const openLeft = /^-\s+(.+)$/.exec(trimmed);
|
|
278
|
+
if (openLeft?.[1]) {
|
|
279
|
+
const right = openLeft[1].trim();
|
|
280
|
+
const end = parseTimeToken(right, now, false);
|
|
281
|
+
if (!end) {
|
|
282
|
+
return { ok: false, error: `Cannot parse interval "${trimmed}". Use "- 2026-11-10" to run from the default window's start until a date.` };
|
|
283
|
+
}
|
|
284
|
+
const start = new Date(`${rollingWindow(DEFAULT_DEBUG_WINDOW_DAYS, now).start}T00:00:00.000Z`);
|
|
285
|
+
const spanMs = end.getTime() - start.getTime();
|
|
286
|
+
if (spanMs <= 0) return { ok: false, error: `Start (${dateToISO(start)}) must be before end (${right}).` };
|
|
287
|
+
if (spanMs > MAX_INTERVAL_MS) return { ok: false, error: `Interval too large (max 90 days).` };
|
|
288
|
+
return { start: dateToISO(start), end: dateToISO(end), days: Math.max(1, Math.round(spanMs / 86_400_000)) };
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// 3. Try range: split on " - " (dash with spaces)
|
|
292
|
+
// Match " - " but not "--" or "-" at edges
|
|
293
|
+
const rangeMatch = /^(.+?)\s+-\s+(.+)$/.exec(trimmed);
|
|
294
|
+
if (rangeMatch?.[1] && rangeMatch?.[2]) {
|
|
295
|
+
const left = rangeMatch[1].trim();
|
|
296
|
+
const right = rangeMatch[2].trim();
|
|
297
|
+
return parseRange(left, right, now);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// 4. Open right: "<date> -" — from <date> until now (issue #44).
|
|
301
|
+
const openRight = /^(.+?)\s+-\s*$/.exec(trimmed);
|
|
302
|
+
if (openRight?.[1]) {
|
|
303
|
+
const left = openRight[1].trim();
|
|
304
|
+
const start = parseTimeToken(left, now, true);
|
|
305
|
+
if (!start) {
|
|
306
|
+
return { ok: false, error: `Cannot parse interval "${trimmed}". Use "2026-11-10 -" to run from a date until now.` };
|
|
307
|
+
}
|
|
308
|
+
const spanMs = now.getTime() - start.getTime();
|
|
309
|
+
if (spanMs <= 0) return { ok: false, error: `Start (${left}) must be before now.` };
|
|
310
|
+
if (spanMs > MAX_INTERVAL_MS) return { ok: false, error: `Interval too large (max 90 days).` };
|
|
311
|
+
return { start: dateToISO(start), end: dateToISO(now), days: Math.max(1, Math.round(spanMs / 86_400_000)) };
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
// 5. Try single date/time: parse as a single point, default end to now
|
|
315
|
+
const point = parsePartialISO(trimmed);
|
|
316
|
+
if (point) {
|
|
317
|
+
const spanMs = now.getTime() - point.getTime();
|
|
318
|
+
return {
|
|
319
|
+
start: dateToISO(point),
|
|
320
|
+
end: dateToISO(now),
|
|
321
|
+
days: Math.max(1, Math.round(spanMs / 86_400_000)),
|
|
322
|
+
};
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
return { ok: false, error: `Cannot parse interval "${trimmed}". Use relative (5min, 2h, 3d), date ranges (2026-11-10 - 2026-11-11 17:30), or single dates.` };
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* Parse a range: "left - right". Each side can be a date, time, or partial.
|
|
330
|
+
* "now" provides the default date when no date component is present.
|
|
331
|
+
*/
|
|
332
|
+
function parseRange(left: string, right: string, now: Date): DebugWindow | { ok: false; error: string } {
|
|
333
|
+
const start = parseTimeToken(left, now, true);
|
|
334
|
+
const end = parseTimeToken(right, now, false);
|
|
335
|
+
|
|
336
|
+
if (!start || !end) {
|
|
337
|
+
return { ok: false, error: `Cannot parse range "${left} - ${right}". Use dates (2026-11-10), times (10:30 - 11:00), or both.` } as const;
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
// Cross-midnight detection: time-only tokens fall back to `now`'s calendar
|
|
341
|
+
// day (parseTimeToken's fallbackDate), so an end before the start on that
|
|
342
|
+
// same day means the end belongs to the next day — "23:00 - 01:00" becomes
|
|
343
|
+
// 23:00 → 01:00 next day. Everything reads UTC (EV-2026-11-18 A4: the
|
|
344
|
+
// local-time variant of this check was dead code, outcome-identical).
|
|
345
|
+
if (end.getTime() < start.getTime()) {
|
|
346
|
+
const sameCalendarDay = start.getUTCFullYear() === end.getUTCFullYear()
|
|
347
|
+
&& start.getUTCMonth() === end.getUTCMonth()
|
|
348
|
+
&& start.getUTCDate() === end.getUTCDate();
|
|
349
|
+
if (sameCalendarDay) {
|
|
350
|
+
end.setUTCDate(end.getUTCDate() + 1);
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
const spanMs = end.getTime() - start.getTime();
|
|
355
|
+
if (spanMs <= 0) {
|
|
356
|
+
return { ok: false, error: `Start (${left}) must be before end (${right}).` };
|
|
357
|
+
}
|
|
358
|
+
if (spanMs > MAX_INTERVAL_MS) {
|
|
359
|
+
return { ok: false, error: `Interval too large (max 90 days).` };
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
return {
|
|
363
|
+
start: dateToISO(start),
|
|
364
|
+
end: dateToISO(end),
|
|
365
|
+
days: Math.max(1, Math.round(spanMs / 86_400_000)),
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
/**
|
|
370
|
+
* Parse a single time token: could be a full date, a date+time, a time-only,
|
|
371
|
+
* or a partial date. Falls back to `fallbackDate` for missing components.
|
|
372
|
+
* Returns a Date with the parsed components applied to fallbackDate's date.
|
|
373
|
+
*/
|
|
374
|
+
function parseTimeToken(token: string, fallbackDate: Date, _isStart: boolean): Date | null {
|
|
375
|
+
// Try full ISO first
|
|
376
|
+
const d = parsePartialISO(token);
|
|
377
|
+
if (d) return d;
|
|
378
|
+
|
|
379
|
+
// Try time-only: HH:MM[:SS]
|
|
380
|
+
const timeOnly = /^(\d{1,2}):(\d{2})(?::(\d{2}))?$/.exec(token.trim());
|
|
381
|
+
if (timeOnly) {
|
|
382
|
+
const [, hStr, mStr, sStr] = timeOnly;
|
|
383
|
+
const h = Number(hStr);
|
|
384
|
+
const m = Number(mStr);
|
|
385
|
+
const s = sStr ? Number(sStr) : 0;
|
|
386
|
+
if (h < 0 || h > 23 || m < 0 || m > 59 || s < 0 || s > 59) return null;
|
|
387
|
+
const result = new Date(fallbackDate);
|
|
388
|
+
// Keep same date as fallback
|
|
389
|
+
result.setUTCHours(h, m, s, 0);
|
|
390
|
+
return result;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
return null;
|
|
394
|
+
}
|
|
395
|
+
|
|
101
396
|
// ── Error classification ──────────────────────────────────────────────────
|
|
102
397
|
|
|
103
398
|
export type DebugErrorClass = "overflow" | "rate_limited" | "invalid_request" | "transport" | "other";
|
|
@@ -110,8 +405,9 @@ const ERROR_PATTERNS: ReadonlyArray<readonly [DebugErrorClass, RegExp]> = [
|
|
|
110
405
|
];
|
|
111
406
|
|
|
112
407
|
/**
|
|
113
|
-
* Map a raw `errorMessage` to a fixed class.
|
|
114
|
-
* this
|
|
408
|
+
* Map a raw `errorMessage` to a fixed class. Rows, previews and aggregates
|
|
409
|
+
* only ever see this class; the raw text reaches the report solely as
|
|
410
|
+
* `errors.jsonl`'s 200-character fragment plus its MD5 hash (PR #44).
|
|
115
411
|
*/
|
|
116
412
|
export function classifyErrorMessage(message: string | undefined): DebugErrorClass | null {
|
|
117
413
|
if (typeof message !== "string" || message.length === 0) return null;
|
|
@@ -155,6 +451,8 @@ export interface DebugTurn {
|
|
|
155
451
|
stop_reason: string;
|
|
156
452
|
error: DebugErrorClass | null;
|
|
157
453
|
response_id: string | null;
|
|
454
|
+
/** Cloudflare trace id joined from the response-ray sidecar; null when uncaptured. */
|
|
455
|
+
cf_ray: string | null;
|
|
158
456
|
created: number | null;
|
|
159
457
|
input: number;
|
|
160
458
|
output: number;
|
|
@@ -169,6 +467,10 @@ export interface DebugCounts {
|
|
|
169
467
|
sessions: number;
|
|
170
468
|
turns: number;
|
|
171
469
|
models: string[];
|
|
470
|
+
errors: {
|
|
471
|
+
total: number;
|
|
472
|
+
byClass: Record<DebugErrorClass, number>;
|
|
473
|
+
};
|
|
172
474
|
anomalies: {
|
|
173
475
|
duplicateIdCreated: number;
|
|
174
476
|
reasoningOnlyStream: number;
|
|
@@ -176,12 +478,39 @@ export interface DebugCounts {
|
|
|
176
478
|
};
|
|
177
479
|
}
|
|
178
480
|
|
|
481
|
+
/** One row per turn that had an error — written to errors.jsonl. */
|
|
482
|
+
export interface DebugErrorRecord {
|
|
483
|
+
/** ISO 8601 timestamp of the turn. */
|
|
484
|
+
timestamp: string;
|
|
485
|
+
/** MD5[12] of the session file. */
|
|
486
|
+
session_id: string;
|
|
487
|
+
/** MD5[12] of the worktree cwd. */
|
|
488
|
+
worktree_label: string;
|
|
489
|
+
/** Model that returned the error. */
|
|
490
|
+
model: string;
|
|
491
|
+
/** The classified error (one of the fixed classes). */
|
|
492
|
+
error: DebugErrorClass;
|
|
493
|
+
/** The stop reason (usually "error"). */
|
|
494
|
+
stop_reason: string;
|
|
495
|
+
/** The full error message, truncated to 200 chars. */
|
|
496
|
+
message_truncated: string;
|
|
497
|
+
/** MD5 hash of the full error message (so the original is never in the output). */
|
|
498
|
+
message_hash: string;
|
|
499
|
+
/** Response id if present. */
|
|
500
|
+
response_id: string | null;
|
|
501
|
+
/** Input tokens for context. */
|
|
502
|
+
input: number;
|
|
503
|
+
/** Output tokens (usually 0 for errors). */
|
|
504
|
+
output: number;
|
|
505
|
+
}
|
|
506
|
+
|
|
179
507
|
export interface DebugReport {
|
|
180
508
|
window: DebugWindow;
|
|
181
509
|
topic: string | null;
|
|
182
510
|
generatedAt: string;
|
|
183
511
|
rows: DebugUsageRow[];
|
|
184
512
|
turns: DebugTurn[];
|
|
513
|
+
errors: DebugErrorRecord[];
|
|
185
514
|
anomalies: CacheAnomalyRecord[];
|
|
186
515
|
counts: DebugCounts;
|
|
187
516
|
metadata: Record<string, unknown>;
|
|
@@ -193,13 +522,18 @@ export type FetchUsageWindow = (window: DebugWindow, apiKey: string) => Promise<
|
|
|
193
522
|
export interface BuildDebugReportOptions {
|
|
194
523
|
agentDir?: string;
|
|
195
524
|
now?: Date;
|
|
525
|
+
/** Day count for --window (1-90). Ignored when `interval` is set. */
|
|
196
526
|
windowDays?: number;
|
|
527
|
+
/** Flexible time interval from --interval (replaces windowDays when set). */
|
|
528
|
+
interval?: string;
|
|
197
529
|
topic?: string;
|
|
198
530
|
/** Only consulted when `includeUsage` is true. */
|
|
199
531
|
apiKey?: string;
|
|
200
532
|
fetchUsage?: FetchUsageWindow;
|
|
201
533
|
includeUsage?: boolean;
|
|
202
534
|
anomalyFile?: string;
|
|
535
|
+
/** Per-response ray sidecar; defaults to the agent-dir file (issue #35 S11). */
|
|
536
|
+
raysFile?: string;
|
|
203
537
|
sessionsDir?: string;
|
|
204
538
|
}
|
|
205
539
|
|
|
@@ -254,6 +588,38 @@ function listSessionFiles(root: string): string[] {
|
|
|
254
588
|
return files.sort();
|
|
255
589
|
}
|
|
256
590
|
|
|
591
|
+
/** List session files whose date falls within the given window. */
|
|
592
|
+
function listSessionFilesFiltered(root: string, window: DebugWindow): string[] {
|
|
593
|
+
const allFiles = listSessionFiles(root);
|
|
594
|
+
return allFiles.filter((file) => {
|
|
595
|
+
const fileDate = sessionFileDate(file);
|
|
596
|
+
return fileDate >= window.start.slice(0, 10) && fileDate <= window.end.slice(0, 10);
|
|
597
|
+
});
|
|
598
|
+
}
|
|
599
|
+
|
|
600
|
+
/**
|
|
601
|
+
* Embed a raw session transcript with only its `cwd` header hashed: `sessions/`
|
|
602
|
+
* ships the transcript verbatim on the PR #44 owner request, but raw paths
|
|
603
|
+
* must never reach any rendered file. Lines without a `cwd` key, and lines
|
|
604
|
+
* that no longer parse as JSON, pass through untouched (EV-2026-11-18 B5).
|
|
605
|
+
*/
|
|
606
|
+
function scrubSessionTranscript(text: string): string {
|
|
607
|
+
if (!text.includes('"cwd"')) return text;
|
|
608
|
+
return text
|
|
609
|
+
.split("\n")
|
|
610
|
+
.map((line) => {
|
|
611
|
+
if (!line.includes('"cwd"')) return line;
|
|
612
|
+
try {
|
|
613
|
+
const entry = JSON.parse(line) as Record<string, unknown>;
|
|
614
|
+
if (typeof entry.cwd === "string") entry.cwd = md5Short(entry.cwd);
|
|
615
|
+
return JSON.stringify(entry);
|
|
616
|
+
} catch {
|
|
617
|
+
return line;
|
|
618
|
+
}
|
|
619
|
+
})
|
|
620
|
+
.join("\n");
|
|
621
|
+
}
|
|
622
|
+
|
|
257
623
|
/** Date of a session file: the ISO-timestamp filename prefix, else its mtime. */
|
|
258
624
|
function sessionFileDate(file: string): string {
|
|
259
625
|
const match = /^(\d{4}-\d{2}-\d{2})T/.exec(basename(file));
|
|
@@ -326,7 +692,10 @@ function readAnomalies(file: string): CacheAnomalyRecord[] {
|
|
|
326
692
|
}
|
|
327
693
|
|
|
328
694
|
function inWindow(date: string, window: DebugWindow): boolean {
|
|
329
|
-
|
|
695
|
+
// Day-granular on both sides: interval bounds are full ISO strings while
|
|
696
|
+
// session/anomaly dates are YYYY-MM-DD — comparing them raw silently
|
|
697
|
+
// dropped the whole start date (EV-2026-11-18 B4).
|
|
698
|
+
return date >= window.start.slice(0, 10) && date <= window.end.slice(0, 10);
|
|
330
699
|
}
|
|
331
700
|
|
|
332
701
|
// ── Report building ───────────────────────────────────────────────────────
|
|
@@ -334,17 +703,37 @@ function inWindow(date: string, window: DebugWindow): boolean {
|
|
|
334
703
|
export async function buildDebugReport(options: BuildDebugReportOptions = {}): Promise<DebugReport> {
|
|
335
704
|
const agentDir = options.agentDir ?? getAgentDir();
|
|
336
705
|
const now = options.now ?? new Date();
|
|
337
|
-
|
|
706
|
+
// Use flexible interval if provided, else fall back to day-count window
|
|
707
|
+
let window: DebugWindow;
|
|
708
|
+
if (options.interval) {
|
|
709
|
+
const result = parseFlexibleTime(options.interval, now);
|
|
710
|
+
if (typeof result === "object" && result !== null && "ok" in result && result.ok === false) {
|
|
711
|
+
throw new Error((result as { error: string }).error);
|
|
712
|
+
}
|
|
713
|
+
window = result as DebugWindow;
|
|
714
|
+
} else {
|
|
715
|
+
window = rollingWindow(options.windowDays ?? DEFAULT_DEBUG_WINDOW_DAYS, now);
|
|
716
|
+
}
|
|
338
717
|
const sessionsDir = options.sessionsDir ?? join(agentDir, "sessions");
|
|
339
718
|
const anomalyFile = options.anomalyFile ?? (options.agentDir ? join(agentDir, CACHE_ANOMALY_FILE) : defaultCacheAnomalyPath());
|
|
719
|
+
// Per-response cf-ray sidecar (issue #35 S11): joined onto turns below.
|
|
720
|
+
const rayByResponseId = readResponseRays(options.raysFile ?? join(agentDir, RESPONSE_RAYS_FILE));
|
|
340
721
|
|
|
341
722
|
const anomalies = readAnomalies(anomalyFile).filter((record) => inWindow(record.detected_at.slice(0, 10), window));
|
|
342
723
|
|
|
343
724
|
const turns: DebugTurn[] = [];
|
|
725
|
+
const errors: DebugErrorRecord[] = [];
|
|
344
726
|
const usages = new Map<string, DebugUsageRow>();
|
|
345
727
|
const worktreeLabels = new Set<string>();
|
|
346
728
|
const sessionIds = new Set<string>();
|
|
347
729
|
const models = new Set<string>();
|
|
730
|
+
const errorCounts: Record<DebugErrorClass, number> = {
|
|
731
|
+
overflow: 0,
|
|
732
|
+
rate_limited: 0,
|
|
733
|
+
invalid_request: 0,
|
|
734
|
+
transport: 0,
|
|
735
|
+
other: 0,
|
|
736
|
+
};
|
|
348
737
|
let reasoningOnlyCount = 0;
|
|
349
738
|
let contextOverflowCount = 0;
|
|
350
739
|
|
|
@@ -385,6 +774,7 @@ export async function buildDebugReport(options: BuildDebugReportOptions = {}): P
|
|
|
385
774
|
stop_reason: stopReason,
|
|
386
775
|
error: errorClass,
|
|
387
776
|
response_id: responseId,
|
|
777
|
+
cf_ray: responseId !== null ? (rayByResponseId.get(responseId) ?? null) : null,
|
|
388
778
|
created: null,
|
|
389
779
|
input: numberOrZero(usage.input),
|
|
390
780
|
output: numberOrZero(usage.output),
|
|
@@ -395,6 +785,26 @@ export async function buildDebugReport(options: BuildDebugReportOptions = {}): P
|
|
|
395
785
|
model_ms: numberOrZero(message.durationMs),
|
|
396
786
|
});
|
|
397
787
|
|
|
788
|
+
// Track errors separately for errors.jsonl
|
|
789
|
+
if (errorClass) {
|
|
790
|
+
const msgTruncated = errorMessage?.slice(0, 200) ?? "";
|
|
791
|
+
const msgHash = errorMessage ? createHash("md5").update(errorMessage).digest("hex").slice(0, 12) : "";
|
|
792
|
+
errors.push({
|
|
793
|
+
timestamp,
|
|
794
|
+
session_id: sessionId,
|
|
795
|
+
worktree_label: worktreeLabel,
|
|
796
|
+
model,
|
|
797
|
+
error: errorClass,
|
|
798
|
+
stop_reason: stopReason,
|
|
799
|
+
message_truncated: msgTruncated,
|
|
800
|
+
message_hash: msgHash,
|
|
801
|
+
response_id: responseId,
|
|
802
|
+
input: numberOrZero(usage.input),
|
|
803
|
+
output: numberOrZero(usage.output),
|
|
804
|
+
});
|
|
805
|
+
errorCounts[errorClass] += 1;
|
|
806
|
+
}
|
|
807
|
+
|
|
398
808
|
const key = `${dateOfTurn}\u0000${sessionId}\u0000${model}`;
|
|
399
809
|
let row = usages.get(key);
|
|
400
810
|
if (!row) {
|
|
@@ -463,6 +873,10 @@ export async function buildDebugReport(options: BuildDebugReportOptions = {}): P
|
|
|
463
873
|
prompt_response_bytes: 0,
|
|
464
874
|
credentials: 0,
|
|
465
875
|
},
|
|
876
|
+
error_summary: {
|
|
877
|
+
total: errors.length,
|
|
878
|
+
byClass: { ...errorCounts },
|
|
879
|
+
},
|
|
466
880
|
};
|
|
467
881
|
|
|
468
882
|
const report: DebugReport = {
|
|
@@ -473,11 +887,16 @@ export async function buildDebugReport(options: BuildDebugReportOptions = {}): P
|
|
|
473
887
|
turns: turns.sort((a, b) =>
|
|
474
888
|
a.timestamp === b.timestamp ? a.session_id.localeCompare(b.session_id) : a.timestamp.localeCompare(b.timestamp),
|
|
475
889
|
),
|
|
890
|
+
errors: errors.sort((a, b) => a.timestamp.localeCompare(b.timestamp)),
|
|
476
891
|
anomalies,
|
|
477
892
|
counts: {
|
|
478
893
|
sessions: sessionIds.size,
|
|
479
894
|
turns: turns.length,
|
|
480
895
|
models: [...models].sort(),
|
|
896
|
+
errors: {
|
|
897
|
+
total: errors.length,
|
|
898
|
+
byClass: { ...errorCounts },
|
|
899
|
+
},
|
|
481
900
|
anomalies: {
|
|
482
901
|
duplicateIdCreated: anomalies.length,
|
|
483
902
|
reasoningOnlyStream: reasoningOnlyCount,
|
|
@@ -524,15 +943,18 @@ function renderReadme(report: DebugReport, versions: Record<string, string>): st
|
|
|
524
943
|
"## What is collected",
|
|
525
944
|
"",
|
|
526
945
|
"- `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.",
|
|
946
|
+
"- `turns.jsonl` — one row per assistant turn: model, usage counters, stop reason, classified error, response id, `cf_ray` (Cloudflare trace id from `<agentDir>/nan-response-rays.jsonl`, null when uncaptured), `created` (null when the transcript has none), duration.",
|
|
947
|
+
"- `errors.jsonl` — one row per turn that produced an error: error class, truncated message (200 chars max), MD5 hash of the full message, input/output tokens for context.",
|
|
528
948
|
"- `anomalies.jsonl` — duplicate `id`/`created` pairs captured by the provider, with both `cf-ray` values (see issue #35).",
|
|
949
|
+
"- `sessions/` — the raw session JSONL files filtered to the window, so you can inspect the full transcript locally.",
|
|
529
950
|
"- `metadata.json` — versions, catalog provenance, window, redaction counters.",
|
|
530
951
|
"",
|
|
531
952
|
"## What is never collected",
|
|
532
953
|
"",
|
|
533
|
-
"- Prompt or response content.",
|
|
534
|
-
"- Raw file paths or worktree names (MD5
|
|
535
|
-
"- Credentials or auth headers.",
|
|
954
|
+
"- Prompt or response content in the root files — except under `sessions/`, which embeds your raw session transcripts on request (issue #44); only their `cwd` header is MD5-truncated to 12 chars.",
|
|
955
|
+
"- Raw file paths or worktree names outside transcripts (labels are MD5-truncated to 12 chars).",
|
|
956
|
+
"- Credentials or auth headers, in any file.",
|
|
957
|
+
"- Full error messages: `errors.jsonl` keeps at most 200 characters plus an MD5 hash of the full text.",
|
|
536
958
|
"",
|
|
537
959
|
"## Versions",
|
|
538
960
|
"",
|
|
@@ -543,12 +965,13 @@ function renderReadme(report: DebugReport, versions: Record<string, string>): st
|
|
|
543
965
|
].join("\n");
|
|
544
966
|
}
|
|
545
967
|
|
|
546
|
-
export function renderDebugReport(report: DebugReport): RenderedReport {
|
|
968
|
+
export function renderDebugReport(report: DebugReport, sessionsDir?: string): RenderedReport {
|
|
547
969
|
const versions = (report.metadata as { versions: Record<string, string> }).versions;
|
|
548
970
|
const files: Record<string, string> = {
|
|
549
971
|
"README.md": renderReadme(report, versions),
|
|
550
972
|
"anonymized_usage.jsonl": report.rows.map((row) => JSON.stringify(row)).join("\n") + (report.rows.length > 0 ? "\n" : ""),
|
|
551
973
|
"turns.jsonl": report.turns.map((turn) => JSON.stringify(turn)).join("\n") + (report.turns.length > 0 ? "\n" : ""),
|
|
974
|
+
"errors.jsonl": report.errors.map((err) => JSON.stringify(err)).join("\n") + (report.errors.length > 0 ? "\n" : ""),
|
|
552
975
|
"anomalies.jsonl": report.anomalies.map((record) => JSON.stringify(record)).join("\n") + (report.anomalies.length > 0 ? "\n" : ""),
|
|
553
976
|
"metadata.json": `${JSON.stringify(report.metadata, null, 2)}\n`,
|
|
554
977
|
};
|
|
@@ -556,6 +979,21 @@ export function renderDebugReport(report: DebugReport): RenderedReport {
|
|
|
556
979
|
files["usage_window.json"] = `${JSON.stringify(report.usageWindow, null, 2)}\n`;
|
|
557
980
|
}
|
|
558
981
|
|
|
982
|
+
// Include session JSONL files filtered by the window.
|
|
983
|
+
if (sessionsDir) {
|
|
984
|
+
try {
|
|
985
|
+
const sessionFiles = listSessionFilesFiltered(sessionsDir, report.window);
|
|
986
|
+
for (const file of sessionFiles) {
|
|
987
|
+
const content = readFileSync(file, "utf8");
|
|
988
|
+
const relPath = file.startsWith(sessionsDir) ? file.slice(sessionsDir.length + 1) : basename(file);
|
|
989
|
+
files[`sessions/${relPath}`] = scrubSessionTranscript(content);
|
|
990
|
+
}
|
|
991
|
+
} catch {
|
|
992
|
+
// If sessionsDir doesn't exist or can't be read, skip session files.
|
|
993
|
+
// This can happen in tests or when the directory is moved.
|
|
994
|
+
}
|
|
995
|
+
}
|
|
996
|
+
|
|
559
997
|
const perModel = report.counts.models
|
|
560
998
|
.map((model) => {
|
|
561
999
|
const rows = report.rows.filter((row) => row.model === model);
|
|
@@ -565,12 +1003,19 @@ export function renderDebugReport(report: DebugReport): RenderedReport {
|
|
|
565
1003
|
})
|
|
566
1004
|
.join(" · ");
|
|
567
1005
|
|
|
1006
|
+
const errorCounts = report.counts.errors;
|
|
1007
|
+
const errorParts = Object.entries(errorCounts.byClass)
|
|
1008
|
+
.filter(([, count]) => count > 0)
|
|
1009
|
+
.map(([kind, count]) => `${kind}: ${count}`)
|
|
1010
|
+
.join(" · ");
|
|
1011
|
+
|
|
568
1012
|
const preview = [
|
|
569
1013
|
`nan-debug report — ${report.window.start} → ${report.window.end} (window: ${report.window.days}d)`,
|
|
570
1014
|
`sessions: ${report.counts.sessions} · turns: ${report.counts.turns} · models: ${report.counts.models.length}`,
|
|
1015
|
+
`errors: ${errorCounts.total} total${errorParts.length > 0 ? ` (${errorParts})` : ""}`,
|
|
571
1016
|
`per-model avg tokens/turn: ${perModel.length > 0 ? perModel : "(none)"}`,
|
|
572
1017
|
`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`,
|
|
1018
|
+
`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 (root files; sessions/ excepted)`,
|
|
574
1019
|
"→ nothing shared yet. Run with --emit to write nan-debug-report.zip",
|
|
575
1020
|
].join("\n");
|
|
576
1021
|
|
|
@@ -580,7 +1025,9 @@ export function renderDebugReport(report: DebugReport): RenderedReport {
|
|
|
580
1025
|
export function writeDebugReport(files: Record<string, string>, outDir: string): void {
|
|
581
1026
|
mkdirSync(outDir, { recursive: true });
|
|
582
1027
|
for (const [name, content] of Object.entries(files)) {
|
|
583
|
-
|
|
1028
|
+
const filePath = join(outDir, name);
|
|
1029
|
+
mkdirSync(dirname(filePath), { recursive: true });
|
|
1030
|
+
writeFileSync(filePath, content);
|
|
584
1031
|
}
|
|
585
1032
|
}
|
|
586
1033
|
|