@gtrabanco/pi-nan-provider 1.6.0 → 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
@@ -317,6 +317,28 @@ Since 1.0.0 the package version **aligns its MAJOR.MINOR with the pi release lin
317
317
  A model with a confirmed per-token price can still override `cost` through
318
318
  `MANUAL_OVERRIDES`; to adopt models.dev's numbers everywhere, delete the constant.
319
319
  Regression test: `test/larger-models-2026-11-17.test.ts`.
320
+ - **`NAN_MODEL_FACTS` is the public facts surface (issue #47, package 1.6.1).**
321
+ `src/model-facts.ts` exports the deep-frozen record keyed by chat model id plus
322
+ `NAN_ENDPOINT_FACTS` and `NAN_MODEL_FACTS_META`; `src/model-facts-core.ts` owns
323
+ the value unions, the `NAN_FACT_SOURCES` citation table, the builder guards and
324
+ the freezer (deliberately free of catalog imports so the generator can validate
325
+ the entries it just built before writing them); the manual values live in
326
+ `scripts/model-facts.ts`, next to the override path they belong to. The
327
+ generator fails when a catalog id has no declaration, a declaration names a
328
+ ghost id, a value falls outside its documented union, or a cell carries no
329
+ provenance id — an unsourced cell can never reach a published catalog. Carried
330
+ cells (limits, cost, modalities, reasoning list/map, compat) are read from the
331
+ generated catalog entry; the eight new cells come from the manual layer with a
332
+ per-cell source id. Two rules the data encodes: `"unmeasured"` is never
333
+ "false" (nothing was measured — `parallelToolCalls` is unmeasured on every
334
+ model, `structuredOutput` is a boolean only where the docs name
335
+ `json_object`/`json_schema`), and the cold-prompt ceiling is endpoint-wide, so
336
+ every `coldCeilingTokens` cell is `"unmeasured"` while the 200,000-token
337
+ measurement ships as `NAN_ENDPOINT_FACTS.coldCacheCeilingTokens` (measured
338
+ 2026-10-01, scope "not a model capability"). Importing the record performs no
339
+ network read and never feeds provider registration: the #19 read-time overlay
340
+ stays the only thing that shapes the models a session sees.
341
+ Regression test: `test/issue-47-model-facts.test.ts`.
320
342
  - A NaN request that still exceeds the destination model's context window (the
321
343
  cross-model thinking guard is disabled with `NAN_THINKING_GUARD=0`, the
322
344
  inflation is not a `thinking` block, or the window is smaller) gets NaN's
@@ -570,8 +592,8 @@ Since 1.0.0 the package version **aligns its MAJOR.MINOR with the pi release lin
570
592
  called by openai-completions right after the HTTP response). The gateway
571
593
  `id`/`created` pair comes from raw `onProviderStreamEvent` chunks: pi-ai copies
572
594
  only `chunk.id` into `AssistantMessage.responseId`, and `created` is never
