@gtrabanco/pi-nan-provider 1.6.1 → 1.6.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
@@ -350,6 +350,31 @@ Since 1.0.0 the package version **aligns its MAJOR.MINOR with the pi release lin
350
350
  only when estimated over the window). Wired in `src/provider-factory.ts` after
351
351
  the sanitizer. Regression tests: `test/issue-3-model-switch-overflow.test.ts`,
352
352
  `test/context-overflow-classifier.test.ts`; issue #3.
353
+ - **The #52 wedge is a payload defect, not an under-counting estimator** (verified
354
+ 2026-11-26 against the archived transcript and attempt log). A
355
+ `mimo-v2.6-flash` session sat on the opaque 400 for two hours; the turn before
356
+ the first 400 reports `input` 2,075 + `cacheRead` 559,232 = **561,307 prompt
357
+ tokens** against a **1,048,576** window, while `estimateRequestTokens` answers
358
+ 625,484 for the same 2,170,428 payload bytes. Real ratio = 3.867 bytes/token,
359
+ so the 3.47 divisor **over**-estimates by 11.4 % — the issue's "systematically
360
+ underestimated" is backwards, and its ÷2.0 proposal would fabricate 1,085,214
361
+ tokens for a request at 53.5 % of the window (a forced compaction plus a false
362
+ cause on the error text). The real cause: the gateway streamed
363
+ `{"type":"toolCall","id":"","name":"","arguments":{}}`, pi persisted pi's
364
+ `"Tool not found"` result with `toolCallId: ""`, and pi-ai copies both ids
365
+ verbatim onto the wire (`api/openai-completions.js:1015-1022` for
366
+ `tool_calls`, `:1073-1077` for `role:"tool"`) — so every replay of the history
367
+ was rejected until a compaction removed the pair. `src/openai-compat-sanitizer.ts`
368
+ now reconciles announced calls with their results in one ordered pass
369
+ (`reconcileToolCalls`): empty id ← the answering `tool_call_id`, else a
370
+ deterministic `call_<name>_<messageIndex>_<callIndex>` fallback (never a
371
+ counter — a request-varying id invalidates the prefix cache); empty
372
+ `function.name` → `function`; empty `tool_call_id` ← the announced call; a
373
+ result with nothing to bind to is dropped. Real ids, `type !== "function"`
374
+ grammar calls and unrelated fields are untouched. The overflow thresholds are
375
+ unchanged on purpose. Regression tests: `test/issue-52-empty-tool-call-ids.test.ts`
376
+ (the repair, the deterministic ids, the trailing invariants and the pinned
377
+ measurement); `test/openai-compat-sanitizer.test.ts` stays byte-identical.
353
378
  - Relative imports inside this package use `.ts` extensions (pi's official
354
379
  extension examples do the same; pi transpiles extension sources).
355
380
  - pi 0.87 breaking changes NOT used by this package: `ContextEditEntry` added to
@@ -592,8 +617,8 @@ Since 1.0.0 the package version **aligns its MAJOR.MINOR with the pi release lin
592
617
  called by openai-completions right after the HTTP response). The gateway
593
618
  `id`/`created` pair comes from raw `onProviderStreamEvent` chunks: pi-ai copies
594
619
  only `chunk.id` into `AssistantMessage.responseId`, and `created` is never
595
- persisted. `src/cache-anomaly.ts` wraps the provider api outermost
596
- (`withCacheAnomalyCapture`), compares each completed stream against the
620
+ persisted. `src/cache-anomaly.ts` wraps the provider api immediately inside
621
+ the #49 attempt tap (`withCacheAnomalyCapture`), compares each completed stream against the
597
622
  previous one **per model**, and on the #17 signature (same `id` + `created`)
598
623
  appends one record to `<agentDir>/nan-cache-anomalies.jsonl`. Bursts record
599
624
  the first pair once; a differing signature resets the baseline. The record is
@@ -603,10 +628,8 @@ Since 1.0.0 the package version **aligns its MAJOR.MINOR with the pi release lin
603
628
  `src/debug-report.ts` reads `<agentDir>/sessions/**/*.jsonl` (filename date
604
629
  prefix, else mtime), extracts only assistant `provider: "nan"` turns, and
605
630
  renders the 2026-11-10 report shape plus `turns.jsonl`. PR #44 (2026-11-18)
606
- adds `errors.jsonl` rows and `error_summary` in `metadata.json`, embeds the
607
- window-filtered raw transcripts under `sessions/` (their `cwd` header is
608
- MD5-hashed; root files stay redacted — the transcripts are the owner's
609
- explicit ask, issue #44), and adds `--interval` (day-granular windows capped
631
+ adds `errors.jsonl` rows and `error_summary` in `metadata.json` and adds
632
+ `--interval` (day-granular windows capped
610
633
  at 90 days, mutually exclusive with `--window`; its value joins tokens up to
611
634
  the next `--` flag because pi passes slash-command args raw). Since 1.5.9
612
635
  every response's `cf-ray` is appended by the same wrapper to
@@ -616,8 +639,48 @@ Since 1.0.0 the package version **aligns its MAJOR.MINOR with the pi release lin
616
639
  2026-11-18; null when uncaptured). The zip is built by
617
640
  `src/zip.ts` (store method, sorted entries, fixed 1980-01-01 timestamps)
618
641
  because `Bun.Archive` is Bun-only and pi also runs on Node. Session/worktree
619
- labels are MD5[:12]; `errorMessage` maps to
642
+ labels are MD5[:16] since issue #49 (no salt, so a session links across
643
+ reports); `errorMessage` maps to
620
644
  `overflow|rate_limited|invalid_request|transport|other`.
