@gtrabanco/pi-nan-provider 1.6.1 → 1.6.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.
- package/AGENTS.md +45 -7
- package/README.es.md +70 -26
- package/README.md +64 -24
- package/package.json +1 -1
- package/scripts/models.generated.ts +4 -4
- package/src/debug-command.ts +11 -6
- package/src/debug-report.ts +464 -74
- package/src/http-attempts.ts +615 -0
- package/src/provider-factory.ts +21 -11
package/src/debug-report.ts
CHANGED
|
@@ -8,41 +8,55 @@
|
|
|
8
8
|
* the per-response ray sidecar (`nan-response-rays.jsonl`, issue #35 S11),
|
|
9
9
|
* and renders a report that can be shared verbatim.
|
|
10
10
|
*
|
|
11
|
-
* Contract (issue #35, scoped by PR #44):
|
|
11
|
+
* Contract (issue #35, scoped by PR #44 and issue #49):
|
|
12
12
|
* - no LLM, no network unless `--window` explicitly asks for `/v1/usage`;
|
|
13
|
-
* - the
|
|
14
|
-
* credentials or raw paths
|
|
15
|
-
*
|
|
16
|
-
*
|
|
13
|
+
* - the default artifact never collects prompt, response or tool content,
|
|
14
|
+
* credentials or raw paths: `sessions/` is opt-in (`--include-prompts`,
|
|
15
|
+
* tool calls stripped; `--include-tools` keeps them) and `cwd` is
|
|
16
|
+
* MD5-hashed whenever it is embedded;
|
|
17
|
+
* - session and worktree identifiers are MD5-truncated to 16 chars;
|
|
18
|
+
* - `topic` is hashed (`topic_hash`), never stored in clear;
|
|
17
19
|
* - error text in rows and the preview is reduced to a fixed class;
|
|
18
|
-
* `errors.jsonl`
|
|
19
|
-
* an MD5 hash
|
|
20
|
+
* `errors.jsonl` stores only the gateway body's own fields (message capped
|
|
21
|
+
* at 200 chars plus an MD5 hash) and never transport/local exception text;
|
|
22
|
+
* - `usage_window.json` stays local unless `--all` puts it in the zip;
|
|
20
23
|
* - the same inputs produce byte-identical zip bytes.
|
|
21
24
|
*
|
|
22
25
|
* The report layout matches the 2026-11-10 anonymized dataset: one aggregated
|
|
23
26
|
* `anonymized_usage.jsonl` row per (date, session, model), plus `turns.jsonl`
|
|
24
|
-
* with the per-turn detail the issue asks for (`response_id`, `created`
|
|
25
|
-
*
|
|
27
|
+
* with the per-turn detail the issue asks for (`response_id`, `created` and
|
|
28
|
+
* `attempt_n` joined from the HTTP attempt tap, usage, stop reason, error class)
|
|
29
|
+
* and `http_attempts.jsonl` with one row per HTTP attempt.
|
|
26
30
|
*/
|
|
27
31
|
|
|
28
32
|
import { createHash } from "node:crypto";
|
|
29
33
|
import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";
|
|
34
|
+
import { homedir as osHomedir } from "node:os";
|
|
30
35
|
import { basename, dirname, join } from "node:path";
|
|
31
36
|
import { PI_AI_VERSION } from "@earendil-works/pi-ai";
|
|
32
37
|
import { VERSION as PI_VERSION, getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
33
38
|
import { GENERATED_CATALOG_META } from "../scripts/models.generated.ts";
|
|
34
39
|
import { CACHE_ANOMALY_FILE, defaultCacheAnomalyPath, type CacheAnomalyRecord } from "./cache-anomaly.ts";
|
|
40
|
+
import {
|
|
41
|
+
HTTP_ATTEMPTS_FILE,
|
|
42
|
+
defaultHttpAttemptPath,
|
|
43
|
+
readHttpAttempts,
|
|
44
|
+
type HttpAttemptEntry,
|
|
45
|
+
type HttpAttemptRecord,
|
|
46
|
+
type HttpResponseRecord,
|
|
47
|
+
} from "./http-attempts.ts";
|
|
35
48
|
import { RESPONSE_RAYS_FILE, readResponseRays } from "./response-rays.ts";
|
|
36
49
|
import { fetchUsageReport, rollingWindow, type UsageWindow } from "./usage.ts";
|
|
37
50
|
import { createZip } from "./zip.ts";
|
|
38
51
|
|
|
39
52
|
export const DEFAULT_DEBUG_WINDOW_DAYS = 7;
|
|
40
53
|
export const MAX_DEBUG_WINDOW_DAYS = 90;
|
|
41
|
-
|
|
42
|
-
|
|
54
|
+
|
|
55
|
+
/** Prefix of the default report directory and zip names. */
|
|
56
|
+
export const NAN_DEBUG_REPORT_PREFIX = "nan-debug-report";
|
|
43
57
|
|
|
44
58
|
export const DEBUG_USAGE_LINE =
|
|
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.";
|
|
59
|
+
"Usage: /nan-debug [topic] [--window N] [--interval FLEXIBLE] [--out file] [--emit] [--include-prompts] [--include-tools] [--all] — collects a redacted NaN evidence report locally; --emit writes the shareable zip.\n\nContent flags: default shares no prompt/response/tool content; --include-prompts embeds raw transcripts; --include-tools also keeps tool calls/results; --all equals both plus usage_window.json.\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.";
|
|
46
60
|
|
|
47
61
|
/** A flexible time window with ISO-capable boundaries (YYYY-MM-DD or full ISO 8601). */
|
|
48
62
|
export interface DebugWindow {
|
|
@@ -74,6 +88,29 @@ export interface SinglePoint {
|
|
|
74
88
|
point: string; // ISO string
|
|
75
89
|
}
|
|
76
90
|
|
|
91
|
+
// ── Artifact naming ───────────────────────────────────────────────────────
|
|
92
|
+
|
|
93
|
+
function utcStamp(now: Date, separator: string): string {
|
|
94
|
+
const iso = now.toISOString();
|
|
95
|
+
// YYYY-MM-DDTHH:mm:ss in UTC; the date and time parts are already fixed-width.
|
|
96
|
+
return `${iso.slice(0, 10)}T${iso.slice(11, 19).replace(/:/g, separator)}`;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Default report directory name: `nan-debug-report-YYYY-MM-DDTHH:mm:ss` (UTC).
|
|
101
|
+
* `:` is legal in a POSIX directory name but not on Windows, so the separator
|
|
102
|
+
* follows the platform. The emission timestamp distinguishes runs; the
|
|
103
|
+
* reported window lives in `metadata.window`.
|
|
104
|
+
*/
|
|
105
|
+
export function debugReportDirName(now: Date, platform: NodeJS.Platform = process.platform): string {
|
|
106
|
+
return `${NAN_DEBUG_REPORT_PREFIX}-${utcStamp(now, platform === "win32" ? "-" : ":")}`;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** Default zip name: the same stamp with `:` sanitized, since zip readers and Windows both dislike it. */
|
|
110
|
+
export function debugReportZipName(now: Date): string {
|
|
111
|
+
return `${NAN_DEBUG_REPORT_PREFIX}-${utcStamp(now, "-")}.zip`;
|
|
112
|
+
}
|
|
113
|
+
|
|
77
114
|
// ── Argument parsing ──────────────────────────────────────────────────────
|
|
78
115
|
|
|
79
116
|
export interface DebugArgs {
|
|
@@ -86,6 +123,12 @@ export interface DebugArgs {
|
|
|
86
123
|
interval?: string;
|
|
87
124
|
out?: string;
|
|
88
125
|
emit: boolean;
|
|
126
|
+
/** Embed raw transcripts (prompts and responses) in `sessions/`. */
|
|
127
|
+
includePrompts: boolean;
|
|
128
|
+
/** Also keep tool calls and their results; implies `includePrompts`. */
|
|
129
|
+
includeTools: boolean;
|
|
130
|
+
/** `--include-prompts --include-tools`, plus `usage_window.json` in the zip. */
|
|
131
|
+
all: boolean;
|
|
89
132
|
}
|
|
90
133
|
|
|
91
134
|
export type ParseDebugArgsResult = { ok: true; args: DebugArgs } | { ok: false; error: string };
|
|
@@ -95,7 +138,14 @@ const TOPIC_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,31}$/;
|
|
|
95
138
|
/** Parse `/nan-debug` arguments. Deterministic; no filesystem or clock access. */
|
|
96
139
|
export function parseDebugArgs(input: string): ParseDebugArgsResult {
|
|
97
140
|
const tokens = input.trim().split(/\s+/).filter(Boolean);
|
|
98
|
-
const args: DebugArgs = {
|
|
141
|
+
const args: DebugArgs = {
|
|
142
|
+
windowDays: DEFAULT_DEBUG_WINDOW_DAYS,
|
|
143
|
+
windowProvided: false,
|
|
144
|
+
emit: false,
|
|
145
|
+
includePrompts: false,
|
|
146
|
+
includeTools: false,
|
|
147
|
+
all: false,
|
|
148
|
+
};
|
|
99
149
|
|
|
100
150
|
for (let i = 0; i < tokens.length; i++) {
|
|
101
151
|
const token = tokens[i]!;
|
|
@@ -103,6 +153,22 @@ export function parseDebugArgs(input: string): ParseDebugArgsResult {
|
|
|
103
153
|
args.emit = true;
|
|
104
154
|
continue;
|
|
105
155
|
}
|
|
156
|
+
if (token === "--include-prompts") {
|
|
157
|
+
args.includePrompts = true;
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
if (token === "--include-tools") {
|
|
161
|
+
// "incluye además": tool calls only exist inside a transcript.
|
|
162
|
+
args.includeTools = true;
|
|
163
|
+
args.includePrompts = true;
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
if (token === "--all") {
|
|
167
|
+
args.all = true;
|
|
168
|
+
args.includePrompts = true;
|
|
169
|
+
args.includeTools = true;
|
|
170
|
+
continue;
|
|
171
|
+
}
|
|
106
172
|
if (token === "--window") {
|
|
107
173
|
const value = tokens[i + 1];
|
|
108
174
|
if (value === undefined) return { ok: false, error: `--window needs a day count (1-${MAX_DEBUG_WINDOW_DAYS}). ${DEBUG_USAGE_LINE}` };
|
|
@@ -406,8 +472,10 @@ const ERROR_PATTERNS: ReadonlyArray<readonly [DebugErrorClass, RegExp]> = [
|
|
|
406
472
|
|
|
407
473
|
/**
|
|
408
474
|
* Map a raw `errorMessage` to a fixed class. Rows, previews and aggregates
|
|
409
|
-
* only ever see this class;
|
|
410
|
-
* `errors.jsonl`'s 200-character fragment plus its MD5 hash
|
|
475
|
+
* only ever see this class; a raw message reaches the report solely as
|
|
476
|
+
* `errors.jsonl`'s 200-character fragment plus its MD5 hash, and only when it
|
|
477
|
+
* is a gateway error body (PR #44; scoped by issue #49 — transport/local
|
|
478
|
+
* exception text never reaches the report).
|
|
411
479
|
*/
|
|
412
480
|
export function classifyErrorMessage(message: string | undefined): DebugErrorClass | null {
|
|
413
481
|
if (typeof message !== "string" || message.length === 0) return null;
|
|
@@ -453,7 +521,14 @@ export interface DebugTurn {
|
|
|
453
521
|
response_id: string | null;
|
|
454
522
|
/** Cloudflare trace id joined from the response-ray sidecar; null when uncaptured. */
|
|
455
523
|
cf_ray: string | null;
|
|
524
|
+
/** Gateway `created` joined from the attempt tap; null when not observed. */
|
|
456
525
|
created: number | null;
|
|
526
|
+
/** HTTP status of the terminal attempt; null when no attempt was observed. */
|
|
527
|
+
status: number | null;
|
|
528
|
+
/** Attempts the logical request made (retries included); null when unobserved. */
|
|
529
|
+
attempt_n: number | null;
|
|
530
|
+
/** Request parameters of that logical request; null when unobserved. */
|
|
531
|
+
request: DebugRequestParams | null;
|
|
457
532
|
input: number;
|
|
458
533
|
output: number;
|
|
459
534
|
cache_read: number;
|
|
@@ -478,13 +553,21 @@ export interface DebugCounts {
|
|
|
478
553
|
};
|
|
479
554
|
}
|
|
480
555
|
|
|
556
|
+
/** Request parameters carried by `turns.jsonl` (issue #49 S13). */
|
|
557
|
+
export interface DebugRequestParams {
|
|
558
|
+
reasoning_effort: string | null;
|
|
559
|
+
max_tokens: number | null;
|
|
560
|
+
max_tokens_field: "max_tokens" | "max_completion_tokens" | null;
|
|
561
|
+
stream: boolean | null;
|
|
562
|
+
}
|
|
563
|
+
|
|
481
564
|
/** One row per turn that had an error — written to errors.jsonl. */
|
|
482
565
|
export interface DebugErrorRecord {
|
|
483
566
|
/** ISO 8601 timestamp of the turn. */
|
|
484
567
|
timestamp: string;
|
|
485
|
-
/** MD5[
|
|
568
|
+
/** MD5[16] of the session file. */
|
|
486
569
|
session_id: string;
|
|
487
|
-
/** MD5[
|
|
570
|
+
/** MD5[16] of the worktree cwd. */
|
|
488
571
|
worktree_label: string;
|
|
489
572
|
/** Model that returned the error. */
|
|
490
573
|
model: string;
|
|
@@ -492,10 +575,22 @@ export interface DebugErrorRecord {
|
|
|
492
575
|
error: DebugErrorClass;
|
|
493
576
|
/** The stop reason (usually "error"). */
|
|
494
577
|
stop_reason: string;
|
|
495
|
-
/**
|
|
496
|
-
|
|
497
|
-
/**
|
|
498
|
-
|
|
578
|
+
/** HTTP status of the terminal attempt, when the tap observed one. */
|
|
579
|
+
status: number | null;
|
|
580
|
+
/** `cf-ray` of the terminal attempt, when observed. */
|
|
581
|
+
cf_ray: string | null;
|
|
582
|
+
/** Attempts of that logical request, when correlated. */
|
|
583
|
+
attempt_n: number | null;
|
|
584
|
+
/** The gateway error body, truncated to 200 chars; null when absent. */
|
|
585
|
+
message_truncated: string | null;
|
|
586
|
+
/** MD5[16] of the full gateway message; null when absent. */
|
|
587
|
+
message_hash: string | null;
|
|
588
|
+
/** `error.type` from an OpenAI-style gateway body. */
|
|
589
|
+
error_type: string | null;
|
|
590
|
+
/** `error.code` from an OpenAI-style gateway body. */
|
|
591
|
+
error_code: string | null;
|
|
592
|
+
/** `error.param` from an OpenAI-style gateway body. */
|
|
593
|
+
error_param: string | null;
|
|
499
594
|
/** Response id if present. */
|
|
500
595
|
response_id: string | null;
|
|
501
596
|
/** Input tokens for context. */
|
|
@@ -512,6 +607,8 @@ export interface DebugReport {
|
|
|
512
607
|
turns: DebugTurn[];
|
|
513
608
|
errors: DebugErrorRecord[];
|
|
514
609
|
anomalies: CacheAnomalyRecord[];
|
|
610
|
+
/** Window-filtered attempt/response rows embedded as `http_attempts.jsonl`. */
|
|
611
|
+
httpAttempts: HttpAttemptEntry[];
|
|
515
612
|
counts: DebugCounts;
|
|
516
613
|
metadata: Record<string, unknown>;
|
|
517
614
|
usageWindow?: unknown;
|
|
@@ -534,13 +631,19 @@ export interface BuildDebugReportOptions {
|
|
|
534
631
|
anomalyFile?: string;
|
|
535
632
|
/** Per-response ray sidecar; defaults to the agent-dir file (issue #35 S11). */
|
|
536
633
|
raysFile?: string;
|
|
634
|
+
/** HTTP attempt sidecar; defaults to the agent-dir file (issue #49). */
|
|
635
|
+
attemptsFile?: string;
|
|
537
636
|
sessionsDir?: string;
|
|
538
637
|
}
|
|
539
638
|
|
|
540
639
|
// ── Helpers ───────────────────────────────────────────────────────────────
|
|
541
640
|
|
|
542
641
|
function md5Short(value: string): string {
|
|
543
|
-
return createHash("md5").update(value).digest("hex").slice(0,
|
|
642
|
+
return createHash("md5").update(value).digest("hex").slice(0, 16);
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
function isObject(value: unknown): value is Record<string, unknown> {
|
|
646
|
+
return typeof value === "object" && value !== null;
|
|
544
647
|
}
|
|
545
648
|
|
|
546
649
|
function numberOrZero(value: unknown): number {
|
|
@@ -597,29 +700,6 @@ function listSessionFilesFiltered(root: string, window: DebugWindow): string[] {
|
|
|
597
700
|
});
|
|
598
701
|
}
|
|
599
702
|
|
|
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
|
-
|
|
623
703
|
/** Date of a session file: the ISO-timestamp filename prefix, else its mtime. */
|
|
624
704
|
function sessionFileDate(file: string): string {
|
|
625
705
|
const match = /^(\d{4}-\d{2}-\d{2})T/.exec(basename(file));
|
|
@@ -698,6 +778,171 @@ function inWindow(date: string, window: DebugWindow): boolean {
|
|
|
698
778
|
return date >= window.start.slice(0, 10) && date <= window.end.slice(0, 10);
|
|
699
779
|
}
|
|
700
780
|
|
|
781
|
+
function readAttempts(file: string): HttpAttemptEntry[] {
|
|
782
|
+
try {
|
|
783
|
+
return readHttpAttempts(file);
|
|
784
|
+
} catch {
|
|
785
|
+
return [];
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
/**
|
|
790
|
+
* Parse an OpenAI-style gateway error body out of a transcript `errorMessage`.
|
|
791
|
+
* pi-ai may prefix the JSON with its own status text, so the first `{` to the
|
|
792
|
+
* last `}` is tried. Returns null when the text is not a gateway error body —
|
|
793
|
+
* local exception text is never reinterpreted as one.
|
|
794
|
+
*/
|
|
795
|
+
export function parseGatewayError(message: string | undefined): {
|
|
796
|
+
type: string | null;
|
|
797
|
+
code: string | null;
|
|
798
|
+
param: string | null;
|
|
799
|
+
message: string | null;
|
|
800
|
+
} | null {
|
|
801
|
+
if (typeof message !== "string" || message.length === 0) return null;
|
|
802
|
+
const start = message.indexOf("{");
|
|
803
|
+
const end = message.lastIndexOf("}");
|
|
804
|
+
if (start === -1 || end <= start) return null;
|
|
805
|
+
try {
|
|
806
|
+
const parsed = JSON.parse(message.slice(start, end + 1)) as unknown;
|
|
807
|
+
if (!isObject(parsed)) return null;
|
|
808
|
+
// Two shapes reach the transcript: the raw HTTP body wraps the error in
|
|
809
|
+
// `error`, while pi-ai's `formatProviderError` writes the inner object
|
|
810
|
+
// directly after the status (`429: {"message":…,"type":…,"code":…}`).
|
|
811
|
+
const error = isObject(parsed.error) ? parsed.error : parsed;
|
|
812
|
+
const type = typeof error.type === "string" ? error.type : null;
|
|
813
|
+
const code = typeof error.code === "string" ? error.code : null;
|
|
814
|
+
const param = typeof error.param === "string" ? error.param : null;
|
|
815
|
+
const text = typeof error.message === "string" ? error.message : null;
|
|
816
|
+
if (type === null && code === null && text === null) return null;
|
|
817
|
+
return { type, code, param, message: text };
|
|
818
|
+
} catch {
|
|
819
|
+
return null;
|
|
820
|
+
}
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
/**
|
|
824
|
+
* Replace the user's home directory with `~` so a surviving free-text fragment
|
|
825
|
+
* cannot leak the account name or a project path (issue #49 S26).
|
|
826
|
+
*/
|
|
827
|
+
export function scrubHome(text: string, home: string = osHomedir()): string {
|
|
828
|
+
if (home.length === 0) return text;
|
|
829
|
+
// Require a path boundary so `/home/agent2` is never rewritten as `~2`.
|
|
830
|
+
const escaped = home.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
831
|
+
return text.replace(new RegExp(`${escaped}(?=/|$)`, "g"), "~");
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
/**
|
|
835
|
+
* Correlate an errored turn with the terminal attempt of its logical request.
|
|
836
|
+
* pi's transcript records no response id for a failed request, so the join is
|
|
837
|
+
* model + the turn's own span: an attempt that ended while the turn was
|
|
838
|
+
* running, extended by pi-ai's 60 s max server-requested retry delay. No match
|
|
839
|
+
* means null, never a guess.
|
|
840
|
+
*/
|
|
841
|
+
export function findTerminalAttempt(
|
|
842
|
+
attempts: readonly HttpAttemptRecord[],
|
|
843
|
+
model: string,
|
|
844
|
+
turnEndMs: number,
|
|
845
|
+
durationMs: number,
|
|
846
|
+
): HttpAttemptRecord | null {
|
|
847
|
+
const lower = turnEndMs - Math.max(0, durationMs) - 65_000;
|
|
848
|
+
const upper = turnEndMs + 2_000;
|
|
849
|
+
let best: HttpAttemptRecord | null = null;
|
|
850
|
+
for (const attempt of attempts) {
|
|
851
|
+
if (attempt.model !== model) continue;
|
|
852
|
+
const ended = Date.parse(attempt.ended_at);
|
|
853
|
+
if (!Number.isFinite(ended) || ended < lower || ended > upper) continue;
|
|
854
|
+
if (!best) {
|
|
855
|
+
best = attempt;
|
|
856
|
+
continue;
|
|
857
|
+
}
|
|
858
|
+
const bestEnded = Date.parse(best.ended_at);
|
|
859
|
+
if (ended > bestEnded || (ended === bestEnded && attempt.attempt_n > best.attempt_n)) best = attempt;
|
|
860
|
+
}
|
|
861
|
+
return best;
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
interface AttemptSummary {
|
|
865
|
+
total: number;
|
|
866
|
+
by_status: Record<string, number>;
|
|
867
|
+
by_model: Array<{ model: string; attempts: number; rate_limited: number; rate_limited_pct: number }>;
|
|
868
|
+
by_model_hour: Array<{
|
|
869
|
+
model: string;
|
|
870
|
+
hour: string;
|
|
871
|
+
attempts: number;
|
|
872
|
+
rate_limited: number;
|
|
873
|
+
rate_limited_pct: number;
|
|
874
|
+
}>;
|
|
875
|
+
longest_429_streak: { model: string; length: number; started_at: string; ended_at: string } | null;
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
function pct(part: number, total: number): number {
|
|
879
|
+
return total > 0 ? Math.round((part / total) * 1000) / 10 : 0;
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
/** CSV-style aggregates over the window's attempts (issue #49 S14). */
|
|
883
|
+
export function summarizeAttempts(attempts: readonly HttpAttemptRecord[]): AttemptSummary {
|
|
884
|
+
const ordered = [...attempts].sort((a, b) => a.started_at.localeCompare(b.started_at));
|
|
885
|
+
const byStatus: Record<string, number> = {};
|
|
886
|
+
const perModel = new Map<string, { attempts: number; rateLimited: number }>();
|
|
887
|
+
const perModelHour = new Map<string, { model: string; hour: string; attempts: number; rateLimited: number }>();
|
|
888
|
+
|
|
889
|
+
for (const attempt of ordered) {
|
|
890
|
+
const statusKey = attempt.status === null ? "null" : String(attempt.status);
|
|
891
|
+
byStatus[statusKey] = (byStatus[statusKey] ?? 0) + 1;
|
|
892
|
+
const model = perModel.get(attempt.model) ?? { attempts: 0, rateLimited: 0 };
|
|
893
|
+
model.attempts += 1;
|
|
894
|
+
if (attempt.status === 429) model.rateLimited += 1;
|
|
895
|
+
perModel.set(attempt.model, model);
|
|
896
|
+
|
|
897
|
+
const hour = attempt.started_at.slice(0, 13);
|
|
898
|
+
const key = `${attempt.model}\u0000${hour}`;
|
|
899
|
+
const bucket = perModelHour.get(key) ?? { model: attempt.model, hour, attempts: 0, rateLimited: 0 };
|
|
900
|
+
bucket.attempts += 1;
|
|
901
|
+
if (attempt.status === 429) bucket.rateLimited += 1;
|
|
902
|
+
perModelHour.set(key, bucket);
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
// Longest run of consecutive 429s per model, in start order.
|
|
906
|
+
let streak: AttemptSummary["longest_429_streak"] = null;
|
|
907
|
+
let current: { model: string; length: number; started_at: string; ended_at: string } | null = null;
|
|
908
|
+
for (const attempt of ordered) {
|
|
909
|
+
if (attempt.status === 429) {
|
|
910
|
+
if (current && current.model === attempt.model) {
|
|
911
|
+
current.length += 1;
|
|
912
|
+
current.ended_at = attempt.ended_at;
|
|
913
|
+
} else {
|
|
914
|
+
current = { model: attempt.model, length: 1, started_at: attempt.started_at, ended_at: attempt.ended_at };
|
|
915
|
+
}
|
|
916
|
+
if (!streak || current.length > streak.length) streak = { ...current };
|
|
917
|
+
} else {
|
|
918
|
+
current = null;
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
return {
|
|
923
|
+
total: ordered.length,
|
|
924
|
+
by_status: byStatus,
|
|
925
|
+
by_model: [...perModel.entries()]
|
|
926
|
+
.map(([model, counts]) => ({
|
|
927
|
+
model,
|
|
928
|
+
attempts: counts.attempts,
|
|
929
|
+
rate_limited: counts.rateLimited,
|
|
930
|
+
rate_limited_pct: pct(counts.rateLimited, counts.attempts),
|
|
931
|
+
}))
|
|
932
|
+
.sort((a, b) => a.model.localeCompare(b.model)),
|
|
933
|
+
by_model_hour: [...perModelHour.values()]
|
|
934
|
+
.map((bucket) => ({
|
|
935
|
+
model: bucket.model,
|
|
936
|
+
hour: bucket.hour,
|
|
937
|
+
attempts: bucket.attempts,
|
|
938
|
+
rate_limited: bucket.rateLimited,
|
|
939
|
+
rate_limited_pct: pct(bucket.rateLimited, bucket.attempts),
|
|
940
|
+
}))
|
|
941
|
+
.sort((a, b) => (a.hour === b.hour ? a.model.localeCompare(b.model) : a.hour.localeCompare(b.hour))),
|
|
942
|
+
longest_429_streak: streak,
|
|
943
|
+
};
|
|
944
|
+
}
|
|
945
|
+
|
|
701
946
|
// ── Report building ───────────────────────────────────────────────────────
|
|
702
947
|
|
|
703
948
|
export async function buildDebugReport(options: BuildDebugReportOptions = {}): Promise<DebugReport> {
|
|
@@ -721,6 +966,16 @@ export async function buildDebugReport(options: BuildDebugReportOptions = {}): P
|
|
|
721
966
|
|
|
722
967
|
const anomalies = readAnomalies(anomalyFile).filter((record) => inWindow(record.detected_at.slice(0, 10), window));
|
|
723
968
|
|
|
969
|
+
// HTTP attempt tap (issue #49): one row per attempt plus one per response.
|
|
970
|
+
const attemptEntries = readAttempts(
|
|
971
|
+
options.attemptsFile ?? (options.agentDir ? join(agentDir, HTTP_ATTEMPTS_FILE) : defaultHttpAttemptPath()),
|
|
972
|
+
).filter((entry) => inWindow((entry.kind === "attempt" ? entry.started_at : entry.ended_at).slice(0, 10), window));
|
|
973
|
+
const attemptsOnly = attemptEntries.filter((entry): entry is HttpAttemptRecord => entry.kind === "attempt");
|
|
974
|
+
const responseByResponseId = new Map<string, HttpResponseRecord>();
|
|
975
|
+
for (const entry of attemptEntries) {
|
|
976
|
+
if (entry.kind === "response" && entry.response_id) responseByResponseId.set(entry.response_id, entry);
|
|
977
|
+
}
|
|
978
|
+
|
|
724
979
|
const turns: DebugTurn[] = [];
|
|
725
980
|
const errors: DebugErrorRecord[] = [];
|
|
726
981
|
const usages = new Map<string, DebugUsageRow>();
|
|
@@ -744,7 +999,7 @@ export async function buildDebugReport(options: BuildDebugReportOptions = {}): P
|
|
|
744
999
|
if (rawTurns.length === 0) continue;
|
|
745
1000
|
|
|
746
1001
|
const sessionId = md5Short(file);
|
|
747
|
-
const worktreeLabel = cwd ? md5Short(cwd) : "
|
|
1002
|
+
const worktreeLabel = cwd ? md5Short(cwd) : "0000000000000000";
|
|
748
1003
|
sessionIds.add(sessionId);
|
|
749
1004
|
worktreeLabels.add(worktreeLabel);
|
|
750
1005
|
|
|
@@ -762,6 +1017,19 @@ export async function buildDebugReport(options: BuildDebugReportOptions = {}): P
|
|
|
762
1017
|
? raw.timestamp
|
|
763
1018
|
: new Date(numberOrZero(message.timestamp)).toISOString();
|
|
764
1019
|
const dateOfTurn = isoDateOf(timestamp) ?? date;
|
|
1020
|
+
const durationMs = numberOrZero(message.durationMs);
|
|
1021
|
+
|
|
1022
|
+
// A successful logical request joins by response id: the tap's
|
|
1023
|
+
// `response` row carries the gateway `created`, terminal status,
|
|
1024
|
+
// attempt count and request parameters the transcript never had.
|
|
1025
|
+
const responseRow = responseId !== null ? (responseByResponseId.get(responseId) ?? null) : null;
|
|
1026
|
+
const terminalForResponse =
|
|
1027
|
+
responseRow !== null
|
|
1028
|
+
? (attemptsOnly.find(
|
|
1029
|
+
(attempt) =>
|
|
1030
|
+
attempt.request_id === responseRow.request_id && attempt.attempt_n === responseRow.attempts,
|
|
1031
|
+
) ?? null)
|
|
1032
|
+
: null;
|
|
765
1033
|
|
|
766
1034
|
models.add(model);
|
|
767
1035
|
turns.push({
|
|
@@ -774,21 +1042,30 @@ export async function buildDebugReport(options: BuildDebugReportOptions = {}): P
|
|
|
774
1042
|
stop_reason: stopReason,
|
|
775
1043
|
error: errorClass,
|
|
776
1044
|
response_id: responseId,
|
|
777
|
-
cf_ray:
|
|
778
|
-
|
|
1045
|
+
cf_ray:
|
|
1046
|
+
responseId !== null
|
|
1047
|
+
? (rayByResponseId.get(responseId) ?? terminalForResponse?.headers["cf-ray"] ?? null)
|
|
1048
|
+
: null,
|
|
1049
|
+
created: responseRow?.created ?? null,
|
|
1050
|
+
status: responseRow?.status ?? null,
|
|
1051
|
+
attempt_n: responseRow?.attempts ?? null,
|
|
1052
|
+
request: responseRow?.request ?? null,
|
|
779
1053
|
input: numberOrZero(usage.input),
|
|
780
1054
|
output: numberOrZero(usage.output),
|
|
781
1055
|
cache_read: numberOrZero(usage.cacheRead),
|
|
782
1056
|
cache_write: numberOrZero(usage.cacheWrite),
|
|
783
1057
|
reasoning: numberOrZero(usage.reasoning),
|
|
784
1058
|
total: numberOrZero(usage.totalTokens),
|
|
785
|
-
model_ms:
|
|
1059
|
+
model_ms: durationMs,
|
|
786
1060
|
});
|
|
787
1061
|
|
|
788
|
-
// Track errors separately for errors.jsonl
|
|
1062
|
+
// Track errors separately for errors.jsonl. A failed logical request
|
|
1063
|
+
// has no response id, so the terminal attempt is correlated by model
|
|
1064
|
+
// and the turn's own span; no match leaves the cells null.
|
|
789
1065
|
if (errorClass) {
|
|
790
|
-
const
|
|
791
|
-
const
|
|
1066
|
+
const terminal = findTerminalAttempt(attemptsOnly, model, Date.parse(timestamp), durationMs);
|
|
1067
|
+
const gatewayError = parseGatewayError(errorMessage);
|
|
1068
|
+
const serverMessage = gatewayError?.message ? scrubHome(gatewayError.message) : null;
|
|
792
1069
|
errors.push({
|
|
793
1070
|
timestamp,
|
|
794
1071
|
session_id: sessionId,
|
|
@@ -796,8 +1073,14 @@ export async function buildDebugReport(options: BuildDebugReportOptions = {}): P
|
|
|
796
1073
|
model,
|
|
797
1074
|
error: errorClass,
|
|
798
1075
|
stop_reason: stopReason,
|
|
799
|
-
|
|
800
|
-
|
|
1076
|
+
status: terminal?.status ?? null,
|
|
1077
|
+
cf_ray: terminal?.headers["cf-ray"] ?? null,
|
|
1078
|
+
attempt_n: terminal?.attempt_n ?? null,
|
|
1079
|
+
message_truncated: serverMessage !== null ? serverMessage.slice(0, 200) : null,
|
|
1080
|
+
message_hash: serverMessage !== null && errorMessage ? md5Short(errorMessage) : null,
|
|
1081
|
+
error_type: gatewayError?.type ?? terminal?.error_type ?? null,
|
|
1082
|
+
error_code: gatewayError?.code ?? terminal?.error_code ?? null,
|
|
1083
|
+
error_param: gatewayError?.param ?? null,
|
|
801
1084
|
response_id: responseId,
|
|
802
1085
|
input: numberOrZero(usage.input),
|
|
803
1086
|
output: numberOrZero(usage.output),
|
|
@@ -858,7 +1141,9 @@ export async function buildDebugReport(options: BuildDebugReportOptions = {}): P
|
|
|
858
1141
|
const versions = { provider: packageVersion(), pi_ai: PI_AI_VERSION, pi: PI_VERSION };
|
|
859
1142
|
const metadata: Record<string, unknown> = {
|
|
860
1143
|
generated_at: generatedAt,
|
|
861
|
-
|
|
1144
|
+
// Free text: hashed so a descriptive topic cannot name a client or project
|
|
1145
|
+
// in the shared artifact (issue #49 S25).
|
|
1146
|
+
topic_hash: options.topic ? md5Short(options.topic) : null,
|
|
862
1147
|
window,
|
|
863
1148
|
versions,
|
|
864
1149
|
catalog: {
|
|
@@ -877,6 +1162,7 @@ export async function buildDebugReport(options: BuildDebugReportOptions = {}): P
|
|
|
877
1162
|
total: errors.length,
|
|
878
1163
|
byClass: { ...errorCounts },
|
|
879
1164
|
},
|
|
1165
|
+
attempt_summary: summarizeAttempts(attemptsOnly),
|
|
880
1166
|
};
|
|
881
1167
|
|
|
882
1168
|
const report: DebugReport = {
|
|
@@ -889,6 +1175,7 @@ export async function buildDebugReport(options: BuildDebugReportOptions = {}): P
|
|
|
889
1175
|
),
|
|
890
1176
|
errors: errors.sort((a, b) => a.timestamp.localeCompare(b.timestamp)),
|
|
891
1177
|
anomalies,
|
|
1178
|
+
httpAttempts: attemptEntries,
|
|
892
1179
|
counts: {
|
|
893
1180
|
sessions: sessionIds.size,
|
|
894
1181
|
turns: turns.length,
|
|
@@ -931,30 +1218,61 @@ export interface RenderedReport {
|
|
|
931
1218
|
preview: string;
|
|
932
1219
|
}
|
|
933
1220
|
|
|
1221
|
+
/** Opt-in content flags; the default artifact carries no prompt or tool content. */
|
|
1222
|
+
export interface DebugRenderOptions {
|
|
1223
|
+
/** Embed the window-filtered raw transcripts under `sessions/`. */
|
|
1224
|
+
includePrompts?: boolean;
|
|
1225
|
+
/** Keep tool calls and their results; implies `includePrompts`. */
|
|
1226
|
+
includeTools?: boolean;
|
|
1227
|
+
}
|
|
1228
|
+
|
|
934
1229
|
function renderReadme(report: DebugReport, versions: Record<string, string>): string {
|
|
1230
|
+
const topic = report.topic ? "(hashed for sharing)" : "(none)";
|
|
935
1231
|
return [
|
|
936
1232
|
"# nan-debug report",
|
|
937
1233
|
"",
|
|
938
|
-
`Generated by \`/nan-debug\` (issue #35) on ${report.generatedAt}. Local-only: nothing was uploaded.`,
|
|
1234
|
+
`Generated by \`/nan-debug\` (issue #35; HTTP attempt evidence from issue #49) on ${report.generatedAt}. Local-only: nothing was uploaded.`,
|
|
1235
|
+
`Artifact name: ${NAN_DEBUG_REPORT_PREFIX}-<emission timestamp, UTC> — the name identifies when the report was emitted, not the window it reports.`,
|
|
939
1236
|
"",
|
|
940
1237
|
`Window: ${report.window.start} → ${report.window.end} (${report.window.days}d)`,
|
|
941
|
-
`Topic: ${
|
|
1238
|
+
`Topic: ${topic}`,
|
|
942
1239
|
"",
|
|
943
1240
|
"## What is collected",
|
|
944
1241
|
"",
|
|
945
1242
|
"- `anonymized_usage.jsonl` — one aggregated row per date/session/model: token counters, turn count, stop-reason counts, cache-hit rate, anomaly signatures.",
|
|
946
|
-
"- `turns.jsonl` — one row per assistant turn: model, usage counters, stop reason, classified error, response id, `cf_ray` (Cloudflare trace id
|
|
947
|
-
"- `errors.jsonl` — one row per turn
|
|
1243
|
+
"- `turns.jsonl` — one row per assistant turn: model, usage counters, stop reason, classified error, response id, `cf_ray` (Cloudflare trace id, null when uncaptured), gateway `created`, terminal `status`, `attempt_n`, and the request parameters (`reasoning_effort`, `max_tokens`, the field actually sent, `stream`).",
|
|
1244
|
+
"- `errors.jsonl` — one row per errored turn: class, `status`, `cf_ray`, `attempt_n`, the parsed gateway body (`error_type`, `error_code`, `error_param`), its message (200 chars max) and the MD5 hash of the full message. Transport errors carry no message, hash or path. A failed request has no response id, so those three attempt cells are correlated by model and the turn's own span; with concurrent requests to the same model treat them as best-effort — `http_attempts.jsonl` is the authoritative per-attempt record.",
|
|
1245
|
+
"- `http_attempts.jsonl` — one `kind: \"attempt\"` row per HTTP attempt: `status`, the gateway `error_type`/`error_code` parsed from a non-2xx body, whitelisted response headers, `started_at`/`ended_at`/`time_to_header_ms` (start → headers: the early-rejection signal, not the body read), `attempt_n`, `payload_bytes`, request parameters and the process-scoped inflight/60 s counters. `transport_error` is the fetch-rejection class (`TypeError`, `AbortError`, …), never its message. One `kind: \"response\"` row per completed request carries the gateway `response_id`/`created`, the terminal `status`, the attempt count, `duration_ms` (first attempt start → completion, retries included), the token `usage` (`prompt_tokens`/`completion_tokens`/`reasoning_tokens`/`cache_read_tokens`) and the raw `finish_reason`. Retries pi-ai hides from the transcript are rows here.",
|
|
948
1246
|
"- `anomalies.jsonl` — duplicate `id`/`created` pairs captured by the provider, with both `cf-ray` values (see issue #35).",
|
|
949
|
-
"- `
|
|
950
|
-
"- `metadata.json` — versions, catalog provenance, window, redaction counters.",
|
|
1247
|
+
"- `metadata.json` — versions, catalog provenance, window, `topic_hash`, redaction counters and `attempt_summary` (status counts, 429 ratio per model and per model-hour, longest 429 streak).",
|
|
951
1248
|
"",
|
|
952
1249
|
"## What is never collected",
|
|
953
1250
|
"",
|
|
954
|
-
"- Prompt or
|
|
955
|
-
"-
|
|
956
|
-
"-
|
|
957
|
-
"-
|
|
1251
|
+
"- Prompt, response or tool content unless you opt in: `--include-prompts` embeds the window-filtered raw transcripts under `sessions/` with tool calls and results stripped; `--include-tools` keeps them; `--all` equals both and also includes `usage_window.json`.",
|
|
1252
|
+
"- Credentials, auth headers, or any response header outside the whitelist (`cf-ray`, `x-request-id`, `retry-after`, `retry-after-ms`, `x-should-retry`, `rate-limit-*`).",
|
|
1253
|
+
"- Request or response bodies: the tap stores `payload_bytes`, never the payload.",
|
|
1254
|
+
"- Local absolute paths and pi-side exception text — outside the opt-in `sessions/` transcripts, raw by request: their `cwd` header is still MD5-hashed. Session ids and worktree labels are MD5-truncated to 16 chars (no per-report salt, so the same session links across reports); a surviving server message has the home directory scrubbed to `~`.",
|
|
1255
|
+
"- Raw error text: `errors.jsonl` keeps only the fields of a gateway error body, never a local exception message.",
|
|
1256
|
+
"",
|
|
1257
|
+
"## Mapping to the reference attempt CSV",
|
|
1258
|
+
"",
|
|
1259
|
+
"- `start_utc`/`end_utc` → `started_at`/`ended_at` (UTC, milliseconds).",
|
|
1260
|
+
"- `first_byte_ms` → `time_to_header_ms`; the full request duration → `duration_ms` on the `response` row.",
|
|
1261
|
+
"- `status`, `error_type`, `error_code` → same names (from the gateway JSON body); a fetch rejection sets `transport_error` instead.",
|
|
1262
|
+
"- `request_size`/`prompt_chars` → `payload_bytes` (serialized body bytes only — the body itself is never stored).",
|
|
1263
|
+
"- `prompt_tokens`/`completion_tokens`/`reasoning_tokens`/`finish_reason` → `response.usage.*` / `response.finish_reason`.",
|
|
1264
|
+
"- `response_id` → `response.response_id`.",
|
|
1265
|
+
"- `inflight_key_at_start` → `inflight_process_at_start`; `inflight_same_model_at_start` keeps its name.",
|
|
1266
|
+
"- `starts_last_60s_key`/`starts_last_60s_same_model` → `starts_last_60s_process`/`starts_last_60s_same_model`.",
|
|
1267
|
+
"- `over_documented_limit` is not emitted: NaN's limits are not baked into the provider, and both raw counters are exported so support can apply the documented values themselves.",
|
|
1268
|
+
"",
|
|
1269
|
+
"## `inflight_*` is process-scoped",
|
|
1270
|
+
"",
|
|
1271
|
+
"A tap inside one pi process sees only that process's attempts. `inflight_process_at_start` and `starts_last_60s_process*` are therefore **not** the concurrency or RPM of your API key when several clients share it; the reference CSV's key-wide counts require merging the logs of every client.",
|
|
1272
|
+
"",
|
|
1273
|
+
"## Not public",
|
|
1274
|
+
"",
|
|
1275
|
+
"This report is for NaN support, not for publication. `cf-ray`, `response_id` and millisecond timestamps are deliberately not anonymized — support correlates their logs with them. `payload_sha256` in `anomalies.jsonl` fingerprints a prompt. The default artifact carries no prompt or response content; `sessions/` (with `--include-prompts` / `--include-tools` / `--all`) and `usage_window.json` (billing period and credits: account/tier identity) are private material.",
|
|
958
1276
|
"",
|
|
959
1277
|
"## Versions",
|
|
960
1278
|
"",
|
|
@@ -965,28 +1283,75 @@ function renderReadme(report: DebugReport, versions: Record<string, string>): st
|
|
|
965
1283
|
].join("\n");
|
|
966
1284
|
}
|
|
967
1285
|
|
|
968
|
-
|
|
1286
|
+
/**
|
|
1287
|
+
* Strip content the caller did not opt into from one raw transcript line:
|
|
1288
|
+
* `toolResult` entries are dropped whole and `toolCall` blocks are removed from
|
|
1289
|
+
* assistant messages. `cwd` is hashed in every line that carries it.
|
|
1290
|
+
*/
|
|
1291
|
+
function scrubSessionTranscript(text: string, includeTools: boolean): string {
|
|
1292
|
+
const kept: string[] = [];
|
|
1293
|
+
for (const line of text.split("\n")) {
|
|
1294
|
+
if (line.trim().length === 0) continue;
|
|
1295
|
+
let entry: Record<string, unknown>;
|
|
1296
|
+
try {
|
|
1297
|
+
entry = JSON.parse(line) as Record<string, unknown>;
|
|
1298
|
+
} catch {
|
|
1299
|
+
kept.push(line);
|
|
1300
|
+
continue;
|
|
1301
|
+
}
|
|
1302
|
+
if (typeof entry.cwd === "string") entry.cwd = md5Short(entry.cwd);
|
|
1303
|
+
if (!includeTools && isObject(entry.message)) {
|
|
1304
|
+
const message = entry.message;
|
|
1305
|
+
if (message.role === "toolResult") continue;
|
|
1306
|
+
if (Array.isArray(message.content)) {
|
|
1307
|
+
message.content = message.content.filter(
|
|
1308
|
+
(block) => !(isObject(block) && block.type === "toolCall"),
|
|
1309
|
+
);
|
|
1310
|
+
}
|
|
1311
|
+
}
|
|
1312
|
+
kept.push(JSON.stringify(entry));
|
|
1313
|
+
}
|
|
1314
|
+
return kept.join("\n");
|
|
1315
|
+
}
|
|
1316
|
+
|
|
1317
|
+
export function renderDebugReport(
|
|
1318
|
+
report: DebugReport,
|
|
1319
|
+
sessionsDir?: string,
|
|
1320
|
+
options: DebugRenderOptions = {},
|
|
1321
|
+
): RenderedReport {
|
|
969
1322
|
const versions = (report.metadata as { versions: Record<string, string> }).versions;
|
|
1323
|
+
const includePrompts = options.includePrompts === true || options.includeTools === true;
|
|
1324
|
+
const includeTools = options.includeTools === true;
|
|
1325
|
+
|
|
1326
|
+
const metadata = { ...report.metadata } as Record<string, unknown>;
|
|
1327
|
+
metadata.redaction = {
|
|
1328
|
+
...((isObject(metadata.redaction) ? metadata.redaction : {}) as Record<string, unknown>),
|
|
1329
|
+
transcripts_included: includePrompts,
|
|
1330
|
+
tool_calls_included: includeTools,
|
|
1331
|
+
};
|
|
1332
|
+
|
|
970
1333
|
const files: Record<string, string> = {
|
|
971
1334
|
"README.md": renderReadme(report, versions),
|
|
972
1335
|
"anonymized_usage.jsonl": report.rows.map((row) => JSON.stringify(row)).join("\n") + (report.rows.length > 0 ? "\n" : ""),
|
|
973
1336
|
"turns.jsonl": report.turns.map((turn) => JSON.stringify(turn)).join("\n") + (report.turns.length > 0 ? "\n" : ""),
|
|
974
1337
|
"errors.jsonl": report.errors.map((err) => JSON.stringify(err)).join("\n") + (report.errors.length > 0 ? "\n" : ""),
|
|
1338
|
+
"http_attempts.jsonl": report.httpAttempts.map((entry) => JSON.stringify(entry)).join("\n") + (report.httpAttempts.length > 0 ? "\n" : ""),
|
|
975
1339
|
"anomalies.jsonl": report.anomalies.map((record) => JSON.stringify(record)).join("\n") + (report.anomalies.length > 0 ? "\n" : ""),
|
|
976
|
-
"metadata.json": `${JSON.stringify(
|
|
1340
|
+
"metadata.json": `${JSON.stringify(metadata, null, 2)}\n`,
|
|
977
1341
|
};
|
|
978
1342
|
if (report.usageWindow !== undefined) {
|
|
979
1343
|
files["usage_window.json"] = `${JSON.stringify(report.usageWindow, null, 2)}\n`;
|
|
980
1344
|
}
|
|
981
1345
|
|
|
982
|
-
//
|
|
983
|
-
|
|
1346
|
+
// Transcripts are opt-in: the default artifact carries no prompt, response
|
|
1347
|
+
// or tool content at all (issue #49 S20/S21).
|
|
1348
|
+
if (sessionsDir && includePrompts) {
|
|
984
1349
|
try {
|
|
985
1350
|
const sessionFiles = listSessionFilesFiltered(sessionsDir, report.window);
|
|
986
1351
|
for (const file of sessionFiles) {
|
|
987
1352
|
const content = readFileSync(file, "utf8");
|
|
988
1353
|
const relPath = file.startsWith(sessionsDir) ? file.slice(sessionsDir.length + 1) : basename(file);
|
|
989
|
-
files[`sessions/${relPath}`] = scrubSessionTranscript(content);
|
|
1354
|
+
files[`sessions/${relPath}`] = scrubSessionTranscript(content, includeTools);
|
|
990
1355
|
}
|
|
991
1356
|
} catch {
|
|
992
1357
|
// If sessionsDir doesn't exist or can't be read, skip session files.
|
|
@@ -1009,14 +1374,28 @@ export function renderDebugReport(report: DebugReport, sessionsDir?: string): Re
|
|
|
1009
1374
|
.map(([kind, count]) => `${kind}: ${count}`)
|
|
1010
1375
|
.join(" · ");
|
|
1011
1376
|
|
|
1377
|
+
const attemptSummary = (report.metadata as { attempt_summary?: { total: number; by_status: Record<string, number> } })
|
|
1378
|
+
.attempt_summary;
|
|
1379
|
+
const attempt429 = attemptSummary?.by_status["429"] ?? 0;
|
|
1380
|
+
const attempt5xx = Object.entries(attemptSummary?.by_status ?? {})
|
|
1381
|
+
.filter(([status]) => Number(status) >= 500)
|
|
1382
|
+
.reduce((sum, [, count]) => sum + count, 0);
|
|
1383
|
+
const attemptsLine =
|
|
1384
|
+
attemptSummary && attemptSummary.total > 0
|
|
1385
|
+
? `http attempts: ${attemptSummary.total} (429: ${attempt429} · 5xx: ${attempt5xx})`
|
|
1386
|
+
: "http attempts: 0";
|
|
1387
|
+
|
|
1012
1388
|
const preview = [
|
|
1013
1389
|
`nan-debug report — ${report.window.start} → ${report.window.end} (window: ${report.window.days}d)`,
|
|
1014
1390
|
`sessions: ${report.counts.sessions} · turns: ${report.counts.turns} · models: ${report.counts.models.length}`,
|
|
1391
|
+
attemptsLine,
|
|
1015
1392
|
`errors: ${errorCounts.total} total${errorParts.length > 0 ? ` (${errorParts})` : ""}`,
|
|
1016
1393
|
`per-model avg tokens/turn: ${perModel.length > 0 ? perModel : "(none)"}`,
|
|
1017
1394
|
`anomalies: ${report.counts.anomalies.duplicateIdCreated} duplicate id/created pairs · ${report.counts.anomalies.reasoningOnlyStream} reasoning-only stream · ${report.counts.anomalies.contextOverflow} context overflow`,
|
|
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
|
|
1019
|
-
"
|
|
1395
|
+
`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`,
|
|
1396
|
+
"sharing: shared by default = usage, turns, errors, http attempts, anomalies, metadata — no prompts, no tool calls",
|
|
1397
|
+
"→ --include-prompts embeds raw transcripts · --include-tools adds tool calls/results · --all adds both plus usage_window.json",
|
|
1398
|
+
`→ nothing shared yet. Run with --emit to write ${NAN_DEBUG_REPORT_PREFIX}-<timestamp>.zip`,
|
|
1020
1399
|
].join("\n");
|
|
1021
1400
|
|
|
1022
1401
|
return { files, preview };
|
|
@@ -1031,9 +1410,20 @@ export function writeDebugReport(files: Record<string, string>, outDir: string):
|
|
|
1031
1410
|
}
|
|
1032
1411
|
}
|
|
1033
1412
|
|
|
1034
|
-
export
|
|
1413
|
+
export interface WriteDebugZipOptions {
|
|
1414
|
+
/** `--all` only: `usage_window.json` identifies the account/tier and stays local otherwise. */
|
|
1415
|
+
includeUsageWindow?: boolean;
|
|
1416
|
+
}
|
|
1417
|
+
|
|
1418
|
+
export function writeDebugZip(
|
|
1419
|
+
files: Record<string, string>,
|
|
1420
|
+
zipPath: string,
|
|
1421
|
+
options: WriteDebugZipOptions = {},
|
|
1422
|
+
): void {
|
|
1035
1423
|
mkdirSync(dirname(zipPath), { recursive: true });
|
|
1036
|
-
const entries = Object.entries(files)
|
|
1424
|
+
const entries = Object.entries(files)
|
|
1425
|
+
.filter(([name]) => options.includeUsageWindow === true || name !== "usage_window.json")
|
|
1426
|
+
.map(([name, data]) => ({ name, data }));
|
|
1037
1427
|
writeFileSync(zipPath, createZip(entries));
|
|
1038
1428
|
}
|
|
1039
1429
|
|