@gtrabanco/pi-nan-provider 1.5.6 → 1.5.8

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.
@@ -201,12 +201,12 @@ export interface SanitizerOptions {
201
201
  /**
202
202
  * Keep `max_completion_tokens` in the payload instead of renaming it to
203
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.
204
+ * is `"max_completion_tokens"` — the per-model mechanism introduced for
205
+ * issue #34. `qwen3.8-flash` used it until the gateway fix landed (#36);
206
+ * `qwen3.8-max` still declares it because its `max_tokens` bounds only the
207
+ * visible answer. When false/absent the documented rename runs — NaN's
208
+ * published OpenAPI schema only documents `max_tokens`, so hand-built
209
+ * payloads and non-overridden models stay on the strict shape.
210
210
  */
211
211
  preserveMaxCompletionTokens?: boolean;
212
212
  }
@@ -255,9 +255,10 @@ export function sanitizeOpenAICompatPayload(payload: unknown, options: Sanitizer
255
255
  // must stay schema-strict.
256
256
  if (options.preserveStreamOptions !== true) delete out.stream_options;
257
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.
258
+ // model's compat declares `max_completion_tokens` (the #34 mechanism,
259
+ // still used by `qwen3.8-max`): the gateway honors it there to bound the
260
+ // total, so the rename would undo the catalog's maxTokensField override
261
+ // before the payload leaves pi.
261
262
  if (
262
263
  "max_completion_tokens" in out &&
263
264
  !("max_tokens" in out) &&
@@ -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
  /**
@@ -121,10 +124,12 @@ function modelSupportsUsageInStreaming(model: unknown): boolean {
121
124
 
122
125
  /**
123
126
  * Whether the model's effective compat sends the `max_completion_tokens`
124
- * request field instead of the classic `max_tokens` (issue #34). The model
125
- * object here is pi-ai's post-registry view — baseline catalog, live-merge
126
- * refresh, `models.json` override and the #19 stale-store overlay all flow
127
- * through `compat`, so this reads the value the user actually runs with.
127
+ * request field instead of the classic `max_tokens` (the per-model mechanism
128
+ * from issue #34; `qwen3.8-max` is the catalog model that still uses it).
129
+ * The model object here is pi-ai's post-registry view — baseline catalog,
130
+ * live-merge refresh, `models.json` override and the #19 stale-store overlay
131
+ * all flow through `compat`, so this reads the value the user actually runs
132
+ * with.
128
133
  */
129
134
  function modelSendsMaxCompletionTokens(model: unknown): boolean {
130
135
  if (!isObject(model)) return false;
@@ -303,12 +308,16 @@ export async function createNanCompatibleProvider(
303
308
  // (NOT onPayload, which only receives the outgoing request params).
304
309
  // Outermost: cache-anomaly evidence capture (issue #35). It only adds
305
310
  // observation hooks (onResponse for `cf-ray`, onProviderStreamEvent for
306
- // 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.
307
313
  api: withCacheAnomalyCapture(
308
314
  withContextOverflowClassification(
309
315
  withReasoningOnlyStreamGuard(wrapApiForStrictSanitization(apiFactory())),
310
316
  ),
311
- { sink: options.cacheAnomalySink ?? createCacheAnomalyFileSink() },
317
+ {
318
+ sink: options.cacheAnomalySink ?? createCacheAnomalyFileSink(),
319
+ raySink: options.responseRaySink ?? createResponseRayFileSink(),
320
+ },
312
321
  ),
313
322
  }),
314
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
+ }