@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 CHANGED
@@ -592,8 +592,8 @@ Since 1.0.0 the package version **aligns its MAJOR.MINOR with the pi release lin
592
592
  called by openai-completions right after the HTTP response). The gateway
593
593
  `id`/`created` pair comes from raw `onProviderStreamEvent` chunks: pi-ai copies
594
594
  only `chunk.id` into `AssistantMessage.responseId`, and `created` is never
595
- persisted. `src/cache-anomaly.ts` wraps the provider api outermost
596
- (`withCacheAnomalyCapture`), compares each completed stream against the
595
+ persisted. `src/cache-anomaly.ts` wraps the provider api immediately inside
596
+ the #49 attempt tap (`withCacheAnomalyCapture`), compares each completed stream against the
597
597
  previous one **per model**, and on the #17 signature (same `id` + `created`)
598
598
  appends one record to `<agentDir>/nan-cache-anomalies.jsonl`. Bursts record
599
599
  the first pair once; a differing signature resets the baseline. The record is
@@ -603,10 +603,8 @@ Since 1.0.0 the package version **aligns its MAJOR.MINOR with the pi release lin
603
603
  `src/debug-report.ts` reads `<agentDir>/sessions/**/*.jsonl` (filename date
604
604
  prefix, else mtime), extracts only assistant `provider: "nan"` turns, and
605
605
  renders the 2026-11-10 report shape plus `turns.jsonl`. PR #44 (2026-11-18)
606
- adds `errors.jsonl` rows and `error_summary` in `metadata.json`, embeds the
607
- window-filtered raw transcripts under `sessions/` (their `cwd` header is
608
- MD5-hashed; root files stay redacted — the transcripts are the owner's
609
- explicit ask, issue #44), and adds `--interval` (day-granular windows capped
606
+ adds `errors.jsonl` rows and `error_summary` in `metadata.json` and adds
607
+ `--interval` (day-granular windows capped
610
608
  at 90 days, mutually exclusive with `--window`; its value joins tokens up to
611
609
  the next `--` flag because pi passes slash-command args raw). Since 1.5.9
612
610
  every response's `cf-ray` is appended by the same wrapper to
@@ -616,8 +614,48 @@ Since 1.0.0 the package version **aligns its MAJOR.MINOR with the pi release lin
616
614
  2026-11-18; null when uncaptured). The zip is built by
617
615
  `src/zip.ts` (store method, sorted entries, fixed 1980-01-01 timestamps)
618
616
  because `Bun.Archive` is Bun-only and pi also runs on Node. Session/worktree
619
- labels are MD5[:12]; `errorMessage` maps to
617
+ labels are MD5[:16] since issue #49 (no salt, so a session links across
618
+ reports); `errorMessage` maps to
620
619
  `overflow|rate_limited|invalid_request|transport|other`.
