@gtrabanco/pi-nan-provider 1.2.1 → 1.4.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
@@ -150,9 +150,11 @@ Since 1.0.0 the package version **aligns its MAJOR.MINOR with the pi release lin
150
150
  `ctx.model` is the **selection** (the virtual entry), never the routed physical
151
151
  model (`core/virtual-models.js`; `agent-session.js` "The selection stays in
152
152
  agent state; only this request uses the routed model"), and the routed target is
153
- not exposed to the hook. `stripCrossModelThinking` therefore skips virtual
153
+ not exposed to the hook. `stripCrossModelThinking` therefore skipped virtual
154
154
  selections (`src/cross-model-thinking-guard.ts`, `VIRTUAL_MODEL_API`); otherwise
155
- its same-model check would strip reasoning on every continuation. Registered
155
+ its same-model check would strip reasoning on every continuation. (The guard
156
+ was REMOVED in package 1.4.0 — pi-ai >= 1.3.0 drops cross-model thinking
157
+ itself — so virtual selections now need no special handling.) Registered
156
158
  virtual models are otherwise transparent to the catalog/factory.
157
159
  - **Factory-time ExtensionAPI has NO `modelRegistry`** (verified pi 0.99.1):
158
160
  The `ExtensionAPI` interface does not include `modelRegistry`; it exists only on
@@ -344,8 +346,55 @@ Since 1.0.0 the package version **aligns its MAJOR.MINOR with the pi release lin
344
346
  `src/reasoning-only-stream-guard.ts` (issue #21) keys on that marker;
345
347
  earlier comment/message text said "60,000 characters" and was corrected to
346
348
  the documented figures.
347
- - **pi 1.2.0 / pi-ai 1.2.0 compat** (verified 2026-10-14, the current verified
348
- baseline): the peer range stays `">=0.99.0 <2"` (1.2.0 is inside it). The pi-ai
349
+ - **pi 1.4.0 / pi-ai 1.4.0 compat** (verified 2026-10-24, the current verified
350
+ baseline): devDependencies bumped 1.3.0 → 1.4.0; **the peer range floor rose to
351
+ `"^1.3.0"`** and the version-gated cross-model thinking guard plus
352
+ `src/pi-ai-version.ts` were REMOVED as scheduled (pi-ai >= 1.3.0 drops
353
+ cross-model thinking itself). The pi-ai 1.4.0 type surface only ADDS exports
354
+ (`utils/identity.ts`: `ClientIdentity`/`UserAgentMode`/`PI_ATTRIBUTION`, and
355
+ `PI_AI_VERSION`); `compat.d.ts` and `api/openai-completions.d.ts` are
356
+ byte-identical to 1.3.0. `transform-messages.js` (cross-model thinking drop)
357
+ is identical to 1.3.0 → `CROSS_MODEL_GUARD_PI_AI_CEILING` stays `1.3.0`.
358
+ The `thinkingLevelMap.off` branch in `buildRequest` still fires (~line 665).
359
+ Attribution headers moved to `options.identity` (`getIdentityHeaders`);
360
+ `before_provider_headers` no longer sees OpenRouter/NVIDIA/OpenCode headers
361
+ (this package never used the hook). `RETRYABLE_PROVIDER_ERROR_PATTERN`:
362
+ status codes now wrapped in `(?<![a-z0-9])…(?![a-z0-9])` lookarounds plus
363
+ more upstream-failure wordings — upstream-side, relevant to the LiteLLM
364
+ gateway. Upstream fixes benefiting NaN users: whitespace-only tool output no
365
+ longer 400s on OpenAI Completions (#8720); sessions survive output-limit
366
+ cutoff recovery (#11227). pi 1.4.0 fixes extension imports of
367
+ `@earendil-works/pi-ai/models` (#11156) — `clampThinkingLevel` usable on
368
+ pi >= 1.4.0 hosts, subpath imports still avoided (peer floor >= 0.99.0).
369
+ All tests + typecheck pass against 1.4.0. **New in this release:**
370
+ `src/attribution.ts` attaches `X-Pi-Provider:
371
+ gtrabanco/pi-nan-provider@<version>` to every registered model (pi-ai
372
+ merges `model.headers` over identity headers on 0.99.1 and 1.4.0 alike),
373
+ covering baseline, live merge, placeholders, overlay, image models and the
374
+ `/nan-usage` fetch; omitted silently when the version is unreadable, and
375
+ GATED on pi's `enableInstallTelemetry` setting (privacy: the header
376
+ identifies the package; gate evaluated live on every read, installed by the
377
+ extension entrypoint via `configureProviderAttribution`, stripped on read
378
+ paths by the overlay wrappers when disabled).
379
+ - **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
380
+ `">=0.99.0 <2"`. The pi-ai 1.3.0 `compat.d.ts` and `api/openai-completions.d.ts`
381
+ surfaces are byte-identical to 1.2.0; `index.d.ts` only drops the
382
+ `utils/assistant-message-frame` re-export (unused here), and the
383
+ `thinkingLevelMap.off` branch in `buildRequest` still fires. **pi-ai 1.3.0 lands
384
+ the upstream fix for issue #3**: `transformMessages` now DROPS cross-model
385
+ `thinking` blocks (`if (!isSameModel) return []`) instead of downgrading them to
386
+ unbounded text — the cross-model-thinking guard was therefore VERSION-GATED
387
+ (`CROSS_MODEL_GUARD_PI_AI_CEILING = "1.3.0"`; registers only on hosts older than
388
+ that, unknown version keeps it on) and was REMOVED in package 1.4.0 (peer floor
389
+ raised to `>=1.3.0`, as scheduled). `RETRYABLE_PROVIDER_ERROR_PATTERN`
390
+ expands with gateway/upstream wording ("service is temporarily unavailable" #10965,
391
+ upstream wrapper text #10842) and #10926 fixes OpenAI-compatible streams where
392
+ LiteLLM sends reasoning and content in the same chunk — both relevant to NaN's
393
+ LiteLLM gateway, both upstream-side. Package tests (319) and typecheck pass against
394
+ 1.3.0; the issue-3 acceptance tests were re-pointed at the new upstream reality
395
+ (thinking scenario pins pi-ai's drop; the opaque-400 reclassification contract is
396
+ exercised via oversized user content pi-ai cannot shrink).
397
+ - **pi 1.2.0 / pi-ai 1.2.0 compat** (verified 2026-10-14): the peer range stays `">=0.99.0 <2"` (1.2.0 is inside it). The pi-ai
349
398
  1.2.0 index/compat type surface is byte-identical to 1.0.0 (`index.d.ts` diff is
350
399
  empty); the only additions are `KnownProvider` gaining `"azure"` (renamed from
351
400
  `"azure-openai-responses"` in pi 1.0.3 — not used here), a new
package/README.es.md CHANGED
@@ -1,7 +1,7 @@
1
- # @gtrabanco/pi-nan-provider
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.2.1-blue)](https://github.com/gtrabanco/pi-nan-provider/releases)
4
+ [![Version](https://img.shields.io/badge/version-1.4.0-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).
@@ -46,13 +46,17 @@ Los ids no-chat que devuelve `/models` en vivo (embedding, rerank, TTS, STT, ima
46
46
 
47
47
  El registro es síncrono a propósito: el catálogo de fallback está disponible al instante, y el runtime de Models de pi dirige el refresco en vivo (refresco de red en el arranque interactivo y periódico, solo caché en el registro), persistiendo el overlay entre ejecuciones.
48
48
 
49
- ### 🧠 Seguridad al cambiar de modelo (guard de razonamiento cross-model)
49
+ ### 🏷️ Cabecera de atribución
50
50
 
51
- Al cambiar de modelo, pi-ai reenvía el razonamiento del modelo anterior como texto plano de asistente — **sin límite de tamaño**. Un único razonamiento largo o degenerado puede desbordar la ventana de un modelo de 262K, y NaN responde con un `400 Invalid request. Check your request parameters.` genérico que parece un bug del proveedor (seguimiento upstream: [pi-nan-provider#3](https://github.com/gtrabanco/pi-nan-provider/issues/3); issue abierta upstream: [pi#6167](https://github.com/earendil-works/pi/issues/6167)).
51
+ 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.
52
52
 
53
- Este paquete **elimina todos los bloques de razonamiento cross-model reenviados**, de modo que cambiar de un modelo de 1M de contexto a uno de 262K (`qwen3.6`) ya no desborda la ventana. Las respuestas y los tool results de los modelos no se tocan — solo se quitan sus trazas internas de razonamiento, así que `qwen3.6` puede seguir respondiendo sobre lo que hizo otro modelo. El razonamiento del mismo modelo no se toca nunca, y el guard solo actúa sobre peticiones dirigidas a los proveedores de este paquete. Pon `NAN_THINKING_GUARD=0` para desactivarlo.
53
+ 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.
54
54
 
55
- Si una petición sigue desbordando — guard desactivado, inflado que no es un bloque de razonamiento (tool outputs grandes, imágenes) o una ventana de destino más pequeña — NaN responde con el mismo 400 genérico en lugar de nombrar el desbordamiento, y la auto-compactación de pi no lo reconoce, así que la sesión se queda 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.
55
+ ### 🧠 Seguridad al cambiar de modelo
56
+
57
+ Al cambiar de modelo, versiones antiguas de pi-ai reenviaban el razonamiento del modelo anterior como texto plano de asistente **sin límite de tamaño**, lo que podía desbordar la ventana de un modelo de 262K; NaN respondía con un `400 Invalid request. Check your request parameters.` genérico que parecía un bug del proveedor (seguimiento upstream: [pi-nan-provider#3](https://github.com/gtrabanco/pi-nan-provider/issues/3)). pi-ai 1.3.0 arregló esto upstream (`transformMessages` ahora descarta los bloques de thinking de otro modelo) y este paquete requiere **pi ≥ 1.3.0** (rango peer `^1.3.0`), así que el guard extension-side que lo mitigaba fue **eliminado en la versión 1.4.0 del paquete** — no hay que hacer nada, upstream lo gestiona.
58
+
59
+ 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.
56
60
 
57
61
  ### ⏱️ Streams truncados intermitentes (auto-retry, sin stall silencioso)
58
62
 
@@ -102,7 +106,7 @@ Consigue una clave en la [plataforma NaN](https://cloud.nan.builders/r/7GK06FX8)
102
106
 
103
107
  ## 🔌 MCP nativo
104
108
 
105
- Dado que [pi 0.99.0 incluye un cliente MCP integrado](https://github.com/earendil-works/pi/blob/main/docs/usage.md), este paquete usa MCP nativo (requiere `pi >=0.99, <2` — pi 0.99 hasta 1.2 son compatibles; el rango peer se amplió a `<2` en 0.11.0).
109
+ Dado que [pi 0.99.0 incluye un cliente MCP integrado](https://github.com/earendil-works/pi/blob/main/docs/usage.md), este paquete usa MCP nativo (requiere **pi >= 1.3.0**, el floor del rango peer desde la versión 1.4.0 del paquete).
106
110
 
107
111
  El puente de media está **activado por defecto** (por sesión, visible en `/mcp`). Usa `/nan-mcp` para gestionarlo.
108
112
 
@@ -218,7 +222,7 @@ conector con `pi config` → Built-in extensions → `mcp`.
218
222
 
219
223
  > pi 0.99.0–0.99.1 usaba la forma con guiones (`mcp__nan-media__*`); pi 0.99.2+ sanitiza los
220
224
  > nombres de herramientas a solo `[A-Za-z0-9_]`, así que los guiones se convirtieron en guiones
221
- > bajos. La forma con guiones bajos aplica desde 0.99.2 hasta pi 1.2.
225
+ > bajos. La forma con guiones bajos aplica en todas las versiones soportadas (pi >= 1.3.0).
222
226
 
223
227
  #### 🔧 Configuración del Puente de Media
224
228
 
@@ -239,6 +243,12 @@ bun run check-nan-mcp-server --json # JSON para máquinas
239
243
  bun run check-nan-mcp-server --issue # crea/refresca el issue
240
244
  ```
241
245
 
246
+ Las actualizaciones del SDK de pi (`@earendil-works/pi-ai` / `@earendil-works/pi-coding-agent`)
247
+ también están automatizadas: el workflow semanal `check-pi-sdk-versions` abre el issue
248
+ `sdk-monitor` **y** prepara un PR con el bump de devDependencies (`bun test` +
249
+ `bun run typecheck` + diff de superficie de tipos incluidos) para revisión humana — ver
250
+ `docs/sdk-version-monitoring.md`.
251
+
242
252
  ---
243
253
 
244
254
  ## 📊 Uso de Cuotas: `/nan-usage`
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
- # @gtrabanco/pi-nan-provider
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.2.1-blue)](https://github.com/gtrabanco/pi-nan-provider/releases)
4
+ [![Version](https://img.shields.io/badge/version-1.4.0-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).
@@ -46,13 +46,17 @@ NaN's live `/models` also returns non-chat endpoint ids (embedding, rerank, TTS,
46
46
 
47
47
  The registration is synchronous on purpose: the generated fallback catalog is available immediately, and pi's Models runtime drives the live refresh (network refresh at interactive startup and periodically, cache-only at registration), persisting the overlay between runs.
48
48
 
49
- ### 🧠 Model-switch safety (cross-model reasoning guard)
49
+ ### 🏷️ Attribution header
50
50
 
51
- When you switch models, pi-ai replays the previous model's reasoning as plain assistant text — with **no size bound**. A single long or degenerate reasoning trace can therefore overflow a 262K-context model's window, and NaN answers with a generic `400 Invalid request. Check your request parameters.` that looks like a provider bug (upstream tracking: [pi-nan-provider#3](https://github.com/gtrabanco/pi-nan-provider/issues/3); open upstream issue: [pi#6167](https://github.com/earendil-works/pi/issues/6167)).
51
+ 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.
52
52
 
53
- This package **drops every replayed cross-model reasoning block**, so switching from a 1M-context model to a 262K one (`qwen3.6`) no longer overflows the window. The models' answers and tool results are untouched — only their internal reasoning traces are removed, so `qwen3.6` can still answer about what another model did. Same-model reasoning is never altered, and the guard only acts on requests targeting this package's providers. Set `NAN_THINKING_GUARD=0` to disable it.
53
+ 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.
54
54
 
55
- If a request still overflows — the guard is disabled, the inflation is not a reasoning block (large tool outputs, images), or the destination window is simply smaller — NaN answers the same generic 400 instead of naming the overflow, and pi's auto-compaction does not recognize it, so the session wedges 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.
55
+ ### 🧠 Model-switch safety
56
+
57
+ When you switch models, older pi-ai versions replayed the previous model's reasoning as plain assistant text with **no size bound**, which could overflow a 262K-context model's window; NaN answered with a generic `400 Invalid request. Check your request parameters.` that looked like a provider bug (upstream tracking: [pi-nan-provider#3](https://github.com/gtrabanco/pi-nan-provider/issues/3)). pi-ai 1.3.0 fixed this upstream (`transformMessages` now drops thinking blocks from a different model) and this package requires **pi ≥ 1.3.0** (peer range `^1.3.0`), so the extension-side guard that used to mitigate it was **removed in package 1.4.0** — no action is needed, upstream handles it.
58
+
59
+ 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.
56
60
 
57
61
  ### ⏱️ Intermittent truncated streams (auto-retry, no silent stall)
58
62
 
@@ -102,7 +106,7 @@ Get a key from the [NaN platform](https://cloud.nan.builders/r/7GK06FX8) (user s
102
106
 
103
107
  ## 🔌 Native MCP Server
104
108
 
105
- Since [pi 0.99.0 ships a built-in MCP client](https://github.com/earendil-works/pi/blob/main/docs/usage.md), this package bridges to native MCP (requires `pi >=0.99, <2` — pi 0.99 through 1.2 are supported; the peer range was widened to `<2` in 0.11.0).
109
+ Since [pi 0.99.0 ships a built-in MCP client](https://github.com/earendil-works/pi/blob/main/docs/usage.md), this package bridges to native MCP (requires **pi >= 1.3.0**, the peer range floor since package 1.4.0).
106
110
 
107
111
  The media bridge is **enabled by default** (session-scoped, visible in `/mcp`). Use `/nan-mcp` to manage it.
108
112
 
@@ -164,8 +168,7 @@ registering a server that can never connect. To get MCP in the CLI, enable the c
164
168
  ### pi 0.99-1.0 features and NaN models
165
169
 
166
170
  - **Virtual models** — register a router under `nan` (`pi.registerVirtualModel({ provider: "nan", ... })`);
167
- it routes to the physical NaN models with no provider-side configuration. The cross-model thinking
168
- guard skips virtual selections, because the routed physical model is not visible to the `context` hook.
171
+ it routes to the physical NaN models with no provider-side configuration.
169
172
  - **Codemode** — works with any tool-calling NaN model. This package's MCP tools use
170
173
  `exposure: "direct"`, so codemode scripts can call them as well. Requires pi's built-in `codemode`
171
174
  extension (see the PI WEB note above).
@@ -214,8 +217,8 @@ registering a server that can never connect. To get MCP in the CLI, enable the c
214
217
  | `mcp__nan_media__get_quota` | Per-model token quota (used / cap / remaining / reset) |
215
218
 
216
219
  > pi 0.99.0–0.99.1 used the hyphenated form (`mcp__nan-media__*`); pi 0.99.2+ sanitizes tool
217
- > names to `[A-Za-z0-9_]` only, so hyphens became underscores. The underscore form applies from
218
- > 0.99.2 onward through pi 1.2.
220
+ > names to `[A-Za-z0-9_]` only, so hyphens became underscores. The underscore form applies
221
+ > on every supported version (pi >= 1.3.0).
219
222
 
220
223
  #### 🔧 Media Bridge Configuration
221
224
 
@@ -236,6 +239,11 @@ bun run check-nan-mcp-server --json # machine-readable JSON
236
239
  bun run check-nan-mcp-server --issue # create/refresh the issue
237
240
  ```
238
241
 
242
+ PI SDK updates (`@earendil-works/pi-ai` / `@earendil-works/pi-coding-agent`) are automated
243
+ too: the weekly `check-pi-sdk-versions` workflow files the `sdk-monitor` issue **and**
244
+ prepares a devDependencies-bump PR (`bun test` + `bun run typecheck` + type-surface diff
245
+ included) for human review — see `docs/sdk-version-monitoring.md`.
246
+
239
247
  ---
240
248
 
241
249
  ## 📊 Quota Usage: `/nan-usage`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gtrabanco/pi-nan-provider",
3
- "version": "1.2.1",
3
+ "version": "1.4.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",
@@ -42,12 +42,12 @@
42
42
  "check-pi-sdk-versions": "node scripts/check-pi-sdk-versions.mjs --report"
43
43
  },
44
44
  "peerDependencies": {
45
- "@earendil-works/pi-ai": ">=0.99.0 <2",
46
- "@earendil-works/pi-coding-agent": ">=0.99.0 <2"
45
+ "@earendil-works/pi-ai": "^1.3.0",
46
+ "@earendil-works/pi-coding-agent": "^1.3.0"
47
47
  },
48
48
  "devDependencies": {
49
- "@earendil-works/pi-ai": "1.2.0",
50
- "@earendil-works/pi-coding-agent": "1.2.0",
49
+ "@earendil-works/pi-ai": "1.4.0",
50
+ "@earendil-works/pi-coding-agent": "1.4.0",
51
51
  "@types/bun": "1.4",
52
52
  "typescript": "7"
53
53
  },
@@ -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-10-16T17:43:45.590Z
4
+ // Source: https://models.dev/api.json (provider "nan"), fetched 2026-10-26T17:25:23.828Z
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.
@@ -52,7 +52,20 @@ export const NAN_GENERATED_MODELS: readonly GeneratedModelEntry[] = [
52
52
  "family": "deepseek-flash",
53
53
  "attachment": true,
54
54
  "reasoning": true,
55
- "reasoning_options": [],
55
+ "reasoning_options": [
56
+ {
57
+ "type": "effort",
58
+ "values": [
59
+ "none",
60
+ "minimal",
61
+ "low",
62
+ "medium",
63
+ "high",
64
+ "xhigh",
65
+ "max"
66
+ ]
67
+ }
68
+ ],
56
69
  "tool_call": true,
57
70
  "structured_output": true,
58
71
  "temperature": true,
@@ -211,9 +224,11 @@ export const NAN_GENERATED_MODELS: readonly GeneratedModelEntry[] = [
211
224
  {
212
225
  "type": "effort",
213
226
  "values": [
227
+ "minimal",
214
228
  "low",
215
229
  "medium",
216
230
  "high",
231
+ "xhigh",
217
232
  "max"
218
233
  ]
219
234
  }
@@ -283,7 +298,18 @@ export const NAN_GENERATED_MODELS: readonly GeneratedModelEntry[] = [
283
298
  "family": "mimo",
284
299
  "attachment": true,
285
300
  "reasoning": true,
286
- "reasoning_options": [],
301
+ "reasoning_options": [
302
+ {
303
+ "type": "effort",
304
+ "values": [
305
+ "none",
306
+ "low",
307
+ "medium",
308
+ "high",
309
+ "max"
310
+ ]
311
+ }
312
+ ],
287
313
  "tool_call": true,
288
314
  "temperature": true,
289
315
  "release_date": "2026-09-22",
@@ -428,9 +454,23 @@ export const NAN_GENERATED_MODELS: readonly GeneratedModelEntry[] = [
428
454
  "family": "qwen",
429
455
  "attachment": true,
430
456
  "reasoning": true,
431
- "reasoning_options": [],
457
+ "reasoning_options": [
458
+ {
459
+ "type": "effort",
460
+ "values": [
461
+ "none",
462
+ "minimal",
463
+ "low",
464
+ "medium",
465
+ "high",
466
+ "xhigh",
467
+ "max"
468
+ ]
469
+ }
470
+ ],
432
471
  "tool_call": true,
433
472
  "structured_output": true,
473
+ "temperature": true,
434
474
  "release_date": "2026-08-26",
435
475
  "last_updated": "2026-08-26",
436
476
  "modalities": {
@@ -444,7 +484,7 @@ export const NAN_GENERATED_MODELS: readonly GeneratedModelEntry[] = [
444
484
  },
445
485
  "open_weights": false,
446
486
  "limit": {
447
- "context": 262144,
487
+ "context": 1048576,
448
488
  "output": 131072
449
489
  },
450
490
  "cost": {
@@ -459,12 +499,12 @@ export const NAN_GENERATED_MODELS: readonly GeneratedModelEntry[] = [
459
499
  export const GENERATED_CATALOG_META = {
460
500
  source: "https://models.dev/api.json",
461
501
  modelsDevProvider: "nan",
462
- fetchedAt: "2026-10-16T17:43:45.590Z",
502
+ fetchedAt: "2026-10-26T17:25:23.828Z",
463
503
  modelCount: 6,
464
504
  models: ["deepseek-v4-flash","gemma4","glm5.3-flash","mimo-v2.6-flash","qwen3.6","qwen3.8-flash"],
465
505
  notes: [
466
- "non-chat: \"qwen-image-2.1\" excluded from the chat catalog (image-generation model (text→image; output modality image) documented in https://nan.builders/docs/models and https://nan.builders/openapi.json (checked 2026-09-29) — not a chat model, out of the static chat catalog (models.dev reports limit.output 0))",
467
506
  "live-only: \"glm5.3\" kept out of the static catalog (premium-tier model (models.dev now documents it with 1M context / 131,072 max output; NaN docs https://nan.builders/docs/models + https://nan.builders/openapi.json, checked 2026-09-13) kept live-only so a non-premium key never sees a model it cannot call when the live /models fetch is unavailable; premium keys still get it via the /models refresh with conservative placeholder limits)",
507
+ "non-chat: \"qwen-image-2.1\" excluded from the chat catalog (image-generation model (text→image; output modality image) documented in https://nan.builders/docs/models and https://nan.builders/openapi.json (checked 2026-09-29) — not a chat model, out of the static chat catalog (models.dev reports limit.output 0))",
468
508
  "provider-removed: \"glm5.2\" excluded from the catalog (removed by NaN (2026-09-05); absent from the official chat model list in https://nan.builders/openapi.json and https://nan.builders/docs/models (checked 2026-09-07) while models.dev provider nan still listed it — excluded so regeneration does not resurrect it)",
469
509
  "provider-removed: \"mimo-v2.5\" excluded from the catalog (removed by NaN (checked 2026-09-29): zero mentions in https://nan.builders/docs/models and in the model param description of https://nan.builders/openapi.json, and models.dev provider nan dropped it as well — superseded by mimo-v2.6-flash; excluded so regeneration does not resurrect it)",
470
510
  "non-chat: \"qwen3-embedding\" excluded from the chat catalog (embedding endpoint (https://nan.builders/docs/models, checked 2026-10-01) — not a chat model)",
@@ -0,0 +1,145 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Prepare an SDK update PR for the packages monitored by
4
+ * scripts/check-pi-sdk-versions.mjs: bump their devDependencies in
5
+ * package.json and emit the branch/PR metadata the
6
+ * `.github/workflows/check-pi-sdk-versions.yml` workflow needs to open the PR.
7
+ *
8
+ * This script ONLY edits package.json. Installing, testing, typechecking, the
9
+ * type-surface diff, git and `gh pr create` stay in the workflow so a failure
10
+ * anywhere aborts the PR.
11
+ *
12
+ * Usage:
13
+ * node scripts/prepare-sdk-update-pr.mjs --body-file /tmp/pr-body.md
14
+ *
15
+ * Output (stdout, single JSON line):
16
+ * {"updates":false}
17
+ * {"updates":true,"branch":"chore/pi-sdk-1.3.0","title":"...","bodyFile":"...",
18
+ * "bumps":[{"name":"@earendil-works/pi-ai","from":"1.2.0","to":"1.3.0"}]}
19
+ *
20
+ * Exit codes: 0 = nothing to do or prepared; 2 = unexpected failure.
21
+ */
22
+
23
+ import https from "node:https";
24
+ import { readFileSync, writeFileSync } from "node:fs";
25
+ import { fileURLToPath } from "node:url";
26
+
27
+ const SDK_PACKAGES = ["@earendil-works/pi-ai", "@earendil-works/pi-coding-agent"];
28
+
29
+ function npmLatest(packageName) {
30
+ return new Promise((resolve, reject) => {
31
+ const req = https.get(
32
+ `https://registry.npmjs.org/${encodeURIComponent(packageName)}`,
33
+ { headers: { accept: "application/json" } },
34
+ (res) => {
35
+ if (res.statusCode !== 200) {
36
+ reject(new Error(`npm registry returned ${res.statusCode} for ${packageName}`));
37
+ return;
38
+ }
39
+ let data = "";
40
+ res.on("data", (chunk) => (data += chunk));
41
+ res.on("end", () => {
42
+ const latest = JSON.parse(data)["dist-tags"]?.["latest"];
43
+ if (!latest) reject(new Error(`No "latest" dist-tag for ${packageName}`));
44
+ else resolve(latest);
45
+ });
46
+ },
47
+ );
48
+ req.on("error", reject);
49
+ req.setTimeout(15_000, () => {
50
+ req.destroy();
51
+ reject(new Error(`Timeout fetching ${packageName} from npm`));
52
+ });
53
+ });
54
+ }
55
+
56
+ async function main() {
57
+ const bodyFileArg = process.argv.indexOf("--body-file");
58
+ const bodyFile =
59
+ bodyFileArg !== -1 ? process.argv[bodyFileArg + 1] : "/tmp/sdk-update-pr-body.md";
60
+
61
+ const packageUrl = new URL("../package.json", import.meta.url);
62
+ const raw = readFileSync(packageUrl, "utf-8");
63
+ const pkg = JSON.parse(raw);
64
+
65
+ const bumps = [];
66
+ for (const name of SDK_PACKAGES) {
67
+ const from = pkg.devDependencies?.[name];
68
+ if (!from) throw new Error(`${name} is not a devDependency of this package`);
69
+ const to = await npmLatest(name);
70
+ if (to !== from) bumps.push({ name, from, to });
71
+ }
72
+
73
+ if (bumps.length === 0) {
74
+ console.log(JSON.stringify({ updates: false }));
75
+ return;
76
+ }
77
+
78
+ // Bump via exact-string replacement so the rest of package.json (ordering,
79
+ // indentation, other fields) is untouched.
80
+ let updated = raw;
81
+ for (const bump of bumps) {
82
+ const needle = `"${bump.name}": "${bump.from}"`;
83
+ if (!updated.includes(needle)) {
84
+ throw new Error(`Could not locate ${needle} in package.json to bump it`);
85
+ }
86
+ updated = updated.replace(needle, `"${bump.name}": "${bump.to}"`);
87
+ }
88
+ writeFileSync(packageUrl, updated);
89
+
90
+ const versionTag = bumps.map((b) => b.to).join("-");
91
+ const branch = `chore/pi-sdk-${versionTag}`;
92
+ const title = `chore: bump PI SDK to ${bumps.map((b) => `${b.name.split("/")[1]} ${b.to}`).join(" / ")}`;
93
+ const peer = pkg.peerDependencies ?? {};
94
+
95
+ const body = `## PI SDK update (automated)
96
+
97
+ Prepared from the weekly \`check-pi-sdk-versions\` run. Resolves the \`sdk-monitor\` issue
98
+ for this cycle. **A human must review the upstream changelog before merging** — a minor
99
+ pi release can change provider-relevant behavior (see \`AGENTS.md\` "Verified API facts").
100
+
101
+ ### Version bumps
102
+
103
+ | Package | From | To | Peer range |
104
+ | --- | --- | --- | --- |
105
+ ${bumps.map((b) => `| \`${b.name}\` | ${b.from} | **${b.to}** | \`${peer[b.name] ?? "n/a"}\` |`).join("\n")}
106
+
107
+ ### Review checklist
108
+
109
+ - [ ] Upstream release notes reviewed (https://pi.dev/changelog)
110
+ - [ ] \`bun test\` + \`bun run typecheck\` green (executed by CI before this PR was opened)
111
+ - [ ] Type-surface diff (below) contains no removals this package uses
112
+ - [ ] Version policy applied: package MAJOR.MINOR realigns with the pi release line
113
+ (\`package.json\` version bump included in this PR when the pi MINOR moved)
114
+
115
+ The results of the two sections below were produced by CI while preparing this PR.
116
+
117
+ ## Verification
118
+
119
+ <!-- VERIFICATION -->
120
+
121
+ ## Type-surface diff (previous → new)
122
+
123
+ <details><summary>Click to expand</summary>
124
+
125
+ <!-- SURFACE_DIFF -->
126
+
127
+ </details>
128
+ `;
129
+
130
+ writeFileSync(bodyFile, body);
131
+ console.log(
132
+ JSON.stringify({
133
+ updates: true,
134
+ branch,
135
+ title,
136
+ bodyFile,
137
+ bumps,
138
+ }),
139
+ );
140
+ }
141
+
142
+ main().catch((err) => {
143
+ console.error("Fatal:", err.message);
144
+ process.exit(2);
145
+ });
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Provider attribution: an identity header on every outgoing request that
3
+ * says this package (and its exact version) is serving the models.
4
+ *
5
+ * pi-ai merges `model.headers` over its own identity headers in
6
+ * `createClient` (`{ ...getIdentityHeaders(model, identity), ...model.headers }`,
7
+ * the same shape since pi-ai 0.99.1), so attaching the header to every model
8
+ * entry — generated catalog, live merge, unknown-id placeholders, live-only
9
+ * documented entries, the stale-catalog overlay and image models — reaches
10
+ * the gateway on every supported host without touching the request payload
11
+ * or pi's own `User-Agent`.
12
+ *
13
+ * The header is additive: a dedicated `X-Pi-Provider` value, never a rewrite
14
+ * of headers pi-ai or the host already sends. If the package version cannot
15
+ * be resolved (e.g. a virtual-module bundle with no readable package.json),
16
+ * the header is simply omitted — attribution must never break a request.
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).
27
+ */
28
+
29
+ import { readFileSync } from "node:fs";
30
+
31
+ /** Header added to every model registered by this package's providers. */
32
+ export const PROVIDER_ATTRIBUTION_HEADER = "X-Pi-Provider";
33
+
34
+ /** Package identity used as the header value prefix (npm scope without the `@`). */
35
+ const PACKAGE_IDENTITY = "gtrabanco/pi-nan-provider";
36
+
37
+ const ATTRIBUTION_CACHE_KEY = Symbol.for("gtrabanco.pi-nan-provider.attribution");
38
+
39
+ interface AttributionCache {
40
+ value?: string;
41
+ resolved: boolean;
42
+ }
43
+
44
+ /** Cache on globalThis so multi-load (extension + tests + host) resolves once. */
45
+ function cache(): AttributionCache {
46
+ const store = globalThis as typeof globalThis & Record<symbol, unknown>;
47
+ if (!store[ATTRIBUTION_CACHE_KEY]) store[ATTRIBUTION_CACHE_KEY] = { resolved: false };
48
+ return store[ATTRIBUTION_CACHE_KEY] as AttributionCache;
49
+ }
50
+
51
+ /**
52
+ * The attribution header value: `gtrabanco/pi-nan-provider@<version>`, or
53
+ * `undefined` when this package's version cannot be read (header omitted).
54
+ */
55
+ export function providerAttributionHeaderValue(): string | undefined {
56
+ const state = cache();
57
+ if (state.resolved) return state.value;
58
+ state.resolved = true;
59
+ try {
60
+ const pkg = JSON.parse(
61
+ readFileSync(new URL("../package.json", import.meta.url), "utf-8"),
62
+ ) as { version?: unknown };
63
+ if (typeof pkg.version === "string" && pkg.version.length > 0) {
64
+ state.value = `${PACKAGE_IDENTITY}@${pkg.version}`;
65
+ }
66
+ } catch {
67
+ // Unreadable package.json (virtual-module bundle, atypical loader):
68
+ // attribution is best-effort — omit the header, never fail a request.
69
+ }
70
+ return state.value;
71
+ }
72
+
73
+ type AttributionGate = () => boolean;
74
+
75
+ let gate: AttributionGate = () => true;
76
+
77
+ /**
78
+ * Read the current enablement. Overridable via {@link configureProviderAttribution};
79
+ * the default (no gate configured) is enabled. A throwing gate — e.g. a host
80
+ * without `getSettings()` — falls back to enabled (pi's shipped default).
81
+ */
82
+ export function providerAttributionEnabled(): boolean {
83
+ try {
84
+ return gate();
85
+ } catch {
86
+ return true;
87
+ }
88
+ }
89
+
90
+ /**
91
+ * 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.
94
+ */
95
+ export function configureProviderAttribution(isEnabled: AttributionGate): void {
96
+ gate = isEnabled;
97
+ }
98
+
99
+ /**
100
+ * Attach the attribution header to a model (or any object carrying
101
+ * `headers`), preserving existing headers. Returns the same object when the
102
+ * version is unavailable or the privacy gate is disabled. Our own header wins
103
+ * over any pre-existing value.
104
+ */
105
+ export function withProviderAttribution<T extends { headers?: Record<string, string> }>(model: T): T {
106
+ const value = providerAttributionEnabled() ? providerAttributionHeaderValue() : undefined;
107
+ if (!value) return model;
108
+ return { ...model, headers: { ...model.headers, [PROVIDER_ATTRIBUTION_HEADER]: value } } as T;
109
+ }
110
+
111
+ /**
112
+ * Remove the attribution header from a model that already carries it (factory-
113
+ * time entries baked the header when the gate was enabled). Used on read paths
114
+ * so a mid-session gate flip takes effect without rebuilding the catalog.
115
+ */
116
+ export function stripProviderAttribution<T extends { headers?: Record<string, string> }>(model: T): T {
117
+ if (!model.headers || !(PROVIDER_ATTRIBUTION_HEADER in model.headers)) return model;
118
+ const { [PROVIDER_ATTRIBUTION_HEADER]: _drop, ...rest } = model.headers;
119
+ return { ...model, headers: rest } as T;
120
+ }
@@ -2,18 +2,16 @@
2
2
  * NaN-aware context-overflow classification.
3
3
  *
4
4
  * Root cause (pi-ai, verified on 0.87.1): when history is replayed
5
- * into a DIFFERENT model, `transformMessages` downgrades every non-redacted
6
- * `thinking` block to plain `text` verbatim, with no size bound — and nothing
7
- * bounds the SUM across messages. Switching from a 1M-context model
8
- * (`glm5.3-flash`, `deepseek-v4-flash`) to a 262K one (`qwen3.6`) can therefore
9
- * push the request past the destination window (see
10
- * `src/cross-model-thinking-guard.ts` for the primary mitigation, which drops
11
- * that replayed reasoning before pi-ai converts it).
5
+ * into a DIFFERENT model, `transformMessages` downgraded every non-redacted
6
+ * `thinking` block to plain `text` verbatim, with no size bound. pi-ai 1.3.0
7
+ * landed the upstream fix (`if (!isSameModel) return []`: the blocks are now
8
+ * dropped on a model switch) and this package's peer floor is `>=1.3.0`, so
9
+ * the extension-side guard that used to mitigate it was REMOVED in package
10
+ * 1.4.0.
12
11
  *
13
- * When the request still overflows — the guard is disabled
14
- * (`NAN_THINKING_GUARD=0`), the trace is not a `thinking` block (large tool
15
- * outputs, images), or the destination window is simply smaller — NaN's LiteLLM
16
- * gateway answers the generic
12
+ * The request can still overflow — the inflation is not a `thinking` block
13
+ * (large tool outputs, images), or the destination window is simply smaller —
14
+ * and NaN's LiteLLM gateway answers the generic
17
15
  * HTTP 400 `Invalid request. Check your request parameters.`
18
16
  * instead of naming the context overflow. pi's auto-compaction keys on pi-ai's
19
17
  * `isContextOverflow()`, whose documented patterns do NOT match that text, so
@@ -25,6 +25,7 @@
25
25
 
26
26
  import type { ImageModel, Model } from "@earendil-works/pi-ai";
27
27
  import type { ThinkingLevelMap, OpenAICompletionsCompat } from "@earendil-works/pi-ai";
28
+ import { withProviderAttribution } from "./attribution.ts";
28
29
  import { GENERATED_CATALOG_META, NAN_GENERATED_MODELS } from "../scripts/models.generated.ts";
29
30
 
30
31
  export { NAN_GENERATED_MODELS };
@@ -155,7 +156,7 @@ export interface CatalogSource {
155
156
 
156
157
  /** Convert a generated catalog entry into a pi-ai Model for the given provider. */
157
158
  export function toModel(entry: GeneratedModelEntry, source: CatalogSource): Model<"openai-completions"> {
158
- return {
159
+ const model: Model<"openai-completions"> = {
159
160
  id: entry.id,
160
161
  name: entry.name,
161
162
  api: NAN_COMPAT_API,
@@ -169,6 +170,7 @@ export function toModel(entry: GeneratedModelEntry, source: CatalogSource): Mode
169
170
  ...(entry.compat ? { compat: { ...entry.compat } } : {}),
170
171
  ...(entry.thinkingLevelMap ? { thinkingLevelMap: { ...entry.thinkingLevelMap } } : {}),
171
172
  };
173
+ return withProviderAttribution(model);
172
174
  }
173
175
 
174
176
  /** The generated fallback catalog as pi-ai Models for the given provider. */
@@ -296,7 +298,7 @@ export function mergeLiveWithGenerated(
296
298
  // silent (issue #7, measured 2026-09-16): the sanitizer forwards the
297
299
  // field and pi reports real token counts. A model can still opt out
298
300
  // with a models.json override of false.
299
- models.push({
301
+ const placeholder: Model<"openai-completions"> = {
300
302
  id,
301
303
  name: id,
302
304
  api: NAN_COMPAT_API,
@@ -308,7 +310,8 @@ export function mergeLiveWithGenerated(
308
310
  contextWindow: UNKNOWN_MODEL_LIMITS.contextWindow,
309
311
  maxTokens: UNKNOWN_MODEL_LIMITS.maxTokens,
310
312
  compat: { supportsFinishReason: true, supportsUsageInStreaming: true },
311
- });
313
+ };
314
+ models.push(withProviderAttribution(placeholder));
312
315
  unknown.push(id);
313
316
  }
314
317
  }
package/src/images.ts CHANGED
@@ -29,6 +29,7 @@ import type {
29
29
  ImageModel,
30
30
  ProviderImages,
31
31
  } from "@earendil-works/pi-ai";
32
+ import { withProviderAttribution } from "./attribution.ts";
32
33
 
33
34
  // ── Custom API id ──────────────────────────────────────────────────────────
34
35
 
@@ -121,8 +122,8 @@ interface ImageCatalogSource {
121
122
  export function baselineImageModels(
122
123
  source: ImageCatalogSource,
123
124
  ): ImageModel<typeof NAN_IMAGE_API>[] {
124
- return NAN_IMAGE_MODELS.map(
125
- (model): ImageModel<typeof NAN_IMAGE_API> => ({
125
+ return NAN_IMAGE_MODELS.map((model) => {
126
+ const entry: ImageModel<typeof NAN_IMAGE_API> = {
126
127
  id: model.id,
127
128
  name: model.name,
128
129
  type: "image",
@@ -132,8 +133,9 @@ export function baselineImageModels(
132
133
  input: [...model.input],
133
134
  output: [...model.output],
134
135
  cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 },
135
- }),
136
- );
136
+ };
137
+ return withProviderAttribution(entry);
138
+ });
137
139
  }
138
140
 
139
141
  // ── API implementation ─────────────────────────────────────────────────────
package/src/index.ts CHANGED
@@ -25,14 +25,11 @@
25
25
  * Exposure: `direct` — tools are declared to the model like built-ins.
26
26
  */
27
27
 
28
- import type { ContextEvent, ExtensionAPI, ProviderConfig } from "@earendil-works/pi-coding-agent";
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
31
  import { registerNanMcpCommand } from "./commands.ts";
31
32
  import { registerNanUsageCommand } from "./usage.ts";
32
- import {
33
- crossModelThinkingGuardEnabled,
34
- stripCrossModelThinking,
35
- } from "./cross-model-thinking-guard.ts";
36
33
  import { baselineModels } from "./fetch-models.ts";
37
34
  import { createNanCompatibleProvider, type OpenAICompatibleProviderConfig } from "./provider-factory.ts";
38
35
  import { PROVIDERS } from "./providers.ts";
@@ -143,35 +140,16 @@ async function registerMcpServersNative(pi: ExtensionAPI): Promise<void> {
143
140
 
144
141
  // ── Extension entrypoint ─────────────────────────────────────────────────
145
142
 
146
- /**
147
- * Drop the reasoning pi-ai replays across a model switch.
148
- *
149
- * pi-ai's `transformMessages` downgrades a previous model's `thinking` blocks
150
- * to plain text with no size bound (verified on 0.87.1), and nothing
151
- * bounds the sum across messages — measured at 30–60% of the whole context on
152
- * real sessions. Switching from a 1M-context model to a 262K one (`qwen3.6`)
153
- * then overflows the window, and NaN's gateway answers a generic
154
- * `400 Invalid request. Check your request parameters.` This hook runs before
155
- * pi-ai converts the blocks, so removing the cross-model reasoning here keeps
156
- * the replayed context small. Answers and tool results are untouched. See
157
- * src/cross-model-thinking-guard.ts.
158
- *
159
- * Scope: only requests targeting this package's providers are touched, and
160
- * only messages from a DIFFERENT model — same-model reasoning is never removed.
161
- */
162
- export function registerCrossModelThinkingGuard(pi: ExtensionAPI): void {
163
- if (typeof pi.on !== "function") return; // old pi without the context hook
164
- const providerIds = new Set(PROVIDERS.map((provider) => provider.id));
165
- pi.on("context", (event, ctx) => {
166
- if (!crossModelThinkingGuardEnabled()) return;
167
- const guarded = stripCrossModelThinking(event.messages, ctx.model, { providerIds });
168
- if (guarded === event.messages) return;
169
- return { messages: guarded as ContextEvent["messages"] };
170
- });
171
- }
172
-
173
143
  export default async function nanProviderExtension(pi: ExtensionAPI): Promise<void> {
174
- registerCrossModelThinkingGuard(pi);
144
+ // Attribution privacy gate: the X-Pi-Provider header identifies this
145
+ // package, so it follows pi's telemetry setting. Evaluated fresh on every
146
+ // read (model reads, /nan-usage fetch) so a mid-session change applies
147
+ // without a restart. A host without getSettings() keeps the shipped
148
+ // default (enabled) — handled inside the attribution module.
149
+ configureProviderAttribution(() => {
150
+ const settings = pi.getSettings() as { enableInstallTelemetry?: boolean } | undefined;
151
+ return settings?.enableInstallTelemetry !== false;
152
+ });
175
153
  // Replaces pi's cryptic "no loaded extension connects MCP servers" error with
176
154
  // actionable guidance when the host loads no built-in `mcp` extension (PI WEB).
177
155
  registerMcpHostGuard(pi);
@@ -36,6 +36,7 @@ import type {
36
36
  ProviderStreams,
37
37
  RefreshModelsContext,
38
38
  } from "@earendil-works/pi-ai";
39
+ import { providerAttributionEnabled, stripProviderAttribution } from "./attribution.ts";
39
40
  import { withContextOverflowClassification } from "./context-overflow-classifier.ts";
40
41
  import { withReasoningOnlyStreamGuard } from "./reasoning-only-stream-guard.ts";
41
42
  import { NAN_IMAGE_API, baselineImageModels, createNanImagesApi } from "./images.ts";
@@ -174,16 +175,22 @@ function withStaleCatalogOverlay(
174
175
  provider: Provider<"openai-completions">,
175
176
  overlayMap: Map<string, OverlayEntry>,
176
177
  ): Provider<"openai-completions"> {
178
+ // Attribution is evaluated at READ time, not only factory time: entries
179
+ // built while the privacy gate was enabled carry the baked header, and a
180
+ // mid-session `enableInstallTelemetry: false` must strip it on the next
181
+ // read without rebuilding the catalog.
182
+ const policy = <T extends { headers?: Record<string, string> }>(m: T): T =>
183
+ providerAttributionEnabled() ? m : stripProviderAttribution(m);
177
184
  return {
178
185
  ...provider,
179
186
  getModels: () => {
180
187
  const models = provider.getModels();
181
- return models.map((m) => applyOverlay(m, overlayMap)) as typeof models;
188
+ return models.map((m) => policy(applyOverlay(m, overlayMap))) as typeof models;
182
189
  },
183
190
  getAllModels: () => {
184
191
  const all = provider.getAllModels?.();
185
192
  if (!all) return [];
186
- return all.map((m) => applyOverlay(m, overlayMap));
193
+ return all.map((m) => policy(applyOverlay(m, overlayMap)));
187
194
  },
188
195
  };
189
196
  }
package/src/usage.ts CHANGED
@@ -25,6 +25,11 @@
25
25
  */
26
26
 
27
27
  import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
28
+ import {
29
+ PROVIDER_ATTRIBUTION_HEADER,
30
+ providerAttributionEnabled,
31
+ providerAttributionHeaderValue,
32
+ } from "./attribution.ts";
28
33
  import { NAN_API_KEY_ENV, resolveNanApiKey, tryResolveNanApiKeyViaRegistry } from "./mcp/api-key.ts";
29
34
 
30
35
  // ── Known quota limits per model (from NaN docs) ──────────────────────────
@@ -382,10 +387,15 @@ export async function fetchUsageReport(options: FetchUsageOptions): Promise<Fetc
382
387
 
383
388
  const controller = new AbortController();
384
389
  const timeout = setTimeout(() => controller.abort(), timeoutMs);
390
+ const attribution = providerAttributionEnabled() ? providerAttributionHeaderValue() : undefined;
385
391
  try {
386
392
  const response = await fetchImpl(url, {
387
393
  method: "GET",
388
- headers: { Authorization: `Bearer ${apiKey}`, Accept: "application/json" },
394
+ headers: {
395
+ Authorization: `Bearer ${apiKey}`,
396
+ Accept: "application/json",
397
+ ...(attribution ? { [PROVIDER_ATTRIBUTION_HEADER]: attribution } : {}),
398
+ },
389
399
  cache: "no-store",
390
400
  signal: controller.signal,
391
401
  });
@@ -1,122 +0,0 @@
1
- /**
2
- * Cross-model thinking guard.
3
- *
4
- * Root cause this guards against (pi-ai, verified on 0.87.1): when
5
- * history is replayed into a DIFFERENT model, `transformMessages` downgrades
6
- * every non-redacted `thinking` block to a plain `text` block verbatim
7
- * (`packages/ai/src/api/transform-messages.ts`), and `openai-completions`
8
- * serializes that into the assistant `content` string. Nothing bounds
9
- * `block.thinking`, and nothing bounds the SUM across messages.
10
- *
11
- * Measured on real sessions: replayed reasoning is 30–60% of the whole context
12
- * (e.g. 356,723 of 903,464 chars in one session; 349,882 of 749,525 in another).
13
- * Switching from a 1M-context model (glm5.3-flash, deepseek-v4-flash) to a
14
- * 262K-context one (`qwen3.6`) then overflows the window, and NaN's gateway
15
- * answers a generic `400 Invalid request. Check your request parameters.`
16
- *
17
- * A per-block cap was tried first and is NOT enough: many medium blocks sum to
18
- * hundreds of thousands of tokens. This guard therefore DROPS every replayed
19
- * cross-model `thinking` block outright — it is the reasoning trace that
20
- * pi-ai would have replayed as plain text, not the model's answers or tool
21
- * results, so qwen can still answer questions about what glm/deepseek did.
22
- * Same-model reasoning is never touched (signatures and continuity depend on
23
- * it), and the guard only acts on requests targeting this package's providers.
24
- *
25
- * The extension runs in pi's `context` hook, which fires BEFORE pi-ai's
26
- * `transformMessages` (pi-agent-core `transformContext` → `convertToLlm` →
27
- * provider stream). It therefore sees the original `thinking` blocks and can
28
- * remove them before they become text.
29
- *
30
- * This is a bounded mitigation, not the fix: the unbounded conversion (and pi
31
- * not re-checking the context size on a model switch) belongs upstream. See
32
- * https://github.com/gtrabanco/pi-nan-provider/issues/3.
33
- */
34
-
35
- /** Env var that opts out of the guard (`0`, `false`, `no` or `off`). Default: enabled. */
36
- export const NAN_THINKING_GUARD_ENV = "NAN_THINKING_GUARD";
37
-
38
- export interface CrossModelThinkingGuardOptions {
39
- /** Provider ids this guard applies to (the caller's registered providers). */
40
- providerIds: ReadonlySet<string>;
41
- }
42
-
43
- interface GuardTarget {
44
- provider?: string;
45
- api?: string;
46
- id?: string;
47
- }
48
-
49
- interface ThinkingBlock {
50
- type?: string;
51
- [k: string]: unknown;
52
- }
53
-
54
- interface GuardMessage {
55
- role?: string;
56
- provider?: string;
57
- api?: string;
58
- model?: string;
59
- content?: unknown;
60
- }
61
-
62
- /** Explicit opt-out only: anything other than a known falsy value keeps the guard on. */
63
- export function crossModelThinkingGuardEnabled(env: NodeJS.ProcessEnv = process.env): boolean {
64
- const value = env[NAN_THINKING_GUARD_ENV]?.trim().toLowerCase();
65
- return value !== "0" && value !== "false" && value !== "no" && value !== "off";
66
- }
67
-
68
- /**
69
- * API id pi 0.99 assigns to virtual catalog entries (`core/virtual-models.js`,
70
- * `VIRTUAL_MODEL_API`). A virtual selection routes each request to a physical
71
- * model; the physical target is not exposed to the `context` hook, so the guard
72
- * cannot tell which physical model will answer.
73
- */
74
- const VIRTUAL_MODEL_API = "pi-virtual";
75
-
76
- function isGuardMessage(value: unknown): value is GuardMessage {
77
- return typeof value === "object" && value !== null;
78
- }
79
-
80
- function isThinkingBlock(value: unknown): value is ThinkingBlock {
81
- return typeof value === "object" && value !== null && (value as ThinkingBlock).type === "thinking";
82
- }
83
-
84
- /**
85
- * Remove every `thinking` block from assistant messages produced by a model
86
- * other than the target. Returns the SAME array reference when nothing changed,
87
- * so callers can skip cloning on the common path. Never mutates the input.
88
- */
89
- export function stripCrossModelThinking<T>(
90
- messages: readonly T[],
91
- target: GuardTarget | undefined,
92
- options: CrossModelThinkingGuardOptions,
93
- ): readonly T[] {
94
- if (!target?.provider || !options.providerIds.has(target.provider)) return messages;
95
-
96
- // Virtual selection (pi 0.99): `ctx.model` is the selectable virtual entry
97
- // (api "pi-virtual"), not the physical model the router picks for this
98
- // request. Its api/id never match a physical assistant message, so the
99
- // same-model check below would strip reasoning on EVERY continuation —
100
- // including when the router keeps the same physical model — losing the
101
- // prompt cache and thinking continuity the guard promises to preserve.
102
- // The routed physical model is not available here, so skip virtual
103
- // selections entirely; cross-model trimming is the router's concern there.
104
- if (target.api === VIRTUAL_MODEL_API) return messages;
105
-
106
- let changed = false;
107
-
108
- const next = messages.map((raw) => {
109
- if (!isGuardMessage(raw) || raw.role !== "assistant" || !Array.isArray(raw.content)) return raw;
110
-
111
- // Same-model replay keeps reasoning intact: signatures and continuity depend on it.
112
- const isSameModel = raw.provider === target.provider && raw.api === target.api && raw.model === target.id;
113
- if (isSameModel) return raw;
114
-
115
- const content = (raw.content as unknown[]).filter((block) => !isThinkingBlock(block));
116
- if (content.length === (raw.content as unknown[]).length) return raw;
117
- changed = true;
118
- return { ...raw, content };
119
- });
120
-
121
- return changed ? next : messages;
122
- }