@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.
@@ -40,6 +40,7 @@ import { providerAttributionEnabled, stripProviderAttribution } from "./attribut
40
40
  import { withContextOverflowClassification } from "./context-overflow-classifier.ts";
41
41
  import { withReasoningOnlyStreamGuard } from "./reasoning-only-stream-guard.ts";
42
42
  import { createCacheAnomalyFileSink, withCacheAnomalyCapture, type CacheAnomalySink } from "./cache-anomaly.ts";
43
+ import { createResponseRayFileSink, type ResponseRaySink } from "./response-rays.ts";
43
44
  import { NAN_IMAGE_API, baselineImageModels, createNanImagesApi } from "./images.ts";
44
45
  import {
45
46
  baselineModels,
@@ -74,6 +75,8 @@ export interface NanCompatibleProviderOptions {
74
75
  fetchImpl?: typeof fetch;
75
76
  /** Sink for the issue #35 cache-anomaly evidence; defaults to the agent-dir JSONL file. */
76
77
  cacheAnomalySink?: CacheAnomalySink;
78
+ /** Sink for the per-response cf-ray sidecar (issue #35 S11); defaults to the agent-dir JSONL file. */
79
+ responseRaySink?: ResponseRaySink;
77
80
  }
78
81
 
79
82
  /**
@@ -305,12 +308,16 @@ export async function createNanCompatibleProvider(
305
308
  // (NOT onPayload, which only receives the outgoing request params).
306
309
  // Outermost: cache-anomaly evidence capture (issue #35). It only adds
307
310
  // observation hooks (onResponse for `cf-ray`, onProviderStreamEvent for
308
- // the raw id/created pair) and never rewrites the stream.
311
+ // the raw id/created pair) and never rewrites the stream. Since S11 it
312
+ // also appends every observed cf-ray to the response-ray sidecar.
309
313
  api: withCacheAnomalyCapture(
310
314
  withContextOverflowClassification(
311
315
  withReasoningOnlyStreamGuard(wrapApiForStrictSanitization(apiFactory())),
312
316
  ),
313
- { sink: options.cacheAnomalySink ?? createCacheAnomalyFileSink() },
317
+ {
318
+ sink: options.cacheAnomalySink ?? createCacheAnomalyFileSink(),
319
+ raySink: options.responseRaySink ?? createResponseRayFileSink(),
320
+ },
314
321
  ),
315
322
  }),
316
323
  overlayMap,
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Persistent per-response `cf-ray` capture (issue #35 S11, owner order
3
+ * 2026-11-18: "El cf-ray hay que incluirlo en el reporte de debug").
4
+ *
5
+ * NaN support correlates edge/origin logs by Cloudflare's trace id, and the
6
+ * anomaly pair in `nan-cache-anomalies.jsonl` only exists after the #17
7
+ * signature recurs. This sidecar closes the gap: every stream that produced a
8
+ * gateway `id` and saw a `cf-ray` response header appends one JSONL record —
9
+ * success or failure — so the debug report can join `cf_ray` onto any turn
10
+ * without waiting for a recurrence.
11
+ *
12
+ * Contract:
13
+ * - exactly four fields per record: `response_id`, `cf_ray`, `model`,
14
+ * `observed_at` — no content, no credentials, no paths;
15
+ * - local-only; writes are best-effort (never break a stream, warn once);
16
+ * - bounded: the newest `RESPONSE_RAYS_MAX_LINES` lines are kept, compacted
17
+ * deterministically; concurrent writers may interleave (same best-effort
18
+ * contract as the anomaly sink);
19
+ * - reading tolerates a missing or corrupted file — no rays, no crash.
20
+ */
21
+
22
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
23
+ import { dirname, join } from "node:path";
24
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
25
+
26
+ /** Default file name inside pi's agent dir. */
27
+ export const RESPONSE_RAYS_FILE = "nan-response-rays.jsonl";
28
+
29
+ /** Lines kept after a compact: newest first-in, oldest dropped. */
30
+ export const RESPONSE_RAYS_MAX_LINES = 50_000;
31
+
32
+ /** One persisted response ray: exactly the fields the join and support need. */
33
+ export interface ResponseRayRecord {
34
+ /** Gateway completion id (`AssistantMessage.responseId`), unique per response. */
35
+ response_id: string;
36
+ /** Cloudflare trace id of that response. */
37
+ cf_ray: string;
38
+ model: string;
39
+ /** ISO timestamp of when the response headers were observed. */
40
+ observed_at: string;
41
+ }
42
+
43
+ export interface ResponseRaySink {
44
+ record(record: ResponseRayRecord): void;
45
+ }
46
+
47
+ /** The response-ray file path for the current pi agent dir. */
48
+ export function defaultResponseRayPath(): string {
49
+ return join(getAgentDir(), RESPONSE_RAYS_FILE);
50
+ }
51
+
52
+ function countLines(text: string): number {
53
+ if (text.length === 0) return 0;
54
+ const lines = text.split("\n").length;
55
+ return text.endsWith("\n") ? lines - 1 : lines;
56
+ }
57
+
58
+ /**
59
+ * File sink: append one JSON line per response, keeping the file bounded by
60
+ * `maxLines` (compact keeps the newest lines). Never throws — the first
61
+ * failure warns once, then stays quiet so a broken disk cannot spam the
62
+ * console or break a turn. The line counter is initialised once per sink
63
+ * from the existing file, then maintained in process.
64
+ */
65
+ export function createResponseRayFileSink(filePath?: string, options: { maxLines?: number } = {}): ResponseRaySink {
66
+ const maxLines = options.maxLines ?? RESPONSE_RAYS_MAX_LINES;
67
+ let warned = false;
68
+ let counted = false;
69
+ let lines = 0;
70
+
71
+ const warnOnce = (error: unknown): void => {
72
+ if (warned) return;
73
+ warned = true;
74
+ console.warn(
75
+ `[pi-nan-provider] could not persist response-ray evidence (${error instanceof Error ? error.message : String(error)}); streams continue.`,
76
+ );
77
+ };
78
+
79
+ const compact = (path: string): void => {
80
+ try {
81
+ const kept = readFileSync(path, "utf8")
82
+ .split("\n")
83
+ .filter((line) => line.length > 0)
84
+ .slice(-maxLines);
85
+ writeFileSync(path, kept.length > 0 ? `${kept.join("\n")}\n` : "");
86
+ lines = kept.length;
87
+ } catch {
88
+ // Best-effort: a failed compact is retried on the next overflow.
89
+ }
90
+ };
91
+
92
+ return {
93
+ record(record) {
94
+ try {
95
+ const path = filePath ?? defaultResponseRayPath();
96
+ mkdirSync(dirname(path), { recursive: true });
97
+ if (!counted) {
98
+ counted = true;
99
+ lines = existsSync(path) ? countLines(readFileSync(path, "utf8")) : 0;
100
+ }
101
+ appendFileSync(path, `${JSON.stringify(record)}\n`);
102
+ lines += 1;
103
+ if (lines > maxLines) compact(path);
104
+ } catch (error) {
105
+ warnOnce(error);
106
+ }
107
+ },
108
+ };
109
+ }
110
+
111
+ /**
112
+ * Read the sidecar into a `response_id → cf_ray` map for the report join.
113
+ * Later lines win for a repeated id; malformed lines are skipped; a missing
114
+ * file yields an empty map.
115
+ */
116
+ export function readResponseRays(filePath?: string): Map<string, string> {
117
+ const rays = new Map<string, string>();
118
+ try {
119
+ const path = filePath ?? defaultResponseRayPath();
120
+ if (!existsSync(path)) return rays;
121
+ for (const line of readFileSync(path, "utf8").split("\n")) {
122
+ if (line.trim().length === 0) continue;
123
+ try {
124
+ const entry = JSON.parse(line) as Partial<ResponseRayRecord>;
125
+ if (
126
+ typeof entry.response_id === "string" &&
127
+ typeof entry.cf_ray === "string" &&
128
+ entry.cf_ray.length > 0
129
+ ) {
130
+ rays.set(entry.response_id, entry.cf_ray);
131
+ }
132
+ } catch {
133
+ // A corrupted line must not break the collector.
134
+ }
135
+ }
136
+ } catch {
137
+ // Unreadable sidecar = no rays, never a crash.
138
+ }
139
+ return rays;
140
+ }