573
- persisted. `src/cache-anomaly.ts` wraps the provider api outermost
574
- (`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
575
597
  previous one **per model**, and on the #17 signature (same `id` + `created`)
576
598
  appends one record to `<agentDir>/nan-cache-anomalies.jsonl`. Bursts record
577
599
  the first pair once; a differing signature resets the baseline. The record is
@@ -581,10 +603,8 @@ Since 1.0.0 the package version **aligns its MAJOR.MINOR with the pi release lin
581
603
  `src/debug-report.ts` reads `<agentDir>/sessions/**/*.jsonl` (filename date
582
604
  prefix, else mtime), extracts only assistant `provider: "nan"` turns, and
583
605
  renders the 2026-11-10 report shape plus `turns.jsonl`. PR #44 (2026-11-18)
584
- adds `errors.jsonl` rows and `error_summary` in `metadata.json`, embeds the
585
- window-filtered raw transcripts under `sessions/` (their `cwd` header is
586
- MD5-hashed; root files stay redacted — the transcripts are the owner's
587
- 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
588
608
  at 90 days, mutually exclusive with `--window`; its value joins tokens up to
589
609
  the next `--` flag because pi passes slash-command args raw). Since 1.5.9
590
610
  every response's `cf-ray` is appended by the same wrapper to
@@ -594,8 +614,48 @@ Since 1.0.0 the package version **aligns its MAJOR.MINOR with the pi release lin
594
614
  2026-11-18; null when uncaptured). The zip is built by
595
615
  `src/zip.ts` (store method, sorted entries, fixed 1980-01-01 timestamps)
596
616
  because `Bun.Archive` is Bun-only and pi also runs on Node. Session/worktree
597
- 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
598
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`.
599
659
  Regression tests: `test/issue-35-cache-anomaly-capture.test.ts`,
600
660
  `test/issue-35-debug-report.test.ts`, `test/issue-35-nan-debug-command.test.ts`.
601
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.0-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).
@@ -23,11 +23,12 @@ Registra el proveedor `nan` vía `pi.registerProvider()` usando la API OpenAI-co
23
23
  | **Reintento de streams truncados** | `supportsFinishReason: true` convierte un stream SSE cerrado antes de `finish_reason` en un error reintentable en vez de un stall silencioso ([#2](https://github.com/gtrabanco/pi-nan-provider/issues/2)). |
24
24
  | **Uso de tokens en streaming** | `stream_options.include_usage` activo por defecto, así que pi reporta recuentos reales de entrada/salida/razonamiento/caché ([#4](https://github.com/gtrabanco/pi-nan-provider/issues/4), [#7](https://github.com/gtrabanco/pi-nan-provider/issues/7)). |
25
25
  | **Controles de razonamiento** | `reasoningEffortValues` + `thinkingLevelMap` por modelo ([#16](https://github.com/gtrabanco/pi-nan-provider/issues/16)), el guard de stream solo-razonamiento ([#21](https://github.com/gtrabanco/pi-nan-provider/issues/21)) y el campo de tokens máximo por modelo (`qwen3.8-max` mantiene `max_completion_tokens`; `qwen3.8-flash` volvió a `max_tokens` tras el arreglo del gateway de NaN, [#34](https://github.com/gtrabanco/pi-nan-provider/issues/34) → [#36](https://github.com/gtrabanco/pi-nan-provider/issues/36)). |
26
+ | **Export de model facts** | `NAN_MODEL_FACTS` — una entrada congelada y tipada por modelo de chat facturado: límites, tarifas, contrato de razonamiento, protocolo de herramientas, semántica de `max_tokens`, presupuesto de pensamiento, modo de caché y clase de facturación, con un id de procedencia en cada celda ([#47](https://github.com/gtrabanco/pi-nan-provider/issues/47)). |
26
27
  | **Cabecera de atribución** | `X-Pi-Provider: gtrabanco/pi-nan-provider@<version>` en cada petición, eliminada cuando la telemetría de instalación de pi está desactivada. |
27
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. |
28
29
  | **Puente MCP nativo de media** | El servidor `nan-media` (10 herramientas) registrado con `pi.registerMcpServer()`, gestionado con `/nan-mcp`. |
29
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)). |
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
+ | **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. |
31
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. |
32
33
 
33
34
  Comandos:
@@ -36,7 +37,7 @@ Comandos:
36
37
  | :--- | :--- |
37
38
  | `/nan-mcp` | Gestionar el puente MCP de media (`status` / `enable` / `disable`) |
38
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 |
39
- | `/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 |
40
41
 
41
42
  ---
42
43
 
@@ -409,21 +410,46 @@ guarda en `<agentDir>/nan-response-rays.jsonl` — `response_id`, `cf_ray`,
409
410
  soporte tiene los rays de cualquier par de llamadas sin esperar a una
410
411
  recurrencia.
411
412
 
412
- `/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
413
430
  redactado y reproducible para NaN:
414
431
 
415
432
  ```text
416
- /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>/
417
434
  /nan-debug cache --window 2 # etiqueta de tema + ventana de 2 días
418
- /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)
419
438
  /nan-debug cache --out ~/evidence --emit
420
439
  /nan-debug --interval 5min # intervalos relativos: 5min, 2h, 3d, 1mes
421
440
  /nan-debug --interval "2026-11-10 - 2026-11-11 17:30" # rangos, extremos abiertos y puntos únicos también
422
441
  ```
423
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.
424
448
  - `--window N` (1–90 días) consulta además `GET /v1/usage` para el mismo periodo
425
449
  con tu clave guardada y escribe `usage_window.json`; sin el flag no se hace
426
- 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.
427
453
  - `--interval <desc>` sustituye a `--window` (usar ambos es un error) y acepta
428
454
  intervalos relativos (`5min`, `2h`, `3d`, `1mes`), rangos fecha/hora
429
455
  (`2026-11-10 - 2026-11-11 17:30`, `10:30 - 11:00`, cruce de medianoche
@@ -431,31 +457,107 @@ redactado y reproducible para NaN:
431
457
  año-mes (`2026-11 - 2026-12`) y puntos únicos (`2026-11-10`,
432
458
  `2026-11-10T10:00:00Z`). El span máximo es de 90 días y el parseo es
433
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.
434
484
  - El zip se escribe **solo** con `--emit`; la ejecución por defecto escribe el
435
485
  informe local e imprime un resumen.
436
486
  - `--out <ruta>` escribe el informe donde lo indiques (y, con `--emit`,
437
487
  `<ruta>.zip`); un `~/` inicial se expande a tu directorio home, así que los
438
488
  ejemplos de arriba escriben donde dicen. Un token de flag nunca se acepta
439
489
  como ruta.
440
- - El informe contiene `README.md`, `anonymized_usage.jsonl` (totales por
441
- fecha/sesión/modelo, conteo de `stopReason`, tasa de acierto de caché),
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.
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.
504
+
505
+ ## 🧭 Model facts: `NAN_MODEL_FACTS`
506
+
507
+ Casi todo lo que este paquete sabe de la flota vivía en este README y en
508
+ comentarios del código. El issue [#47](https://github.com/gtrabanco/pi-nan-provider/issues/47)
509
+ lo convierte en datos: un registro congelado y tipado, exportado desde el punto
510
+ de entrada, para que tus scripts planifiquen contexto, caché y gasto sin leer
511
+ prosa ni entrar en `scripts/`.
512
+
513
+ ```ts
514
+ import { NAN_MODEL_FACTS, NAN_ENDPOINT_FACTS, NAN_MODEL_FACTS_META } from "@gtrabanco/pi-nan-provider";
515
+
516
+ const facts = NAN_MODEL_FACTS["deepseek-v4-flash"];
517
+ facts.contextWindow; // 1048576
518
+ facts.maxTokens; // 32768
519
+ facts.cost; // { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }
520
+ facts.input; // ["text", "image"]
521
+ facts.toolCalling; // "openai-tools" | "xml"
522
+ facts.maxTokensSemantics; // "bounds-total" | "bounds-visible-answer"
523
+ facts.thinkingBudget; // "honoured" | "ignored" | "unmeasured"
524
+ facts.cacheMode; // "automatic" | "opt-in" | "unsupported" | "unmeasured"
525
+ facts.billingClass; // "quota-only" | "credit-standard" | "credit-larger"
526
+ facts.parallelToolCalls; // boolean | "unmeasured"
527
+ facts.structuredOutput; // boolean | "unmeasured"
528
+
529
+ facts.provenance.toolCalling; // "docs"
530
+ NAN_MODEL_FACTS_META.sources["docs"]; // URL + fecha de comprobación
531
+ ```
532
+
533
+ - **Hechos, no política.** El registro dice qué *es* un modelo. Cómo lo uses —
534
+ fases por contexto, una escalera de enrutado, una estrategia de caché — sigue
535
+ siendo tuyo.
536
+ - **Una entrada por modelo de chat facturado** (13 hoy), con el id de modelo como
537
+ clave. Los endpoints que no son de chat (embedding, rerank, TTS, STT, imagen,
538
+ vídeo) no son modelos de chat y no se exportan.
539
+ - **Procedencia por celda.** Cada celda nombra un id de fuente;
540
+ `NAN_MODEL_FACTS_META.sources` lo resuelve a una URL con su fecha de
541
+ comprobación o a una medición fechada registrada en este repo. Los ids
542
+ `override`, `compat` y `catalog-cost` apuntan a las `notes` de la propia
543
+ entrada, que ya llevan esas citas.
544
+ - **`"unmeasured"` significa que no se afirma nada**, nunca "falso".
545
+ `parallelToolCalls` es `"unmeasured"` en todos los modelos porque nada
546
+ documenta ni mide varias llamadas de herramienta por turno; `structuredOutput`
547
+ es booleano solo donde los docs de NaN documentan `json_object` /
548
+ `json_schema` para ese modelo.
549
+ - **Techo de prompt frío.** `coldCeilingTokens` es `"unmeasured"` en todas las
550
+ entradas: la única medición es de extremo a extremo, así que viaja aparte como
551
+ `NAN_ENDPOINT_FACTS.coldCacheCeilingTokens` (200.000 tokens, medido el
552
+ 2026-10-01) con un `coldCeilingScope` que aclara que es el límite de lectura
553
+ del proxy de Cloudflare (120 s), no una capacidad del modelo. Dimensiona la
554
+ primera petición en frío por debajo de ese valor.
555
+ - **Offline y congelado.** El registro se deriva del catálogo generado que se
556
+ publica más la capa de hechos de build, así que leerlo no hace ninguna llamada
557
+ de red, y está congelado en profundidad: un consumidor no puede cambiar lo que
558
+ lee el siguiente. Nunca alimenta el registro del proveedor — el overlay de
559
+ lectura ([#19](https://github.com/gtrabanco/pi-nan-provider/issues/19)) sigue
560
+ decidiendo los modelos que ve una sesión.
459
561
 
460
562
  ## 📊 Modelos
461
563
 
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.0-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).
@@ -23,11 +23,12 @@ Registers the `nan` provider via `pi.registerProvider()` using NaN's OpenAI-comp
23
23
  | **Truncated-stream retry** | `supportsFinishReason: true` turns an SSE stream closed before `finish_reason` into a retryable error instead of a silent stall ([#2](https://github.com/gtrabanco/pi-nan-provider/issues/2)). |
24
24
  | **Streaming token usage** | `stream_options.include_usage` is on by default, so pi reports real input/output/reasoning/cache counts ([#4](https://github.com/gtrabanco/pi-nan-provider/issues/4), [#7](https://github.com/gtrabanco/pi-nan-provider/issues/7)). |
25
25
  | **Reasoning controls** | Per-model `reasoningEffortValues` + `thinkingLevelMap` ([#16](https://github.com/gtrabanco/pi-nan-provider/issues/16)), the reasoning-only stream guard ([#21](https://github.com/gtrabanco/pi-nan-provider/issues/21)), and the per-model max-token field (`qwen3.8-max` keeps `max_completion_tokens`; `qwen3.8-flash` returned to `max_tokens` after NaN's gateway fix, [#34](https://github.com/gtrabanco/pi-nan-provider/issues/34) → [#36](https://github.com/gtrabanco/pi-nan-provider/issues/36)). |
26
+ | **Model-facts export** | `NAN_MODEL_FACTS` — one frozen, typed entry per billed chat model: limits, cost rates, reasoning contract, tool protocol, `max_tokens` semantics, thinking budget, cache mode and billing class, every cell carrying a provenance id ([#47](https://github.com/gtrabanco/pi-nan-provider/issues/47)). |
26
27
  | **Attribution header** | `X-Pi-Provider: gtrabanco/pi-nan-provider@<version>` on every request, stripped when pi's install telemetry is disabled. |
27
28
  | **Native image models** | `flux-2-klein` and `qwen-image-2.1` registered as pi `type: "image"` models, reachable from codemode and extensions. |
28
29
  | **Native MCP media bridge** | The `nan-media` server (10 tools) registered through `pi.registerMcpServer()`, managed with `/nan-mcp`. |
29
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)). |
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
+ | **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. |
31
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. |
32
33
 
33
34
  Commands:
@@ -36,7 +37,7 @@ Commands:
36
37
  | :--- | :--- |
37
38
  | `/nan-mcp` | Manage the media MCP bridge (`status` / `enable` / `disable`) |
38
39
  | `/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] [--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 |
40
41
 
41
42
  ---
42
43
 
@@ -406,21 +407,43 @@ Independently of any anomaly, every response's `cf-ray` is kept in
406
407
  report joins it into `turns.jsonl` as `cf_ray`, so support gets the rays of
407
408
  any pair of calls without waiting for a recurrence.
408
409
 
409
- `/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,
410
425
  reproducible evidence package for NaN:
411
426
 
412
427
  ```text
413
- /nan-debug # last 7 days, writes <agentDir>/nan-debug-report/
428
+ /nan-debug # last 7 days; writes <agentDir>/nan-debug-report-<emission timestamp>/
414
429
  /nan-debug cache --window 2 # topic label + a 2-day window
415
- /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)
416
433
  /nan-debug cache --out ~/evidence --emit
417
434
  /nan-debug --interval 5min # relative spans: 5min, 2h, 3d, 1mes
418
435
  /nan-debug --interval "2026-11-10 - 2026-11-11 17:30" # ranges, open ends, single points too
419
436
  ```
420
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.
421
443
  - `--window N` (1–90 days) also fetches `GET /v1/usage` for the same period with
422
444
  your stored key and writes `usage_window.json`; without the flag nothing is
423
- 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.
424
447
  - `--interval <desc>` replaces `--window` (using both is an error) and accepts
425
448
  relative spans (`5min`, `2h`, `3d`, `1mes`), date/time ranges
426
449
  (`2026-11-10 - 2026-11-11 17:30`, `10:30 - 11:00`, cross-midnight
@@ -428,27 +451,98 @@ reproducible evidence package for NaN:
428
451
  (`2026-11 - 2026-12`) and single points (`2026-11-10`,
429
452
  `2026-11-10T10:00:00Z`). The span is capped at 90 days and parsing is fully
430
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.
431
475
  - The zip is written **only** with `--emit`; the default run writes the local
432
- report and prints a preview.
476
+ report and prints the preview.
433
477
  - `--out <path>` writes the report anywhere you name it (and, with `--emit`,
434
478
  `<path>.zip`); a leading `~/` expands to your home directory, so the examples
435
479
  above write where they say. A flag token is never accepted as the path.
436
- - The report contains `README.md`, `anonymized_usage.jsonl` (per date/session/
437
- model totals, stop-reason counts, cache-hit rate), `turns.jsonl` (per-turn
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.
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.
493
+
494
+ ## 🧭 Model facts: `NAN_MODEL_FACTS`
495
+
496
+ Most of what this package knows about the fleet used to live in this README and
497
+ in inline comments. Issue [#47](https://github.com/gtrabanco/pi-nan-provider/issues/47)
498
+ promotes it to data: one frozen, typed record, exported from the package entry
499
+ point, so your own scripts can plan context, caching and spend without parsing
500
+ prose or reaching into `scripts/`.
501
+
502
+ ```ts
503
+ import { NAN_MODEL_FACTS, NAN_ENDPOINT_FACTS, NAN_MODEL_FACTS_META } from "@gtrabanco/pi-nan-provider";
504
+
505
+ const facts = NAN_MODEL_FACTS["deepseek-v4-flash"];
506
+ facts.contextWindow; // 1048576
507
+ facts.maxTokens; // 32768
508
+ facts.cost; // { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 }
509
+ facts.input; // ["text", "image"]
510
+ facts.toolCalling; // "openai-tools" | "xml"
511
+ facts.maxTokensSemantics; // "bounds-total" | "bounds-visible-answer"
512
+ facts.thinkingBudget; // "honoured" | "ignored" | "unmeasured"
513
+ facts.cacheMode; // "automatic" | "opt-in" | "unsupported" | "unmeasured"
514
+ facts.billingClass; // "quota-only" | "credit-standard" | "credit-larger"
515
+ facts.parallelToolCalls; // boolean | "unmeasured"
516
+ facts.structuredOutput; // boolean | "unmeasured"
517
+
518
+ facts.provenance.toolCalling; // "docs"
519
+ NAN_MODEL_FACTS_META.sources["docs"]; // URL + check date
520
+ ```
521
+
522
+ - **Facts, not policy.** The record says what a model *is*. How you use it —
523
+ phases per context, a routing ladder, a cache-warming strategy — stays yours.
524
+ - **One entry per billed chat model** (13 today), keyed by model id. Non-chat
525
+ endpoints (embedding, rerank, TTS, STT, image, video) are not chat models and
526
+ are not exported.
527
+ - **Provenance per cell.** Every cell names a source id; `NAN_MODEL_FACTS_META.sources`
528
+ resolves it to a URL with its check date or to a dated measurement recorded in
529
+ this repo. The `override`, `compat` and `catalog-cost` ids point at the
530
+ entry's own `notes`, which already carry those citations.
531
+ - **`"unmeasured"` means no claim was made**, never "false". `parallelToolCalls`
532
+ is `"unmeasured"` on every model because nothing documents or measures several
533
+ tool calls per turn; `structuredOutput` is a boolean only where the NaN docs
534
+ document `json_object` / `json_schema` for that model.
535
+ - **Cold-prompt ceiling.** `coldCeilingTokens` is `"unmeasured"` on every entry:
536
+ the only measurement is endpoint-wide, so it ships separately as
537
+ `NAN_ENDPOINT_FACTS.coldCacheCeilingTokens` (200,000 tokens, measured
538
+ 2026-10-01) with a `coldCeilingScope` stating it is Cloudflare's 120 s
539
+ proxy-read limit, not a model capability. Size a first cold request under it.
540
+ - **Offline and frozen.** The record is derived from the shipped generated
541
+ catalog plus the build-time facts layer, so reading it performs no network
542
+ call, and it is deep-frozen: one consumer cannot change what the next one
543
+ reads. It never feeds provider registration — the read-time overlay
544
+ ([#19](https://github.com/gtrabanco/pi-nan-provider/issues/19)) still decides
545
+ the models a session sees.
452
546
 
453
547
  ## 📊 Models
454
548
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gtrabanco/pi-nan-provider",
3
- "version": "1.6.0",
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",
@@ -36,8 +36,10 @@
36
36
 
37
37
  import type { GeneratedModelEntry } from "../src/fetch-models.ts";
38
38
  import { NON_CHAT_MODEL_IDS } from "../src/fetch-models.ts";
39
+ import { buildModelFacts, overrideFieldKeys } from "../src/model-facts-core.ts";
39
40
  import type { ManualModelOverride } from "./manual-overrides.ts";
40
41
  import { MANUAL_OVERRIDES, MANUAL_ONLY_MODEL_IDS } from "./manual-overrides.ts";
42
+ import { MODEL_FACTS } from "./model-facts.ts";
41
43
 
42
44
  const MODELS_DEV_API_URL = "https://models.dev/api.json";
43
45
  const SOURCE_PROVIDER_ID = "nan";
@@ -362,7 +364,22 @@ async function main(): Promise<void> {
362
364
  );
363
365
  }
364
366
 
367
+ // Validate the manual facts layer against the catalog just built: a missing
368
+ // declaration, a ghost id, a value outside its documented union or a cell
369
+ // without provenance is a build failure, never a silently incomplete export.
365
370
  const fetchedAt = new Date().toISOString();
371
+ const factsMeta = {
372
+ source: MODELS_DEV_API_URL,
373
+ modelsDevProvider: SOURCE_PROVIDER_ID,
374
+ fetchedAt,
375
+ modelCount: entries.length,
376
+ };
377
+ try {
378
+ buildModelFacts(entries, MODEL_FACTS, overrideFieldKeys(MANUAL_OVERRIDES), factsMeta);
379
+ } catch (error) {
380
+ fail(error instanceof Error ? error.message : String(error));
381
+ }
382
+ console.log(`generate-models: model-facts catalog validated (${entries.length} models)`);
366
383
  const allNotes = [
367
384
  ...new Set([
368
385
  ...skipped,