620
+
621
+ - **HTTP attempt tap (issue #49, verified 2026-11-24 on pi-ai 1.6.0):**
622
+ `CreateProviderOptions` has **no** `fetch` field — issue #49's claim that
623
+ "`createProvider` acepta el `fetch` en options" is wrong for the pinned
624
+ version. `fetch` is a `StreamOptions` field forwarded to the OpenAI client
625
+ (`dist/api/openai-completions.js:createClient`). `retryProviderRequest`
626
+ retries by re-invoking the same client with `maxRetries: 0`, and `onResponse`
627
+ fires only **after** that loop, so a rejected attempt never reaches it.
628
+ `src/http-attempts.ts` therefore wraps the provider api outermost
629
+ (`withHttpAttemptCapture`) and injects `StreamOptions.fetch` — the only tap
630
+ that sees every attempt, including a 429 that never produced a gateway `id`.
631
+ It appends one `attempt` row per fetch (status, whitelisted headers, ms
632
+ timing, `attempt_n`, `payload_bytes`, request parameters, process-scoped
633
+ inflight/60 s counters) and one `response` row per completed request
634
+ (`response_id`/`created`) to `<agentDir>/nan-http-attempts.jsonl`, bounded to
635
+ 50k lines and best-effort. `onPayload` is awaited once per logical request
636
+ before the retry loop, so the payload size and parameters measured there hold
637
+ for every attempt; the request body itself is never read (consuming the SDK's
638
+ request body would break the call). A non-2xx response is cloned and at most
639
+ 8 KB are read to keep only `error.type`/`error.code` (never the body or its
640
+ message). A fetch rejection sets `transport_error` (the exception name), while
641
+ `error_type`/`error_code` stay the gateway's. `time_to_header_ms` is start →
642
+ headers; the response row carries `duration_ms` (first attempt start →
643
+ completion), `usage` and the raw `finish_reason`, so the artifact is a
644
+ superset of the reporter's per-attempt CSV. The default report carries no prompt,
645
+ response or tool content: `sessions/` is opt-in (`--include-prompts`,
646
+ tool calls stripped; `--include-tools` keeps them; `--all` also puts
647
+ `usage_window.json` in the zip), embedded transcripts keep only their
648
+ `cwd` header MD5-hashed, `topic` is a `topic_hash`, and
649
+ `errors.jsonl` stores only gateway-body fields. `errors.jsonl` correlates a
650
+ failed logical request to its terminal attempt by model + the turn's own span
651
+ (pi records no response id for a failure), leaving the cells null when
652
+ nothing matches. `parseGatewayError` accepts BOTH shapes that reach the
653
+ transcript: the raw HTTP body `{"error":{…}}` and pi-ai's normalized
654
+ `429: {"message":…,"type":…,"code":…}` (verified against the pinned SDK:
655
+ `formatProviderError(normalizeProviderError(APIError.generate(...)))` emits
656
+ the inner object without the `error` envelope — requiring `parsed.error`
657
+ alone silently nulled every structured field). Regression tests: `test/issue-49-http-attempts.test.ts`,
658
+ `test/issue-49-debug-report.test.ts`, `test/issue-49-nan-debug-command.test.ts`.
621
659
  Regression tests: `test/issue-35-cache-anomaly-capture.test.ts`,
622
660
  `test/issue-35-debug-report.test.ts`, `test/issue-35-nan-debug-command.test.ts`.
623
661
 
package/README.es.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # @gtrabanco/𝜋-nan-provider
2
2
 
3
3
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
4
- [![Version](https://img.shields.io/badge/version-1.6.1-blue)](https://github.com/gtrabanco/pi-nan-provider/releases)
4
+ [![Version](https://img.shields.io/badge/version-1.6.3-blue)](https://github.com/gtrabanco/pi-nan-provider/releases)
5
5
  [![Built with NaN](https://nan.builders/badge/built-with-nan-compact.svg)](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).
@@ -28,7 +28,7 @@ Registra el proveedor `nan` vía `pi.registerProvider()` usando la API OpenAI-co
28
28
  | **Modelos de imagen nativos** | `flux-2-klein` y `qwen-image-2.1` registrados como modelos de pi `type: "image"`, accesibles desde codemode y extensiones. |
29
29
  | **Puente MCP nativo de media** | El servidor `nan-media` (10 herramientas) registrado con `pi.registerMcpServer()`, gestionado con `/nan-mcp`. |
30
30
  | **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)). |
31
- | **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
+ | **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), ventanas flexibles `--interval` ([#44](https://github.com/gtrabanco/pi-nan-provider/issues/44)) y el tap de intentos HTTP ([#49](https://github.com/gtrabanco/pi-nan-provider/issues/49)): status, cabeceras de la whitelist, reintentos invisibles (`attempt_n`), concurrencia/RPM del proceso y `payload_bytes` — el zip no lleva prompt ni tool content salvo que lo pidas. |
32
32
  | **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. |
33
33
 
34
34
  Comandos:
@@ -37,7 +37,7 @@ Comandos:
37
37
  | :--- | :--- |
38
38
  | `/nan-mcp` | Gestionar el puente MCP de media (`status` / `enable` / `disable`) |
39
39
  | `/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 |
40
- | `/nan-debug [tema] [--window N] [--interval FLEX] [--out ruta] [--emit]` | Paquete de evidencia reproducible y redactado para NaN |
40
+ | `/nan-debug [tema] [--window N] [--interval FLEX] [--out ruta] [--emit] [--include-prompts] [--include-tools] [--all]` | Paquete de evidencia reproducible y redactado para NaN; el contenido es opcional |
41
41
 
42
42
  ---
43
43
 
@@ -410,21 +410,46 @@ guarda en `<agentDir>/nan-response-rays.jsonl` — `response_id`, `cf_ray`,
410
410
  soporte tiene los rays de cualquier par de llamadas sin esperar a una
411
411
  recurrencia.
412
412
 
413
- `/nan-debug` convierte ese fichero y tus transcripts en un paquete de evidencia
413
+ Cada **intento HTTP** — incluidos los reintentos que pi-ai oculta y los 429 que
414
+ nunca producen un id de gateway — se guarda en
415
+ `<agentDir>/nan-http-attempts.jsonl`
416
+ (issue [#49](https://github.com/gtrabanco/pi-nan-provider/issues/49)): status,
417
+ las cabeceras de respuesta de la whitelist (`cf-ray`, `x-request-id`,
418
+ `Retry-After`, `x-should-retry`, `rate-limit-*`), inicio/fin en milisegundos más
419
+ `latency_ms`, `attempt_n`, `payload_bytes`, los parámetros de la petición
420
+ (`reasoning_effort`, `max_tokens`, el campo realmente enviado, `stream`), el
421
+ `error_type`/`error_code` del cuerpo no-2xx y los contadores de concurrencia e
422
+ inicios en 60 s, que son del proceso. `time_to_header_ms` es inicio → cabeceras
423
+ (la señal de rechazo temprano, p. ej. la mediana de 237 ms); la duración total,
424
+ el `usage` de tokens y el `finish_reason` en bruto van en la fila `response` de
425
+ cada petición. El informe embebe las filas filtradas por la ventana como
426
+ `http_attempts.jsonl`, así que un solo zip responde *qué intento falló, con qué
427
+ status y cabeceras y tras cuántos reintentos*.
428
+
429
+ `/nan-debug` convierte esos ficheros y tus transcripts en un paquete de evidencia
414
430
  redactado y reproducible para NaN:
415
431
 
416
432
  ```text
417
- /nan-debug # últimos 7 días, escribe <agentDir>/nan-debug-report/
433
+ /nan-debug # últimos 7 días; escribe <agentDir>/nan-debug-report-<fecha-hora de emisión>/
418
434
  /nan-debug cache --window 2 # etiqueta de tema + ventana de 2 días
419
- /nan-debug --window 2 --emit # además escribe <agentDir>/nan-debug-report.zip
435
+ /nan-debug --window 2 --emit # además escribe <agentDir>/nan-debug-report-<fecha-hora de emisión>.zip
436
+ /nan-debug cache --include-prompts --emit # embebe los transcripts en bruto (sin tool calls)
437
+ /nan-debug --all --emit # transcripts + tool calls + usage_window.json (el volcado previo a #49)
420
438
  /nan-debug cache --out ~/evidence --emit
421
439
  /nan-debug --interval 5min # intervalos relativos: 5min, 2h, 3d, 1mes
422
440
  /nan-debug --interval "2026-11-10 - 2026-11-11 17:30" # rangos, extremos abiertos y puntos únicos también
423
441
  ```
424
442
 
443
+ - El directorio y el zip por defecto llevan la fecha-hora de **emisión** en UTC
444
+ (`nan-debug-report-YYYY-MM-DDTHH:mm:ss`; el zip usa `-` en vez de `:` para que
445
+ el nombre sea portable), así que ejecuciones consecutivas no se machacan. La
446
+ ventana reportada vive en `metadata.window`. Un `--out` explícito se respeta
447
+ tal cual.
425
448
  - `--window N` (1–90 días) consulta además `GET /v1/usage` para el mismo periodo
426
449
  con tu clave guardada y escribe `usage_window.json`; sin el flag no se hace
427
- ninguna petición. Esa llamada en vivo consume el límite de peticiones.
450
+ ninguna petición. Esa llamada en vivo consume el límite de peticiones. La
451
+ ventana de usage queda fuera del zip salvo con `--all`: identifica tu
452
+ cuenta/tier.
428
453
  - `--interval <desc>` sustituye a `--window` (usar ambos es un error) y acepta
429
454
  intervalos relativos (`5min`, `2h`, `3d`, `1mes`), rangos fecha/hora
430
455
  (`2026-11-10 - 2026-11-11 17:30`, `10:30 - 11:00`, cruce de medianoche
@@ -432,31 +457,50 @@ redactado y reproducible para NaN:
432
457
  año-mes (`2026-11 - 2026-12`) y puntos únicos (`2026-11-10`,
433
458
  `2026-11-10T10:00:00Z`). El span máximo es de 90 días y el parseo es
434
459
  determinista — sin llamadas a LLM. El tema, si usas uno, va antes del flag.
460
+ - El contenido es opcional y está **desactivado por defecto**:
461
+ `--include-prompts` embebe los transcripts filtrados por la ventana bajo
462
+ `sessions/` sin tool calls ni resultados (solo su cabecera `cwd` queda
463
+ hasheada en MD5); `--include-tools` los conserva
464
+ (implica prompts); `--all` equivale a ambos más `usage_window.json`. El
465
+ resumen previo indica qué se va a compartir antes de que `--emit` escriba nada.
466
+ - El artefacto por defecto contiene `README.md`, `anonymized_usage.jsonl`
467
+ (totales por fecha/sesión/modelo, conteo de `stopReason`, tasa de acierto de
468
+ caché), `turns.jsonl` (uso por turno, `stopReason`, clase de error,
469
+ `responseId`, `cf_ray`, `created` del gateway, `status` terminal, `attempt_n` y
470
+ los parámetros de la petición), `errors.jsonl` (clase, `status`, `cf_ray`,
471
+ `attempt_n`, los campos parseados `error_type`/`error_code`/`error_param`
472
+ (tanto el envoltorio HTTP en bruto como la forma `status: {objeto interno}`
473
+ que escribe pi-ai), el
474
+ mensaje del propio gateway limitado a 200 caracteres y un hash MD5; una
475
+ petición fallida no tiene response id, así que su `status`/`cf_ray`/`attempt_n`
476
+ se correlacionan por modelo y por el span del turno — con peticiones
477
+ concurrentes al mismo modelo, `http_attempts.jsonl` es el registro autoritativo
478
+ por intento), `http_attempts.jsonl` (una fila por intento más una fila `response` por
479
+ petición completada), `anomalies.jsonl` (el par de `cf-ray`) y `metadata.json`
480
+ (versiones de paquete, pi-ai y pi; procedencia del catálogo; `error_summary`;
481
+ `topic_hash`; y `attempt_summary` con conteos por status, ratios de 429 por
482
+ modelo/hora y la racha de 429 más larga). **No** lleva contenido de prompt,
483
+ respuesta ni tool.
435
484
  - El zip se escribe **solo** con `--emit`; la ejecución por defecto escribe el
436
485
  informe local e imprime un resumen.
437
486
  - `--out <ruta>` escribe el informe donde lo indiques (y, con `--emit`,
438
487
  `<ruta>.zip`); un `~/` inicial se expande a tu directorio home, así que los
439
488
  ejemplos de arriba escriben donde dicen. Un token de flag nunca se acepta
440
489
  como ruta.
441
- - El informe contiene `README.md`, `anonymized_usage.jsonl` (totales por
442
- fecha/sesión/modelo, conteo de `stopReason`, tasa de acierto de caché),
443
- `turns.jsonl` (uso por turno, `stopReason`, clase de error, `responseId`,
444
- `cf_ray`),
445
- `errors.jsonl` (una fila por turno con error: clase, fragmento de 200
446
- caracteres del mensaje, hash MD5 del mensaje completo, tokens de entrada/
447
- salida, `responseId`), `anomalies.jsonl` (par de `cf-ray`), `sessions/` (los
448
- JSONL de sesión en bruto filtrados por la ventana) y `metadata.json`
449
- (versiones de paquete, pi-ai y pi; procedencia del catálogo;
450
- `error_summary`).
451
- - Las etiquetas de sesión y worktree son MD5 truncado a 12 caracteres (incluida
452
- la cabecera `cwd` dentro de `sessions/`); `errorMessage` se reduce a
453
- `overflow | rate_limited | invalid_request | transport | other`, y
454
- `errors.jsonl` conserva como mucho 200 caracteres del mensaje en bruto más
455
- un hash MD5. Las credenciales nunca se recogen en ningún sitio; el contenido
456
- de prompt/respuesta nunca se recoge en los ficheros raíz — `sessions/` es la
457
- excepción: transcripts en bruto incluidos a petición
458
- ([#44](https://github.com/gtrabanco/pi-nan-provider/issues/44)), solo con
459
- `cwd` hasheado. Entradas idénticas producen bytes de zip idénticos.
490
+ - El `topic` va hasheado en el artefacto (`topic_hash`, MD5[:16]); el resumen de
491
+ consola es solo local. Las etiquetas de sesión y worktree son MD5 truncado a
492
+ 16 caracteres (sin salt por informe, para enlazar la misma sesión entre
493
+ informes). `errors.jsonl` nunca guarda texto de transporte ni excepciones del
494
+ lado pi, un mensaje del servidor que sobreviva tiene tu home sustituido por
495
+ `~`, y las credenciales y toda cabecera fuera de la whitelist nunca se
496
+ recogen.
497
+ - `inflight_process_at_start` y `starts_last_60s_process*` son del proceso de pi:
498
+ **no** son la concurrencia/RPM de tu clave si otros clientes la comparten.
499
+ Une el log de todos los clientes para cifras por clave.
500
+ - **No público.** El artefacto es para soporte de NaN: `cf-ray`, `response_id` y
501
+ los timestamps al milisegundo no se anonimizan a propósito, y
502
+ `anomalies.jsonl` huella el payload de la petición con SHA-256. Entradas
503
+ idénticas siguen produciendo bytes de zip idénticos.
460
504
 
461
505
  ## 🧭 Model facts: `NAN_MODEL_FACTS`
462
506
 
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # @gtrabanco/𝜋-nan-provider
2
2
 
3
3
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
4
- [![Version](https://img.shields.io/badge/version-1.6.1-blue)](https://github.com/gtrabanco/pi-nan-provider/releases)
4
+ [![Version](https://img.shields.io/badge/version-1.6.3-blue)](https://github.com/gtrabanco/pi-nan-provider/releases)
5
5
  [![Built with NaN](https://nan.builders/badge/built-with-nan-compact.svg)](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).
@@ -28,7 +28,7 @@ Registers the `nan` provider via `pi.registerProvider()` using NaN's OpenAI-comp
28
28
  | **Native image models** | `flux-2-klein` and `qwen-image-2.1` registered as pi `type: "image"` models, reachable from codemode and extensions. |
29
29
  | **Native MCP media bridge** | The `nan-media` server (10 tools) registered through `pi.registerMcpServer()`, managed with `/nan-mcp`. |
30
30
  | **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)). |
31
- | **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
+ | **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), flexible `--interval` windows ([#44](https://github.com/gtrabanco/pi-nan-provider/issues/44)) and the HTTP attempt tap ([#49](https://github.com/gtrabanco/pi-nan-provider/issues/49)): status, whitelisted headers, invisible retries (`attempt_n`), process-scoped concurrency/RPM and `payload_bytes` — the zip carries no prompt or tool content unless you opt in. |
32
32
  | **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. |
33
33
 
34
34
  Commands:
@@ -37,7 +37,7 @@ Commands:
37
37
  | :--- | :--- |
38
38
  | `/nan-mcp` | Manage the media MCP bridge (`status` / `enable` / `disable`) |
39
39
  | `/nan-usage [1-90]` | Credits balance with usage bar, per-model breakdown (in / cached / out in M · credits cr), and all-time totals |
40
- | `/nan-debug [topic] [--window N] [--interval FLEX] [--out path] [--emit]` | Redacted, reproducible evidence package for NaN |
40
+ | `/nan-debug [topic] [--window N] [--interval FLEX] [--out path] [--emit] [--include-prompts] [--include-tools] [--all]` | Redacted, reproducible evidence package for NaN; content is opt-in |
41
41
 
42
42
  ---
43
43
 
@@ -407,21 +407,43 @@ Independently of any anomaly, every response's `cf-ray` is kept in
407
407
  report joins it into `turns.jsonl` as `cf_ray`, so support gets the rays of
408
408
  any pair of calls without waiting for a recurrence.
409
409
 
410
- `/nan-debug` turns that file plus your session transcripts into a redacted,
410
+ Every HTTP **attempt** — including the retries pi-ai hides and the 429s that never
411
+ produce a gateway id — is kept in `<agentDir>/nan-http-attempts.jsonl`
412
+ (issue [#49](https://github.com/gtrabanco/pi-nan-provider/issues/49)): status,
413
+ the whitelisted response headers (`cf-ray`, `x-request-id`, `Retry-After`,
414
+ `x-should-retry`, `rate-limit-*`), millisecond start/end plus `latency_ms`,
415
+ `attempt_n`, `payload_bytes`, the request parameters (`reasoning_effort`,
416
+ `max_tokens`, the field actually sent, `stream`), the gateway
417
+ `error_type`/`error_code` of a non-2xx body and the process-scoped inflight/60 s
418
+ counters. `time_to_header_ms` is start → headers (the early-rejection signal,
419
+ e.g. the 237 ms median); the full request duration, token `usage` and raw
420
+ `finish_reason` ride the per-request `response` row. The report embeds the
421
+ window-filtered rows as `http_attempts.jsonl`, so one zip answers *which attempt
422
+ failed, with which status and headers, after how many retries*.
423
+
424
+ `/nan-debug` turns those files plus your session transcripts into a redacted,
411
425
  reproducible evidence package for NaN:
412
426
 
413
427
  ```text
414
- /nan-debug # last 7 days, writes <agentDir>/nan-debug-report/
428
+ /nan-debug # last 7 days; writes <agentDir>/nan-debug-report-<emission timestamp>/
415
429
  /nan-debug cache --window 2 # topic label + a 2-day window
416
- /nan-debug --window 2 --emit # also writes <agentDir>/nan-debug-report.zip
430
+ /nan-debug --window 2 --emit # also writes <agentDir>/nan-debug-report-<emission timestamp>.zip
431
+ /nan-debug cache --include-prompts --emit # embed raw transcripts (tool calls stripped)
432
+ /nan-debug --all --emit # transcripts + tool calls + usage_window.json (the pre-#49 dump)
417
433
  /nan-debug cache --out ~/evidence --emit
418
434
  /nan-debug --interval 5min # relative spans: 5min, 2h, 3d, 1mes
419
435
  /nan-debug --interval "2026-11-10 - 2026-11-11 17:30" # ranges, open ends, single points too
420
436
  ```
421
437
 
438
+ - The default directory and zip names carry the **emission** timestamp in UTC
439
+ (`nan-debug-report-YYYY-MM-DDTHH:mm:ss`; the zip uses `-` instead of `:` so the
440
+ name is portable), so consecutive runs never overwrite each other. The
441
+ reported window lives in `metadata.window`. An explicit `--out` is respected
442
+ verbatim.
422
443
  - `--window N` (1–90 days) also fetches `GET /v1/usage` for the same period with
423
444
  your stored key and writes `usage_window.json`; without the flag nothing is
424
- fetched. That live call counts against your quota's request rate.
445
+ fetched. That live call counts against your quota's request rate. The usage
446
+ window stays out of the zip unless `--all`: it identifies your account/tier.
425
447
  - `--interval <desc>` replaces `--window` (using both is an error) and accepts
426
448
  relative spans (`5min`, `2h`, `3d`, `1mes`), date/time ranges
427
449
  (`2026-11-10 - 2026-11-11 17:30`, `10:30 - 11:00`, cross-midnight
@@ -429,27 +451,45 @@ reproducible evidence package for NaN:
429
451
  (`2026-11 - 2026-12`) and single points (`2026-11-10`,
430
452
  `2026-11-10T10:00:00Z`). The span is capped at 90 days and parsing is fully
431
453
  deterministic — no LLM calls. The topic, when you use one, goes before the flag.
454
+ - Content is opt-in and **off by default**: `--include-prompts` embeds the
455
+ window-filtered transcripts under `sessions/` with tool calls and results
456
+ stripped (their `cwd` header stays MD5-hashed); `--include-tools` keeps them (it implies prompts); `--all` equals
457
+ both plus `usage_window.json`. The preview states what will be shared before
458
+ `--emit` writes anything.
459
+ - The default artifact contains `README.md`, `anonymized_usage.jsonl` (per
460
+ date/session/model totals, stop-reason counts, cache-hit rate), `turns.jsonl`
461
+ (per-turn usage, stop reason, error class, response id, `cf_ray`, gateway
462
+ `created`, terminal `status`, `attempt_n` and the request parameters),
463
+ `errors.jsonl` (class, `status`, `cf_ray`, `attempt_n`, the parsed
464
+ `error_type`/`error_code`/`error_param` (both the raw HTTP envelope and the
465
+ `status: {inner object}` shape pi-ai writes), the gateway's own message capped at
466
+ 200 chars and an MD5 hash; a failed request has no response id, so its
467
+ `status`/`cf_ray`/`attempt_n` are correlated by model and the turn's span —
468
+ with concurrent requests to the same model, `http_attempts.jsonl` is the
469
+ authoritative per-attempt record), `http_attempts.jsonl` (one row per attempt plus one
470
+ `response` row per completed request), `anomalies.jsonl` (the `cf-ray` pair) and
471
+ `metadata.json` (package/pi-ai/pi versions, catalog provenance,
472
+ `error_summary`, `topic_hash`, and `attempt_summary` with status counts, 429
473
+ ratios per model/hour and the longest 429 streak). It carries **no** prompt,
474
+ response or tool content.
432
475
  - The zip is written **only** with `--emit`; the default run writes the local
433
- report and prints a preview.
476
+ report and prints the preview.
434
477
  - `--out <path>` writes the report anywhere you name it (and, with `--emit`,
435
478
  `<path>.zip`); a leading `~/` expands to your home directory, so the examples
436
479
  above write where they say. A flag token is never accepted as the path.
437
- - The report contains `README.md`, `anonymized_usage.jsonl` (per date/session/
438
- model totals, stop-reason counts, cache-hit rate), `turns.jsonl` (per-turn
439
- usage, stop reason, error class, response id, `cf_ray`), `errors.jsonl` (one row per
440
- errored turn: class, 200-char message fragment, MD5 hash of the full message,
441
- input/output tokens, response id), `anomalies.jsonl` (`cf-ray` pair),
442
- `sessions/` (the raw session JSONL files filtered to the window) and
443
- `metadata.json` (package/pi-ai/pi versions, catalog provenance,
444
- `error_summary`).
445
- - Session and worktree labels are MD5-truncated to 12 chars (including the
446
- `cwd` header inside `sessions/`); `errorMessage` is reduced to `overflow |
447
- rate_limited | invalid_request | transport | other`, and `errors.jsonl` keeps
448
- at most 200 characters of the raw message plus an MD5 hash. Credentials are
449
- never collected anywhere; prompt/response content is never collected in the
450
- root files — `sessions/` is the exception, raw transcripts included on
451
- request ([#44](https://github.com/gtrabanco/pi-nan-provider/issues/44)), with
452
- only `cwd` hashed. Identical inputs produce byte-identical zip bytes.
480
+ - A `topic` is hashed in the artifact (`topic_hash`, MD5[:16]); the console
481
+ preview is local only. Session and worktree labels are MD5 truncated to 16
482
+ characters (no per-report salt, so the same session links across reports).
483
+ `errors.jsonl` never stores transport or pi-side exception text, a surviving
484
+ server message has your home directory scrubbed to `~`, and credentials plus
485
+ every non-whitelisted header are never collected.
486
+ - `inflight_process_at_start` and `starts_last_60s_process*` are scoped to this
487
+ pi process: they are **not** your key's concurrency/RPM when other clients
488
+ share the key. Merge every client's log for key-wide numbers.
489
+ - **Not public.** The artifact is for NaN support: `cf-ray`, `response_id` and
490
+ millisecond timestamps are deliberately not anonymized, and `anomalies.jsonl`
491
+ fingerprints the request payload with SHA-256. Identical inputs still produce
492
+ byte-identical zip bytes.
453
493
 
454
494
  ## 🧭 Model facts: `NAN_MODEL_FACTS`
455
495
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gtrabanco/pi-nan-provider",
3
- "version": "1.6.1",
3
+ "version": "1.6.3",
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-23T00:46:05.244Z
4
+ // Source: https://models.dev/api.json (provider "nan"), fetched 2026-11-25T10:55:49.540Z
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.
@@ -506,10 +506,10 @@ export const NAN_GENERATED_MODELS: readonly GeneratedModelEntry[] = [
506
506
  "text"
507
507
  ]
508
508
  },
509
- "open_weights": false,
509
+ "open_weights": true,
510
510
  "limit": {
511
511
  "context": 1048576,
512
- "input": 983010,
512
+ "input": 983040,
513
513
  "output": 65536
514
514
  },
515
515
  "cost": {
@@ -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-23T00:46:05.244Z",
1030
+ fetchedAt: "2026-11-25T10:55:49.540Z",
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: [
@@ -15,9 +15,9 @@ import { getAgentDir } from "@earendil-works/pi-coding-agent";
15
15
  import { NAN_API_KEY_ENV, resolveStoredNanApiKey, tryResolveNanApiKeyViaRegistry } from "./mcp/api-key.ts";
16
16
  import {
17
17
  DEBUG_USAGE_LINE,
18
- NAN_DEBUG_REPORT_DIR,
19
- NAN_DEBUG_ZIP,
20
18
  buildDebugReport,
19
+ debugReportDirName,
20
+ debugReportZipName,
21
21
  fetchDebugUsageWindow,
22
22
  parseDebugArgs,
23
23
  renderDebugReport,
@@ -91,7 +91,10 @@ export function registerNanDebugCommand(pi: ExtensionAPI, deps: NanDebugCommandD
91
91
  fetchUsage: parsed.args.windowProvided ? (deps.fetchUsage ?? fetchDebugUsageWindow) : undefined,
92
92
  sessionsDir,
93
93
  });
94
- rendered = renderDebugReport(report, sessionsDir);
94
+ rendered = renderDebugReport(report, sessionsDir, {
95
+ includePrompts: parsed.args.includePrompts,
96
+ includeTools: parsed.args.includeTools,
97
+ });
95
98
  } catch (error) {
96
99
  ctx.ui.notify(
97
100
  `nan-debug failed to collect the report: ${error instanceof Error ? error.message : String(error)}`,
@@ -102,14 +105,16 @@ export function registerNanDebugCommand(pi: ExtensionAPI, deps: NanDebugCommandD
102
105
 
103
106
  const explicitZipTarget = parsed.args.out ? expandHomePath(parsed.args.out, deps.homedir ?? osHomedir()) : undefined;
104
107
  const explicitZip = explicitZipTarget?.endsWith(".zip") ? explicitZipTarget : undefined;
108
+ // Default names carry the emission timestamp (UTC) so consecutive runs
109
+ // never overwrite each other; an explicit `--out` is respected verbatim.
105
110
  const outDir = explicitZip
106
111
  ? explicitZip.replace(/\.zip$/, "")
107
- : (explicitZipTarget ?? join(agentDir, NAN_DEBUG_REPORT_DIR));
108
- const zipPath = explicitZip ?? (explicitZipTarget ? `${explicitZipTarget}.zip` : join(agentDir, NAN_DEBUG_ZIP));
112
+ : (explicitZipTarget ?? join(agentDir, debugReportDirName(now)));
113
+ const zipPath = explicitZip ?? (explicitZipTarget ? `${explicitZipTarget}.zip` : join(agentDir, debugReportZipName(now)));
109
114
 
110
115
  try {
111
116
  writeDebugReport(rendered.files, outDir);
112
- if (parsed.args.emit) writeDebugZip(rendered.files, zipPath);
117
+ if (parsed.args.emit) writeDebugZip(rendered.files, zipPath, { includeUsageWindow: parsed.args.all });
113
118
  } catch (error) {
114
119
  ctx.ui.notify(
115
120
  `nan-debug wrote nothing: ${error instanceof Error ? error.message : String(error)}`,