@gtrabanco/pi-nan-provider 1.6.4 → 1.8.0

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
@@ -463,8 +463,133 @@ Since 1.0.0 the package version **aligns its MAJOR.MINOR with the pi release lin
463
463
  `src/reasoning-only-stream-guard.ts` (issue #21) keys on that marker;
464
464
  earlier comment/message text said "60,000 characters" and was corrected to
465
465
  the documented figures.
466
- - **pi 1.6.0 / pi-ai 1.6.0 compat** (verified 2026-11-21, the current verified
467
- baseline; devDependencies 1.5.1 → 1.6.0, package 1.5.8 → 1.6.0, peer range
466
+ - **pi 1.8.0 / pi-ai 1.8.0 compat** (verified 2026-12-03, the current verified
467
+ baseline; devDependencies 1.7.0 → 1.8.0, package 1.7.2 → 1.8.0, peer range
468
+ unchanged at `^1.4.0` because nothing here needs 1.8.0). **No `src/` change,
469
+ no `scripts/` change:** every symbol `src/` imports still exists, and a
470
+ tarball diff (`npm pack`, 1.7.0 vs 1.8.0) shows `dist/compat.js`,
471
+ `dist/index.js`, `dist/models.js`, `dist/api/simple-options.js` and
472
+ `dist/utils/transcript.js` byte-identical, while pi-ai's `compat.d.ts`,
473
+ `api/openai-completions.d.ts` and `index.d.ts` are byte-identical too. What
474
+ DID move, and why it does or does not touch this package:
475
+ - `dist/api/openai-completions.js` changes 7 lines: streamed
476
+ `reasoning_details` deltas now go through `parseOpenAIReasoningDetail`
477
+ (signature-only `reasoning.text` becomes `text: ""`) and merge only when
478
+ the `index` matches — OpenRouter/Bifrost shaping. NaN replays
479
+ `reasoning_content`, untouched.
480
+ - `RETRYABLE_PROVIDER_ERROR_PATTERN` gains `upstream.?sse.?stream.?failed`
481
+ (#12605, "upstream_error: upstream SSE stream failed"),
482
+ `^throttling error:` (Bedrock's `ThrottlingException` prefix, anchored and
483
+ case-insensitive) and `provider stopped with: malformed_response` (#12622,
484
+ Gemini). The first is **directly relevant**: NaN's LiteLLM gateway closes
485
+ SSE streams mid-turn (issue #2), so that drop is now retried with no
486
+ package change; the NaN-facing pins live in
487
+ `test/pi-ai-1-8-0-contract.test.ts`. The deterministic NaN 400 stays
488
+ non-retryable and the truncated-stream error stays retryable.
489
+ - `utils/overflow.js` gains one pattern, `/decoded body exceeds \d+ bytes/i`
490
+ (OpenCode Go byte-size limit). It does not capture a NaN message, so the
491
+ #3/#18 classifiers are untouched and still needed.
492
+ - `dist/types.d.ts` adds `KnownImageApi "openrouter-chat-images"` (the old
493
+ `openrouter-images` stays) and `sessionId?` on
494
+ `ProviderRequestOptions`/`ImagesOptions`; `pi-coding-agent`'s
495
+ `dist/index.d.ts` only ADDS `UsageRecord`, `SHELL_COMMAND_ENV_VAR` and
496
+ `ShellConfig`. Both are additive for `nan-images` and the extension API.
497
+ - **MCP config types are re-derived from the published `mcp.json` schema**
498
+ (`core/mcp-servers.d.ts` → `mcp-config-schema.ts`: `MCP_EXPOSURES` gains
499
+ `deferred`/`hidden`, `MCP_EXPOSURE_ALIASES` added). `description`,
500
+ `timeout` and `exposure` are unchanged, so `pi.registerMcpServer("nan-media", …)`
501
+ compiles and registers as before; `core/model-runtime.d.ts` and
502
+ `core/sdk.d.ts` are identical.
503
+ - **`supportsMidConvoSystemMessages` is NOT new in 1.8.0** — the compat key,
504
+ `resolveTranscript(context, getCompat(model).supportsMidConvoSystemMessages)`
505
+ (`api/openai-completions.js:80`) and `collapseSystemMessages` exist on
506
+ 1.7.0 too. 1.8.0 only moves the value inside its own
507
+ `providers/data/deepseek.json` (`chat:deepseek-v4-pro` true → absent,
508
+ `chat:deepseek-flash` absent → true). NaN models declare no such compat
509
+ key, so the default stays *collapse every system message into the head*,
510
+ and issue #56 §4 (adopting the flag) remains gated on a live gateway
511
+ measurement the maintainer must approve; the mechanism is pinned offline in
512
+ `test/pi-ai-1-8-0-contract.test.ts` (flag absent → one leading system
513
+ message carrying the later text; flag set → the later message stays in
514
+ place).
515
+ - `mcp.json` `$schema`: pi 1.8.0 prescribes
516
+ `"$schema": "https://pi.dev/schemas/mcp.schema.json"` and ships
517
+ `schemas/mcp.schema.json` with that `$id`, but the URL answered **404** on
518
+ 2026-12-03 while `schemas/theme.schema.json` and
519
+ `schemas/settings.schema.json` answered 200 — a pi.dev publish gap, not a
520
+ wrong id. Both READMEs document the line as pi does.
521
+ Regression test: `test/pi-ai-1-8-0-contract.test.ts`. Issue #56.
522
+ - **pi 1.7.0 / pi-ai 1.7.0 compat** (verified 2026-11-28, the baseline before
523
+ 1.8.0; devDependencies 1.6.0 → 1.7.0, package 1.6.4 → 1.7.0, peer range
524
+ unchanged at `^1.4.0` because only the image options are new and they are
525
+ read defensively). pi-ai `index.d.ts` only ADDS `PiImage*`/`PiDecision*` type
526
+ re-exports, `compat.d.ts` and `api/openai-completions.d.ts` are byte-identical
527
+ to 1.6.0, and every symbol this package imports still exists
528
+ (`getAgentDir`, `readStoredCredential`, `ProviderConfig`, both
529
+ `registerProvider` overloads, `registerMcpServer`/`unregisterMcpServer`;
530
+ MCP config types unchanged). What DID move:
531
+ - **Telemetry removed** (`/api/report-install`, `Settings.enableInstallTelemetry`,
532
+ `SettingsManager.get/setEnableInstallTelemetry()`, `PI_TELEMETRY`), and
533
+ `getClientIdentity(settingsManager)` became `getClientIdentity()` which always
534
+ sends `PI_ATTRIBUTION`. The attribution gate therefore no longer reads the
535
+ removed setting on 1.7: `src/attribution.ts` owns
536
+ `NAN_NO_ATTRIBUTION` (any of `1`/`true`/`yes`/`on` disables the header) and
537
+ still honors `enableInstallTelemetry: false` on pi 1.4–1.6 hosts
538
+ (`resolveProviderAttributionEnabled`). Without that change the old gate
539
+ silently became a permanent "enabled" on 1.7, re-identifying users who had
540
+ opted out.
541
+ - **`ImagesOptions` gained `aspectRatio` and `size`** (1.6.0 had neither), and
542
+ codemode 1.7 accepts `models.generateImages(model, ctx, { aspectRatio, size })`
543
+ — it validates that exact key set (so `n`/`seed`/`guidance` remain
544
+ extension-only) and forwards `{ ...options, signal }` into
545
+ `ProviderImages.generateImages`. NaN accepts only a `WxH` canvas (sides
546
+ divisible by 16, 256–1536, ratio 1:3–3:1; `auto` allowed), so
547
+ `src/images.ts` resolves `options.size` (validated) and
548
+ `NAN_ASPECT_RATIO_SIZES` (1:1, 16:9, 9:16, 4:3, 3:4, 3:2, 2:3) before falling
549
+ back to `metadata.size`; an unusable value fails locally instead of spending
550
+ one of the 100 monthly image requests on a guaranteed 400. "Divisible by 16"
551
+ is a grid, not a multiple test (package 1.7.1): `1024x1008` = 63 × 16 is a
552
+ valid canvas, so the check is `side % 16 === 0` and the range check is
553
+ separate — the pre-1.7.1 `side % 16 !== 0` only admitted multiples of 1024.
554
+ The maxTokens budget is an entry-point fact on pi-ai 1.7's
555
+ openai-completions path: the bare `stream()` feeds `options` straight into
556
+ `buildParams`, so an explicit `options.maxTokens` is sent verbatim and an
557
+ absent one sends no budget field at all, while `streamSimple()` — the
558
+ entry real sessions reach through `ModelRuntime.streamSimple` — runs
559
+ `buildBaseOptions`, whose budget is
560
+ `clampMaxTokensToContext(model, context, options?.maxTokens ??
561
+ model.maxTokens)`: the ceiling is always on the wire there, clamped to the
562
+ room left (pi-ai `api/simple-options.js:31-56`,
563
+ `api/openai-completions.js:457-462`). pi's agent loop sets no `maxTokens`
564
+ of its own, so what gets clamped is the catalog ceiling. Both entries are
565
+ pinned by `test/pi-ai-1-7-0-contract.test.ts` (the entry-point pin added
566
+ in 1.7.2: the earlier record denied the `buildBaseOptions` run the
567
+ `streamSimple` entry makes).
568
+ - **`onResponse` fires once per attempt, error responses included**
569
+ (`onErrorResponse` in `utils/provider-retry.js`, wired by
570
+ `api/openai-completions.js`); 1.6.0 called it only after the retry loop.
571
+ `src/cache-anomaly.ts` already overwrote `cf-ray` on every callback, so the
572
+ last (real) response owns it — pinned by `test/issue-35-cache-anomaly-capture.test.ts`.
573
+ The #49 tap stays necessary: the hook has no per-attempt start time, attempt
574
+ number or payload size.
575
+ - Reasoning replay metadata is now encoded in `thinkingSignature`
576
+ (`encodeThinkingSignature`: field/details/opaque) and decoding is backward
577
+ compatible — a 1.6.0 session's plain field name decodes to `kind: "field"`
578
+ and NaN keeps replaying `reasoning_content`, so nothing changed on the wire.
579
+ - Looked relevant, is not: `cost.imageOutput`/`Usage.imageOutput` (catalog cost
580
+ is pinned to 0, NaN bills credits), the new canonical `pi-image` API
581
+ (`POST <baseUrl>/image`; NaN has no such endpoint — `nan-images` stays),
582
+ `compat.supportsReasoningReplay` (read only by
583
+ `api/bedrock-converse-stream.js`), `--agent-dir` (the artifacts call
584
+ `getAgentDir()` per record, no module-load cache), and `models.js` merging the
585
+ dynamic store once per publish (`getModels()` hot path, #12311) — a dynamic
586
+ entry still REPLACES the baseline by id+type, so the #19 read-time overlay is
587
+ still required.
588
+ Regression tests: `test/pi-ai-1-7-0-contract.test.ts` (per-attempt
589
+ `onResponse`, legacy `thinkingSignature` replay), plus the image and
590
+ attribution groups. Issue #54.
591
+ - **pi 1.6.0 / pi-ai 1.6.0 compat** (verified 2026-11-21; devDependencies
592
+ 1.5.1 → 1.6.0, package 1.5.8 → 1.6.0, peer range
468
593
  unchanged at `^1.4.0` because nothing here needs 1.6.0). **No `src/` change:** pi-ai
469
594
  `dist/index.d.ts`, `dist/compat.d.ts`, `dist/api/openai-completions.d.ts` and
470
595
  pi-coding-agent `dist/index.d.ts` are byte-identical to 1.5.1, and a base-vs-change
@@ -525,10 +650,12 @@ Since 1.0.0 the package version **aligns its MAJOR.MINOR with the pi release lin
525
650
  merges `model.headers` over identity headers on 0.99.1 and 1.4.0 alike),
526
651
  covering baseline, live merge, placeholders, overlay, image models and the
527
652
  `/nan-usage` fetch; omitted silently when the version is unreadable, and
528
- GATED on pi's `enableInstallTelemetry` setting (privacy: the header
529
- identifies the package; gate evaluated live on every read, installed by the
530
- extension entrypoint via `configureProviderAttribution`, stripped on read
531
- paths by the overlay wrappers when disabled).
653
+ GATED on `NAN_NO_ATTRIBUTION` plus pi's legacy `enableInstallTelemetry`
654
+ setting (privacy: the header identifies the package; gate evaluated live on
655
+ every read, installed by the extension entrypoint via
656
+ `configureProviderAttribution`, stripped on read paths by the overlay wrappers
657
+ when disabled). See the 1.7.0 bullet for why the setting alone stopped being
658
+ enough.
532
659
  - **pi 1.3.0 / pi-ai 1.3.0 compat** (verified 2026-10-15): devDependencies bumped 1.2.0 → 1.3.0; the peer range stays
533
660
  `">=0.99.0 <2"`. The pi-ai 1.3.0 `compat.d.ts` and `api/openai-completions.d.ts`
534
661
  surfaces are byte-identical to 1.2.0; `index.d.ts` only drops the
@@ -643,13 +770,16 @@ Since 1.0.0 the package version **aligns its MAJOR.MINOR with the pi release lin
643
770
  reports); `errorMessage` maps to
644
771
  `overflow|rate_limited|invalid_request|transport|other`.
645
772
 
646
- - **HTTP attempt tap (issue #49, verified 2026-11-24 on pi-ai 1.6.0):**
773
+ - **HTTP attempt tap (issue #49, verified 2026-11-24 on pi-ai 1.6.0; hook
774
+ contract widened in 1.7.0):**
647
775
  `CreateProviderOptions` has **no** `fetch` field — issue #49's claim that
648
776
  "`createProvider` acepta el `fetch` en options" is wrong for the pinned
649
777
  version. `fetch` is a `StreamOptions` field forwarded to the OpenAI client
650
778
  (`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.
779
+ retries by re-invoking the same client with `maxRetries: 0`; on 1.6.0
780
+ `onResponse` fired only **after** that loop, so a rejected attempt never
781
+ reached it (1.7.0 reports failed attempts too, but still without per-attempt
782
+ timing, attempt number or payload size).
653
783
  `src/http-attempts.ts` therefore wraps the provider api outermost
654
784
  (`withHttpAttemptCapture`) and injects `StreamOptions.fetch` — the only tap
655
785
  that sees every attempt, including a 429 that never produced a gateway `id`.
@@ -708,7 +838,7 @@ uno cite una versión o requisito que el otro no lleve.
708
838
  5. **Cita el peer floor real, no la historia.** El peer range se actualiza con cada
709
839
  release de pi: lee `package.json` peerDependencies, no AGENTS.md (que documenta
710
840
  releases históricos y puede quedar obsoleto). Para este paquete: el floor es
711
- `^1.4.0` (desde package 1.5.0), verificado contra pi 1.6.0 / pi-ai 1.6.0.
841
+ `^1.4.0` (desde package 1.5.0), verificado contra pi 1.8.0 / pi-ai 1.8.0.
712
842
  6. **Las cifras de catálogo van contra `scripts/models.generated.ts`, no contra AGENTS.md.**
713
843
  AGENTS.md es documentación de releases y puede contener floor o ranges ya antiguos;
714
844
  el catálogo generado es la fuente viva de `contextWindow`/`maxTokens`/`reasoningEffortValues`
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.4-blue)](https://github.com/gtrabanco/pi-nan-provider/releases)
4
+ [![Version](https://img.shields.io/badge/version-1.8.1-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).
@@ -9,7 +9,7 @@
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
11
  > [!NOTE]
12
- > **Requisitos:** pi **≥ 1.4.0** (rango peer `^1.4.0`). El paquete está verificado contra **pi 1.6.0 / pi-ai 1.6.0**; el floor del rango peer solo sube con los re-aligns de menor de pi.
12
+ > **Requisitos:** pi **≥ 1.4.0** (rango peer `^1.4.0`). El paquete está verificado contra **pi 1.8.0 / pi-ai 1.8.0**; el floor del rango peer solo sube con los re-aligns de menor de pi.
13
13
 
14
14
  ## ✨ Funciones
15
15
 
@@ -24,8 +24,8 @@ Registra el proveedor `nan` vía `pi.registerProvider()` usando la API OpenAI-co
24
24
  | **Uso de tokens en streaming** | `stream_options.include_usage` activo por defecto, así que pi reporta recuentos reales de entrada/salida/razonamiento/caché ([#4](https://github.com/gtrabanco/pi-nan-provider/issues/4), [#7](https://github.com/gtrabanco/pi-nan-provider/issues/7)). |
25
25
  | **Controles de razonamiento** | `reasoningEffortValues` + `thinkingLevelMap` por modelo ([#16](https://github.com/gtrabanco/pi-nan-provider/issues/16)), el guard de stream solo-razonamiento ([#21](https://github.com/gtrabanco/pi-nan-provider/issues/21)) y el campo de tokens máximo por modelo (`qwen3.8-max` mantiene `max_completion_tokens`; `qwen3.8-flash` volvió a `max_tokens` tras el arreglo del gateway de NaN, [#34](https://github.com/gtrabanco/pi-nan-provider/issues/34) → [#36](https://github.com/gtrabanco/pi-nan-provider/issues/36)). |
26
26
  | **Export de model facts** | `NAN_MODEL_FACTS` — una entrada congelada y tipada por modelo de chat facturado: límites, tarifas, contrato de razonamiento, protocolo de herramientas, semántica de `max_tokens`, presupuesto de pensamiento, modo de caché y clase de facturación, con un id de procedencia en cada celda ([#47](https://github.com/gtrabanco/pi-nan-provider/issues/47)). |
27
- | **Cabecera de atribución** | `X-Pi-Provider: gtrabanco/pi-nan-provider@<version>` en cada petición, eliminada cuando la telemetría de instalación de pi está desactivada. |
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. |
27
+ | **Cabecera de atribución** | `X-Pi-Provider: gtrabanco/pi-nan-provider@<version>` en cada petición, eliminada con `NAN_NO_ATTRIBUTION` (y con el opt-out de telemetría de instalación de pi ≤ 1.6). |
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, con las opciones canónicas `{ size, aspectRatio }` de pi 1.7. |
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
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. |
@@ -94,7 +94,7 @@ Un hook `onPayload` suministrado por el llamante se conserva y se encadena despu
94
94
 
95
95
  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.
96
96
 
97
- La cabecera **sigue la opción de telemetría de pi**: con `enableInstallTelemetry: false` en `settings.json` la cabecera desaparece de todas las peticiones (se evalúa en vivo, así que cambiar la opción aplica en la siguiente petición sin reiniciar) — la cabecera identifica el paquete en uso, y quien haya desactivado la telemetría no debería ser identificable por ella.
97
+ La cabecera **se puede desactivar**: `NAN_NO_ATTRIBUTION=1` (`true`, `yes` u `on` también valen) la elimina de todas las peticiones, y en pi ≤ 1.6 `enableInstallTelemetry: false` sigue haciendo lo mismo. pi 1.7 eliminó la telemetría por completo — la opción, `PI_TELEMETRY` y el informe de instalación ya no existen, y pi envía su propia atribución siempre — así que ahí el interruptor es la variable de entorno. La puerta se evalúa en vivo, así que cambiarla aplica en la siguiente petición sin reiniciar.
98
98
 
99
99
  ### 🧠 Seguridad al cambiar de modelo
100
100
 
@@ -171,6 +171,7 @@ El puente de media está **activado por defecto** (por sesión, visible en `/mcp
171
171
  >
172
172
  > ```json
173
173
  > {
174
+ > "$schema": "https://pi.dev/schemas/mcp.schema.json",
174
175
  > "mcpServers": {
175
176
  > "fetch": { "command": "uvx", "args": ["mcp-server-fetch"] },
176
177
  > "web-search": {
@@ -182,6 +183,8 @@ El puente de media está **activado por defecto** (por sesión, visible en `/mcp
182
183
  > }
183
184
  > ```
184
185
  >
186
+ > La línea `"$schema"` (pi ≥ 1.8.0) da validación y autocompletado del fichero en el editor.
187
+ >
185
188
  > Vuelve a comprobar `https://api.nan.builders/mcp` periódicamente: si NaN publica herramientas otra
186
189
  > vez, este paquete puede restaurar el puente.
187
190
 
@@ -236,6 +239,16 @@ conector con `pi config` → Built-in extensions → `mcp`.
236
239
  for (const block of result.output) if (block.type === "image") image(block)
237
240
  ```
238
241
 
242
+ En pi 1.7+ el tercer argumento acepta las opciones neutrales del proveedor: `{ size: "1536x1024" }`
243
+ para un lienzo concreto o `{ aspectRatio: "16:9" }` para uno de `1:1`, `16:9`, `9:16`, `4:3`,
244
+ `3:4`, `3:2`, `2:3`. NaN solo acepta `WIDTHxHEIGHT` con cada lado en la rejilla de 16
245
+ píxeles (múltiplo de 16, así que `1024x1008` vale — 1008 = 63 × 16) y entre 256 y 1536
246
+ (ratio 1:3–3:1, `auto` permitido), así que `size` se valida y `aspectRatio` se resuelve
247
+ al mayor lienzo exacto; cualquier valor inutilizable falla localmente indicando la regla
248
+ incumplida en vez de gastar una de las peticiones mensuales de imagen en un `400` garantizado.
249
+ `size` gana a `aspectRatio`, y `metadata.size` (además de `n`, `seed` y `guidance`, que codemode
250
+ no expone) sigue funcionando desde código de extensión.
251
+
239
252
  Ambos modelos necesitan el tier de membresía "inference" (403 de lo contrario); los endpoints
240
253
  de imagen tienen su propio límite de tasa separado del chat (20 peticiones/min, 100
241
254
  peticiones/mes compartido entre los dos modelos) y no consumen el presupuesto de tokens del
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.4-blue)](https://github.com/gtrabanco/pi-nan-provider/releases)
4
+ [![Version](https://img.shields.io/badge/version-1.8.1-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).
@@ -9,7 +9,7 @@
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
11
  > [!NOTE]
12
- > **Requirements:** pi **≥ 1.4.0** (peer range `^1.4.0`). The package is verified against **pi 1.6.0 / pi-ai 1.6.0**; the peer floor only rises on pi minor realigns.
12
+ > **Requirements:** pi **≥ 1.4.0** (peer range `^1.4.0`). The package is verified against **pi 1.8.0 / pi-ai 1.8.0**; the peer floor only rises on pi minor realigns.
13
13
 
14
14
  ## ✨ Features
15
15
 
@@ -24,8 +24,8 @@ Registers the `nan` provider via `pi.registerProvider()` using NaN's OpenAI-comp
24
24
  | **Streaming token usage** | `stream_options.include_usage` is on by default, so pi reports real input/output/reasoning/cache counts ([#4](https://github.com/gtrabanco/pi-nan-provider/issues/4), [#7](https://github.com/gtrabanco/pi-nan-provider/issues/7)). |
25
25
  | **Reasoning controls** | Per-model `reasoningEffortValues` + `thinkingLevelMap` ([#16](https://github.com/gtrabanco/pi-nan-provider/issues/16)), the reasoning-only stream guard ([#21](https://github.com/gtrabanco/pi-nan-provider/issues/21)), and the per-model max-token field (`qwen3.8-max` keeps `max_completion_tokens`; `qwen3.8-flash` returned to `max_tokens` after NaN's gateway fix, [#34](https://github.com/gtrabanco/pi-nan-provider/issues/34) → [#36](https://github.com/gtrabanco/pi-nan-provider/issues/36)). |
26
26
  | **Model-facts export** | `NAN_MODEL_FACTS` — one frozen, typed entry per billed chat model: limits, cost rates, reasoning contract, tool protocol, `max_tokens` semantics, thinking budget, cache mode and billing class, every cell carrying a provenance id ([#47](https://github.com/gtrabanco/pi-nan-provider/issues/47)). |
27
- | **Attribution header** | `X-Pi-Provider: gtrabanco/pi-nan-provider@<version>` on every request, stripped when pi's install telemetry is disabled. |
28
- | **Native image models** | `flux-2-klein` and `qwen-image-2.1` registered as pi `type: "image"` models, reachable from codemode and extensions. |
27
+ | **Attribution header** | `X-Pi-Provider: gtrabanco/pi-nan-provider@<version>` on every request, removed by `NAN_NO_ATTRIBUTION` (and by pi's install-telemetry opt-out on pi ≤ 1.6). |
28
+ | **Native image models** | `flux-2-klein` and `qwen-image-2.1` registered as pi `type: "image"` models, reachable from codemode and extensions, with pi 1.7's canonical `{ size, aspectRatio }` options. |
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
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. |
@@ -94,7 +94,7 @@ A caller-supplied `onPayload` hook is preserved and chained after sanitization.
94
94
 
95
95
  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.
96
96
 
97
- The header **follows pi's telemetry setting**: with `enableInstallTelemetry: false` in `settings.json` the header disappears from every request (evaluated live, so toggling the setting applies on the next request without a restart) — the header identifies the package in use, and users who opted out of telemetry should not be identifiable by it.
97
+ The header **can be turned off**: `NAN_NO_ATTRIBUTION=1` (`true`, `yes` or `on` also work) removes it from every request, and on pi ≤ 1.6 `enableInstallTelemetry: false` keeps doing the same. pi 1.7 removed telemetry altogether — the setting, `PI_TELEMETRY` and the install report are gone, and pi sends its own attribution unconditionally — so there the environment variable is the switch. The gate is evaluated live, so toggling it applies on the next request without a restart.
98
98
 
99
99
  ### 🧠 Model-switch safety
100
100
 
@@ -171,6 +171,7 @@ The media bridge is **enabled by default** (session-scoped, visible in `/mcp`).
171
171
  >
172
172
  > ```json
173
173
  > {
174
+ > "$schema": "https://pi.dev/schemas/mcp.schema.json",
174
175
  > "mcpServers": {
175
176
  > "fetch": { "command": "uvx", "args": ["mcp-server-fetch"] },
176
177
  > "web-search": {
@@ -182,6 +183,8 @@ The media bridge is **enabled by default** (session-scoped, visible in `/mcp`).
182
183
  > }
183
184
  > ```
184
185
  >
186
+ > The `"$schema"` line (pi ≥ 1.8.0) gives editors validation and completion for the file.
187
+ >
185
188
  > Re-check `https://api.nan.builders/mcp` periodically: if NaN publishes tools again, this package can
186
189
  > restore the bridge.
187
190
 
@@ -234,6 +237,8 @@ registering a server that can never connect. To get MCP in the CLI, enable the c
234
237
  for (const block of result.output) if (block.type === "image") image(block)
235
238
  ```
236
239
 
240
+ On pi 1.7+ the third argument takes the provider-neutral options: `{ size: "1536x1024" }` for a concrete canvas or `{ aspectRatio: "16:9" }` for one of `1:1`, `16:9`, `9:16`, `4:3`, `3:4`, `3:2`, `2:3`. NaN accepts only `WIDTHxHEIGHT` with each side on the 16-pixel grid (a multiple of 16, so `1024x1008` is fine — 1008 = 63 × 16) and between 256 and 1536 (ratio 1:3–3:1, `auto` allowed), so `size` is validated and `aspectRatio` resolves to the largest exact canvas; anything unusable fails locally with the rule it broke instead of spending one of the monthly image requests on a guaranteed `400`. `size` wins over `aspectRatio`, and `metadata.size` (plus `n`, `seed` and `guidance`, which codemode does not expose) still works from extension code.
241
+
237
242
  Both models need the "inference" membership tier (403 otherwise); the image endpoints
238
243
  are rate-limited separately from chat (20 requests/min, 100 requests/month shared
239
244
  between the two models) and do not consume the chat token budget.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gtrabanco/pi-nan-provider",
3
- "version": "1.6.4",
3
+ "version": "1.8.0",
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",
@@ -47,8 +47,8 @@
47
47
  "@earendil-works/pi-coding-agent": "^1.4.0"
48
48
  },
49
49
  "devDependencies": {
50
- "@earendil-works/pi-ai": "1.6.0",
51
- "@earendil-works/pi-coding-agent": "1.6.0",
50
+ "@earendil-works/pi-ai": "1.8.0",
51
+ "@earendil-works/pi-coding-agent": "1.8.0",
52
52
  "@types/bun": "1.4",
53
53
  "typescript": "7"
54
54
  },
@@ -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-27T00:10:03.719Z
4
+ // Source: https://models.dev/api.json (provider "nan"), fetched 2026-12-03T17:15:57.368Z
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.
@@ -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-27T00:10:03.719Z",
1030
+ fetchedAt: "2026-12-03T17:15:57.368Z",
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,15 +15,19 @@
15
15
  * be resolved (e.g. a virtual-module bundle with no readable package.json),
16
16
  * the header is simply omitted — attribution must never break a request.
17
17
  *
18
- * PRIVACY GATE: the header identifies this package, so it is subject to pi's
19
- * telemetry setting. The extension entrypoint wires
20
- * {@link configureProviderAttribution} to `pi.getSettings()` and the header
21
- * disappears whenever `enableInstallTelemetry` is `false` (the gate is
22
- * evaluated on every read, so toggling the setting mid-session takes effect
23
- * on the next request without a restart). Uncancellable-by-settings callers
24
- * (direct library use of `createNanCompatibleProvider` without the extension
25
- * entrypoint) get the enabled default; if the gate itself throws, attribution
26
- * falls back to pi's shipped default (enabled).
18
+ * PRIVACY GATE: the header identifies this package, so it can be turned off.
19
+ * The extension entrypoint wires {@link configureProviderAttribution} to
20
+ * {@link resolveProviderAttributionEnabled}: `NAN_NO_ATTRIBUTION` disables it,
21
+ * and so does pi's `enableInstallTelemetry: false` on hosts that still have
22
+ * that setting (pi <= 1.6). pi 1.7 removed telemetry altogether — the setting,
23
+ * `PI_TELEMETRY` and the install report are gone, and `getClientIdentity()`
24
+ * always sends pi's own attribution — so there the header is on unless the
25
+ * environment opts out. The gate is evaluated on every read, so toggling it
26
+ * mid-session takes effect on the next request without a restart.
27
+ * Uncancellable-by-settings callers (direct library use of
28
+ * `createNanCompatibleProvider` without the extension entrypoint) get the
29
+ * enabled default; if the gate itself throws, attribution falls back to
30
+ * enabled.
27
31
  */
28
32
 
29
33
  import { readFileSync } from "node:fs";
@@ -31,6 +35,12 @@ import { readFileSync } from "node:fs";
31
35
  /** Header added to every model registered by this package's providers. */
32
36
  export const PROVIDER_ATTRIBUTION_HEADER = "X-Pi-Provider";
33
37
 
38
+ /**
39
+ * Environment variable that turns the attribution header off: any of `1`,
40
+ * `true`, `yes`, `on` (case-insensitive). Empty or absent leaves it on.
41
+ */
42
+ export const PROVIDER_ATTRIBUTION_OPTOUT_ENV = "NAN_NO_ATTRIBUTION";
43
+
34
44
  /** Package identity used as the header value prefix (npm scope without the `@`). */
35
45
  const PACKAGE_IDENTITY = "gtrabanco/pi-nan-provider";
36
46
 
@@ -89,13 +99,40 @@ export function providerAttributionEnabled(): boolean {
89
99
 
90
100
  /**
91
101
  * Install the enablement gate. The extension entrypoint passes a closure over
92
- * `pi.getSettings().enableInstallTelemetry`, evaluated FRESH on every call so
93
- * a mid-session settings change applies on the next request.
102
+ * `pi.getSettings()`, evaluated FRESH on every call so a mid-session change
103
+ * applies on the next request.
94
104
  */
95
105
  export function configureProviderAttribution(isEnabled: AttributionGate): void {
96
106
  gate = isEnabled;
97
107
  }
98
108
 
109
+ /** True when the environment opts out of the attribution header. */
110
+ export function providerAttributionOptedOut(
111
+ env: Record<string, string | undefined> = process.env,
112
+ ): boolean {
113
+ const raw = env[PROVIDER_ATTRIBUTION_OPTOUT_ENV];
114
+ return typeof raw === "string" && /^(1|true|yes|on)$/i.test(raw.trim());
115
+ }
116
+
117
+ /**
118
+ * Resolve the gate for this host: the package opt-out first, then pi's legacy
119
+ * install-telemetry setting (pi 1.4-1.6). A host that reports neither — pi 1.7
120
+ * removed the setting together with its telemetry endpoints — keeps the header
121
+ * on, the same choice pi makes for its own client identity.
122
+ */
123
+ export function resolveProviderAttributionEnabled(
124
+ settings: unknown,
125
+ env: Record<string, string | undefined> = process.env,
126
+ ): boolean {
127
+ if (providerAttributionOptedOut(env)) return false;
128
+ if (settings && typeof settings === "object") {
129
+ const legacy = (settings as { enableInstallTelemetry?: unknown })
130
+ .enableInstallTelemetry;
131
+ if (legacy === false) return false;
132
+ }
133
+ return true;
134
+ }
135
+
99
136
  /**
100
137
  * Attach the attribution header to a model (or any object carrying
101
138
  * `headers`), preserving existing headers. Returns the same object when the
@@ -27,8 +27,11 @@
27
27
  * local-only — nothing is uploaded.
28
28
  *
29
29
  * A missing `onResponse` (older pi-ai or a host that does not call it) simply
30
- * leaves `cf_ray` null; detection still works on `id`+`created`. Every write is
31
- * best-effort: a full disk must never break a stream.
30
+ * leaves `cf_ray` null; detection still works on `id`+`created`. pi-ai 1.7
31
+ * calls the hook once per HTTP attempt, error responses included, so the
32
+ * wrapper overwrites its `cf-ray` with each reported response: the last one is
33
+ * the response that actually streamed. Every write is best-effort: a full disk
34
+ * must never break a stream.
32
35
  */
33
36
 
34
37
  import { createHash } from "node:crypto";
@@ -2,11 +2,15 @@
2
2
  * Provider-level HTTP attempt evidence (issue #49).
3
3
  *
4
4
  * pi's transcript only keeps the terminal outcome of a logical request: pi-ai
5
- * retries 429/408/409/5xx inside `retryProviderRequest`, a retried request that
6
- * finally succeeds appears as one ordinary turn, and `onResponse` fires only
7
- * after the retry loop resolves — so a rejected attempt leaves no `cf-ray`, no
8
- * status and no timing anywhere. Support asked for exactly that evidence (the
9
- * reference CSV in issue #49 has one row per HTTP attempt).
5
+ * retries 429/408/409/5xx inside `retryProviderRequest`, and a retried request
6
+ * that finally succeeds appears as one ordinary turn — every attempt before it
7
+ * leaves no status, timing or payload evidence behind.
8
+ *
9
+ * pi-ai 1.7 started reporting failed attempts to `onResponse` too
10
+ * (`onErrorResponse` in `utils/provider-retry.js`), but that hook carries only
11
+ * the status and headers: no start time per attempt, no attempt number, no
12
+ * payload size and no process-scoped counters. Those are the measurements
13
+ * issue #49 asked for, so the tap below stays necessary.
10
14
  *
11
15
  * `createProvider` exposes no `fetch` option (pi-ai 1.6.0, `CreateProviderOptions`),
12
16
  * but `StreamOptions.fetch` is forwarded to the OpenAI client
package/src/images.ts CHANGED
@@ -138,6 +138,146 @@ export function baselineImageModels(
138
138
  });
139
139
  }
140
140
 
141
+ // ── Output size ───────────────────────────────────────────────────────────
142
+
143
+ /**
144
+ * NaN's documented output-size envelope: `WIDTHxHEIGHT`, each side divisible
145
+ * by 16 and between 256 and 1536, aspect ratio between 1:3 and 3:1; `auto`
146
+ * (or omitting the field) yields 1024x1024
147
+ * (https://nan.builders/openapi.json, tag Images, checked 2026-11-28).
148
+ *
149
+ * pi 1.7 hands providers `ImagesOptions.size` (its own examples are `"1K"`,
150
+ * `"2K"`, `"4K"`) and `ImagesOptions.aspectRatio`. NaN takes neither form, so
151
+ * both are translated here instead of burning one of the 100 monthly image
152
+ * requests on a guaranteed 400.
153
+ */
154
+ export const NAN_IMAGE_SIZE_RULE =
155
+ "WIDTHxHEIGHT, each side divisible by 16 and 256-1536, ratio 1:3-3:1";
156
+
157
+ /**
158
+ * pi's provider-neutral `aspectRatio` resolved to the largest exact canvas
159
+ * inside NaN's envelope. NaN has no aspect-ratio parameter, so this table is
160
+ * our mapping; supported keys are exactly the ratios listed here.
161
+ */
162
+ export const NAN_ASPECT_RATIO_SIZES: Readonly<Record<string, string>> = {
163
+ "1:1": "1024x1024",
164
+ "16:9": "1536x864",
165
+ "9:16": "864x1536",
166
+ "4:3": "1024x768",
167
+ "3:4": "768x1024",
168
+ "3:2": "1536x1024",
169
+ "2:3": "1024x1536",
170
+ };
171
+
172
+ const SIZE_PATTERN = /^(\d{1,5})x(\d{1,5})$/i;
173
+ const RATIO_PATTERN = /^(\d{1,4})\s*[:/]\s*(\d{1,4})$/i;
174
+
175
+ /** Quote strings the way the rule messages always showed them; label the rest. */
176
+ function gotLabel(value: unknown): string {
177
+ return typeof value === "string" ? `"${value}"` : String(value);
178
+ }
179
+
180
+ /** The size-rule failure a non-WxH value raises — shared by the shape and
181
+ * type guards so every unusable input names the same rule. */
182
+ function sizeRuleError(value: unknown): Error {
183
+ return new Error(
184
+ `NaN image models expect size ${NAN_IMAGE_SIZE_RULE} (or "auto"), got ${gotLabel(value)}`,
185
+ );
186
+ }
187
+
188
+ function greatestCommonDivisor(a: number, b: number): number {
189
+ let left = a;
190
+ let right = b;
191
+ while (right !== 0) [left, right] = [right, left % right];
192
+ return left;
193
+ }
194
+
195
+ /** Validate a NaN size string, throwing with the rule that was broken. */
196
+ export function validateNanImageSize(value: string): string {
197
+ // The signature is `string`, but this validator is a published surface: a
198
+ // caller bypassing the resolver's type gates gets the rule it broke, not a
199
+ // TypeError from `.trim()`.
200
+ if (typeof value !== "string") throw sizeRuleError(value);
201
+ const size = value.trim();
202
+ if (/^auto$/i.test(size)) return "auto";
203
+ const match = SIZE_PATTERN.exec(size);
204
+ if (!match) throw sizeRuleError(value);
205
+ const width = Number(match[1]);
206
+ const height = Number(match[2]);
207
+ const sides = [width, height];
208
+ // "divisible by 16" is a grid, not a multiple test: 1024x1008 (1008 = 63 × 16)
209
+ // sits on NaN's grid, so the rule below names it instead of rejecting it.
210
+ if (sides.some((side) => !Number.isInteger(side / 16))) {
211
+ throw new Error(
212
+ `NaN image models require each side of size to be divisible by 16, got "${value}"`,
213
+ );
214
+ }
215
+ if (sides.some((side) => side < 256 || side > 1536)) {
216
+ throw new Error(
217
+ `NaN image models require each side of size to be between 256 and 1536, got "${value}"`,
218
+ );
219
+ }
220
+ if (width / height < 1 / 3 || width / height > 3) {
221
+ throw new Error(
222
+ `NaN image models accept an aspect ratio between 1:3 and 3:1, got "${value}"`,
223
+ );
224
+ }
225
+ return `${width}x${height}`;
226
+ }
227
+
228
+ /** Resolve an `aspectRatio` (e.g. "16:9") to a concrete NaN canvas. */
229
+ export function nanImageSizeForAspectRatio(value: string): string {
230
+ if (typeof value !== "string") {
231
+ throw new Error(
232
+ `NaN image models take no aspect ratio; supported aspectRatio values are ${Object.keys(
233
+ NAN_ASPECT_RATIO_SIZES,
234
+ ).join(", ")} (got ${gotLabel(value)})`,
235
+ );
236
+ }
237
+ const match = RATIO_PATTERN.exec(value.trim());
238
+ if (match) {
239
+ const width = Number(match[1]);
240
+ const height = Number(match[2]);
241
+ if (width > 0 && height > 0) {
242
+ const divisor = greatestCommonDivisor(width, height);
243
+ const size = NAN_ASPECT_RATIO_SIZES[`${width / divisor}:${height / divisor}`];
244
+ if (size) return size;
245
+ }
246
+ }
247
+ throw new Error(
248
+ `NaN image models take no aspect ratio; supported aspectRatio values are ${Object.keys(
249
+ NAN_ASPECT_RATIO_SIZES,
250
+ ).join(", ")} (got "${value}")`,
251
+ );
252
+ }
253
+
254
+ /**
255
+ * Pick the outgoing `size` field: `options.size` > `options.aspectRatio` >
256
+ * `metadata.size` (the extension-side escape hatch that predates pi 1.7).
257
+ */
258
+ export function resolveNanImageSize(requestOptions?: {
259
+ size?: unknown;
260
+ aspectRatio?: unknown;
261
+ metadata?: unknown;
262
+ }): string | undefined {
263
+ const canonicalSize = requestOptions?.size;
264
+ if (typeof canonicalSize === "string" && canonicalSize.trim().length > 0) {
265
+ return validateNanImageSize(canonicalSize);
266
+ }
267
+ const aspectRatio = requestOptions?.aspectRatio;
268
+ if (typeof aspectRatio === "string" && aspectRatio.trim().length > 0) {
269
+ return nanImageSizeForAspectRatio(aspectRatio);
270
+ }
271
+ const metadata = requestOptions?.metadata;
272
+ if (metadata && typeof metadata === "object") {
273
+ const metadataSize = (metadata as { size?: unknown }).size;
274
+ if (typeof metadataSize === "string" && metadataSize.trim().length > 0) {
275
+ return validateNanImageSize(metadataSize);
276
+ }
277
+ }
278
+ return undefined;
279
+ }
280
+
141
281
  // ── API implementation ─────────────────────────────────────────────────────
142
282
 
143
283
  /** Injectable options for createNanImagesApi (fetchImpl is for tests). */
@@ -232,16 +372,19 @@ export function createNanImagesApi(
232
372
  }
233
373
  headers.Authorization = "Bearer " + apiKey;
234
374
 
235
- // ── Optional metadata passthrough ───────────────────────
236
- // n, size, seed and guidance are NaN extensions accepted on
237
- // both endpoints; pass them through only with the right type.
375
+ // ── Optional fields ─────────────────────────────────────
376
+ // n, seed and guidance are NaN extensions accepted on both
377
+ // endpoints; pass them through only with the right type. `size`
378
+ // is resolved from pi's canonical options first (validated
379
+ // against NaN's envelope) and from metadata.size last.
238
380
  const metadata = (requestOptions?.metadata ?? {}) as Record<
239
381
  string,
240
382
  unknown
241
383
  >;
242
384
  const optionalFields: Record<string, string | number> = {};
385
+ const size = resolveNanImageSize(requestOptions);
386
+ if (size !== undefined) optionalFields.size = size;
243
387
  if (typeof metadata.n === "number") optionalFields.n = metadata.n;
244
- if (typeof metadata.size === "string") optionalFields.size = metadata.size;
245
388
  if (typeof metadata.seed === "number") optionalFields.seed = metadata.seed;
246
389
  if (typeof metadata.guidance === "number") {
247
390
  optionalFields.guidance = metadata.guidance;
package/src/index.ts CHANGED
@@ -27,7 +27,7 @@
27
27
 
28
28
  import type { ExtensionAPI, ProviderConfig } from "@earendil-works/pi-coding-agent";
29
29
  import type { Provider } from "@earendil-works/pi-ai";
30
- import { configureProviderAttribution } from "./attribution.ts";
30
+ import { configureProviderAttribution, resolveProviderAttributionEnabled } from "./attribution.ts";
31
31
  import { registerNanMcpCommand } from "./commands.ts";
32
32
  import { registerNanUsageCommand } from "./usage.ts";
33
33
  import { registerNanDebugCommand } from "./debug-command.ts";
@@ -142,15 +142,16 @@ async function registerMcpServersNative(pi: ExtensionAPI): Promise<void> {
142
142
  // ── Extension entrypoint ─────────────────────────────────────────────────
143
143
 
144
144
  export default async function nanProviderExtension(pi: ExtensionAPI): Promise<void> {
145
- // Attribution privacy gate: the X-Pi-Provider header identifies this
146
- // package, so it follows pi's telemetry setting. Evaluated fresh on every
145
+ // Attribution privacy gate: the header identifies this package, so it
146
+ // follows `NAN_NO_ATTRIBUTION` and, on hosts that still have it (pi <= 1.6),
147
+ // pi's install-telemetry setting. pi 1.7 removed telemetry entirely, so
148
+ // there the header is sent unless the environment opts out — the same
149
+ // choice pi makes for its own client identity. Evaluated fresh on every
147
150
  // read (model reads, /nan-usage fetch) so a mid-session change applies
148
- // without a restart. A host without getSettings() keeps the shipped
149
- // default (enabled) — handled inside the attribution module.
150
- configureProviderAttribution(() => {
151
- const settings = pi.getSettings() as { enableInstallTelemetry?: boolean } | undefined;
152
- return settings?.enableInstallTelemetry !== false;
153
- });
151
+ // without a restart.
152
+ configureProviderAttribution(() =>
153
+ resolveProviderAttributionEnabled(pi.getSettings()),
154
+ );
154
155
  // Replaces pi's cryptic "no loaded extension connects MCP servers" error with
155
156
  // actionable guidance when the host loads no built-in `mcp` extension (PI WEB).
156
157
  registerMcpHostGuard(pi);
@@ -203,8 +203,9 @@ function withStaleCatalogOverlay(
203
203
  ): Provider<"openai-completions"> {
204
204
  // Attribution is evaluated at READ time, not only factory time: entries
205
205
  // built while the privacy gate was enabled carry the baked header, and a
206
- // mid-session `enableInstallTelemetry: false` must strip it on the next
207
- // read without rebuilding the catalog.
206
+ // mid-session opt-out (`NAN_NO_ATTRIBUTION`, or pi <= 1.6's
207
+ // `enableInstallTelemetry: false`) must strip it on the next read without
208
+ // rebuilding the catalog.
208
209
  const policy = <T extends { headers?: Record<string, string> }>(m: T): T =>
209
210
  providerAttributionEnabled() ? m : stripProviderAttribution(m);
210
211
  // Issue #32: a pre-#15 models-store.json persists non-chat endpoint ids