@gtrabanco/pi-nan-provider 1.5.7 → 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.
- package/AGENTS.md +12 -1
- package/README.es.md +36 -10
- package/README.md +32 -9
- package/package.json +1 -1
- package/scripts/models.generated.ts +2 -2
- 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/AGENTS.md
CHANGED
|
@@ -544,7 +544,18 @@ Since 1.0.0 the package version **aligns its MAJOR.MINOR with the pi release lin
|
|
|
544
544
|
only network path in `/nan-debug` and stays behind the explicit flag.
|
|
545
545
|
`src/debug-report.ts` reads `<agentDir>/sessions/**/*.jsonl` (filename date
|
|
546
546
|
prefix, else mtime), extracts only assistant `provider: "nan"` turns, and
|
|
547
|
-
renders the 2026-11-10 report shape plus `turns.jsonl`.
|
|
547
|
+
renders the 2026-11-10 report shape plus `turns.jsonl`. PR #44 (2026-11-18)
|
|
548
|
+
adds `errors.jsonl` rows and `error_summary` in `metadata.json`, embeds the
|
|
549
|
+
window-filtered raw transcripts under `sessions/` (their `cwd` header is
|
|
550
|
+
MD5-hashed; root files stay redacted — the transcripts are the owner's
|
|
551
|
+
explicit ask, issue #44), and adds `--interval` (day-granular windows capped
|
|
552
|
+
at 90 days, mutually exclusive with `--window`; its value joins tokens up to
|
|
553
|
+
the next `--` flag because pi passes slash-command args raw). Since 1.5.9
|
|
554
|
+
every response's `cf-ray` is appended by the same wrapper to
|
|
555
|
+
`<agentDir>/nan-response-rays.jsonl` (`{response_id, cf_ray, model,
|
|
556
|
+
observed_at}`, newest 50,000 lines, best-effort — `src/response-rays.ts`)
|
|
557
|
+
and joined into `turns.jsonl` as `cf_ray` (issue #35 S11, owner order
|
|
558
|
+
2026-11-18; null when uncaptured). The zip is built by
|
|
548
559
|
`src/zip.ts` (store method, sorted entries, fixed 1980-01-01 timestamps)
|
|
549
560
|
because `Bun.Archive` is Bun-only and pi also runs on Node. Session/worktree
|
|
550
561
|
labels are MD5[:12]; `errorMessage` maps to
|
package/README.es.md
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# @gtrabanco/𝜋-nan-provider
|
|
2
2
|
|
|
3
3
|
[](https://opensource.org/licenses/MIT)
|
|
4
|
-
[](https://github.com/gtrabanco/pi-nan-provider/releases)
|
|
5
5
|
[](https://cloud.nan.builders/r/7GK06FX8)
|
|
6
6
|
|
|
7
7
|
[NaN Builders](https://cloud.nan.builders/r/7GK06FX8) model provider + MCP nativo para [pi](https://github.com/earendil-works/pi).
|
|
@@ -27,7 +27,7 @@ Registra el proveedor `nan` vía `pi.registerProvider()` usando la API OpenAI-co
|
|
|
27
27
|
| **Modelos de imagen nativos** | `flux-2-klein` y `qwen-image-2.1` registrados como modelos de pi `type: "image"`, accesibles desde codemode y extensiones. |
|
|
28
28
|
| **Puente MCP nativo de media** | El servidor `nan-media` (10 herramientas) registrado con `pi.registerMcpServer()`, gestionado con `/nan-mcp`. |
|
|
29
29
|
| **Informe de créditos** | `/nan-usage` muestra saldo de créditos con barra de progreso, desglose por modelo (input / cached / output en M, créditos consumidos) y periodo de facturación — todo desde `GET /v1/usage` ([#37](https://github.com/gtrabanco/pi-nan-provider/issues/37)). |
|
|
30
|
-
| **Evidencia de anomalías de caché** | Captura de `cf-ray` sobre la firma repetida `id` + `created` del gateway ([#17](https://github.com/gtrabanco/pi-nan-provider/issues/17)) más el recolector determinista `/nan-debug` ([#35](https://github.com/gtrabanco/pi-nan-provider/issues/35)). |
|
|
30
|
+
| **Evidencia de anomalías de caché** | Captura de `cf-ray` sobre la firma repetida `id` + `created` del gateway ([#17](https://github.com/gtrabanco/pi-nan-provider/issues/17)) más el recolector determinista `/nan-debug` ([#35](https://github.com/gtrabanco/pi-nan-provider/issues/35)) con evidencia de errores por turno, el `cf-ray` de cada respuesta unido a `turns.jsonl` (S11) y ventanas flexibles `--interval` ([#44](https://github.com/gtrabanco/pi-nan-provider/issues/44)). |
|
|
31
31
|
| **Integración con pi** | Refresco de modelos dirigido por el runtime Models de pi, overrides por modelo en `models.json` y el changelog de la extensión (`pi.changelogPath`) que pi muestra tras una actualización. |
|
|
32
32
|
|
|
33
33
|
Comandos:
|
|
@@ -36,7 +36,7 @@ Comandos:
|
|
|
36
36
|
| :--- | :--- |
|
|
37
37
|
| `/nan-mcp` | Gestionar el puente MCP de media (`status` / `enable` / `disable`) |
|
|
38
38
|
| `/nan-usage [1-90]` | Saldo de créditos con barra de uso, desglose por modelo (in / cached / out en M · créditos cr) y totales históricos |
|
|
39
|
-
| `/nan-debug [tema] [--window N] [--out ruta] [--emit]` | Paquete de evidencia reproducible y redactado para NaN |
|
|
39
|
+
| `/nan-debug [tema] [--window N] [--interval FLEX] [--out ruta] [--emit]` | Paquete de evidencia reproducible y redactado para NaN |
|
|
40
40
|
|
|
41
41
|
---
|
|
42
42
|
|
|
@@ -402,6 +402,13 @@ añade una línea JSON a `<agentDir>/nan-cache-anomalies.jsonl` — `model`, el
|
|
|
402
402
|
petición. Es **solo local**: ni contenido de prompt/respuesta, ni credenciales,
|
|
403
403
|
ni rutas, ni subida remota. Un fallo de escritura nunca rompe un stream.
|
|
404
404
|
|
|
405
|
+
Independientemente de cualquier anomalía, el `cf-ray` de cada respuesta se
|
|
406
|
+
guarda en `<agentDir>/nan-response-rays.jsonl` — `response_id`, `cf_ray`,
|
|
407
|
+
`model`, `observed_at`, las 50.000 líneas más recientes, solo local (issue
|
|
408
|
+
#35 S11) — y el informe lo une en `turns.jsonl` como `cf_ray`, así que
|
|
409
|
+
soporte tiene los rays de cualquier par de llamadas sin esperar a una
|
|
410
|
+
recurrencia.
|
|
411
|
+
|
|
405
412
|
`/nan-debug` convierte ese fichero y tus transcripts en un paquete de evidencia
|
|
406
413
|
redactado y reproducible para NaN:
|
|
407
414
|
|
|
@@ -410,11 +417,20 @@ redactado y reproducible para NaN:
|
|
|
410
417
|
/nan-debug cache --window 2 # etiqueta de tema + ventana de 2 días
|
|
411
418
|
/nan-debug --window 2 --emit # además escribe <agentDir>/nan-debug-report.zip
|
|
412
419
|
/nan-debug cache --out ~/evidence --emit
|
|
420
|
+
/nan-debug --interval 5min # intervalos relativos: 5min, 2h, 3d, 1mes
|
|
421
|
+
/nan-debug --interval "2026-11-10 - 2026-11-11 17:30" # rangos, extremos abiertos y puntos únicos también
|
|
413
422
|
```
|
|
414
423
|
|
|
415
424
|
- `--window N` (1–90 días) consulta además `GET /v1/usage` para el mismo periodo
|
|
416
425
|
con tu clave guardada y escribe `usage_window.json`; sin el flag no se hace
|
|
417
426
|
ninguna petición. Esa llamada en vivo consume el límite de peticiones.
|
|
427
|
+
- `--interval <desc>` sustituye a `--window` (usar ambos es un error) y acepta
|
|
428
|
+
intervalos relativos (`5min`, `2h`, `3d`, `1mes`), rangos fecha/hora
|
|
429
|
+
(`2026-11-10 - 2026-11-11 17:30`, `10:30 - 11:00`, cruce de medianoche
|
|
430
|
+
`23:00 - 01:00`), extremos abiertos (`2026-11-10 -`, `- 2026-11-10`),
|
|
431
|
+
año-mes (`2026-11 - 2026-12`) y puntos únicos (`2026-11-10`,
|
|
432
|
+
`2026-11-10T10:00:00Z`). El span máximo es de 90 días y el parseo es
|
|
433
|
+
determinista — sin llamadas a LLM. El tema, si usas uno, va antes del flag.
|
|
418
434
|
- El zip se escribe **solo** con `--emit`; la ejecución por defecto escribe el
|
|
419
435
|
informe local e imprime un resumen.
|
|
420
436
|
- `--out <ruta>` escribe el informe donde lo indiques (y, con `--emit`,
|
|
@@ -423,13 +439,23 @@ redactado y reproducible para NaN:
|
|
|
423
439
|
como ruta.
|
|
424
440
|
- El informe contiene `README.md`, `anonymized_usage.jsonl` (totales por
|
|
425
441
|
fecha/sesión/modelo, conteo de `stopReason`, tasa de acierto de caché),
|
|
426
|
-
`turns.jsonl` (uso por turno, `stopReason`, clase de error, `responseId
|
|
427
|
-
`
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
`
|
|
431
|
-
|
|
432
|
-
|
|
442
|
+
`turns.jsonl` (uso por turno, `stopReason`, clase de error, `responseId`,
|
|
443
|
+
`cf_ray`),
|
|
444
|
+
`errors.jsonl` (una fila por turno con error: clase, fragmento de 200
|
|
445
|
+
caracteres del mensaje, hash MD5 del mensaje completo, tokens de entrada/
|
|
446
|
+
salida, `responseId`), `anomalies.jsonl` (par de `cf-ray`), `sessions/` (los
|
|
447
|
+
JSONL de sesión en bruto filtrados por la ventana) y `metadata.json`
|
|
448
|
+
(versiones de paquete, pi-ai y pi; procedencia del catálogo;
|
|
449
|
+
`error_summary`).
|
|
450
|
+
- Las etiquetas de sesión y worktree son MD5 truncado a 12 caracteres (incluida
|
|
451
|
+
la cabecera `cwd` dentro de `sessions/`); `errorMessage` se reduce a
|
|
452
|
+
`overflow | rate_limited | invalid_request | transport | other`, y
|
|
453
|
+
`errors.jsonl` conserva como mucho 200 caracteres del mensaje en bruto más
|
|
454
|
+
un hash MD5. Las credenciales nunca se recogen en ningún sitio; el contenido
|
|
455
|
+
de prompt/respuesta nunca se recoge en los ficheros raíz — `sessions/` es la
|
|
456
|
+
excepción: transcripts en bruto incluidos a petición
|
|
457
|
+
([#44](https://github.com/gtrabanco/pi-nan-provider/issues/44)), solo con
|
|
458
|
+
`cwd` hasheado. Entradas idénticas producen bytes de zip idénticos.
|
|
433
459
|
|
|
434
460
|
## 📊 Modelos
|
|
435
461
|
|
package/README.md
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
# @gtrabanco/𝜋-nan-provider
|
|
2
2
|
|
|
3
3
|
[](https://opensource.org/licenses/MIT)
|
|
4
|
-
[](https://github.com/gtrabanco/pi-nan-provider/releases)
|
|
5
5
|
[](https://cloud.nan.builders/r/7GK06FX8)
|
|
6
6
|
|
|
7
7
|
[NaN Builders](https://cloud.nan.builders/r/7GK06FX8) model provider + a native MCP server for [pi](https://github.com/earendil-works/pi).
|
|
@@ -27,7 +27,7 @@ Registers the `nan` provider via `pi.registerProvider()` using NaN's OpenAI-comp
|
|
|
27
27
|
| **Native image models** | `flux-2-klein` and `qwen-image-2.1` registered as pi `type: "image"` models, reachable from codemode and extensions. |
|
|
28
28
|
| **Native MCP media bridge** | The `nan-media` server (10 tools) registered through `pi.registerMcpServer()`, managed with `/nan-mcp`. |
|
|
29
29
|
| **Credits reporting** | `/nan-usage` shows credits balance with a progress bar, per-model breakdown (input / cached / output in M, credits consumed), and billing period — all from `GET /v1/usage` ([#37](https://github.com/gtrabanco/pi-nan-provider/issues/37)). |
|
|
30
|
-
| **Cache-anomaly evidence** | `cf-ray` capture on the repeated `id` + `created` gateway signature ([#17](https://github.com/gtrabanco/pi-nan-provider/issues/17)) plus the deterministic `/nan-debug` collector ([#35](https://github.com/gtrabanco/pi-nan-provider/issues/35)). |
|
|
30
|
+
| **Cache-anomaly evidence** | `cf-ray` capture on the repeated `id` + `created` gateway signature ([#17](https://github.com/gtrabanco/pi-nan-provider/issues/17)) plus the deterministic `/nan-debug` collector ([#35](https://github.com/gtrabanco/pi-nan-provider/issues/35)) with per-error evidence, every response's `cf-ray` joined into `turns.jsonl` (S11), and flexible `--interval` windows ([#44](https://github.com/gtrabanco/pi-nan-provider/issues/44)). |
|
|
31
31
|
| **pi integration** | Model refresh driven by pi's Models runtime, per-model `models.json` overrides, and the extension changelog (`pi.changelogPath`) that pi shows after an update. |
|
|
32
32
|
|
|
33
33
|
Commands:
|
|
@@ -36,7 +36,7 @@ Commands:
|
|
|
36
36
|
| :--- | :--- |
|
|
37
37
|
| `/nan-mcp` | Manage the media MCP bridge (`status` / `enable` / `disable`) |
|
|
38
38
|
| `/nan-usage [1-90]` | Credits balance with usage bar, per-model breakdown (in / cached / out in M · credits cr), and all-time totals |
|
|
39
|
-
| `/nan-debug [topic] [--window N] [--out path] [--emit]` | Redacted, reproducible evidence package for NaN |
|
|
39
|
+
| `/nan-debug [topic] [--window N] [--interval FLEX] [--out path] [--emit]` | Redacted, reproducible evidence package for NaN |
|
|
40
40
|
|
|
41
41
|
---
|
|
42
42
|
|
|
@@ -400,6 +400,12 @@ SHA-256 of the request payload. It is **local-only**: no prompt or response
|
|
|
400
400
|
content, no credentials, no paths, no upload. A write failure never breaks a
|
|
401
401
|
stream.
|
|
402
402
|
|
|
403
|
+
Independently of any anomaly, every response's `cf-ray` is kept in
|
|
404
|
+
`<agentDir>/nan-response-rays.jsonl` — `response_id`, `cf_ray`, `model`,
|
|
405
|
+
`observed_at`, newest 50,000 lines, local-only (issue #35 S11) — and the
|
|
406
|
+
report joins it into `turns.jsonl` as `cf_ray`, so support gets the rays of
|
|
407
|
+
any pair of calls without waiting for a recurrence.
|
|
408
|
+
|
|
403
409
|
`/nan-debug` turns that file plus your session transcripts into a redacted,
|
|
404
410
|
reproducible evidence package for NaN:
|
|
405
411
|
|
|
@@ -408,11 +414,20 @@ reproducible evidence package for NaN:
|
|
|
408
414
|
/nan-debug cache --window 2 # topic label + a 2-day window
|
|
409
415
|
/nan-debug --window 2 --emit # also writes <agentDir>/nan-debug-report.zip
|
|
410
416
|
/nan-debug cache --out ~/evidence --emit
|
|
417
|
+
/nan-debug --interval 5min # relative spans: 5min, 2h, 3d, 1mes
|
|
418
|
+
/nan-debug --interval "2026-11-10 - 2026-11-11 17:30" # ranges, open ends, single points too
|
|
411
419
|
```
|
|
412
420
|
|
|
413
421
|
- `--window N` (1–90 days) also fetches `GET /v1/usage` for the same period with
|
|
414
422
|
your stored key and writes `usage_window.json`; without the flag nothing is
|
|
415
423
|
fetched. That live call counts against your quota's request rate.
|
|
424
|
+
- `--interval <desc>` replaces `--window` (using both is an error) and accepts
|
|
425
|
+
relative spans (`5min`, `2h`, `3d`, `1mes`), date/time ranges
|
|
426
|
+
(`2026-11-10 - 2026-11-11 17:30`, `10:30 - 11:00`, cross-midnight
|
|
427
|
+
`23:00 - 01:00`), open ends (`2026-11-10 -`, `- 2026-11-10`), year-months
|
|
428
|
+
(`2026-11 - 2026-12`) and single points (`2026-11-10`,
|
|
429
|
+
`2026-11-10T10:00:00Z`). The span is capped at 90 days and parsing is fully
|
|
430
|
+
deterministic — no LLM calls. The topic, when you use one, goes before the flag.
|
|
416
431
|
- The zip is written **only** with `--emit`; the default run writes the local
|
|
417
432
|
report and prints a preview.
|
|
418
433
|
- `--out <path>` writes the report anywhere you name it (and, with `--emit`,
|
|
@@ -420,12 +435,20 @@ reproducible evidence package for NaN:
|
|
|
420
435
|
above write where they say. A flag token is never accepted as the path.
|
|
421
436
|
- The report contains `README.md`, `anonymized_usage.jsonl` (per date/session/
|
|
422
437
|
model totals, stop-reason counts, cache-hit rate), `turns.jsonl` (per-turn
|
|
423
|
-
usage, stop reason, error class, response id), `
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
438
|
+
usage, stop reason, error class, response id, `cf_ray`), `errors.jsonl` (one row per
|
|
439
|
+
errored turn: class, 200-char message fragment, MD5 hash of the full message,
|
|
440
|
+
input/output tokens, response id), `anomalies.jsonl` (`cf-ray` pair),
|
|
441
|
+
`sessions/` (the raw session JSONL files filtered to the window) and
|
|
442
|
+
`metadata.json` (package/pi-ai/pi versions, catalog provenance,
|
|
443
|
+
`error_summary`).
|
|
444
|
+
- Session and worktree labels are MD5-truncated to 12 chars (including the
|
|
445
|
+
`cwd` header inside `sessions/`); `errorMessage` is reduced to `overflow |
|
|
446
|
+
rate_limited | invalid_request | transport | other`, and `errors.jsonl` keeps
|
|
447
|
+
at most 200 characters of the raw message plus an MD5 hash. Credentials are
|
|
448
|
+
never collected anywhere; prompt/response content is never collected in the
|
|
449
|
+
root files — `sessions/` is the exception, raw transcripts included on
|
|
450
|
+
request ([#44](https://github.com/gtrabanco/pi-nan-provider/issues/44)), with
|
|
451
|
+
only `cwd` hashed. Identical inputs produce byte-identical zip bytes.
|
|
429
452
|
|
|
430
453
|
## 📊 Models
|
|
431
454
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@gtrabanco/pi-nan-provider",
|
|
3
|
-
"version": "1.5.
|
|
3
|
+
"version": "1.5.8",
|
|
4
4
|
"description": "NaN Builders (api.nan.builders) model provider for pi - OpenAI-compatible registration with a models.dev-generated fallback, tier-aware live catalog, and an optional community media MCP bridge",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi",
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// This file is auto-generated by scripts/generate-models.ts
|
|
2
2
|
// Do not edit manually — run `bun run generate-models` to update.
|
|
3
3
|
//
|
|
4
|
-
// Source: https://models.dev/api.json (provider "nan"), fetched 2026-11-
|
|
4
|
+
// Source: https://models.dev/api.json (provider "nan"), fetched 2026-11-18T22:57:47.883Z
|
|
5
5
|
// Provenance: every contextWindow/maxTokens/input/cost value traces to
|
|
6
6
|
// models.dev or to the per-entry notes below. Nothing is invented; entries
|
|
7
7
|
// models.dev documents incompletely are omitted and flagged instead.
|
|
@@ -1027,7 +1027,7 @@ export const NAN_GENERATED_MODELS: readonly GeneratedModelEntry[] = [
|
|
|
1027
1027
|
export const GENERATED_CATALOG_META = {
|
|
1028
1028
|
source: "https://models.dev/api.json",
|
|
1029
1029
|
modelsDevProvider: "nan",
|
|
1030
|
-
fetchedAt: "2026-11-
|
|
1030
|
+
fetchedAt: "2026-11-18T22:57:47.883Z",
|
|
1031
1031
|
modelCount: 13,
|
|
1032
1032
|
models: ["deepseek-v4-flash","deepseek-v4-pro","gemma4","glm5.3","glm5.3-flash","hy4","hy4-flash","kimi-k3.1-pro","mimo-v2.6-flash","qwen3.6","qwen3.8-flash","qwen3.8-max","qwen4-max"],
|
|
1033
1033
|
notes: [
|
package/src/cache-anomaly.ts
CHANGED
|
@@ -14,7 +14,11 @@
|
|
|
14
14
|
* chunks (pi-ai only persists `id` as `AssistantMessage.responseId`),
|
|
15
15
|
* - compares each completed stream with the previous one for the same model,
|
|
16
16
|
* and when both `id` and `created` repeat, appends one JSONL record to
|
|
17
|
-
* `<agentDir>/nan-cache-anomalies.jsonl
|
|
17
|
+
* `<agentDir>/nan-cache-anomalies.jsonl`,
|
|
18
|
+
* - appends every observed response's `cf-ray` to the response-ray sidecar
|
|
19
|
+
* (`<agentDir>/nan-response-rays.jsonl`, issue #35 S11, owner-ordered
|
|
20
|
+
* 2026-11-18) when a `raySink` is wired — capture for the report join,
|
|
21
|
+
* independent of anomaly detection.
|
|
18
22
|
*
|
|
19
23
|
* The record deliberately carries no prompt or response content, no
|
|
20
24
|
* credentials and no paths: only the model, the gateway pair, both `cf-ray`
|
|
@@ -32,6 +36,7 @@ import { appendFileSync, mkdirSync } from "node:fs";
|
|
|
32
36
|
import { dirname, join } from "node:path";
|
|
33
37
|
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
34
38
|
import type { AssistantMessage, ProviderStreams } from "@earendil-works/pi-ai";
|
|
39
|
+
import type { ResponseRaySink } from "./response-rays.ts";
|
|
35
40
|
|
|
36
41
|
/** Default file name inside pi's agent dir. */
|
|
37
42
|
export const CACHE_ANOMALY_FILE = "nan-cache-anomalies.jsonl";
|
|
@@ -98,6 +103,8 @@ export function createCacheAnomalyFileSink(filePath?: string): CacheAnomalySink
|
|
|
98
103
|
|
|
99
104
|
export interface CacheAnomalyCaptureOptions {
|
|
100
105
|
sink: CacheAnomalySink;
|
|
106
|
+
/** Per-response ray sidecar (issue #35 S11); when omitted, no rays are captured. */
|
|
107
|
+
raySink?: ResponseRaySink;
|
|
101
108
|
/** Injectable clock for deterministic tests. */
|
|
102
109
|
now?: () => Date;
|
|
103
110
|
}
|
|
@@ -209,10 +216,25 @@ export function withCacheAnomalyCapture(api: ProviderStreams, options: CacheAnom
|
|
|
209
216
|
|
|
210
217
|
const stream = run(opts as T);
|
|
211
218
|
|
|
219
|
+
const captureRay = (id?: string): void => {
|
|
220
|
+
if (!options.raySink || !id || state.cfRay === null) return;
|
|
221
|
+
try {
|
|
222
|
+
options.raySink.record({
|
|
223
|
+
response_id: id,
|
|
224
|
+
cf_ray: state.cfRay,
|
|
225
|
+
model: modelId,
|
|
226
|
+
observed_at: state.observedAt,
|
|
227
|
+
});
|
|
228
|
+
} catch {
|
|
229
|
+
// Ray capture is best-effort; never break the turn.
|
|
230
|
+
}
|
|
231
|
+
};
|
|
232
|
+
|
|
212
233
|
const complete = (message: AssistantMessage | undefined) => {
|
|
213
234
|
// pi-ai persists only the id; keep it as a fallback when the raw
|
|
214
235
|
// chunks did not carry one.
|
|
215
236
|
const id = state.id ?? message?.responseId;
|
|
237
|
+
captureRay(id);
|
|
216
238
|
if (!id || state.created === undefined) return;
|
|
217
239
|
|
|
218
240
|
const current: LastResponse = {
|
|
@@ -262,7 +284,9 @@ export function withCacheAnomalyCapture(api: ProviderStreams, options: CacheAnom
|
|
|
262
284
|
};
|
|
263
285
|
|
|
264
286
|
stream.result().then(complete, () => {
|
|
265
|
-
// A failed stream has no gateway pair worth comparing
|
|
287
|
+
// A failed stream has no gateway pair worth comparing — but when the
|
|
288
|
+
// response already produced an id, its ray is still evidence (S11).
|
|
289
|
+
captureRay(state.id);
|
|
266
290
|
});
|
|
267
291
|
return stream;
|
|
268
292
|
};
|
package/src/debug-command.ts
CHANGED
|
@@ -73,6 +73,7 @@ export function registerNanDebugCommand(pi: ExtensionAPI, deps: NanDebugCommandD
|
|
|
73
73
|
|
|
74
74
|
const now = deps.now?.() ?? new Date();
|
|
75
75
|
const agentDir = deps.agentDir ?? getAgentDir();
|
|
76
|
+
const sessionsDir = join(agentDir, "sessions");
|
|
76
77
|
const apiKey = parsed.args.windowProvided
|
|
77
78
|
? await (deps.resolveApiKey ?? defaultResolveApiKey)(ctx)
|
|
78
79
|
: undefined;
|
|
@@ -83,12 +84,14 @@ export function registerNanDebugCommand(pi: ExtensionAPI, deps: NanDebugCommandD
|
|
|
83
84
|
agentDir,
|
|
84
85
|
now,
|
|
85
86
|
windowDays: parsed.args.windowDays,
|
|
87
|
+
interval: parsed.args.interval,
|
|
86
88
|
topic: parsed.args.topic,
|
|
87
89
|
apiKey,
|
|
88
90
|
includeUsage: parsed.args.windowProvided,
|
|
89
91
|
fetchUsage: parsed.args.windowProvided ? (deps.fetchUsage ?? fetchDebugUsageWindow) : undefined,
|
|
92
|
+
sessionsDir,
|
|
90
93
|
});
|
|
91
|
-
rendered = renderDebugReport(report);
|
|
94
|
+
rendered = renderDebugReport(report, sessionsDir);
|
|
92
95
|
} catch (error) {
|
|
93
96
|
ctx.ui.notify(
|
|
94
97
|
`nan-debug failed to collect the report: ${error instanceof Error ? error.message : String(error)}`,
|
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
|
|
package/src/provider-factory.ts
CHANGED
|
@@ -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
|
-
{
|
|
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
|
+
}
|