@gtrabanco/pi-nan-provider 1.5.3 → 1.5.4

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
@@ -514,3 +514,55 @@ Since 1.0.0 the package version **aligns its MAJOR.MINOR with the pi release lin
514
514
  `overflow|rate_limited|invalid_request|transport|other`.
515
515
  Regression tests: `test/issue-35-cache-anomaly-capture.test.ts`,
516
516
  `test/issue-35-debug-report.test.ts`, `test/issue-35-nan-debug-command.test.ts`.
517
+
518
+ ## README (EN/ES) — mantener sincronizado
519
+
520
+ `README.md` y `README.es.md` son **espejos**: cada sección del inglés tiene contrapartida exacta
521
+ en español. No se acepta que un README muestre una feature que el otro no documente, ni que
522
+ uno cite una versión o requisito que el otro no lleve.
523
+
524
+ **Regla de mantenimiento** (obligatoria al añadir/eliminar código):
525
+
526
+ 1. **Primero el código, después el README.** Si una feature se introduce en `src/`, `test/` o
527
+ `scripts/`, el PR debe contener también la actualización de ambos READMEs en el mismo commit.
528
+ 2. **La tabla `## ✨ Features` (y la tabla de `Commands`) son la fuente.**
529
+ Cada row corresponde a un bloque de código o un issue. Si añades código, comprueba que
530
+ la row existe; si eliminas código, borra la row.
531
+ 3. **El orden de los encabezados debe coincidir.** Verifica con:
532
+ ```bash
533
+ diff <(rg -o "^#{2,4} .*" README.md) <(rg -o "^#{2,4} .*" README.es.md)
534
+ ```
535
+ cualquier divergencia es un error.
536
+ 4. **El badge `[![Version]…)]` en cada README debe cuadrar con `package.json/version`.**
537
+ El badge es un escudo visual: si el README dice `1.5.3` y `package.json` va en `1.5.4`,
538
+ alguien lo verá desfasado.
539
+ 5. **Cita el peer floor real, no la historia.** El peer range se actualiza con cada
540
+ release de pi: lee `package.json` peerDependencies, no AGENTS.md (que documenta
541
+ releases históricos y puede quedar obsoleto). Para este paquete: el floor es
542
+ `^1.4.0` (desde package 1.5.0), verificado contra pi 1.5.1 / pi-ai 1.5.1.
543
+ 6. **Las cifras de catálogo van contra `scripts/models.generated.ts`, no contra AGENTS.md.**
544
+ AGENTS.md es documentación de releases y puede contener floor o ranges ya antiguos;
545
+ el catálogo generado es la fuente viva de `contextWindow`/`maxTokens`/`reasoningEffortValues`
546
+ / `thinkingLevelMap` / `compat` — cada valor tiene una nota de procedencia (`notes` en la
547
+ entry). Re-check: `bun run generate-models` (recarga desde models.dev + manual-overrides)
548
+ y diffa el resultado.
549
+ 7. **Modelos nuevos o eliminados:** si la feature añade/elimina un modelo del catálogo,
550
+ la tabla "## 📊 Models" de ambos READMEs debe actualizarse: la tabla de chat (id,
551
+ contextWindow, maxTokens, input, reasoning) y la tabla de imagen (id, input, purpose).
552
+ No inventes valores: usa `scripts/models.generated.ts` o `scripts/manual-overrides.ts`.
553
+ 8. **Algunas secciones solo existen en inglés.** `src/images.ts`, `src/fetch-models.ts`,
554
+ `src/reasoning-only-stream-guard.ts` y los tests correspondientes están documentados en
555
+ el README inglés; el español puede tener la sección omitida o truncada si no tiene
556
+ contrapartida real (especialmente con features internas como el sanitizer). Al añadir
557
+ código nuevo, comprueba que la sección correspondiente existe en ambos.
558
+ 9. **Al actualizar una sección, actualiza la contrapartida.** Si cambias la tabla de
559
+ `reasoning_effort` en inglés porque un modelo cambió su `reasoningEffortValues`,
560
+ aplica el mismo split/merge en español con los mismos datos y las mismas notas de
561
+ procedencia (el issue #16, la medición, las notas de `MANUAL_OVERRIDES`).
562
+
563
+ **Checklist antes de push:**
564
+ - [ ] `rg -o "^#{2,4} .*" README.md` ↔ `rg -o "^#{2,4} .*" README.es.md` (misma estructura)
565
+ - [ ] Badge `version-X.Y.Z-blue` coincide con `package.json/version`
566
+ - [ ] Peer range de README = `package.json` `peerDependencies`
567
+ - [ ] Todas las filas de la tabla Features tienen código correspondiente
568
+ - [ ] `bun test` pasa, `bun run typecheck` limpio
package/README.es.md CHANGED
@@ -1,13 +1,43 @@
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.5.1-blue)](https://github.com/gtrabanco/pi-nan-provider/releases)
4
+ [![Version](https://img.shields.io/badge/version-1.5.4-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).
8
8
 
9
9
  Registra el proveedor `nan` vía `pi.registerProvider()` usando la API OpenAI-compatible de NaN (`https://api.nan.builders/v1`), y registra el servidor MCP de media de la comunidad con `pi.registerMcpServer()`.
10
10
 
11
+ > [!NOTE]
12
+ > **Requisitos:** pi **≥ 1.4.0** (rango peer `^1.4.0`). El paquete está verificado contra **pi 1.5.1 / pi-ai 1.5.1**; el floor del rango peer solo sube con los re-aligns de menor de pi.
13
+
14
+ ## ✨ Funciones
15
+
16
+ | Área | Qué obtienes |
17
+ | :--- | :--- |
18
+ | **Catálogo de modelos en dos capas** | Fallback generado en build-time (pi arranca aunque no haya red) fusionado con la lista en vivo `GET /v1/models`; después `filterModels` oculta lo que tu clave no pueda usar. |
19
+ | **Overlay de catálogo en tiempo de lectura** | Los datos de capacidad se reaplican desde el catálogo generado en cada lectura de `getModels()` / `getAllModels()`, así que un `models-store.json` escrito por una versión anterior del paquete no puede eclipsarlos ([#19](https://github.com/gtrabanco/pi-nan-provider/issues/19)) ni volver a registrar ids no-chat como modelos de chat ([#32](https://github.com/gtrabanco/pi-nan-provider/issues/32)). La store decide *qué* ids existen; el catálogo generado decide *qué pueden hacer*. |
20
+ | **Guardia de endpoints no-chat** | `NON_CHAT_MODEL_IDS` mantiene los ids de embedding / rerank / TTS / STT / imagen / vídeo fuera del selector de chat de pi. |
21
+ | **Sanitizador de payloads estricto** | Cuerpo de `/chat/completions` reescrito para cumplir [el esquema publicado de NaN](https://nan.builders/openapi.json) antes de salir de pi, sea cual sea la versión de pi-ai incluida. |
22
+ | **Rescate de desbordamiento de contexto** | El `400 Invalid request` genérico de NaN se reclasifica como desbordamiento cuando la petición se estima por encima de la ventana del modelo ([#3](https://github.com/gtrabanco/pi-nan-provider/issues/3)), y un `524` de caché fría por encima de `NAN_COLD_CACHE_CEILING_TOKENS` también ([#18](https://github.com/gtrabanco/pi-nan-provider/issues/18)) — pi compacta y reintenta en vez de quedarse colgado. |
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
+ | **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
+ | **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 límite provisional `max_completion_tokens` para `qwen3.8-flash` ([#34](https://github.com/gtrabanco/pi-nan-provider/issues/34)). |
26
+ | **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
+ | **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
+ | **Puente MCP nativo de media** | El servidor `nan-media` (9 herramientas) registrado con `pi.registerMcpServer()`, gestionado con `/nan-mcp`. |
29
+ | **Informe de cuotas** | `/nan-usage` fusiona `GET /v1/usage` con los topes mensuales documentados. |
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)). |
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
+
33
+ Comandos:
34
+
35
+ | Comando | Propósito |
36
+ | :--- | :--- |
37
+ | `/nan-mcp` | Gestionar el puente MCP de media (`status` / `enable` / `disable`) |
38
+ | `/nan-usage [1-90]` | Uso de tokens por modelo vs. los topes documentados |
39
+ | `/nan-debug [tema] [--window N] [--out ruta] [--emit]` | Paquete de evidencia reproducible y redactado para NaN |
40
+
11
41
  ---
12
42
 
13
43
  ### ⚡ Inicio Rápido
@@ -32,20 +62,32 @@ Registra el proveedor `nan` vía `pi.registerProvider()` usando la API OpenAI-co
32
62
 
33
63
  ## ⚙️ Cómo funciona
34
64
 
35
- El proveedor utiliza un **catálogo de modelos de dos capas** para garantizar la fiabilidad:
65
+ El proveedor utiliza un **catálogo de modelos en dos capas más un overlay en tiempo de lectura** para garantizar la fiabilidad:
36
66
 
37
67
  | Capa | Fuente | Propósito |
38
68
  | :--- | :--- | :--- |
39
- | **1. Fallback generado** | `scripts/models.generated.ts` | Snapshot en tiempo de build desde [models.dev](https://models.dev). Asegura que pi siempre pueda arrancar, incluso si la red falla. |
40
- | **2. Fetch en vivo de `/models`** | NaN Runtime API | Obtiene los modelos disponibles en tiempo real según el tier de tu API key. Se combina con los datos del fallback. |
69
+ | **1. Fallback generado** | `scripts/models.generated.ts` | Snapshot en tiempo de build desde [models.dev](https://models.dev) más overrides manuales con procedencia. Asegura que pi siempre pueda arrancar, incluso si la red falla. |
70
+ | **2. Fetch en vivo de `/models`** | NaN Runtime API | Obtiene los modelos que tu clave realmente puede llamar y los combina con el fallback; `filterModels` oculta lo que la lista en vivo no devuelve. |
71
+ | **3. Overlay en tiempo de lectura** | `withStaleCatalogOverlay` (`src/provider-factory.ts`) | Reaplica los datos de capacidad del catálogo generado en cada lectura de `getModels()` / `getAllModels()`, así que un `models-store.json` escrito por una versión anterior del paquete no puede eclipsarlos ([#19](https://github.com/gtrabanco/pi-nan-provider/issues/19)) ni volver a registrar ids no-chat como modelos de chat ([#32](https://github.com/gtrabanco/pi-nan-provider/issues/32)). |
41
72
 
42
73
  > [!IMPORTANT]
43
74
  > **Lista en vivo**: La lista en vivo es la autoridad. Desde el 2026-11-10 NaN ya no tiene modelos exclusivos por tier, así que todos los modelos del catálogo deben estar disponibles para cualquier clave; un modelo que `/models` en vivo no lista para tu clave sigue filtrándose.
44
75
 
45
- Los ids no-chat que devuelve `/models` en vivo (embedding, rerank, TTS, STT, imagen, vídeo) **no se registran** como modelos de chat — la clasificación es el único `NON_CHAT_MODEL_IDS` exportado desde `src/fetch-models.ts` (la misma fuente que usa el generador en build-time). La fusión salta sus marcadores y los coloca en un bucket observable `nonChat`; `baselineModels` también los filtra como capa defensiva. Esto evita que el selector de chat de pi ofrezca endpoints que no pueden servir chat (las peticiones devolverían 404).
76
+ Los ids no-chat que devuelve `/models` en vivo (embedding, rerank, TTS, STT, imagen, vídeo) **no se registran** como modelos de chat — la clasificación es el único `NON_CHAT_MODEL_IDS` exportado desde `src/fetch-models.ts` (la misma fuente que usa el generador en build-time). La fusión salta sus marcadores y los coloca en un bucket observable `nonChat`; `baselineModels` también los filtra como capa defensiva, y el overlay en tiempo de lectura elimina las entradas de tipo chat cuyo id está en esa lista — un store antiguo escrito antes de #15 (issue #32) no puede resucitarlos. Esto evita que el selector de chat de pi ofrezca endpoints que no pueden servir chat (las peticiones devolverían 404).
46
77
 
47
78
  El registro es síncrono a propósito: el catálogo de fallback está disponible al instante, y el runtime de Models de pi dirige el refresco en vivo (refresco de red en el arranque interactivo y periódico, solo caché en el registro), persistiendo el overlay entre ejecuciones.
48
79
 
80
+ ### 🧾 Sanitizador estricto de peticiones
81
+
82
+ NaN responde HTTP 400 `Invalid request. Check your request parameters.` con cualquier cuerpo que no cumpla el esquema que publica en [nan.builders/openapi.json](https://nan.builders/openapi.json) — un esquema más estricto que lo que pi-ai emite en varios sitios. `src/openai-compat-sanitizer.ts` reescribe cada cuerpo saliente de `/chat/completions`, así que ninguna versión de pi-ai ni ninguna forma de conversación pueden producir una petición inválida:
83
+
84
+ - un array `content` de asistente que lleva una tool call se mueve al campo superior `tool_calls` (el `ContentPart` de NaN solo acepta `text` y `image_url`);
85
+ - se elimina `reasoning_details`, y las partes de contenido desconocidas (p. ej. `thinking`) se pliegan en una parte `text` para que el razonamiento no se pierda en silencio;
86
+ - se eliminan los campos que el esquema de NaN no lista: `store` siempre, un array `tools` vacío siempre, y `stream_options` salvo que `compat.supportsUsageInStreaming` del modelo diga que el gateway lo reporta;
87
+ - `max_completion_tokens` se renombra a `max_tokens` (el campo documentado) salvo que `compat.maxTokensField` del modelo lo desactive ([#34](https://github.com/gtrabanco/pi-nan-provider/issues/34), `qwen3.8-flash`).
88
+
89
+ Un hook `onPayload` suministrado por el llamante se conserva y se encadena después de la sanitización.
90
+
49
91
  ### 🏷️ Cabecera de atribución
50
92
 
51
93
  Cada modelo que este paquete registra lleva una cabecera HTTP `X-Pi-Provider: gtrabanco/pi-nan-provider@<version>`, añadida sobre las cabeceras de identidad que ya envíe pi-ai (el `User-Agent` de pi nunca se modifica). Identifica las peticiones que vienen de esta extensión de proveedor — incluida la consulta de cuota de `/nan-usage` — y se omite silenciosamente si no se puede resolver la versión del paquete. Los overrides de usuario en `models.json` que reemplacen un modelo reemplazan también sus cabeceras.
@@ -54,7 +96,7 @@ La cabecera **sigue la opción de telemetría de pi**: con `enableInstallTelemet
54
96
 
55
97
  ### 🧠 Seguridad al cambiar de modelo
56
98
 
57
- Al cambiar de modelo, versiones antiguas de pi-ai reenviaban el razonamiento del modelo anterior como texto plano de asistente **sin límite de tamaño**, lo que podía desbordar la ventana de un modelo de 262K; NaN respondía con un `400 Invalid request. Check your request parameters.` genérico que parecía un bug del proveedor (seguimiento upstream: [pi-nan-provider#3](https://github.com/gtrabanco/pi-nan-provider/issues/3)). pi-ai 1.3.0 arregló esto upstream (`transformMessages` ahora descarta los bloques de thinking de otro modelo) y este paquete requiere **pi ≥ 1.3.0** (rango peer `^1.3.0`), así que el guard extension-side que lo mitigaba fue **eliminado en la versión 1.4.0 del paquete** — no hay que hacer nada, upstream lo gestiona.
99
+ Al cambiar de modelo, versiones antiguas de pi-ai reenviaban el razonamiento del modelo anterior como texto plano de asistente **sin límite de tamaño**, lo que podía desbordar la ventana de un modelo de 262K; NaN respondía con un `400 Invalid request. Check your request parameters.` genérico que parecía un bug del proveedor (seguimiento upstream: [pi-nan-provider#3](https://github.com/gtrabanco/pi-nan-provider/issues/3)). pi-ai 1.3.0 arregló esto upstream (`transformMessages` ahora descarta los bloques de thinking de otro modelo) y este paquete requiere **pi ≥ 1.4.0** (rango peer `^1.4.0`), así que el guard extension-side que lo mitigaba fue **eliminado en la versión 1.4.0 del paquete** — no hay que hacer nada, upstream lo gestiona.
58
100
 
59
101
  Una petición puede seguir desbordando por méritos propios — tool outputs enormes, imágenes o una ventana de destino simplemente más pequeña que el contenido — y NaN responde con el mismo 400 genérico en lugar de nombrar el desbordamiento, mientras que la auto-compactación de pi no lo reconoce, así que la sesión se quedaría atascada en el techo. Por eso el proveedor **vuelve a comprobar el tamaño de la petición a la salida**: cuando llega ese 400 genérico para una petición estimada por encima de la ventana del modelo, el error se reescribe como un mensaje de context overflow que pi reconoce, de modo que compacta y reintenta en vez de bloquearse. Un 400 genérico en una petición dentro de la ventana no se toca, así que nunca se etiquetan mal errores no relacionados.
60
102
 
@@ -80,7 +122,7 @@ Puedes sobrescribir el `compat` de cualquier modelo en `~/.pi/agent/models.json`
80
122
 
81
123
  **Escape hatches de compatibilidad de pi-ai 1.5.1** (`~/.pi/agent/models.json`, por modelo): `compat.requiresToolsWithToolHistory: true` restaura el envío de `tools: []` en conversaciones con historial de tools (pi-ai 1.5.1 lo omite por defecto, arreglando los rechazos `tools must not be an empty array` de vLLM 0.20+ detrás de LiteLLM); `compat.requiresNonNullAssistantContent: true` envía `""` en vez de `null` en mensajes de asistente que solo llevan tool calls; `compat.promptCacheKeyMode: "disabled"` garantiza que nunca se envíe `prompt_cache_key` al gateway (el valor por defecto `auto` ya nunca lo activa para NaN).
82
124
 
83
- **Uso de tokens en streaming:** `supportsUsageInStreaming` es `true` por defecto. El esquema publicado de NaN no documenta `stream_options`, pero el gateway real lo acepta y lo aplica — medido el 2026-09-16 ([#7](https://github.com/gtrabanco/pi-nan-provider/issues/7)): dos llamadas de streaming idénticas por modelo, 0 chunks de usage sin el flag y exactamente 1 con él, en `deepseek-v4-flash`, `glm5.3-flash`, `qwen3.6`, `mimo-v2.5` y `gemma4`. Por eso pi muestra tokens reales de entrada/salida/reasoning/caché en lugar de ceros. Si un modelo resulta no devolver el usage en streaming, desactívalo por modelo — el sanitizer entonces elimina `stream_options` y el payload vuelve a ser estricto:
125
+ **Uso de tokens en streaming:** `supportsUsageInStreaming` es `true` por defecto. El esquema publicado de NaN no documenta `stream_options`, pero el gateway real lo acepta y lo aplica — medido el 2026-09-16 ([#7](https://github.com/gtrabanco/pi-nan-provider/issues/7)): dos llamadas de streaming idénticas por modelo, 0 chunks de usage sin el flag y exactamente 1 con él, en `deepseek-v4-flash`, `glm5.3-flash`, `qwen3.6`, `gemma4` y `mimo-v2.5` (ya eliminado). Por eso pi muestra tokens reales de entrada/salida/reasoning/caché en lugar de ceros. Si un modelo resulta no devolver el usage en streaming, desactívalo por modelo — el sanitizer entonces elimina `stream_options` y el payload vuelve a ser estricto:
84
126
 
85
127
  ```json
86
128
  {
@@ -108,7 +150,7 @@ Consigue una clave en la [plataforma NaN](https://cloud.nan.builders/r/7GK06FX8)
108
150
 
109
151
  ## 🔌 MCP nativo
110
152
 
111
- Dado que [pi 0.99.0 incluye un cliente MCP integrado](https://github.com/earendil-works/pi/blob/main/docs/usage.md), este paquete usa MCP nativo (requiere **pi >= 1.3.0**, el floor del rango peer desde la versión 1.4.0 del paquete).
153
+ Dado que [pi 0.99.0 incluye un cliente MCP integrado](https://github.com/earendil-works/pi/blob/main/docs/usage.md), este paquete usa MCP nativo (requiere **pi >= 1.4.0**, el floor del rango peer desde la versión 1.5.0 del paquete).
112
154
 
113
155
  El puente de media está **activado por defecto** (por sesión, visible en `/mcp`). Usa `/nan-mcp` para gestionarlo.
114
156
 
@@ -168,12 +210,10 @@ con un único aviso por sesión, mantiene los registros inactivos y deja que `/n
168
210
  el toggle sin registrar un servidor que nunca podrá conectarse. Para tener MCP en la CLI, activa el
169
211
  conector con `pi config` → Built-in extensions → `mcp`.
170
212
 
171
- ### Funciones de pi 0.99-1.0 y modelos NaN
213
+ ### Funciones de pi y modelos NaN
172
214
 
173
215
  - **Modelos virtuales** — registra un router bajo `nan` (`pi.registerVirtualModel({ provider: "nan", ... })`);
174
- enruta a los modelos físicos de NaN sin configuración por parte del proveedor. El guard de
175
- razonamiento entre modelos se salta las selecciones virtuales, porque el modelo físico enrutado no
176
- es visible para el hook `context`.
216
+ enruta a los modelos físicos de NaN sin configuración por parte del proveedor.
177
217
  - **Codemode** — funciona con cualquier modelo NaN que soporte tool calling. Las herramientas MCP de
178
218
  este paquete usan `exposure: "direct"`, así que los scripts de codemode también pueden llamarlas.
179
219
  Requiere la extensión integrada `codemode` de pi (ver la nota de PI WEB arriba).
@@ -224,7 +264,7 @@ conector con `pi config` → Built-in extensions → `mcp`.
224
264
 
225
265
  > pi 0.99.0–0.99.1 usaba la forma con guiones (`mcp__nan-media__*`); pi 0.99.2+ sanitiza los
226
266
  > nombres de herramientas a solo `[A-Za-z0-9_]`, así que los guiones se convirtieron en guiones
227
- > bajos. La forma con guiones bajos aplica en todas las versiones soportadas (pi >= 1.3.0).
267
+ > bajos. La forma con guiones bajos aplica en todas las versiones soportadas (pi >= 1.4.0).
228
268
 
229
269
  #### 🔧 Configuración del Puente de Media
230
270
 
@@ -249,7 +289,7 @@ Las actualizaciones del SDK de pi (`@earendil-works/pi-ai` / `@earendil-works/pi
249
289
  también están automatizadas: el workflow semanal `check-pi-sdk-versions` abre el issue
250
290
  `sdk-monitor` **y** prepara un PR con el bump de devDependencies (`bun test` +
251
291
  `bun run typecheck` + diff de superficie de tipos incluidos) para revisión humana — ver
252
- `docs/sdk-version-monitoring.md`.
292
+ `.github/workflows/check-pi-sdk-versions.yml` y `scripts/check-pi-sdk-versions.mjs`.
253
293
 
254
294
  ---
255
295
 
@@ -438,15 +478,14 @@ Modelos de imagen no-chat (disponibles vía `models.generateImages()` /
438
478
 
439
479
  ---
440
480
 
441
- ---
442
-
443
481
  ## 🧠 Controles de razonamiento
444
482
 
445
483
  El parámetro `reasoning_effort` de NaN controla cuánto piensa el modelo antes de responder — pero el grado de control varía por modelo:
446
484
 
447
485
  | Modelo | Effort de razonamiento | Cómo funciona |
448
486
  | :--- | :--- | :--- |
449
- | `glm5.3`, `glm5.3-flash` | `minimal` · `low` · `medium` · `high` · `max` | Completamente controlable — valores más altos permiten al modelo razonar más; `minimal` produce ~38 tokens de razonamiento (issue #16, medido 2026-09-27); `none` NO suprime el razonamiento en glm5.3-flash (13,382 tokens) |
487
+ | `glm5.3` | `low` · `medium` · `high` · `max` | Completamente controlable — valores más altos permiten al modelo razonar más. `thinking: "off"` envía `low`, el nivel más bajo que listan los docs de NaN, vía el `thinkingLevelMap` del catálogo. `minimal` **no** está entre los valores declarados de este modelo: el issue #16 lo midió solo en `glm5.3-flash`, y `glm5.3` en sí nunca se midió |
488
+ | `glm5.3-flash` | `minimal` · `low` · `medium` · `high` · `max` | Completamente controlable — valores más altos permiten al modelo razonar más; `minimal` produce ~38 tokens de razonamiento (issue #16, medido 2026-09-27). `none` NO suprime el razonamiento (13,382 tokens), así que `thinking: "off"` envía `minimal`, el valor efectivo más bajo, vía el `thinkingLevelMap` del catálogo |
450
489
  | `qwen3.6`, `gemma4` | `none` · `minimal` · `low` · `medium` · `high` · `max` | `none`/`minimal` omiten el razonamiento por completo; otros valores limitan a 2K / 8K / 16K / 32K tokens. `thinking: "off"` envía `reasoning_effort: "none"` automáticamente vía el `thinkingLevelMap` del catálogo — los docs de NaN dicen que sin parámetro estos modelos razonan por defecto (presupuesto de 16,384 tokens), así que `off` debe ser explícito |
451
490
  | `deepseek-v4-flash` | `none` (el catálogo declara ["none"]) | `none` deshabilita el razonamiento (0 tokens de razonamiento, respuesta completa); cualquier otro valor — incluido `minimal` y omitir el parámetro — lo deja ENCENDIDO (57 / 63 / 109 tokens de razonamiento), así que el catálogo solo declara `none`. Re-sondado en vivo 2026-10-14: los docs de NaN afirman "any value (no effect)", pero gana la medición. `thinking: "off"` envía `reasoning_effort: "none"` automáticamente vía el `thinkingLevelMap` del catálogo — sin él el modelo se descontrola hasta `finish_reason: "length"` sin respuesta (issue #16) |
452
491
  | `qwen3.8-flash` | *(aceptado pero no ajustable)* | El parámetro es aceptado y nunca rechazado, pero el modelo gestiona su propia profundidad de razonamiento — nunca es un error enviar un valor que este modelo no ajusta |
@@ -463,6 +502,13 @@ bun install
463
502
  bun run generate-models # Regenerar catálogo de fallback
464
503
  bun test # Ejecutar todos los tests
465
504
  bun run typecheck # Ejecutar typechecking
505
+ bun run check-nan-mcp-server # ¿Hay una versión nueva de nan-mcp-server?
506
+ bun run check-pi-sdk-versions # ¿Hay una versión nueva de pi / pi-ai?
466
507
  ```
467
508
 
468
- *Las versiones siguen semver estricto. CI publica automáticamente al hacer merge a `main`.*
509
+ Cada cambio de código debe subir la versión de `package.json` en el mismo PR; los valores de
510
+ capacidad que diverjan de models.dev van en `scripts/manual-overrides.ts` con una nota de
511
+ procedencia, nunca editados a mano en el catálogo generado.
512
+
513
+ *Las versiones siguen semver estricto. CI publica automáticamente al hacer merge a `main`. Tras una
514
+ actualización, pi muestra el `CHANGELOG.md` de este paquete (`pi.changelogPath`, pi 1.5.0+).*
package/README.md CHANGED
@@ -1,13 +1,43 @@
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.5.1-blue)](https://github.com/gtrabanco/pi-nan-provider/releases)
4
+ [![Version](https://img.shields.io/badge/version-1.5.4-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).
8
8
 
9
9
  Registers the `nan` provider via `pi.registerProvider()` using NaN's OpenAI-compatible API (`https://api.nan.builders/v1`), and registers the community media MCP server via pi's native `pi.registerMcpServer()`.
10
10
 
11
+ > [!NOTE]
12
+ > **Requirements:** pi **≥ 1.4.0** (peer range `^1.4.0`). The package is verified against **pi 1.5.1 / pi-ai 1.5.1**; the peer floor only rises on pi minor realigns.
13
+
14
+ ## ✨ Features
15
+
16
+ | Area | What you get |
17
+ | :--- | :--- |
18
+ | **Two-layer model catalog** | Build-time generated fallback (pi always starts, even offline) merged with the live `GET /v1/models` list; `filterModels` then hides whatever your key cannot call. |
19
+ | **Read-time catalog overlay** | Capability data is re-applied from the generated catalog on every `getModels()` / `getAllModels()` read, so a `models-store.json` written by an older package version can neither shadow it ([#19](https://github.com/gtrabanco/pi-nan-provider/issues/19)) nor re-register non-chat ids as chat models ([#32](https://github.com/gtrabanco/pi-nan-provider/issues/32)). The store decides *which* ids exist; the generated catalog decides *what they can do*. |
20
+ | **Non-chat endpoint guard** | `NON_CHAT_MODEL_IDS` keeps embedding / rerank / TTS / STT / image / video ids out of pi's chat picker. |
21
+ | **Strict payload sanitizer** | Every `/chat/completions` body is rewritten to match [NaN's published schema](https://nan.builders/openapi.json) before it leaves pi, whatever pi-ai version is bundled. |
22
+ | **Context-overflow rescue** | NaN's generic `400 Invalid request` is reclassified as an overflow when the request is estimated over the model's window ([#3](https://github.com/gtrabanco/pi-nan-provider/issues/3)), and a cold-cache `524` over `NAN_COLD_CACHE_CEILING_TOKENS` too ([#18](https://github.com/gtrabanco/pi-nan-provider/issues/18)) — pi compacts and retries instead of wedging. |
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
+ | **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
+ | **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 `max_completion_tokens` interim bound for `qwen3.8-flash` ([#34](https://github.com/gtrabanco/pi-nan-provider/issues/34)). |
26
+ | **Attribution header** | `X-Pi-Provider: gtrabanco/pi-nan-provider@<version>` on every request, stripped when pi's install telemetry is disabled. |
27
+ | **Native image models** | `flux-2-klein` and `qwen-image-2.1` registered as pi `type: "image"` models, reachable from codemode and extensions. |
28
+ | **Native MCP media bridge** | The `nan-media` server (9 tools) registered through `pi.registerMcpServer()`, managed with `/nan-mcp`. |
29
+ | **Quota reporting** | `/nan-usage` merges `GET /v1/usage` with the documented monthly caps. |
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)). |
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
+
33
+ Commands:
34
+
35
+ | Command | Purpose |
36
+ | :--- | :--- |
37
+ | `/nan-mcp` | Manage the media MCP bridge (`status` / `enable` / `disable`) |
38
+ | `/nan-usage [1-90]` | Token usage per model vs. the documented caps |
39
+ | `/nan-debug [topic] [--window N] [--out path] [--emit]` | Redacted, reproducible evidence package for NaN |
40
+
11
41
  ---
12
42
 
13
43
  ### ⚡ Quick Start
@@ -32,20 +62,32 @@ Registers the `nan` provider via `pi.registerProvider()` using NaN's OpenAI-comp
32
62
 
33
63
  ## ⚙️ How it works
34
64
 
35
- The provider uses a **two-layer model catalog** to ensure reliability:
65
+ The provider uses a **two-layer model catalog plus a read-time overlay** to ensure reliability:
36
66
 
37
67
  | Layer | Source | Purpose |
38
68
  | :--- | :--- | :--- |
39
- | **1. Generated Fallback** | `scripts/models.generated.ts` | Build-time snapshot from [models.dev](https://models.dev). Ensures pi can always start, even if the network fails. |
40
- | **2. Live `/models` Fetch** | NaN Runtime API | Fetches your real-time available models based on your API key's tier. Merged with fallback data. |
69
+ | **1. Generated Fallback** | `scripts/models.generated.ts` | Build-time snapshot from [models.dev](https://models.dev) plus manual overrides with provenance. Ensures pi can always start, even if the network fails. |
70
+ | **2. Live `/models` Fetch** | NaN Runtime API | Fetches the models your key can actually call and merges them with the fallback; `filterModels` hides anything the live list does not return. |
71
+ | **3. Read-time Overlay** | `withStaleCatalogOverlay` (`src/provider-factory.ts`) | Re-applies generated capability data on every `getModels()` / `getAllModels()` read, so a `models-store.json` written by an older package version cannot shadow it ([#19](https://github.com/gtrabanco/pi-nan-provider/issues/19)) nor re-register non-chat ids as chat models ([#32](https://github.com/gtrabanco/pi-nan-provider/issues/32)). |
41
72
 
42
73
  > [!IMPORTANT]
43
74
  > **Live list**: The live list is authoritative. Since 2026-11-10 NaN no longer has tier-exclusive models, so every catalog model is meant to be available to every key; a model the live `/models` response does not list for your key is still filtered out.
44
75
 
45
- NaN's live `/models` also returns non-chat endpoint ids (embedding, rerank, TTS, STT, image, video). These are **not registered** as chat models — the classification is the single exported `NON_CHAT_MODEL_IDS` from `src/fetch-models.ts` (the same source used by the build-time generator). The merge skips their placeholders and places them in an observable `nonChat` bucket; `baselineModels` also filters them defensively. This prevents pi's chat picker from offering endpoints that cannot serve chat (requests would 404).
76
+ NaN's live `/models` also returns non-chat endpoint ids (embedding, rerank, TTS, STT, image, video). These are **not registered** as chat models — the classification is the single exported `NON_CHAT_MODEL_IDS` from `src/fetch-models.ts` (the same source used by the build-time generator). The merge skips their placeholders and places them in an observable `nonChat` bucket; `baselineModels` also filters them defensively, and the read-time overlay drops chat-type entries whose id is in that list — a stale store written before #15 (issue #32) cannot resurrect them. This prevents pi's chat picker from offering endpoints that cannot serve chat (requests would 404).
46
77
 
47
78
  The registration is synchronous on purpose: the generated fallback catalog is available immediately, and pi's Models runtime drives the live refresh (network refresh at interactive startup and periodically, cache-only at registration), persisting the overlay between runs.
48
79
 
80
+ ### 🧾 Strict request sanitizer
81
+
82
+ NaN answers HTTP 400 `Invalid request. Check your request parameters.` for any body that does not match the schema it publishes at [nan.builders/openapi.json](https://nan.builders/openapi.json) — a schema stricter than what pi-ai emits in several places. `src/openai-compat-sanitizer.ts` rewrites every outgoing `/chat/completions` payload on the way out, so no pi-ai version or conversation shape can produce an invalid request:
83
+
84
+ - an assistant `content` array carrying a tool call is moved into the top-level `tool_calls` field (NaN's `ContentPart` accepts only `text` and `image_url`);
85
+ - `reasoning_details` is stripped, and unknown content parts (e.g. `thinking`) are folded into a `text` part so reasoning is not silently lost;
86
+ - fields NaN's schema does not list are removed: `store` always, an empty `tools` array always, and `stream_options` unless the model's `compat.supportsUsageInStreaming` says the gateway reports it;
87
+ - `max_completion_tokens` is renamed to `max_tokens` (the documented field) unless the model's `compat.maxTokensField` opts out ([#34](https://github.com/gtrabanco/pi-nan-provider/issues/34), `qwen3.8-flash`).
88
+
89
+ A caller-supplied `onPayload` hook is preserved and chained after sanitization.
90
+
49
91
  ### 🏷️ Attribution header
50
92
 
51
93
  Every model this package registers carries an `X-Pi-Provider: gtrabanco/pi-nan-provider@<version>` HTTP header, added on top of whatever identity headers pi-ai sends (pi's own `User-Agent` is never modified). It identifies the requests coming from this provider extension — including the `/nan-usage` quota fetch — and it is omitted silently when the package version cannot be resolved. User `models.json` overrides that replace a model entry replace its headers too.
@@ -54,7 +96,7 @@ The header **follows pi's telemetry setting**: with `enableInstallTelemetry: fal
54
96
 
55
97
  ### 🧠 Model-switch safety
56
98
 
57
- When you switch models, older pi-ai versions replayed the previous model's reasoning as plain assistant text with **no size bound**, which could overflow a 262K-context model's window; NaN answered with a generic `400 Invalid request. Check your request parameters.` that looked like a provider bug (upstream tracking: [pi-nan-provider#3](https://github.com/gtrabanco/pi-nan-provider/issues/3)). pi-ai 1.3.0 fixed this upstream (`transformMessages` now drops thinking blocks from a different model) and this package requires **pi ≥ 1.3.0** (peer range `^1.3.0`), so the extension-side guard that used to mitigate it was **removed in package 1.4.0** — no action is needed, upstream handles it.
99
+ When you switch models, older pi-ai versions replayed the previous model's reasoning as plain assistant text with **no size bound**, which could overflow a 262K-context model's window; NaN answered with a generic `400 Invalid request. Check your request parameters.` that looked like a provider bug (upstream tracking: [pi-nan-provider#3](https://github.com/gtrabanco/pi-nan-provider/issues/3)). pi-ai 1.3.0 fixed this upstream (`transformMessages` now drops thinking blocks from a different model) and this package requires **pi ≥ 1.4.0** (peer range `^1.4.0`), so the extension-side guard that used to mitigate it was **removed in package 1.4.0** — no action is needed, upstream handles it.
58
100
 
59
101
  A request can still overflow on its own merits — oversized tool outputs, images, or a destination window simply smaller than the content — and NaN answers the same generic 400 instead of naming the overflow, while pi's auto-compaction does not recognize it, so the session would wedge at the ceiling. The provider therefore **re-checks the request size on the way out**: when that generic 400 arrives for a request estimated over the model's window, the error is rewritten into a context-overflow message pi recognizes, so it compacts and retries instead of stalling. A generic 400 on a within-window request is left untouched, so unrelated errors are never mislabelled.
60
102
 
@@ -80,7 +122,7 @@ You can override any model's `compat` per-model in `~/.pi/agent/models.json` (pi
80
122
 
81
123
  **pi-ai 1.5.1 compat escape hatches** (`~/.pi/agent/models.json`, per model): `compat.requiresToolsWithToolHistory: true` restores sending `tools: []` in conversations with tool history (pi-ai 1.5.1 omits it by default, fixing vLLM 0.20+ `tools must not be an empty array` rejections behind LiteLLM); `compat.requiresNonNullAssistantContent: true` sends `""` instead of `null` in assistant messages that only carry tool calls; `compat.promptCacheKeyMode: "disabled"` guarantees `prompt_cache_key` is never sent to the gateway (the default `auto` already never enables it for NaN).
82
124
 
83
- **Streaming token usage:** `supportsUsageInStreaming` is `true` by default. NaN's published schema does not document `stream_options`, but the live gateway honors it — measured 2026-09-16 ([#7](https://github.com/gtrabanco/pi-nan-provider/issues/7)): two identical streaming calls per model, 0 usage chunks without the flag and exactly 1 with it, on `deepseek-v4-flash`, `glm5.3-flash`, `qwen3.6`, `mimo-v2.5` and `gemma4`. pi therefore reports real input/output/reasoning/cache token counts instead of zeros. If a model turns out not to report streaming usage, opt out per model — the request sanitizer then strips `stream_options` and the payload stays strict:
125
+ **Streaming token usage:** `supportsUsageInStreaming` is `true` by default. NaN's published schema does not document `stream_options`, but the live gateway honors it — measured 2026-09-16 ([#7](https://github.com/gtrabanco/pi-nan-provider/issues/7)): two identical streaming calls per model, 0 usage chunks without the flag and exactly 1 with it, on `deepseek-v4-flash`, `glm5.3-flash`, `qwen3.6`, `gemma4` and `mimo-v2.5` (since removed). pi therefore reports real input/output/reasoning/cache token counts instead of zeros. If a model turns out not to report streaming usage, opt out per model — the request sanitizer then strips `stream_options` and the payload stays strict:
84
126
 
85
127
  ```json
86
128
  {
@@ -108,7 +150,7 @@ Get a key from the [NaN platform](https://cloud.nan.builders/r/7GK06FX8) (user s
108
150
 
109
151
  ## 🔌 Native MCP Server
110
152
 
111
- Since [pi 0.99.0 ships a built-in MCP client](https://github.com/earendil-works/pi/blob/main/docs/usage.md), this package bridges to native MCP (requires **pi >= 1.3.0**, the peer range floor since package 1.4.0).
153
+ Since [pi 0.99.0 ships a built-in MCP client](https://github.com/earendil-works/pi/blob/main/docs/usage.md), this package bridges to native MCP (requires **pi >= 1.4.0**, the peer range floor since package 1.5.0).
112
154
 
113
155
  The media bridge is **enabled by default** (session-scoped, visible in `/mcp`). Use `/nan-mcp` to manage it.
114
156
 
@@ -167,7 +209,7 @@ per session, keeps the registrations idle, and lets `/nan-mcp enable` persist th
167
209
  registering a server that can never connect. To get MCP in the CLI, enable the connector with
168
210
  `pi config` → Built-in extensions → `mcp`.
169
211
 
170
- ### pi 0.99-1.0 features and NaN models
212
+ ### pi features and NaN models
171
213
 
172
214
  - **Virtual models** — register a router under `nan` (`pi.registerVirtualModel({ provider: "nan", ... })`);
173
215
  it routes to the physical NaN models with no provider-side configuration.
@@ -220,7 +262,7 @@ registering a server that can never connect. To get MCP in the CLI, enable the c
220
262
 
221
263
  > pi 0.99.0–0.99.1 used the hyphenated form (`mcp__nan-media__*`); pi 0.99.2+ sanitizes tool
222
264
  > names to `[A-Za-z0-9_]` only, so hyphens became underscores. The underscore form applies
223
- > on every supported version (pi >= 1.3.0).
265
+ > on every supported version (pi >= 1.4.0).
224
266
 
225
267
  #### 🔧 Media Bridge Configuration
226
268
 
@@ -244,7 +286,7 @@ bun run check-nan-mcp-server --issue # create/refresh the issue
244
286
  PI SDK updates (`@earendil-works/pi-ai` / `@earendil-works/pi-coding-agent`) are automated
245
287
  too: the weekly `check-pi-sdk-versions` workflow files the `sdk-monitor` issue **and**
246
288
  prepares a devDependencies-bump PR (`bun test` + `bun run typecheck` + type-surface diff
247
- included) for human review — see `docs/sdk-version-monitoring.md`.
289
+ included) for human review — see `.github/workflows/check-pi-sdk-versions.yml` and `scripts/check-pi-sdk-versions.mjs`.
248
290
 
249
291
  ---
250
292
 
@@ -438,7 +480,8 @@ NaN's `reasoning_effort` parameter controls how much the model thinks before ans
438
480
 
439
481
  | Model | Reasoning effort | How it works |
440
482
  | :--- | :--- | :--- |
441
- | `glm5.3`, `glm5.3-flash` | `minimal` · `low` · `medium` · `high` · `max` | Fully controllable — higher values let the model reason longer; `minimal` yields ~38 reasoning tokens (issue #16, measured 2026-09-27); `none` does NOT suppress reasoning on glm5.3-flash (13,382 tokens) |
483
+ | `glm5.3` | `low` · `medium` · `high` · `max` | Fully controllable — higher values let the model reason longer. `thinking: "off"` sends `low`, the shallowest level the NaN docs list, via the catalog's `thinkingLevelMap`. `minimal` is **not** in this model's declared values: issue #16 measured it on `glm5.3-flash` only, and `glm5.3` itself was never measured |
484
+ | `glm5.3-flash` | `minimal` · `low` · `medium` · `high` · `max` | Fully controllable — higher values let the model reason longer; `minimal` yields ~38 reasoning tokens (issue #16, measured 2026-09-27). `none` does NOT suppress reasoning (13,382 tokens), so `thinking: "off"` sends `minimal`, the shallowest effective value, via the catalog's `thinkingLevelMap` |
442
485
  | `qwen3.6`, `gemma4` | `none` · `minimal` · `low` · `medium` · `high` · `max` | `none`/`minimal` skip reasoning entirely; others cap at 2K / 8K / 16K / 32K tokens. `thinking: "off"` sends `reasoning_effort: "none"` automatically via the catalog's `thinkingLevelMap` — the NaN docs state that with no parameter these models reason by default (16,384-token budget), so off must be explicit |
443
486
  | `deepseek-v4-flash` | `none` (catalog declares ["none"]) | `none` disables reasoning (0 reasoning tokens, a full answer); every other value — including `minimal` and omitting the parameter — leaves it ON (57 / 63 / 109 reasoning tokens), so the catalog declares only `none`. Re-probed live 2026-10-14: the NaN docs claim "any value (no effect)", but the measurement wins. `thinking: "off"` sends `reasoning_effort: "none"` automatically via the catalog's `thinkingLevelMap` — without it the model runs away to `finish_reason: "length"` with no answer (issue #16) |
444
487
  | `qwen3.8-flash` | *(accepted but not adjustable)* | The parameter is accepted and never rejected, but the model manages its own reasoning depth — it is never an error to send a value this model doesn't adjust |
@@ -457,6 +500,13 @@ bun install
457
500
  bun run generate-models # Regenerate fallback catalog
458
501
  bun test # Run all tests
459
502
  bun run typecheck # Run typechecking
503
+ bun run check-nan-mcp-server # Newer nan-mcp-server release?
504
+ bun run check-pi-sdk-versions # Newer pi / pi-ai release?
460
505
  ```
461
506
 
462
- *Releases follow strict semver. CI publishes automatically on merge to `main`.*
507
+ Every code change must bump `package.json` in the same PR; capability values that diverge from
508
+ models.dev belong in `scripts/manual-overrides.ts` with a provenance note, never hand-edited into
509
+ the generated catalog.
510
+
511
+ *Releases follow strict semver. CI publishes automatically on merge to `main`. After an update, pi
512
+ shows this package's `CHANGELOG.md` (`pi.changelogPath`, pi 1.5.0+).*
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gtrabanco/pi-nan-provider",
3
- "version": "1.5.3",
3
+ "version": "1.5.4",
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-12T01:10:06.135Z
4
+ // Source: https://models.dev/api.json (provider "nan"), fetched 2026-11-12T22:42:17.308Z
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.
@@ -703,7 +703,7 @@ export const NAN_GENERATED_MODELS: readonly GeneratedModelEntry[] = [
703
703
  export const GENERATED_CATALOG_META = {
704
704
  source: "https://models.dev/api.json",
705
705
  modelsDevProvider: "nan",
706
- fetchedAt: "2026-11-12T01:10:06.135Z",
706
+ fetchedAt: "2026-11-12T22:42:17.308Z",
707
707
  modelCount: 11,
708
708
  models: ["deepseek-v4-flash","deepseek-v4-pro","gemma4","glm5.3","glm5.3-flash","hy4","kimi-k3.1-pro","mimo-v2.6-flash","qwen3.6","qwen3.8-flash","qwen3.8-max"],
709
709
  notes: [
package/src/usage.ts CHANGED
@@ -62,16 +62,24 @@ export const MODEL_QUOTAS: readonly ModelQuota[] = [
62
62
  export interface UsageModelTotals {
63
63
  model: string;
64
64
  prompt_tokens: number;
65
+ /** Cached input tokens (part of `prompt_tokens`, not added to `total_tokens`). 2026-11-11 onward. */
66
+ cached_tokens: number;
65
67
  completion_tokens: number;
66
68
  total_tokens: number;
67
69
  api_requests: number;
70
+ /** Credits billed on this model in the window, one decimal. 2026-11-10 onward. */
71
+ credits: number;
68
72
  }
69
73
 
70
74
  export interface UsageTotals {
71
75
  prompt_tokens: number;
76
+ /** Cached input tokens (part of `prompt_tokens`, not added to `total_tokens`). 2026-11-11 onward. */
77
+ cached_tokens: number;
72
78
  completion_tokens: number;
73
79
  total_tokens: number;
74
80
  api_requests: number;
81
+ /** Credits billed in the window, one decimal. 2026-11-10 onward. */
82
+ credits: number;
75
83
  by_model: UsageModelTotals[];
76
84
  }
77
85
 
@@ -80,9 +88,29 @@ export interface UsageAllTime {
80
88
  completion_tokens: number;
81
89
  total_tokens: number;
82
90
  api_requests: number;
91
+ /** When the all-time summary was last computed, ISO 8601 UTC. */
83
92
  cached_at: string | null;
84
93
  }
85
94
 
95
+ export interface UsageCredits {
96
+ /** Start of the current billing period (UTC). */
97
+ period_start: string;
98
+ /** End of the current billing period (UTC), when the allowance renews. */
99
+ period_end: string;
100
+ /** Credits included in your plan for this period. */
101
+ allowance: number;
102
+ /** Credits used from the allowance this period. */
103
+ used: number;
104
+ /** Credits left in the allowance this period. Pack credits are not included. */
105
+ remaining: number;
106
+ /** Credits left in your purchased packs, used once the allowance runs out. */
107
+ pack_credits: number;
108
+ /** When your pack credits expire, or `null` without pack credits. */
109
+ pack_expires_at: string | null;
110
+ /** `true` while your subscription is not active (e.g. failed payment). */
111
+ frozen: boolean;
112
+ }
113
+
86
114
  export interface UsageReport {
87
115
  object: "usage.report";
88
116
  /** First day of the window actually served (after clamping). */
@@ -92,9 +120,12 @@ export interface UsageReport {
92
120
  /** Daily (date, model) rows — paginated; unused here (totals cover the window). */
93
121
  data: unknown[];
94
122
  totals: UsageTotals;
123
+ /** Lifetime usage, always present. */
95
124
  all_time: UsageAllTime;
96
125
  has_more: boolean;
97
126
  next_cursor: string | null;
127
+ /** Current billing period credits, or `null` if not billed in credits. */
128
+ credits: UsageCredits | null;
98
129
  }
99
130
 
100
131
  export interface UsageFetchError {
@@ -218,24 +249,7 @@ export function formatCount(n: number): string {
218
249
  return String(Math.trunc(n)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
219
250
  }
220
251
 
221
- function progressBar(percentage: number, width = 20): string {
222
- const clamped = Math.min(Math.max(percentage, 0), 100);
223
- const filled = Math.round((clamped / 100) * width);
224
- const empty = width - filled;
225
- return `[${"█".repeat(filled)}${"░".repeat(empty)}]`;
226
- }
227
252
 
228
- /**
229
- * `api_requests` comes back as 0 for some models that do have usage (live
230
- * probe 2026-09-27: qwen3.8-flash 796M tokens / 0 requests, while the window
231
- * total still sums the other models exactly). Reporting a bare "0 requests"
232
- * next to real consumption would read as a bug in this command, so say what
233
- * the endpoint actually reported.
234
- */
235
- function requestsSuffix(tokens: number, requests: number): string {
236
- if (tokens > 0 && requests === 0) return "requests not reported";
237
- return `${formatCount(requests)} requests`;
238
- }
239
253
 
240
254
  // ── Message builders ──────────────────────────────────────────────────────
241
255
 
@@ -263,87 +277,84 @@ export function buildStaticMessage(now = new Date()): string {
263
277
  return lines.join("\n");
264
278
  }
265
279
 
266
- /** Usage report merged with the documented caps. */
280
+ /** Format a credit value — integer or one decimal. */
281
+ function formatCredits(value: number): string {
282
+ return Number.isInteger(value) ? String(value) : `${value}`;
283
+ }
284
+
285
+ /** Credits progress bar: fills based on percentage, width N. */
286
+ function creditsBar(pct: number, width = 20): string {
287
+ const clamped = Math.min(Math.max(pct, 0), 100);
288
+ const filled = Math.round((clamped / 100) * width);
289
+ const empty = width - filled;
290
+ return `[${"█".repeat(filled)}${"░".repeat(empty)}]`;
291
+ }
292
+
293
+ /** Format a model's usage row: "model · X.XM in / YM cached / Z.ZM out · W (cr)" */
294
+ function modelRow(m: UsageModelTotals): string {
295
+ const inM = (m.prompt_tokens / 1_000_000).toFixed(1);
296
+ const cacheM = (m.cached_tokens / 1_000_000).toFixed(1);
297
+ const outM = (m.completion_tokens / 1_000_000).toFixed(1);
298
+ const cr = formatCredits(m.credits ?? 0);
299
+ return ` ${m.model} · ${inM}M in / ${cacheM}M cached / ${outM}M out · ${cr} (cr)`;
300
+ }
301
+
302
+ /** Usage report with credits-first layout. */
267
303
  export function buildUsageMessage(report: UsageReport, now = new Date()): string {
268
- const start = report.start_date;
269
- const end = report.end_date;
270
- const days = daysBetween(start, end);
271
304
  const totals = report.totals;
272
305
  const byModel = totals?.by_model ?? [];
273
- const totalTokens = totals?.total_tokens ?? 0;
274
- const totalRequests = totals?.api_requests ?? 0;
306
+ const credits = report.credits;
307
+
308
+ const lines: string[] = [];
309
+
310
+ // ── Credits banner ────────────────────────────────────────────────────
311
+ lines.push("💳 Credits");
312
+ if (credits) {
313
+ const total = credits.allowance;
314
+ const used = credits.used;
315
+ const remaining = credits.remaining;
316
+ const pct = total > 0 ? (used / total) * 100 : 0;
317
+ const packInfo = credits.pack_credits > 0
318
+ ? ` · packs: ${formatCredits(credits.pack_credits)} cr${credits.pack_expires_at ? ` (exp ${credits.pack_expires_at.slice(0, 10)})` : ""}`
319
+ : "";
275
320
 
276
- const lines: string[] = [
277
- "📊 NaN Usage",
278
- "",
279
- `🗓️ Window: ${start} → ${end} UTC (${days} day${days === 1 ? "" : "s"})`,
280
- "",
281
- resetLine(now),
282
- "",
283
- ];
321
+ lines.push(` ${creditsBar(pct)} ${pct.toFixed(1)}% used · ${formatCredits(used)} / ${formatCredits(total)} (${formatCredits(remaining)} remaining)${packInfo}`);
322
+ if (credits.frozen) {
323
+ lines.push(" ⚠️ Account frozen (subscription inactive): credit-billed requests are refused");
324
+ }
325
+ lines.push(` Period: ${credits.period_start.slice(0, 10)} → ${credits.period_end.slice(0, 10)} UTC`);
326
+ } else {
327
+ lines.push(" Credits not available for this account");
328
+ }
284
329
 
285
- const usageOf = (model: string): UsageModelTotals | undefined => byModel.find((m) => m.model === model);
330
+ lines.push("");
331
+ lines.push(resetLine(now));
332
+ lines.push("");
286
333
 
287
- if (totalTokens === 0 && totalRequests === 0 && byModel.length === 0) {
288
- lines.push("No usage in this window.");
289
- } else {
290
- const capped = MODEL_QUOTAS.filter((q) => q.monthlyCap > 0);
291
- const uncapped = MODEL_QUOTAS.filter((q) => q.monthlyCap === 0);
292
- const known = new Set(MODEL_QUOTAS.map((q) => q.model));
293
- const others = byModel.filter((m) => !known.has(m.model)).sort((a, b) => b.total_tokens - a.total_tokens);
294
-
295
- lines.push("Models with monthly caps:", "");
296
- for (const quota of capped) {
297
- const usage = usageOf(quota.model);
298
- const used = usage?.total_tokens ?? 0;
299
- const requests = usage?.api_requests ?? 0;
300
- const percentage = (used / quota.monthlyCap) * 100;
301
- const remaining = Math.max(quota.monthlyCap - used, 0);
302
-
303
- lines.push(`${quota.label}:`);
304
- lines.push(` ${progressBar(percentage)} ${percentage.toFixed(1)}% of monthly cap`);
305
- lines.push(
306
- ` Used: ${formatTokens(used)} / ${formatTokens(quota.monthlyCap)} (${formatTokens(remaining)} remaining) · ${requestsSuffix(used, requests)}`,
307
- );
308
- if (quota.rollingWindowCap > 0) {
309
- lines.push(
310
- ` ↳ rolling window: ${formatTokens(quota.rollingWindowCap)} / ${quota.rollingWindowHours}h ` +
311
- "(daily granularity — /usage cannot break it down)",
312
- );
313
- }
314
- lines.push("");
315
- }
334
+ // ── Model usage ───────────────────────────────────────────────────────
335
+ const sorted = byModel
336
+ .filter((m) => m.total_tokens > 0)
337
+ .sort((a, b) => (b.credits ?? 0) - (a.credits ?? 0));
316
338
 
317
- const usedUncapped = uncapped.filter((q) => (usageOf(q.model)?.total_tokens ?? 0) > 0);
318
- if (usedUncapped.length > 0) {
319
- lines.push("Uncapped models:", "");
320
- for (const quota of usedUncapped) {
321
- const usage = usageOf(quota.model)!;
322
- lines.push(`${quota.label}: ${formatTokens(usage.total_tokens)} used · ${requestsSuffix(usage.total_tokens, usage.api_requests)}`);
323
- }
324
- lines.push("");
339
+ if (sorted.length > 0) {
340
+ const totalCredits = totals?.credits ?? 0;
341
+ lines.push("⚡ Usage");
342
+ for (const m of sorted) {
343
+ lines.push(modelRow(m));
325
344
  }
326
-
327
- if (others.length > 0) {
328
- lines.push("Other models (no documented cap):", "");
329
- for (const usage of others) {
330
- lines.push(`${usage.model}: ${formatTokens(usage.total_tokens)} used · ${requestsSuffix(usage.total_tokens, usage.api_requests)}`);
331
- }
332
- lines.push("");
345
+ lines.push("");
346
+ if (totalCredits > 0) {
347
+ lines.push(`Total credits consumed: ${formatCredits(totalCredits)} (cr)`);
333
348
  }
334
349
  }
335
350
 
336
- lines.push(
337
- `Window totals: ${formatTokens(totalTokens)} tokens ` +
338
- `(${formatTokens(totals?.prompt_tokens ?? 0)} prompt / ${formatTokens(totals?.completion_tokens ?? 0)} completion) · ` +
339
- `${formatCount(totalRequests)} requests`,
340
- );
351
+ // ── All time ──────────────────────────────────────────────────────────
341
352
  const allTime = report.all_time;
342
353
  if (allTime) {
343
- const cached = allTime.cached_at ? ` (cached ${allTime.cached_at.slice(0, 10)})` : "";
354
+ const cached = allTime.cached_at ? ` (as of ${allTime.cached_at.slice(0, 10)})` : "";
344
355
  lines.push(`All time: ${formatTokens(allTime.total_tokens)} tokens · ${formatCount(allTime.api_requests)} requests${cached}`);
345
356
  }
346
- lines.push("💡 Source: GET /v1/usage · caps from https://nan.builders/docs/models");
357
+ lines.push("💡 Source: GET /v1/usage");
347
358
  return lines.join("\n");
348
359
  }
349
360