@gtrabanco/pi-nan-provider 1.5.2 → 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 +78 -2
- package/README.es.md +107 -19
- package/README.md +105 -14
- package/package.json +1 -1
- package/scripts/generate-models.ts +19 -3
- package/scripts/manual-overrides.ts +15 -1
- package/scripts/models.generated.ts +5 -5
- package/src/cache-anomaly.ts +277 -0
- package/src/debug-command.ts +124 -0
- package/src/debug-report.ts +601 -0
- package/src/index.ts +2 -0
- package/src/openai-compat-sanitizer.ts +20 -2
- package/src/provider-factory.ts +25 -2
- package/src/usage.ts +94 -83
- package/src/zip.ts +114 -0
package/AGENTS.md
CHANGED
|
@@ -174,8 +174,8 @@ Since 1.0.0 the package version **aligns its MAJOR.MINOR with the pi release lin
|
|
|
174
174
|
The `ExtensionAPI` interface does not include `modelRegistry`; it exists only on
|
|
175
175
|
`ExtensionContext` (the `ctx` passed to command/event handlers). At factory time,
|
|
176
176
|
stored credentials are resolved via `readStoredCredential("nan")` from
|
|
177
|
-
`@earendil-works/pi-coding-agent`. Command-time paths (`/nan-mcp`, `/nan-usage
|
|
178
|
-
`ctx.modelRegistry`.
|
|
177
|
+
`@earendil-works/pi-coding-agent`. Command-time paths (`/nan-mcp`, `/nan-usage`,
|
|
178
|
+
`/nan-debug`) use `ctx.modelRegistry`.
|
|
179
179
|
- models.json overrides compose **above** registered native providers.
|
|
180
180
|
- Capability values that diverge from models.dev are recorded as build-time
|
|
181
181
|
`MANUAL_OVERRIDES` (mandatory provenance note) in `scripts/manual-overrides.ts`,
|
|
@@ -490,3 +490,79 @@ Since 1.0.0 the package version **aligns its MAJOR.MINOR with the pi release lin
|
|
|
490
490
|
the network phase already persists correct merged data. Option (a) of the
|
|
491
491
|
reporter (version-stamping persisted entries) is NOT implementable
|
|
492
492
|
provider-side: the store write path belongs to pi-ai.
|
|
493
|
+
|
|
494
|
+
- **Cache-anomaly evidence + `/nan-debug` (issue #35, verified 2026-11-11 on
|
|
495
|
+
pi-ai 1.5.1):** pi-ai's `StreamOptions.onResponse(response, model)` is the
|
|
496
|
+
only response-header surface (`ProviderResponse = { status, headers }`,
|
|
497
|
+
called by openai-completions right after the HTTP response). The gateway
|
|
498
|
+
`id`/`created` pair comes from raw `onProviderStreamEvent` chunks: pi-ai copies
|
|
499
|
+
only `chunk.id` into `AssistantMessage.responseId`, and `created` is never
|
|
500
|
+
persisted. `src/cache-anomaly.ts` wraps the provider api outermost
|
|
501
|
+
(`withCacheAnomalyCapture`), compares each completed stream against the
|
|
502
|
+
previous one **per model**, and on the #17 signature (same `id` + `created`)
|
|
503
|
+
appends one record to `<agentDir>/nan-cache-anomalies.jsonl`. Bursts record
|
|
504
|
+
the first pair once; a differing signature resets the baseline. The record is
|
|
505
|
+
local-only (model, id/created, both `cf-ray`, ISO timestamps, payload
|
|
506
|
+
SHA-256); no content, credentials or paths. `--window`'s usage fetch is the
|
|
507
|
+
only network path in `/nan-debug` and stays behind the explicit flag.
|
|
508
|
+
`src/debug-report.ts` reads `<agentDir>/sessions/**/*.jsonl` (filename date
|
|
509
|
+
prefix, else mtime), extracts only assistant `provider: "nan"` turns, and
|
|
510
|
+
renders the 2026-11-10 report shape plus `turns.jsonl`. The zip is built by
|
|
511
|
+
`src/zip.ts` (store method, sorted entries, fixed 1980-01-01 timestamps)
|
|
512
|
+
because `Bun.Archive` is Bun-only and pi also runs on Node. Session/worktree
|
|
513
|
+
labels are MD5[:12]; `errorMessage` maps to
|
|
514
|
+
`overflow|rate_limited|invalid_request|transport|other`.
|
|
515
|
+
Regression tests: `test/issue-35-cache-anomaly-capture.test.ts`,
|
|
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
|
[](https://opensource.org/licenses/MIT)
|
|
4
|
-
[](https://github.com/gtrabanco/pi-nan-provider/releases)
|
|
5
5
|
[](https://cloud.nan.builders/r/7GK06FX8)
|
|
6
6
|
|
|
7
7
|
[NaN Builders](https://cloud.nan.builders/r/7GK06FX8) model provider + MCP nativo para [pi](https://github.com/earendil-works/pi).
|
|
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
|
|
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
|
|
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.
|
|
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`
|
|
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.
|
|
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
|
|
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.
|
|
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.
|
|
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
|
-
`
|
|
292
|
+
`.github/workflows/check-pi-sdk-versions.yml` y `scripts/check-pi-sdk-versions.mjs`.
|
|
253
293
|
|
|
254
294
|
---
|
|
255
295
|
|
|
@@ -350,6 +390,48 @@ Los errores siguen siendo accionables: `401` → ejecuta `/login nan` o corrige
|
|
|
350
390
|
|
|
351
391
|
---
|
|
352
392
|
|
|
393
|
+
## 🧾 Evidencia de anomalías de caché: `/nan-debug`
|
|
394
|
+
|
|
395
|
+
La caché de respuestas del gateway de NaN puede devolver el mismo `id` y
|
|
396
|
+
`created` en peticiones seguidas (la firma del issue #17). NaN pidió el `model`
|
|
397
|
+
y el `cf-ray` de un par de llamadas si vuelve a pasar; los transcripts de pi no
|
|
398
|
+
guardan cabeceras de respuesta, así que el proveedor las captura.
|
|
399
|
+
|
|
400
|
+
Cuando dos streams del mismo modelo devuelven el mismo `id` + `created`, se
|
|
401
|
+
añade una línea JSON a `<agentDir>/nan-cache-anomalies.jsonl` — `model`, el par
|
|
402
|
+
`id`/`created`, los dos `cf-ray`, timestamps ISO y un SHA-256 del payload de la
|
|
403
|
+
petición. Es **solo local**: ni contenido de prompt/respuesta, ni credenciales,
|
|
404
|
+
ni rutas, ni subida remota. Un fallo de escritura nunca rompe un stream.
|
|
405
|
+
|
|
406
|
+
`/nan-debug` convierte ese fichero y tus transcripts en un paquete de evidencia
|
|
407
|
+
redactado y reproducible para NaN:
|
|
408
|
+
|
|
409
|
+
```text
|
|
410
|
+
/nan-debug # últimos 7 días, escribe <agentDir>/nan-debug-report/
|
|
411
|
+
/nan-debug cache --window 2 # etiqueta de tema + ventana de 2 días
|
|
412
|
+
/nan-debug --window 2 --emit # además escribe <agentDir>/nan-debug-report.zip
|
|
413
|
+
/nan-debug cache --out ~/evidence --emit
|
|
414
|
+
```
|
|
415
|
+
|
|
416
|
+
- `--window N` (1–90 días) consulta además `GET /v1/usage` para el mismo periodo
|
|
417
|
+
con tu clave guardada y escribe `usage_window.json`; sin el flag no se hace
|
|
418
|
+
ninguna petición. Esa llamada en vivo consume el límite de peticiones.
|
|
419
|
+
- El zip se escribe **solo** con `--emit`; la ejecución por defecto escribe el
|
|
420
|
+
informe local e imprime un resumen.
|
|
421
|
+
- `--out <ruta>` escribe el informe donde lo indiques (y, con `--emit`,
|
|
422
|
+
`<ruta>.zip`); un `~/` inicial se expande a tu directorio home, así que los
|
|
423
|
+
ejemplos de arriba escriben donde dicen. Un token de flag nunca se acepta
|
|
424
|
+
como ruta.
|
|
425
|
+
- El informe contiene `README.md`, `anonymized_usage.jsonl` (totales por
|
|
426
|
+
fecha/sesión/modelo, conteo de `stopReason`, tasa de acierto de caché),
|
|
427
|
+
`turns.jsonl` (uso por turno, `stopReason`, clase de error, `responseId`),
|
|
428
|
+
`anomalies.jsonl` (par de `cf-ray`) y `metadata.json` (versiones de paquete,
|
|
429
|
+
pi-ai y pi; procedencia del catálogo).
|
|
430
|
+
- Las etiquetas de sesión y worktree son MD5 truncado a 12 caracteres;
|
|
431
|
+
`errorMessage` se reduce a `overflow | rate_limited | invalid_request |
|
|
432
|
+
transport | other`; el contenido de prompt/respuesta y las credenciales nunca
|
|
433
|
+
se recogen. Entradas idénticas producen bytes de zip idénticos.
|
|
434
|
+
|
|
353
435
|
## 📊 Modelos
|
|
354
436
|
|
|
355
437
|
Catálogo base (verificado contra [docs de NaN](https://nan.builders/docs/models) y [OpenAPI](https://nan.builders/openapi.json)).
|
|
@@ -396,15 +478,14 @@ Modelos de imagen no-chat (disponibles vía `models.generateImages()` /
|
|
|
396
478
|
|
|
397
479
|
---
|
|
398
480
|
|
|
399
|
-
---
|
|
400
|
-
|
|
401
481
|
## 🧠 Controles de razonamiento
|
|
402
482
|
|
|
403
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:
|
|
404
484
|
|
|
405
485
|
| Modelo | Effort de razonamiento | Cómo funciona |
|
|
406
486
|
| :--- | :--- | :--- |
|
|
407
|
-
| `glm5.3
|
|
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 |
|
|
408
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 |
|
|
409
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) |
|
|
410
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 |
|
|
@@ -412,7 +493,7 @@ El parámetro `reasoning_effort` de NaN controla cuánto piensa el modelo antes
|
|
|
412
493
|
| `mimo-v2.6-flash` | `none` | Los docs lo llamaban "profundidad no ajustable", pero el gateway en vivo (2026-10-14) muestra que `none` da 0 tokens de razonamiento con respuesta completa mientras `low` da 22 y omitirlo 17 — así que `thinking: "off"` envía `reasoning_effort: "none"` vía el `thinkingLevelMap` del catálogo |
|
|
413
494
|
|
|
414
495
|
> [!NOTE]
|
|
415
|
-
> `maxTokens` NO limita la fase de razonamiento en los modelos de NaN. La fase de razonamiento corre hasta completarse (o se corta en el límite de stream solo-razonamiento de NaN: 45.000 caracteres de razonamiento, o 420 s sin salida visible) independientemente de `maxTokens` — medido: `max_tokens=512` en deepseek-v4-flash aún consumió 13,376 tokens de completación, todos de razonamiento (26x el techo). Este es un comportamiento del gateway confirmado por el issue #16 (medido 2026-09-27).
|
|
496
|
+
> `maxTokens` NO limita la fase de razonamiento en los modelos de NaN. La fase de razonamiento corre hasta completarse (o se corta en el límite de stream solo-razonamiento de NaN: 45.000 caracteres de razonamiento, o 420 s sin salida visible) independientemente de `maxTokens` — medido: `max_tokens=512` en deepseek-v4-flash aún consumió 13,376 tokens de completación, todos de razonamiento (26x el techo). Este es un comportamiento del gateway confirmado por el issue #16 (medido 2026-09-27) y por NaN para `qwen3.8-flash` (issue #34, 2026-11-11 — el exceso además factura contra la cuota). Como límite provisional para `qwen3.8-flash` el catálogo envía `max_completion_tokens`, que NaN confirmó que SÍ se respeta; sobrevive porque la compat de ese modelo desactiva el renombrado a `max_tokens` del sanitizador de esquema (su OpenAPI publicado solo documenta `max_tokens`). Retira ese override cuando NaN publique el arreglo en su gateway — `test/issue-34-max-completion-tokens.test.ts` es el tripwire. Solo el razonamiento aún puede agotar el presupuesto completo y cerrar el turno con contenido vacío; ese corte lleva el marcador `reasoning_only_stream` de NaN y pi-ai reintenta el turno (issue #21).
|
|
416
497
|
|
|
417
498
|
## 🚀 Desarrollo
|
|
418
499
|
|
|
@@ -421,6 +502,13 @@ bun install
|
|
|
421
502
|
bun run generate-models # Regenerar catálogo de fallback
|
|
422
503
|
bun test # Ejecutar todos los tests
|
|
423
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?
|
|
424
507
|
```
|
|
425
508
|
|
|
426
|
-
|
|
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
|
[](https://opensource.org/licenses/MIT)
|
|
4
|
-
[](https://github.com/gtrabanco/pi-nan-provider/releases)
|
|
5
5
|
[](https://cloud.nan.builders/r/7GK06FX8)
|
|
6
6
|
|
|
7
7
|
[NaN Builders](https://cloud.nan.builders/r/7GK06FX8) model provider + a native MCP server for [pi](https://github.com/earendil-works/pi).
|
|
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
|
|
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.
|
|
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`
|
|
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.
|
|
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
|
|
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.
|
|
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 `
|
|
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
|
|
|
@@ -345,6 +387,47 @@ Failures stay actionable: `401` → run `/login nan` or fix `NAN_API_KEY`, `404`
|
|
|
345
387
|
|
|
346
388
|
---
|
|
347
389
|
|
|
390
|
+
## 🧾 Cache anomaly evidence: `/nan-debug`
|
|
391
|
+
|
|
392
|
+
NaN's gateway response cache can replay the same completion `id` and `created`
|
|
393
|
+
timestamp for back-to-back requests (the issue #17 signature). NaN asked for the
|
|
394
|
+
`model` and the `cf-ray` of a couple of calls when it recurs; pi transcripts do
|
|
395
|
+
not keep response headers, so the provider captures them itself.
|
|
396
|
+
|
|
397
|
+
When two streams for the same model return the same `id` + `created`, one JSON
|
|
398
|
+
line is appended to `<agentDir>/nan-cache-anomalies.jsonl` —
|
|
399
|
+
`model`, the `id`/`created` pair, both `cf-ray` values, ISO timestamps and a
|
|
400
|
+
SHA-256 of the request payload. It is **local-only**: no prompt or response
|
|
401
|
+
content, no credentials, no paths, no upload. A write failure never breaks a
|
|
402
|
+
stream.
|
|
403
|
+
|
|
404
|
+
`/nan-debug` turns that file plus your session transcripts into a redacted,
|
|
405
|
+
reproducible evidence package for NaN:
|
|
406
|
+
|
|
407
|
+
```text
|
|
408
|
+
/nan-debug # last 7 days, writes <agentDir>/nan-debug-report/
|
|
409
|
+
/nan-debug cache --window 2 # topic label + a 2-day window
|
|
410
|
+
/nan-debug --window 2 --emit # also writes <agentDir>/nan-debug-report.zip
|
|
411
|
+
/nan-debug cache --out ~/evidence --emit
|
|
412
|
+
```
|
|
413
|
+
|
|
414
|
+
- `--window N` (1–90 days) also fetches `GET /v1/usage` for the same period with
|
|
415
|
+
your stored key and writes `usage_window.json`; without the flag nothing is
|
|
416
|
+
fetched. That live call counts against your quota's request rate.
|
|
417
|
+
- The zip is written **only** with `--emit`; the default run writes the local
|
|
418
|
+
report and prints a preview.
|
|
419
|
+
- `--out <path>` writes the report anywhere you name it (and, with `--emit`,
|
|
420
|
+
`<path>.zip`); a leading `~/` expands to your home directory, so the examples
|
|
421
|
+
above write where they say. A flag token is never accepted as the path.
|
|
422
|
+
- The report contains `README.md`, `anonymized_usage.jsonl` (per date/session/
|
|
423
|
+
model totals, stop-reason counts, cache-hit rate), `turns.jsonl` (per-turn
|
|
424
|
+
usage, stop reason, error class, response id), `anomalies.jsonl` (`cf-ray`
|
|
425
|
+
pair) and `metadata.json` (package/pi-ai/pi versions, catalog provenance).
|
|
426
|
+
- Session and worktree labels are MD5-truncated to 12 chars; `errorMessage` is
|
|
427
|
+
reduced to `overflow | rate_limited | invalid_request | transport | other`;
|
|
428
|
+
prompt/response content and credentials are never collected. Identical inputs
|
|
429
|
+
produce byte-identical zip bytes.
|
|
430
|
+
|
|
348
431
|
## 📊 Models
|
|
349
432
|
|
|
350
433
|
Baseline catalog (verified against [NaN docs](https://nan.builders/docs/models) and [OpenAPI](https://nan.builders/openapi.json)).
|
|
@@ -397,14 +480,15 @@ NaN's `reasoning_effort` parameter controls how much the model thinks before ans
|
|
|
397
480
|
|
|
398
481
|
| Model | Reasoning effort | How it works |
|
|
399
482
|
| :--- | :--- | :--- |
|
|
400
|
-
| `glm5.3
|
|
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` |
|
|
401
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 |
|
|
402
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) |
|
|
403
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 |
|
|
404
488
|
| `kimi-k3.1-pro`, `qwen3.8-max`, `deepseek-v4-pro`, `hy4` | *(no mapping declared)* | External-provider models launched 2026-11-10; how the gateway translates `reasoning_effort` for them is unmeasured, so the catalog declares no effort values and no `thinkingLevelMap` (`thinking: "off"` sends no parameter) |
|
|
405
489
|
| `mimo-v2.6-flash` | `none` | The docs called this "depth not adjustable", but the live gateway (2026-10-14) shows `none` gives 0 reasoning tokens with a full answer while `low` gives 22 and omitting the parameter 17 — so `thinking: "off"` sends `reasoning_effort: "none"` via the catalog's `thinkingLevelMap` |
|
|
406
490
|
> [!NOTE]
|
|
407
|
-
> `maxTokens` does NOT bound the reasoning phase on NaN models. The reasoning phase runs to completion (or is cut at NaN's reasoning-only stream limit: 45,000 reasoning characters, or 420 s without visible output) regardless of `maxTokens` — measured: `max_tokens=512` on deepseek-v4-flash still consumed 13,376 completion tokens, all reasoning (26x the ceiling). This is gateway behavior confirmed by issue #16 (measured 2026-09-27).
|
|
491
|
+
> `maxTokens` does NOT bound the reasoning phase on NaN models. The reasoning phase runs to completion (or is cut at NaN's reasoning-only stream limit: 45,000 reasoning characters, or 420 s without visible output) regardless of `maxTokens` — measured: `max_tokens=512` on deepseek-v4-flash still consumed 13,376 completion tokens, all reasoning (26x the ceiling). This is gateway behavior confirmed by issue #16 (measured 2026-09-27) and by NaN for `qwen3.8-flash` (issue #34, 2026-11-11 — the excess also bills against the quota). As an interim bound for `qwen3.8-flash` the catalog sends `max_completion_tokens` instead, which NaN confirmed IS respected; it survives because that model's compat opts out of the schema sanitizer's rename to `max_tokens` (its published OpenAPI schema still documents only `max_tokens`). Remove that override once NaN ships their gateway fix — `test/issue-34-max-completion-tokens.test.ts` is the tripwire. Reasoning alone can still consume the whole budget and end the turn with empty content; that closure carries NaN's `reasoning_only_stream` marker and pi-ai retries the turn (issue #21).
|
|
408
492
|
|
|
409
493
|
|
|
410
494
|
---
|
|
@@ -416,6 +500,13 @@ bun install
|
|
|
416
500
|
bun run generate-models # Regenerate fallback catalog
|
|
417
501
|
bun test # Run all tests
|
|
418
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?
|
|
419
505
|
```
|
|
420
506
|
|
|
421
|
-
|
|
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
|
+
"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",
|