645
+
646
+ - **HTTP attempt tap (issue #49, verified 2026-11-24 on pi-ai 1.6.0):**
647
+ `CreateProviderOptions` has **no** `fetch` field — issue #49's claim that
648
+ "`createProvider` acepta el `fetch` en options" is wrong for the pinned
649
+ version. `fetch` is a `StreamOptions` field forwarded to the OpenAI client
650
+ (`dist/api/openai-completions.js:createClient`). `retryProviderRequest`
651
+ retries by re-invoking the same client with `maxRetries: 0`, and `onResponse`
652
+ fires only **after** that loop, so a rejected attempt never reaches it.
653
+ `src/http-attempts.ts` therefore wraps the provider api outermost
654
+ (`withHttpAttemptCapture`) and injects `StreamOptions.fetch` — the only tap
655
+ that sees every attempt, including a 429 that never produced a gateway `id`.
656
+ It appends one `attempt` row per fetch (status, whitelisted headers, ms
657
+ timing, `attempt_n`, `payload_bytes`, request parameters, process-scoped
658
+ inflight/60 s counters) and one `response` row per completed request
659
+ (`response_id`/`created`) to `<agentDir>/nan-http-attempts.jsonl`, bounded to
660
+ 50k lines and best-effort. `onPayload` is awaited once per logical request
661
+ before the retry loop, so the payload size and parameters measured there hold
662
+ for every attempt; the request body itself is never read (consuming the SDK's
663
+ request body would break the call). A non-2xx response is cloned and at most
664
+ 8 KB are read to keep only `error.type`/`error.code` (never the body or its
665
+ message). A fetch rejection sets `transport_error` (the exception name), while
666
+ `error_type`/`error_code` stay the gateway's. `time_to_header_ms` is start →
667
+ headers; the response row carries `duration_ms` (first attempt start →
668
+ completion), `usage` and the raw `finish_reason`, so the artifact is a
669
+ superset of the reporter's per-attempt CSV. The default report carries no prompt,
670
+ response or tool content: `sessions/` is opt-in (`--include-prompts`,
671
+ tool calls stripped; `--include-tools` keeps them; `--all` also puts
672
+ `usage_window.json` in the zip), embedded transcripts keep only their
673
+ `cwd` header MD5-hashed, `topic` is a `topic_hash`, and
674
+ `errors.jsonl` stores only gateway-body fields. `errors.jsonl` correlates a
675
+ failed logical request to its terminal attempt by model + the turn's own span
676
+ (pi records no response id for a failure), leaving the cells null when
677
+ nothing matches. `parseGatewayError` accepts BOTH shapes that reach the
678
+ transcript: the raw HTTP body `{"error":{…}}` and pi-ai's normalized
679
+ `429: {"message":…,"type":…,"code":…}` (verified against the pinned SDK:
680
+ `formatProviderError(normalizeProviderError(APIError.generate(...)))` emits
681
+ the inner object without the `error` envelope — requiring `parsed.error`
682
+ alone silently nulled every structured field). Regression tests: `test/issue-49-http-attempts.test.ts`,
683
+ `test/issue-49-debug-report.test.ts`, `test/issue-49-nan-debug-command.test.ts`.
621
684
  Regression tests: `test/issue-35-cache-anomaly-capture.test.ts`,
622
685
  `test/issue-35-debug-report.test.ts`, `test/issue-35-nan-debug-command.test.ts`.
623
686
 
package/README.es.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # @gtrabanco/𝜋-nan-provider
2
2
 
3
3
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
4
- [![Version](https://img.shields.io/badge/version-1.6.1-blue)](https://github.com/gtrabanco/pi-nan-provider/releases)
4
+ [![Version](https://img.shields.io/badge/version-1.6.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).
@@ -18,7 +18,7 @@ Registra el proveedor `nan` vía `pi.registerProvider()` usando la API OpenAI-co
18
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
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
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. |
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 — incluidos los ids de tool call y de resultado, de modo que una tool call fantasma emitida con `id: ""` no puede bloquear la sesión ([#52](https://github.com/gtrabanco/pi-nan-provider/issues/52)). |
22
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
23
  | **Reintento de streams truncados** | `supportsFinishReason: true` convierte un stream SSE cerrado antes de `finish_reason` en un error reintentable en vez de un stall silencioso ([#2](https://github.com/gtrabanco/pi-nan-provider/issues/2)). |
24
24
  | **Uso de tokens en streaming** | `stream_options.include_usage` activo por defecto, así que pi reporta recuentos reales de entrada/salida/razonamiento/caché ([#4](https://github.com/gtrabanco/pi-nan-provider/issues/4), [#7](https://github.com/gtrabanco/pi-nan-provider/issues/7)). |
@@ -28,7 +28,7 @@ Registra el proveedor `nan` vía `pi.registerProvider()` usando la API OpenAI-co
28
28
  | **Modelos de imagen nativos** | `flux-2-klein` y `qwen-image-2.1` registrados como modelos de pi `type: "image"`, accesibles desde codemode y extensiones. |
29
29
  | **Puente MCP nativo de media** | El servidor `nan-media` (10 herramientas) registrado con `pi.registerMcpServer()`, gestionado con `/nan-mcp`. |
30
30
  | **Informe de créditos** | `/nan-usage` muestra saldo de créditos con barra de progreso, desglose por modelo (input / cached / output en M, créditos consumidos) y periodo de facturación — todo desde `GET /v1/usage` ([#37](https://github.com/gtrabanco/pi-nan-provider/issues/37)). |
31
- | **Evidencia de anomalías de caché** | Captura de `cf-ray` sobre la firma repetida `id` + `created` del gateway ([#17](https://github.com/gtrabanco/pi-nan-provider/issues/17)) más el recolector determinista `/nan-debug` ([#35](https://github.com/gtrabanco/pi-nan-provider/issues/35)) con evidencia de errores por turno, el `cf-ray` de cada respuesta unido a `turns.jsonl` (S11) y ventanas flexibles `--interval` ([#44](https://github.com/gtrabanco/pi-nan-provider/issues/44)). |
31
+ | **Evidencia de anomalías de caché** | Captura de `cf-ray` sobre la firma repetida `id` + `created` del gateway ([#17](https://github.com/gtrabanco/pi-nan-provider/issues/17)) más el recolector determinista `/nan-debug` ([#35](https://github.com/gtrabanco/pi-nan-provider/issues/35)) con evidencia de errores por turno, el `cf-ray` de cada respuesta unido a `turns.jsonl` (S11), ventanas flexibles `--interval` ([#44](https://github.com/gtrabanco/pi-nan-provider/issues/44)) y el tap de intentos HTTP ([#49](https://github.com/gtrabanco/pi-nan-provider/issues/49)): status, cabeceras de la whitelist, reintentos invisibles (`attempt_n`), concurrencia/RPM del proceso y `payload_bytes` — el zip no lleva prompt ni tool content salvo que lo pidas. |
32
32
  | **Integración con pi** | Refresco de modelos dirigido por el runtime Models de pi, overrides por modelo en `models.json` y el changelog de la extensión (`pi.changelogPath`) que pi muestra tras una actualización. |
33
33
 
34
34
  Comandos:
@@ -37,7 +37,7 @@ Comandos:
37
37
  | :--- | :--- |
38
38
  | `/nan-mcp` | Gestionar el puente MCP de media (`status` / `enable` / `disable`) |
39
39
  | `/nan-usage [1-90]` | Saldo de créditos con barra de uso, desglose por modelo (in / cached / out en M · créditos cr) y totales históricos |
40
- | `/nan-debug [tema] [--window N] [--interval FLEX] [--out ruta] [--emit]` | Paquete de evidencia reproducible y redactado para NaN |
40
+ | `/nan-debug [tema] [--window N] [--interval FLEX] [--out ruta] [--emit] [--include-prompts] [--include-tools] [--all]` | Paquete de evidencia reproducible y redactado para NaN; el contenido es opcional |
41
41
 
42
42
  ---
43
43
 
@@ -83,6 +83,7 @@ El registro es síncrono a propósito: el catálogo de fallback está disponible
83
83
  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:
84
84
 
85
85
  - 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`);
86
+ - tool call anunciada de tipo `function` lleva un `id` no vacío y un `function.name` no vacío — una llamada cuyo `type` no es `function` (una grammar tool) se deja intacta — y el `tool_call_id` de cada mensaje `tool` nombra la llamada que responde: una tool call fantasma emitida con `id: ""` se repara posicionalmente en lugar de bloquear la sesión con el 400 opaco de NaN ([#52](https://github.com/gtrabanco/pi-nan-provider/issues/52)). Los ids de relleno salen de la posición del mensaje, así que un historial reenviado mantiene caliente la caché de prefijo del gateway, y un id real nunca se reescribe;
86
87
  - 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;
87
88
  - 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;
88
89
  - `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-max` es el único modelo del catálogo que lo desactiva tras la reversión del [#36](https://github.com/gtrabanco/pi-nan-provider/issues/36)).
@@ -99,7 +100,7 @@ La cabecera **sigue la opción de telemetría de pi**: con `enableInstallTelemet
99
100
 
100
101
  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.
101
102
 
102
- 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.
103
+ 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. Las dos rutas de rescate se mantienen separadas: un defecto de payload que provocaría el 400 — como los ids de tool call vacíos de [#52](https://github.com/gtrabanco/pi-nan-provider/issues/52) — se repara antes de que la petición salga de pi (ver el sanitizador arriba), mientras que la revisión de tamaño solo juzga cuán grande es la petición.
103
104
 
104
105
  ### ⏱️ Streams truncados intermitentes (auto-retry, sin stall silencioso)
105
106
 
@@ -410,21 +411,46 @@ guarda en `<agentDir>/nan-response-rays.jsonl` — `response_id`, `cf_ray`,
410
411
  soporte tiene los rays de cualquier par de llamadas sin esperar a una
411
412
  recurrencia.
412
413
 
413
- `/nan-debug` convierte ese fichero y tus transcripts en un paquete de evidencia
414
+ Cada **intento HTTP** — incluidos los reintentos que pi-ai oculta y los 429 que
415
+ nunca producen un id de gateway — se guarda en
416
+ `<agentDir>/nan-http-attempts.jsonl`
417
+ (issue [#49](https://github.com/gtrabanco/pi-nan-provider/issues/49)): status,
418
+ las cabeceras de respuesta de la whitelist (`cf-ray`, `x-request-id`,
419
+ `Retry-After`, `x-should-retry`, `rate-limit-*`), inicio/fin en milisegundos más
420
+ `latency_ms`, `attempt_n`, `payload_bytes`, los parámetros de la petición
421
+ (`reasoning_effort`, `max_tokens`, el campo realmente enviado, `stream`), el
422
+ `error_type`/`error_code` del cuerpo no-2xx y los contadores de concurrencia e
423
+ inicios en 60 s, que son del proceso. `time_to_header_ms` es inicio → cabeceras
424
+ (la señal de rechazo temprano, p. ej. la mediana de 237 ms); la duración total,
425
+ el `usage` de tokens y el `finish_reason` en bruto van en la fila `response` de
426
+ cada petición. El informe embebe las filas filtradas por la ventana como
427
+ `http_attempts.jsonl`, así que un solo zip responde *qué intento falló, con qué
428
+ status y cabeceras y tras cuántos reintentos*.
429
+
430
+ `/nan-debug` convierte esos ficheros y tus transcripts en un paquete de evidencia
414
431
  redactado y reproducible para NaN:
415
432
 
416
433
  ```text
417
- /nan-debug # últimos 7 días, escribe <agentDir>/nan-debug-report/
434
+ /nan-debug # últimos 7 días; escribe <agentDir>/nan-debug-report-<fecha-hora de emisión>/
418
435
  /nan-debug cache --window 2 # etiqueta de tema + ventana de 2 días
419
- /nan-debug --window 2 --emit # además escribe <agentDir>/nan-debug-report.zip
436
+ /nan-debug --window 2 --emit # además escribe <agentDir>/nan-debug-report-<fecha-hora de emisión>.zip
437
+ /nan-debug cache --include-prompts --emit # embebe los transcripts en bruto (sin tool calls)
438
+ /nan-debug --all --emit # transcripts + tool calls + usage_window.json (el volcado previo a #49)
420
439
  /nan-debug cache --out ~/evidence --emit
421
440
  /nan-debug --interval 5min # intervalos relativos: 5min, 2h, 3d, 1mes
422
441
  /nan-debug --interval "2026-11-10 - 2026-11-11 17:30" # rangos, extremos abiertos y puntos únicos también
423
442
  ```
424
443
 
444
+ - El directorio y el zip por defecto llevan la fecha-hora de **emisión** en UTC
445
+ (`nan-debug-report-YYYY-MM-DDTHH:mm:ss`; el zip usa `-` en vez de `:` para que
446
+ el nombre sea portable), así que ejecuciones consecutivas no se machacan. La
447
+ ventana reportada vive en `metadata.window`. Un `--out` explícito se respeta
448
+ tal cual.
425
449
  - `--window N` (1–90 días) consulta además `GET /v1/usage` para el mismo periodo
426
450
  con tu clave guardada y escribe `usage_window.json`; sin el flag no se hace
427
- ninguna petición. Esa llamada en vivo consume el límite de peticiones.
451
+ ninguna petición. Esa llamada en vivo consume el límite de peticiones. La
452
+ ventana de usage queda fuera del zip salvo con `--all`: identifica tu
453
+ cuenta/tier.
428
454
  - `--interval <desc>` sustituye a `--window` (usar ambos es un error) y acepta
429
455
  intervalos relativos (`5min`, `2h`, `3d`, `1mes`), rangos fecha/hora
430
456
  (`2026-11-10 - 2026-11-11 17:30`, `10:30 - 11:00`, cruce de medianoche
@@ -432,31 +458,50 @@ redactado y reproducible para NaN:
432
458
  año-mes (`2026-11 - 2026-12`) y puntos únicos (`2026-11-10`,
433
459
  `2026-11-10T10:00:00Z`). El span máximo es de 90 días y el parseo es
434
460
  determinista — sin llamadas a LLM. El tema, si usas uno, va antes del flag.
461
+ - El contenido es opcional y está **desactivado por defecto**:
462
+ `--include-prompts` embebe los transcripts filtrados por la ventana bajo
463
+ `sessions/` sin tool calls ni resultados (solo su cabecera `cwd` queda
464
+ hasheada en MD5); `--include-tools` los conserva
465
+ (implica prompts); `--all` equivale a ambos más `usage_window.json`. El
466
+ resumen previo indica qué se va a compartir antes de que `--emit` escriba nada.
467
+ - El artefacto por defecto contiene `README.md`, `anonymized_usage.jsonl`
468
+ (totales por fecha/sesión/modelo, conteo de `stopReason`, tasa de acierto de
469
+ caché), `turns.jsonl` (uso por turno, `stopReason`, clase de error,
470
+ `responseId`, `cf_ray`, `created` del gateway, `status` terminal, `attempt_n` y
471
+ los parámetros de la petición), `errors.jsonl` (clase, `status`, `cf_ray`,
472
+ `attempt_n`, los campos parseados `error_type`/`error_code`/`error_param`
473
+ (tanto el envoltorio HTTP en bruto como la forma `status: {objeto interno}`
474
+ que escribe pi-ai), el
475
+ mensaje del propio gateway limitado a 200 caracteres y un hash MD5; una
476
+ petición fallida no tiene response id, así que su `status`/`cf_ray`/`attempt_n`
477
+ se correlacionan por modelo y por el span del turno — con peticiones
478
+ concurrentes al mismo modelo, `http_attempts.jsonl` es el registro autoritativo
479
+ por intento), `http_attempts.jsonl` (una fila por intento más una fila `response` por
480
+ petición completada), `anomalies.jsonl` (el par de `cf-ray`) y `metadata.json`
481
+ (versiones de paquete, pi-ai y pi; procedencia del catálogo; `error_summary`;
482
+ `topic_hash`; y `attempt_summary` con conteos por status, ratios de 429 por
483
+ modelo/hora y la racha de 429 más larga). **No** lleva contenido de prompt,
484
+ respuesta ni tool.
435
485
  - El zip se escribe **solo** con `--emit`; la ejecución por defecto escribe el
436
486
  informe local e imprime un resumen.
437
487
  - `--out <ruta>` escribe el informe donde lo indiques (y, con `--emit`,
438
488
  `<ruta>.zip`); un `~/` inicial se expande a tu directorio home, así que los
439
489
  ejemplos de arriba escriben donde dicen. Un token de flag nunca se acepta
440
490
  como ruta.
441
- - El informe contiene `README.md`, `anonymized_usage.jsonl` (totales por
442
- fecha/sesión/modelo, conteo de `stopReason`, tasa de acierto de caché),
443
- `turns.jsonl` (uso por turno, `stopReason`, clase de error, `responseId`,
444
- `cf_ray`),
445
- `errors.jsonl` (una fila por turno con error: clase, fragmento de 200
446
- caracteres del mensaje, hash MD5 del mensaje completo, tokens de entrada/
447
- salida, `responseId`), `anomalies.jsonl` (par de `cf-ray`), `sessions/` (los
448
- JSONL de sesión en bruto filtrados por la ventana) y `metadata.json`
449
- (versiones de paquete, pi-ai y pi; procedencia del catálogo;
450
- `error_summary`).
451
- - Las etiquetas de sesión y worktree son MD5 truncado a 12 caracteres (incluida
452
- la cabecera `cwd` dentro de `sessions/`); `errorMessage` se reduce a
453
- `overflow | rate_limited | invalid_request | transport | other`, y
454
- `errors.jsonl` conserva como mucho 200 caracteres del mensaje en bruto más
455
- un hash MD5. Las credenciales nunca se recogen en ningún sitio; el contenido
456
- de prompt/respuesta nunca se recoge en los ficheros raíz — `sessions/` es la
457
- excepción: transcripts en bruto incluidos a petición
458
- ([#44](https://github.com/gtrabanco/pi-nan-provider/issues/44)), solo con
459
- `cwd` hasheado. Entradas idénticas producen bytes de zip idénticos.
491
+ - El `topic` va hasheado en el artefacto (`topic_hash`, MD5[:16]); el resumen de
492
+ consola es solo local. Las etiquetas de sesión y worktree son MD5 truncado a
493
+ 16 caracteres (sin salt por informe, para enlazar la misma sesión entre
494
+ informes). `errors.jsonl` nunca guarda texto de transporte ni excepciones del
495
+ lado pi, un mensaje del servidor que sobreviva tiene tu home sustituido por
496
+ `~`, y las credenciales y toda cabecera fuera de la whitelist nunca se
497
+ recogen.
498
+ - `inflight_process_at_start` y `starts_last_60s_process*` son del proceso de pi:
499
+ **no** son la concurrencia/RPM de tu clave si otros clientes la comparten.
500
+ Une el log de todos los clientes para cifras por clave.
501
+ - **No público.** El artefacto es para soporte de NaN: `cf-ray`, `response_id` y
502
+ los timestamps al milisegundo no se anonimizan a propósito, y
503
+ `anomalies.jsonl` huella el payload de la petición con SHA-256. Entradas
504
+ idénticas siguen produciendo bytes de zip idénticos.
460
505
 
461
506
  ## 🧭 Model facts: `NAN_MODEL_FACTS`
462
507
 
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # @gtrabanco/𝜋-nan-provider
2
2
 
3
3
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
4
- [![Version](https://img.shields.io/badge/version-1.6.1-blue)](https://github.com/gtrabanco/pi-nan-provider/releases)
4
+ [![Version](https://img.shields.io/badge/version-1.6.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).
@@ -18,7 +18,7 @@ Registers the `nan` provider via `pi.registerProvider()` using NaN's OpenAI-comp
18
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
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
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. |
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 — including tool-call/result ids, so a phantom call streamed with `id: ""` cannot wedge the session ([#52](https://github.com/gtrabanco/pi-nan-provider/issues/52)). |
22
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
23
  | **Truncated-stream retry** | `supportsFinishReason: true` turns an SSE stream closed before `finish_reason` into a retryable error instead of a silent stall ([#2](https://github.com/gtrabanco/pi-nan-provider/issues/2)). |
24
24
  | **Streaming token usage** | `stream_options.include_usage` is on by default, so pi reports real input/output/reasoning/cache counts ([#4](https://github.com/gtrabanco/pi-nan-provider/issues/4), [#7](https://github.com/gtrabanco/pi-nan-provider/issues/7)). |
@@ -28,7 +28,7 @@ Registers the `nan` provider via `pi.registerProvider()` using NaN's OpenAI-comp
28
28
  | **Native image models** | `flux-2-klein` and `qwen-image-2.1` registered as pi `type: "image"` models, reachable from codemode and extensions. |
29
29
  | **Native MCP media bridge** | The `nan-media` server (10 tools) registered through `pi.registerMcpServer()`, managed with `/nan-mcp`. |
30
30
  | **Credits reporting** | `/nan-usage` shows credits balance with a progress bar, per-model breakdown (input / cached / output in M, credits consumed), and billing period — all from `GET /v1/usage` ([#37](https://github.com/gtrabanco/pi-nan-provider/issues/37)). |
31
- | **Cache-anomaly evidence** | `cf-ray` capture on the repeated `id` + `created` gateway signature ([#17](https://github.com/gtrabanco/pi-nan-provider/issues/17)) plus the deterministic `/nan-debug` collector ([#35](https://github.com/gtrabanco/pi-nan-provider/issues/35)) with per-error evidence, every response's `cf-ray` joined into `turns.jsonl` (S11), and flexible `--interval` windows ([#44](https://github.com/gtrabanco/pi-nan-provider/issues/44)). |
31
+ | **Cache-anomaly evidence** | `cf-ray` capture on the repeated `id` + `created` gateway signature ([#17](https://github.com/gtrabanco/pi-nan-provider/issues/17)) plus the deterministic `/nan-debug` collector ([#35](https://github.com/gtrabanco/pi-nan-provider/issues/35)) with per-error evidence, every response's `cf-ray` joined into `turns.jsonl` (S11), flexible `--interval` windows ([#44](https://github.com/gtrabanco/pi-nan-provider/issues/44)) and the HTTP attempt tap ([#49](https://github.com/gtrabanco/pi-nan-provider/issues/49)): status, whitelisted headers, invisible retries (`attempt_n`), process-scoped concurrency/RPM and `payload_bytes` — the zip carries no prompt or tool content unless you opt in. |
32
32
  | **pi integration** | Model refresh driven by pi's Models runtime, per-model `models.json` overrides, and the extension changelog (`pi.changelogPath`) that pi shows after an update. |
33
33
 
34
34
  Commands:
@@ -37,7 +37,7 @@ Commands:
37
37
  | :--- | :--- |
38
38
  | `/nan-mcp` | Manage the media MCP bridge (`status` / `enable` / `disable`) |
39
39
  | `/nan-usage [1-90]` | Credits balance with usage bar, per-model breakdown (in / cached / out in M · credits cr), and all-time totals |
40
- | `/nan-debug [topic] [--window N] [--interval FLEX] [--out path] [--emit]` | Redacted, reproducible evidence package for NaN |
40
+ | `/nan-debug [topic] [--window N] [--interval FLEX] [--out path] [--emit] [--include-prompts] [--include-tools] [--all]` | Redacted, reproducible evidence package for NaN; content is opt-in |
41
41
 
42
42
  ---
43
43
 
@@ -83,6 +83,7 @@ The registration is synchronous on purpose: the generated fallback catalog is av
83
83
  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:
84
84
 
85
85
  - 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`);
86
+ - every announced function-type tool call carries a non-empty `id` and a non-empty `function.name` — a call whose `type` is not `function` (a grammar tool) is left untouched — and every `tool` message's `tool_call_id` names the call it answers: a phantom call streamed with `id: ""` is repaired positionally instead of wedging the session on NaN's opaque 400 ([#52](https://github.com/gtrabanco/pi-nan-provider/issues/52)). Fallback ids come from the message position, so a replayed history keeps the gateway's prefix cache warm, and a real id is never rewritten;
86
87
  - `reasoning_details` is stripped, and unknown content parts (e.g. `thinking`) are folded into a `text` part so reasoning is not silently lost;
87
88
  - 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;
88
89
  - `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-max` is the only catalog model that opts out after the [#36](https://github.com/gtrabanco/pi-nan-provider/issues/36) revert).
@@ -99,7 +100,7 @@ The header **follows pi's telemetry setting**: with `enableInstallTelemetry: fal
99
100
 
100
101
  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.
101
102
 
102
- 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.
103
+ 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. The two rescue paths stay separate: a payload defect that would provoke the 400 — like the empty tool-call ids of [#52](https://github.com/gtrabanco/pi-nan-provider/issues/52) — is repaired before the request leaves pi (see the sanitizer above), while the size recheck only judges how large the request is.
103
104
 
104
105
  ### ⏱️ Intermittent truncated streams (auto-retry, no silent stall)
105
106
 
@@ -407,21 +408,43 @@ Independently of any anomaly, every response's `cf-ray` is kept in
407
408
  report joins it into `turns.jsonl` as `cf_ray`, so support gets the rays of
408
409
  any pair of calls without waiting for a recurrence.
409
410
 
410
- `/nan-debug` turns that file plus your session transcripts into a redacted,
411
+ Every HTTP **attempt** — including the retries pi-ai hides and the 429s that never
412
+ produce a gateway id — is kept in `<agentDir>/nan-http-attempts.jsonl`
413
+ (issue [#49](https://github.com/gtrabanco/pi-nan-provider/issues/49)): status,
414
+ the whitelisted response headers (`cf-ray`, `x-request-id`, `Retry-After`,
415
+ `x-should-retry`, `rate-limit-*`), millisecond start/end plus `latency_ms`,
416
+ `attempt_n`, `payload_bytes`, the request parameters (`reasoning_effort`,
417
+ `max_tokens`, the field actually sent, `stream`), the gateway
418
+ `error_type`/`error_code` of a non-2xx body and the process-scoped inflight/60 s
419
+ counters. `time_to_header_ms` is start → headers (the early-rejection signal,
420
+ e.g. the 237 ms median); the full request duration, token `usage` and raw
421
+ `finish_reason` ride the per-request `response` row. The report embeds the
422
+ window-filtered rows as `http_attempts.jsonl`, so one zip answers *which attempt
423
+ failed, with which status and headers, after how many retries*.
424
+
425
+ `/nan-debug` turns those files plus your session transcripts into a redacted,
411
426
  reproducible evidence package for NaN:
412
427
 
413
428
  ```text
414
- /nan-debug # last 7 days, writes <agentDir>/nan-debug-report/
429
+ /nan-debug # last 7 days; writes <agentDir>/nan-debug-report-<emission timestamp>/
415
430
  /nan-debug cache --window 2 # topic label + a 2-day window
416
- /nan-debug --window 2 --emit # also writes <agentDir>/nan-debug-report.zip
431
+ /nan-debug --window 2 --emit # also writes <agentDir>/nan-debug-report-<emission timestamp>.zip
432
+ /nan-debug cache --include-prompts --emit # embed raw transcripts (tool calls stripped)
433
+ /nan-debug --all --emit # transcripts + tool calls + usage_window.json (the pre-#49 dump)
417
434
  /nan-debug cache --out ~/evidence --emit
418
435
  /nan-debug --interval 5min # relative spans: 5min, 2h, 3d, 1mes
419
436
  /nan-debug --interval "2026-11-10 - 2026-11-11 17:30" # ranges, open ends, single points too
420
437
  ```
421
438
 
439
+ - The default directory and zip names carry the **emission** timestamp in UTC
440
+ (`nan-debug-report-YYYY-MM-DDTHH:mm:ss`; the zip uses `-` instead of `:` so the
441
+ name is portable), so consecutive runs never overwrite each other. The
442
+ reported window lives in `metadata.window`. An explicit `--out` is respected
443
+ verbatim.
422
444
  - `--window N` (1–90 days) also fetches `GET /v1/usage` for the same period with
423
445
  your stored key and writes `usage_window.json`; without the flag nothing is
424
- fetched. That live call counts against your quota's request rate.
446
+ fetched. That live call counts against your quota's request rate. The usage
447
+ window stays out of the zip unless `--all`: it identifies your account/tier.
425
448
  - `--interval <desc>` replaces `--window` (using both is an error) and accepts
426
449
  relative spans (`5min`, `2h`, `3d`, `1mes`), date/time ranges
427
450
  (`2026-11-10 - 2026-11-11 17:30`, `10:30 - 11:00`, cross-midnight
@@ -429,27 +452,45 @@ reproducible evidence package for NaN:
429
452
  (`2026-11 - 2026-12`) and single points (`2026-11-10`,
430
453
  `2026-11-10T10:00:00Z`). The span is capped at 90 days and parsing is fully
431
454
  deterministic — no LLM calls. The topic, when you use one, goes before the flag.
455
+ - Content is opt-in and **off by default**: `--include-prompts` embeds the
456
+ window-filtered transcripts under `sessions/` with tool calls and results
457
+ stripped (their `cwd` header stays MD5-hashed); `--include-tools` keeps them (it implies prompts); `--all` equals
458
+ both plus `usage_window.json`. The preview states what will be shared before
459
+ `--emit` writes anything.
460
+ - The default artifact contains `README.md`, `anonymized_usage.jsonl` (per
461
+ date/session/model totals, stop-reason counts, cache-hit rate), `turns.jsonl`
462
+ (per-turn usage, stop reason, error class, response id, `cf_ray`, gateway
463
+ `created`, terminal `status`, `attempt_n` and the request parameters),
464
+ `errors.jsonl` (class, `status`, `cf_ray`, `attempt_n`, the parsed
465
+ `error_type`/`error_code`/`error_param` (both the raw HTTP envelope and the
466
+ `status: {inner object}` shape pi-ai writes), the gateway's own message capped at
467
+ 200 chars and an MD5 hash; a failed request has no response id, so its
468
+ `status`/`cf_ray`/`attempt_n` are correlated by model and the turn's span —
469
+ with concurrent requests to the same model, `http_attempts.jsonl` is the
470
+ authoritative per-attempt record), `http_attempts.jsonl` (one row per attempt plus one
471
+ `response` row per completed request), `anomalies.jsonl` (the `cf-ray` pair) and
472
+ `metadata.json` (package/pi-ai/pi versions, catalog provenance,
473
+ `error_summary`, `topic_hash`, and `attempt_summary` with status counts, 429
474
+ ratios per model/hour and the longest 429 streak). It carries **no** prompt,
475
+ response or tool content.
432
476
  - The zip is written **only** with `--emit`; the default run writes the local
433
- report and prints a preview.
477
+ report and prints the preview.
434
478
  - `--out <path>` writes the report anywhere you name it (and, with `--emit`,
435
479
  `<path>.zip`); a leading `~/` expands to your home directory, so the examples
436
480
  above write where they say. A flag token is never accepted as the path.
437
- - The report contains `README.md`, `anonymized_usage.jsonl` (per date/session/
438
- model totals, stop-reason counts, cache-hit rate), `turns.jsonl` (per-turn
439
- usage, stop reason, error class, response id, `cf_ray`), `errors.jsonl` (one row per
440
- errored turn: class, 200-char message fragment, MD5 hash of the full message,
441
- input/output tokens, response id), `anomalies.jsonl` (`cf-ray` pair),
442
- `sessions/` (the raw session JSONL files filtered to the window) and
443
- `metadata.json` (package/pi-ai/pi versions, catalog provenance,
444
- `error_summary`).
445
- - Session and worktree labels are MD5-truncated to 12 chars (including the
446
- `cwd` header inside `sessions/`); `errorMessage` is reduced to `overflow |
447
- rate_limited | invalid_request | transport | other`, and `errors.jsonl` keeps
448
- at most 200 characters of the raw message plus an MD5 hash. Credentials are
449
- never collected anywhere; prompt/response content is never collected in the
450
- root files — `sessions/` is the exception, raw transcripts included on
451
- request ([#44](https://github.com/gtrabanco/pi-nan-provider/issues/44)), with
452
- only `cwd` hashed. Identical inputs produce byte-identical zip bytes.
481
+ - A `topic` is hashed in the artifact (`topic_hash`, MD5[:16]); the console
482
+ preview is local only. Session and worktree labels are MD5 truncated to 16
483
+ characters (no per-report salt, so the same session links across reports).
484
+ `errors.jsonl` never stores transport or pi-side exception text, a surviving
485
+ server message has your home directory scrubbed to `~`, and credentials plus
486
+ every non-whitelisted header are never collected.
487
+ - `inflight_process_at_start` and `starts_last_60s_process*` are scoped to this
488
+ pi process: they are **not** your key's concurrency/RPM when other clients
489
+ share the key. Merge every client's log for key-wide numbers.
490
+ - **Not public.** The artifact is for NaN support: `cf-ray`, `response_id` and
491
+ millisecond timestamps are deliberately not anonymized, and `anomalies.jsonl`
492
+ fingerprints the request payload with SHA-256. Identical inputs still produce
493
+ byte-identical zip bytes.
453
494
 
454
495
  ## 🧭 Model facts: `NAN_MODEL_FACTS`
455
496
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gtrabanco/pi-nan-provider",
3
- "version": "1.6.1",
3
+ "version": "1.6.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-23T00:46:05.244Z
4
+ // Source: https://models.dev/api.json (provider "nan"), fetched 2026-11-27T00:10:03.719Z
5
5
  // Provenance: every contextWindow/maxTokens/input/cost value traces to
6
6
  // models.dev or to the per-entry notes below. Nothing is invented; entries
7
7
  // models.dev documents incompletely are omitted and flagged instead.
@@ -506,10 +506,10 @@ export const NAN_GENERATED_MODELS: readonly GeneratedModelEntry[] = [
506
506
  "text"
507
507
  ]
508
508
  },
509
- "open_weights": false,
509
+ "open_weights": true,
510
510
  "limit": {
511
511
  "context": 1048576,
512
- "input": 983010,
512
+ "input": 983040,
513
513
  "output": 65536
514
514
  },
515
515
  "cost": {
@@ -1027,7 +1027,7 @@ export const NAN_GENERATED_MODELS: readonly GeneratedModelEntry[] = [
1027
1027
  export const GENERATED_CATALOG_META = {
1028
1028
  source: "https://models.dev/api.json",
1029
1029
  modelsDevProvider: "nan",
1030
- fetchedAt: "2026-11-23T00:46:05.244Z",
1030
+ fetchedAt: "2026-11-27T00:10:03.719Z",
1031
1031
  modelCount: 13,
1032
1032
  models: ["deepseek-v4-flash","deepseek-v4-pro","gemma4","glm5.3","glm5.3-flash","hy4","hy4-flash","kimi-k3.1-pro","mimo-v2.6-flash","qwen3.6","qwen3.8-flash","qwen3.8-max","qwen4-max"],
1033
1033
  notes: [
@@ -15,9 +15,9 @@ import { getAgentDir } from "@earendil-works/pi-coding-agent";
15
15
  import { NAN_API_KEY_ENV, resolveStoredNanApiKey, tryResolveNanApiKeyViaRegistry } from "./mcp/api-key.ts";
16
16
  import {
17
17
  DEBUG_USAGE_LINE,
18
- NAN_DEBUG_REPORT_DIR,
19
- NAN_DEBUG_ZIP,
20
18
  buildDebugReport,
19
+ debugReportDirName,
20
+ debugReportZipName,
21
21
  fetchDebugUsageWindow,
22
22
  parseDebugArgs,
23
23
  renderDebugReport,
@@ -91,7 +91,10 @@ export function registerNanDebugCommand(pi: ExtensionAPI, deps: NanDebugCommandD
91
91
  fetchUsage: parsed.args.windowProvided ? (deps.fetchUsage ?? fetchDebugUsageWindow) : undefined,
92
92
  sessionsDir,
93
93
  });
94
- rendered = renderDebugReport(report, sessionsDir);
94
+ rendered = renderDebugReport(report, sessionsDir, {
95
+ includePrompts: parsed.args.includePrompts,
96
+ includeTools: parsed.args.includeTools,
97
+ });
95
98
  } catch (error) {
96
99
  ctx.ui.notify(
97
100
  `nan-debug failed to collect the report: ${error instanceof Error ? error.message : String(error)}`,
@@ -102,14 +105,16 @@ export function registerNanDebugCommand(pi: ExtensionAPI, deps: NanDebugCommandD
102
105
 
103
106
  const explicitZipTarget = parsed.args.out ? expandHomePath(parsed.args.out, deps.homedir ?? osHomedir()) : undefined;
104
107
  const explicitZip = explicitZipTarget?.endsWith(".zip") ? explicitZipTarget : undefined;
108
+ // Default names carry the emission timestamp (UTC) so consecutive runs
109
+ // never overwrite each other; an explicit `--out` is respected verbatim.
105
110
  const outDir = explicitZip
106
111
  ? explicitZip.replace(/\.zip$/, "")
107
- : (explicitZipTarget ?? join(agentDir, NAN_DEBUG_REPORT_DIR));
108
- const zipPath = explicitZip ?? (explicitZipTarget ? `${explicitZipTarget}.zip` : join(agentDir, NAN_DEBUG_ZIP));
112
+ : (explicitZipTarget ?? join(agentDir, debugReportDirName(now)));
113
+ const zipPath = explicitZip ?? (explicitZipTarget ? `${explicitZipTarget}.zip` : join(agentDir, debugReportZipName(now)));
109
114
 
110
115
  try {
111
116
  writeDebugReport(rendered.files, outDir);
112
- if (parsed.args.emit) writeDebugZip(rendered.files, zipPath);
117
+ if (parsed.args.emit) writeDebugZip(rendered.files, zipPath, { includeUsageWindow: parsed.args.all });
113
118
  } catch (error) {
114
119
  ctx.ui.notify(
115
120
  `nan-debug wrote nothing: ${error instanceof Error ? error.message : String(error)}`,