@gtrabanco/pi-nan-provider 1.6.3 → 1.7.2
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 +109 -10
- package/README.es.md +18 -7
- package/README.md +10 -7
- package/package.json +3 -3
- package/scripts/models.generated.ts +2 -2
- package/src/attribution.ts +48 -11
- package/src/cache-anomaly.ts +5 -2
- package/src/http-attempts.ts +9 -5
- package/src/images.ts +147 -4
- package/src/index.ts +10 -9
- package/src/openai-compat-sanitizer.ts +159 -33
- package/src/provider-factory.ts +3 -2
package/AGENTS.md
CHANGED
|
@@ -350,6 +350,31 @@ Since 1.0.0 the package version **aligns its MAJOR.MINOR with the pi release lin
|
|
|
350
350
|
only when estimated over the window). Wired in `src/provider-factory.ts` after
|
|
351
351
|
the sanitizer. Regression tests: `test/issue-3-model-switch-overflow.test.ts`,
|
|
352
352
|
`test/context-overflow-classifier.test.ts`; issue #3.
|
|
353
|
+
- **The #52 wedge is a payload defect, not an under-counting estimator** (verified
|
|
354
|
+
2026-11-26 against the archived transcript and attempt log). A
|
|
355
|
+
`mimo-v2.6-flash` session sat on the opaque 400 for two hours; the turn before
|
|
356
|
+
the first 400 reports `input` 2,075 + `cacheRead` 559,232 = **561,307 prompt
|
|
357
|
+
tokens** against a **1,048,576** window, while `estimateRequestTokens` answers
|
|
358
|
+
625,484 for the same 2,170,428 payload bytes. Real ratio = 3.867 bytes/token,
|
|
359
|
+
so the 3.47 divisor **over**-estimates by 11.4 % — the issue's "systematically
|
|
360
|
+
underestimated" is backwards, and its ÷2.0 proposal would fabricate 1,085,214
|
|
361
|
+
tokens for a request at 53.5 % of the window (a forced compaction plus a false
|
|
362
|
+
cause on the error text). The real cause: the gateway streamed
|
|
363
|
+
`{"type":"toolCall","id":"","name":"","arguments":{}}`, pi persisted pi's
|
|
364
|
+
`"Tool not found"` result with `toolCallId: ""`, and pi-ai copies both ids
|
|
365
|
+
verbatim onto the wire (`api/openai-completions.js:1015-1022` for
|
|
366
|
+
`tool_calls`, `:1073-1077` for `role:"tool"`) — so every replay of the history
|
|
367
|
+
was rejected until a compaction removed the pair. `src/openai-compat-sanitizer.ts`
|
|
368
|
+
now reconciles announced calls with their results in one ordered pass
|
|
369
|
+
(`reconcileToolCalls`): empty id ← the answering `tool_call_id`, else a
|
|
370
|
+
deterministic `call_<name>_<messageIndex>_<callIndex>` fallback (never a
|
|
371
|
+
counter — a request-varying id invalidates the prefix cache); empty
|
|
372
|
+
`function.name` → `function`; empty `tool_call_id` ← the announced call; a
|
|
373
|
+
result with nothing to bind to is dropped. Real ids, `type !== "function"`
|
|
374
|
+
grammar calls and unrelated fields are untouched. The overflow thresholds are
|
|
375
|
+
unchanged on purpose. Regression tests: `test/issue-52-empty-tool-call-ids.test.ts`
|
|
376
|
+
(the repair, the deterministic ids, the trailing invariants and the pinned
|
|
377
|
+
measurement); `test/openai-compat-sanitizer.test.ts` stays byte-identical.
|
|
353
378
|
- Relative imports inside this package use `.ts` extensions (pi's official
|
|
354
379
|
extension examples do the same; pi transpiles extension sources).
|
|
355
380
|
- pi 0.87 breaking changes NOT used by this package: `ContextEditEntry` added to
|
|
@@ -438,8 +463,77 @@ Since 1.0.0 the package version **aligns its MAJOR.MINOR with the pi release lin
|
|
|
438
463
|
`src/reasoning-only-stream-guard.ts` (issue #21) keys on that marker;
|
|
439
464
|
earlier comment/message text said "60,000 characters" and was corrected to
|
|
440
465
|
the documented figures.
|
|
441
|
-
- **pi 1.
|
|
442
|
-
baseline; devDependencies 1.
|
|
466
|
+
- **pi 1.7.0 / pi-ai 1.7.0 compat** (verified 2026-11-28, the current verified
|
|
467
|
+
baseline; devDependencies 1.6.0 → 1.7.0, package 1.6.4 → 1.7.0, peer range
|
|
468
|
+
unchanged at `^1.4.0` because only the image options are new and they are
|
|
469
|
+
read defensively). pi-ai `index.d.ts` only ADDS `PiImage*`/`PiDecision*` type
|
|
470
|
+
re-exports, `compat.d.ts` and `api/openai-completions.d.ts` are byte-identical
|
|
471
|
+
to 1.6.0, and every symbol this package imports still exists
|
|
472
|
+
(`getAgentDir`, `readStoredCredential`, `ProviderConfig`, both
|
|
473
|
+
`registerProvider` overloads, `registerMcpServer`/`unregisterMcpServer`;
|
|
474
|
+
MCP config types unchanged). What DID move:
|
|
475
|
+
- **Telemetry removed** (`/api/report-install`, `Settings.enableInstallTelemetry`,
|
|
476
|
+
`SettingsManager.get/setEnableInstallTelemetry()`, `PI_TELEMETRY`), and
|
|
477
|
+
`getClientIdentity(settingsManager)` became `getClientIdentity()` which always
|
|
478
|
+
sends `PI_ATTRIBUTION`. The attribution gate therefore no longer reads the
|
|
479
|
+
removed setting on 1.7: `src/attribution.ts` owns
|
|
480
|
+
`NAN_NO_ATTRIBUTION` (any of `1`/`true`/`yes`/`on` disables the header) and
|
|
481
|
+
still honors `enableInstallTelemetry: false` on pi 1.4–1.6 hosts
|
|
482
|
+
(`resolveProviderAttributionEnabled`). Without that change the old gate
|
|
483
|
+
silently became a permanent "enabled" on 1.7, re-identifying users who had
|
|
484
|
+
opted out.
|
|
485
|
+
- **`ImagesOptions` gained `aspectRatio` and `size`** (1.6.0 had neither), and
|
|
486
|
+
codemode 1.7 accepts `models.generateImages(model, ctx, { aspectRatio, size })`
|
|
487
|
+
— it validates that exact key set (so `n`/`seed`/`guidance` remain
|
|
488
|
+
extension-only) and forwards `{ ...options, signal }` into
|
|
489
|
+
`ProviderImages.generateImages`. NaN accepts only a `WxH` canvas (sides
|
|
490
|
+
divisible by 16, 256–1536, ratio 1:3–3:1; `auto` allowed), so
|
|
491
|
+
`src/images.ts` resolves `options.size` (validated) and
|
|
492
|
+
`NAN_ASPECT_RATIO_SIZES` (1:1, 16:9, 9:16, 4:3, 3:4, 3:2, 2:3) before falling
|
|
493
|
+
back to `metadata.size`; an unusable value fails locally instead of spending
|
|
494
|
+
one of the 100 monthly image requests on a guaranteed 400. "Divisible by 16"
|
|
495
|
+
is a grid, not a multiple test (package 1.7.1): `1024x1008` = 63 × 16 is a
|
|
496
|
+
valid canvas, so the check is `side % 16 === 0` and the range check is
|
|
497
|
+
separate — the pre-1.7.1 `side % 16 !== 0` only admitted multiples of 1024.
|
|
498
|
+
The maxTokens budget is an entry-point fact on pi-ai 1.7's
|
|
499
|
+
openai-completions path: the bare `stream()` feeds `options` straight into
|
|
500
|
+
`buildParams`, so an explicit `options.maxTokens` is sent verbatim and an
|
|
501
|
+
absent one sends no budget field at all, while `streamSimple()` — the
|
|
502
|
+
entry real sessions reach through `ModelRuntime.streamSimple` — runs
|
|
503
|
+
`buildBaseOptions`, whose budget is
|
|
504
|
+
`clampMaxTokensToContext(model, context, options?.maxTokens ??
|
|
505
|
+
model.maxTokens)`: the ceiling is always on the wire there, clamped to the
|
|
506
|
+
room left (pi-ai `api/simple-options.js:31-56`,
|
|
507
|
+
`api/openai-completions.js:457-462`). pi's agent loop sets no `maxTokens`
|
|
508
|
+
of its own, so what gets clamped is the catalog ceiling. Both entries are
|
|
509
|
+
pinned by `test/pi-ai-1-7-0-contract.test.ts` (the entry-point pin added
|
|
510
|
+
in 1.7.2: the earlier record denied the `buildBaseOptions` run the
|
|
511
|
+
`streamSimple` entry makes).
|
|
512
|
+
- **`onResponse` fires once per attempt, error responses included**
|
|
513
|
+
(`onErrorResponse` in `utils/provider-retry.js`, wired by
|
|
514
|
+
`api/openai-completions.js`); 1.6.0 called it only after the retry loop.
|
|
515
|
+
`src/cache-anomaly.ts` already overwrote `cf-ray` on every callback, so the
|
|
516
|
+
last (real) response owns it — pinned by `test/issue-35-cache-anomaly-capture.test.ts`.
|
|
517
|
+
The #49 tap stays necessary: the hook has no per-attempt start time, attempt
|
|
518
|
+
number or payload size.
|
|
519
|
+
- Reasoning replay metadata is now encoded in `thinkingSignature`
|
|
520
|
+
(`encodeThinkingSignature`: field/details/opaque) and decoding is backward
|
|
521
|
+
compatible — a 1.6.0 session's plain field name decodes to `kind: "field"`
|
|
522
|
+
and NaN keeps replaying `reasoning_content`, so nothing changed on the wire.
|
|
523
|
+
- Looked relevant, is not: `cost.imageOutput`/`Usage.imageOutput` (catalog cost
|
|
524
|
+
is pinned to 0, NaN bills credits), the new canonical `pi-image` API
|
|
525
|
+
(`POST <baseUrl>/image`; NaN has no such endpoint — `nan-images` stays),
|
|
526
|
+
`compat.supportsReasoningReplay` (read only by
|
|
527
|
+
`api/bedrock-converse-stream.js`), `--agent-dir` (the artifacts call
|
|
528
|
+
`getAgentDir()` per record, no module-load cache), and `models.js` merging the
|
|
529
|
+
dynamic store once per publish (`getModels()` hot path, #12311) — a dynamic
|
|
530
|
+
entry still REPLACES the baseline by id+type, so the #19 read-time overlay is
|
|
531
|
+
still required.
|
|
532
|
+
Regression tests: `test/pi-ai-1-7-0-contract.test.ts` (per-attempt
|
|
533
|
+
`onResponse`, legacy `thinkingSignature` replay), plus the image and
|
|
534
|
+
attribution groups. Issue #54.
|
|
535
|
+
- **pi 1.6.0 / pi-ai 1.6.0 compat** (verified 2026-11-21; devDependencies
|
|
536
|
+
1.5.1 → 1.6.0, package 1.5.8 → 1.6.0, peer range
|
|
443
537
|
unchanged at `^1.4.0` because nothing here needs 1.6.0). **No `src/` change:** pi-ai
|
|
444
538
|
`dist/index.d.ts`, `dist/compat.d.ts`, `dist/api/openai-completions.d.ts` and
|
|
445
539
|
pi-coding-agent `dist/index.d.ts` are byte-identical to 1.5.1, and a base-vs-change
|
|
@@ -500,10 +594,12 @@ Since 1.0.0 the package version **aligns its MAJOR.MINOR with the pi release lin
|
|
|
500
594
|
merges `model.headers` over identity headers on 0.99.1 and 1.4.0 alike),
|
|
501
595
|
covering baseline, live merge, placeholders, overlay, image models and the
|
|
502
596
|
`/nan-usage` fetch; omitted silently when the version is unreadable, and
|
|
503
|
-
GATED on pi's `enableInstallTelemetry`
|
|
504
|
-
identifies the package; gate evaluated live on
|
|
505
|
-
|
|
506
|
-
paths by the overlay wrappers
|
|
597
|
+
GATED on `NAN_NO_ATTRIBUTION` plus pi's legacy `enableInstallTelemetry`
|
|
598
|
+
setting (privacy: the header identifies the package; gate evaluated live on
|
|
599
|
+
every read, installed by the extension entrypoint via
|
|
600
|
+
`configureProviderAttribution`, stripped on read paths by the overlay wrappers
|
|
601
|
+
when disabled). See the 1.7.0 bullet for why the setting alone stopped being
|
|
602
|
+
enough.
|
|
507
603
|
- **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
|
|
508
604
|
`">=0.99.0 <2"`. The pi-ai 1.3.0 `compat.d.ts` and `api/openai-completions.d.ts`
|
|
509
605
|
surfaces are byte-identical to 1.2.0; `index.d.ts` only drops the
|
|
@@ -618,13 +714,16 @@ Since 1.0.0 the package version **aligns its MAJOR.MINOR with the pi release lin
|
|
|
618
714
|
reports); `errorMessage` maps to
|
|
619
715
|
`overflow|rate_limited|invalid_request|transport|other`.
|
|
620
716
|
|
|
621
|
-
- **HTTP attempt tap (issue #49, verified 2026-11-24 on pi-ai 1.6.0
|
|
717
|
+
- **HTTP attempt tap (issue #49, verified 2026-11-24 on pi-ai 1.6.0; hook
|
|
718
|
+
contract widened in 1.7.0):**
|
|
622
719
|
`CreateProviderOptions` has **no** `fetch` field — issue #49's claim that
|
|
623
720
|
"`createProvider` acepta el `fetch` en options" is wrong for the pinned
|
|
624
721
|
version. `fetch` is a `StreamOptions` field forwarded to the OpenAI client
|
|
625
722
|
(`dist/api/openai-completions.js:createClient`). `retryProviderRequest`
|
|
626
|
-
retries by re-invoking the same client with `maxRetries: 0
|
|
627
|
-
|
|
723
|
+
retries by re-invoking the same client with `maxRetries: 0`; on 1.6.0
|
|
724
|
+
`onResponse` fired only **after** that loop, so a rejected attempt never
|
|
725
|
+
reached it (1.7.0 reports failed attempts too, but still without per-attempt
|
|
726
|
+
timing, attempt number or payload size).
|
|
628
727
|
`src/http-attempts.ts` therefore wraps the provider api outermost
|
|
629
728
|
(`withHttpAttemptCapture`) and injects `StreamOptions.fetch` — the only tap
|
|
630
729
|
that sees every attempt, including a 429 that never produced a gateway `id`.
|
|
@@ -683,7 +782,7 @@ uno cite una versión o requisito que el otro no lleve.
|
|
|
683
782
|
5. **Cita el peer floor real, no la historia.** El peer range se actualiza con cada
|
|
684
783
|
release de pi: lee `package.json` peerDependencies, no AGENTS.md (que documenta
|
|
685
784
|
releases históricos y puede quedar obsoleto). Para este paquete: el floor es
|
|
686
|
-
`^1.4.0` (desde package 1.5.0), verificado contra pi 1.
|
|
785
|
+
`^1.4.0` (desde package 1.5.0), verificado contra pi 1.7.0 / pi-ai 1.7.0.
|
|
687
786
|
6. **Las cifras de catálogo van contra `scripts/models.generated.ts`, no contra AGENTS.md.**
|
|
688
787
|
AGENTS.md es documentación de releases y puede contener floor o ranges ya antiguos;
|
|
689
788
|
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
|
[](https://opensource.org/licenses/MIT)
|
|
4
|
-
[](https://github.com/gtrabanco/pi-nan-provider/releases)
|
|
5
5
|
[](https://cloud.nan.builders/r/7GK06FX8)
|
|
6
6
|
|
|
7
7
|
[NaN Builders](https://cloud.nan.builders/r/7GK06FX8) model provider + MCP nativo para [pi](https://github.com/earendil-works/pi).
|
|
@@ -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.
|
|
12
|
+
> **Requisitos:** pi **≥ 1.4.0** (rango peer `^1.4.0`). El paquete está verificado contra **pi 1.7.0 / pi-ai 1.7.0**; el floor del rango peer solo sube con los re-aligns de menor de pi.
|
|
13
13
|
|
|
14
14
|
## ✨ Funciones
|
|
15
15
|
|
|
@@ -18,14 +18,14 @@ Registra el proveedor `nan` vía `pi.registerProvider()` usando la API OpenAI-co
|
|
|
18
18
|
| **Catálogo de modelos en dos capas** | Fallback generado en build-time (pi arranca aunque no haya red) fusionado con la lista en vivo `GET /v1/models`; después `filterModels` oculta lo que tu clave no pueda usar. |
|
|
19
19
|
| **Overlay de catálogo en tiempo de lectura** | Los datos de capacidad se reaplican desde el catálogo generado en cada lectura de `getModels()` / `getAllModels()`, así que un `models-store.json` escrito por una versión anterior del paquete no puede eclipsarlos ([#19](https://github.com/gtrabanco/pi-nan-provider/issues/19)) ni volver a registrar ids no-chat como modelos de chat ([#32](https://github.com/gtrabanco/pi-nan-provider/issues/32)). La store decide *qué* ids existen; el catálogo generado decide *qué pueden hacer*. |
|
|
20
20
|
| **Guardia de endpoints no-chat** | `NON_CHAT_MODEL_IDS` mantiene los ids de embedding / rerank / TTS / STT / imagen / vídeo fuera del selector de chat de pi. |
|
|
21
|
-
| **Sanitizador de payloads estricto** | Cuerpo de `/chat/completions` reescrito para cumplir [el esquema publicado de NaN](https://nan.builders/openapi.json) antes de salir de pi, sea cual sea la versión de pi-ai incluida. |
|
|
21
|
+
| **Sanitizador de payloads estricto** | Cuerpo de `/chat/completions` reescrito para cumplir [el esquema publicado de NaN](https://nan.builders/openapi.json) antes de salir de pi, sea cual sea la versión de pi-ai incluida — incluidos los ids de tool call y de resultado, de modo que una tool call fantasma emitida con `id: ""` no puede bloquear la sesión ([#52](https://github.com/gtrabanco/pi-nan-provider/issues/52)). |
|
|
22
22
|
| **Rescate de desbordamiento de contexto** | El `400 Invalid request` genérico de NaN se reclasifica como desbordamiento cuando la petición se estima por encima de la ventana del modelo ([#3](https://github.com/gtrabanco/pi-nan-provider/issues/3)), y un `524` de caché fría por encima de `NAN_COLD_CACHE_CEILING_TOKENS` también ([#18](https://github.com/gtrabanco/pi-nan-provider/issues/18)) — pi compacta y reintenta en vez de quedarse colgado. |
|
|
23
23
|
| **Reintento de streams truncados** | `supportsFinishReason: true` convierte un stream SSE cerrado antes de `finish_reason` en un error reintentable en vez de un stall silencioso ([#2](https://github.com/gtrabanco/pi-nan-provider/issues/2)). |
|
|
24
24
|
| **Uso de tokens en streaming** | `stream_options.include_usage` activo por defecto, así que pi reporta recuentos reales de entrada/salida/razonamiento/caché ([#4](https://github.com/gtrabanco/pi-nan-provider/issues/4), [#7](https://github.com/gtrabanco/pi-nan-provider/issues/7)). |
|
|
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
|
|
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. |
|
|
@@ -83,6 +83,7 @@ El registro es síncrono a propósito: el catálogo de fallback está disponible
|
|
|
83
83
|
NaN responde HTTP 400 `Invalid request. Check your request parameters.` con cualquier cuerpo que no cumpla el esquema que publica en [nan.builders/openapi.json](https://nan.builders/openapi.json) — un esquema más estricto que lo que pi-ai emite en varios sitios. `src/openai-compat-sanitizer.ts` reescribe cada cuerpo saliente de `/chat/completions`, así que ninguna versión de pi-ai ni ninguna forma de conversación pueden producir una petición inválida:
|
|
84
84
|
|
|
85
85
|
- un array `content` de asistente que lleva una tool call se mueve al campo superior `tool_calls` (el `ContentPart` de NaN solo acepta `text` y `image_url`);
|
|
86
|
+
- tool call anunciada de tipo `function` lleva un `id` no vacío y un `function.name` no vacío — una llamada cuyo `type` no es `function` (una grammar tool) se deja intacta — y el `tool_call_id` de cada mensaje `tool` nombra la llamada que responde: una tool call fantasma emitida con `id: ""` se repara posicionalmente en lugar de bloquear la sesión con el 400 opaco de NaN ([#52](https://github.com/gtrabanco/pi-nan-provider/issues/52)). Los ids de relleno salen de la posición del mensaje, así que un historial reenviado mantiene caliente la caché de prefijo del gateway, y un id real nunca se reescribe;
|
|
86
87
|
- se elimina `reasoning_details`, y las partes de contenido desconocidas (p. ej. `thinking`) se pliegan en una parte `text` para que el razonamiento no se pierda en silencio;
|
|
87
88
|
- se eliminan los campos que el esquema de NaN no lista: `store` siempre, un array `tools` vacío siempre, y `stream_options` salvo que `compat.supportsUsageInStreaming` del modelo diga que el gateway lo reporta;
|
|
88
89
|
- `max_completion_tokens` se renombra a `max_tokens` (el campo documentado) salvo que `compat.maxTokensField` del modelo lo desactive ([#34](https://github.com/gtrabanco/pi-nan-provider/issues/34); `qwen3.8-max` es el único modelo del catálogo que lo desactiva tras la reversión del [#36](https://github.com/gtrabanco/pi-nan-provider/issues/36)).
|
|
@@ -93,13 +94,13 @@ Un hook `onPayload` suministrado por el llamante se conserva y se encadena despu
|
|
|
93
94
|
|
|
94
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.
|
|
95
96
|
|
|
96
|
-
La cabecera **
|
|
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.
|
|
97
98
|
|
|
98
99
|
### 🧠 Seguridad al cambiar de modelo
|
|
99
100
|
|
|
100
101
|
Al cambiar de modelo, versiones antiguas de pi-ai reenviaban el razonamiento del modelo anterior como texto plano de asistente **sin límite de tamaño**, lo que podía desbordar la ventana de un modelo de 262K; NaN respondía con un `400 Invalid request. Check your request parameters.` genérico que parecía un bug del proveedor (seguimiento upstream: [pi-nan-provider#3](https://github.com/gtrabanco/pi-nan-provider/issues/3)). pi-ai 1.3.0 arregló esto upstream (`transformMessages` ahora descarta los bloques de thinking de otro modelo) y este paquete requiere **pi ≥ 1.4.0** (rango peer `^1.4.0`), así que el guard extension-side que lo mitigaba fue **eliminado en la versión 1.4.0 del paquete** — no hay que hacer nada, upstream lo gestiona.
|
|
101
102
|
|
|
102
|
-
Una petición puede seguir desbordando por méritos propios — tool outputs enormes, imágenes o una ventana de destino simplemente más pequeña que el contenido — y NaN responde con el mismo 400 genérico en lugar de nombrar el desbordamiento, mientras que la auto-compactación de pi no lo reconoce, así que la sesión se quedaría atascada en el techo. Por eso el proveedor **vuelve a comprobar el tamaño de la petición a la salida**: cuando llega ese 400 genérico para una petición estimada por encima de la ventana del modelo, el error se reescribe como un mensaje de context overflow que pi reconoce, de modo que compacta y reintenta en vez de bloquearse. Un 400 genérico en una petición dentro de la ventana no se toca, así que nunca se etiquetan mal errores no relacionados.
|
|
103
|
+
Una petición puede seguir desbordando por méritos propios — tool outputs enormes, imágenes o una ventana de destino simplemente más pequeña que el contenido — y NaN responde con el mismo 400 genérico en lugar de nombrar el desbordamiento, mientras que la auto-compactación de pi no lo reconoce, así que la sesión se quedaría atascada en el techo. Por eso el proveedor **vuelve a comprobar el tamaño de la petición a la salida**: cuando llega ese 400 genérico para una petición estimada por encima de la ventana del modelo, el error se reescribe como un mensaje de context overflow que pi reconoce, de modo que compacta y reintenta en vez de bloquearse. Un 400 genérico en una petición dentro de la ventana no se toca, así que nunca se etiquetan mal errores no relacionados. Las dos rutas de rescate se mantienen separadas: un defecto de payload que provocaría el 400 — como los ids de tool call vacíos de [#52](https://github.com/gtrabanco/pi-nan-provider/issues/52) — se repara antes de que la petición salga de pi (ver el sanitizador arriba), mientras que la revisión de tamaño solo juzga cuán grande es la petición.
|
|
103
104
|
|
|
104
105
|
### ⏱️ Streams truncados intermitentes (auto-retry, sin stall silencioso)
|
|
105
106
|
|
|
@@ -235,6 +236,16 @@ conector con `pi config` → Built-in extensions → `mcp`.
|
|
|
235
236
|
for (const block of result.output) if (block.type === "image") image(block)
|
|
236
237
|
```
|
|
237
238
|
|
|
239
|
+
En pi 1.7+ el tercer argumento acepta las opciones neutrales del proveedor: `{ size: "1536x1024" }`
|
|
240
|
+
para un lienzo concreto o `{ aspectRatio: "16:9" }` para uno de `1:1`, `16:9`, `9:16`, `4:3`,
|
|
241
|
+
`3:4`, `3:2`, `2:3`. NaN solo acepta `WIDTHxHEIGHT` con cada lado en la rejilla de 16
|
|
242
|
+
píxeles (múltiplo de 16, así que `1024x1008` vale — 1008 = 63 × 16) y entre 256 y 1536
|
|
243
|
+
(ratio 1:3–3:1, `auto` permitido), así que `size` se valida y `aspectRatio` se resuelve
|
|
244
|
+
al mayor lienzo exacto; cualquier valor inutilizable falla localmente indicando la regla
|
|
245
|
+
incumplida en vez de gastar una de las peticiones mensuales de imagen en un `400` garantizado.
|
|
246
|
+
`size` gana a `aspectRatio`, y `metadata.size` (además de `n`, `seed` y `guidance`, que codemode
|
|
247
|
+
no expone) sigue funcionando desde código de extensión.
|
|
248
|
+
|
|
238
249
|
Ambos modelos necesitan el tier de membresía "inference" (403 de lo contrario); los endpoints
|
|
239
250
|
de imagen tienen su propio límite de tasa separado del chat (20 peticiones/min, 100
|
|
240
251
|
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
|
[](https://opensource.org/licenses/MIT)
|
|
4
|
-
[](https://github.com/gtrabanco/pi-nan-provider/releases)
|
|
5
5
|
[](https://cloud.nan.builders/r/7GK06FX8)
|
|
6
6
|
|
|
7
7
|
[NaN Builders](https://cloud.nan.builders/r/7GK06FX8) model provider + a native MCP server for [pi](https://github.com/earendil-works/pi).
|
|
@@ -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.
|
|
12
|
+
> **Requirements:** pi **≥ 1.4.0** (peer range `^1.4.0`). The package is verified against **pi 1.7.0 / pi-ai 1.7.0**; the peer floor only rises on pi minor realigns.
|
|
13
13
|
|
|
14
14
|
## ✨ Features
|
|
15
15
|
|
|
@@ -18,14 +18,14 @@ Registers the `nan` provider via `pi.registerProvider()` using NaN's OpenAI-comp
|
|
|
18
18
|
| **Two-layer model catalog** | Build-time generated fallback (pi always starts, even offline) merged with the live `GET /v1/models` list; `filterModels` then hides whatever your key cannot call. |
|
|
19
19
|
| **Read-time catalog overlay** | Capability data is re-applied from the generated catalog on every `getModels()` / `getAllModels()` read, so a `models-store.json` written by an older package version can neither shadow it ([#19](https://github.com/gtrabanco/pi-nan-provider/issues/19)) nor re-register non-chat ids as chat models ([#32](https://github.com/gtrabanco/pi-nan-provider/issues/32)). The store decides *which* ids exist; the generated catalog decides *what they can do*. |
|
|
20
20
|
| **Non-chat endpoint guard** | `NON_CHAT_MODEL_IDS` keeps embedding / rerank / TTS / STT / image / video ids out of pi's chat picker. |
|
|
21
|
-
| **Strict payload sanitizer** | Every `/chat/completions` body is rewritten to match [NaN's published schema](https://nan.builders/openapi.json) before it leaves pi, whatever pi-ai version is bundled. |
|
|
21
|
+
| **Strict payload sanitizer** | Every `/chat/completions` body is rewritten to match [NaN's published schema](https://nan.builders/openapi.json) before it leaves pi, whatever pi-ai version is bundled — including tool-call/result ids, so a phantom call streamed with `id: ""` cannot wedge the session ([#52](https://github.com/gtrabanco/pi-nan-provider/issues/52)). |
|
|
22
22
|
| **Context-overflow rescue** | NaN's generic `400 Invalid request` is reclassified as an overflow when the request is estimated over the model's window ([#3](https://github.com/gtrabanco/pi-nan-provider/issues/3)), and a cold-cache `524` over `NAN_COLD_CACHE_CEILING_TOKENS` too ([#18](https://github.com/gtrabanco/pi-nan-provider/issues/18)) — pi compacts and retries instead of wedging. |
|
|
23
23
|
| **Truncated-stream retry** | `supportsFinishReason: true` turns an SSE stream closed before `finish_reason` into a retryable error instead of a silent stall ([#2](https://github.com/gtrabanco/pi-nan-provider/issues/2)). |
|
|
24
24
|
| **Streaming token usage** | `stream_options.include_usage` is on by default, so pi reports real input/output/reasoning/cache counts ([#4](https://github.com/gtrabanco/pi-nan-provider/issues/4), [#7](https://github.com/gtrabanco/pi-nan-provider/issues/7)). |
|
|
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,
|
|
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. |
|
|
@@ -83,6 +83,7 @@ The registration is synchronous on purpose: the generated fallback catalog is av
|
|
|
83
83
|
NaN answers HTTP 400 `Invalid request. Check your request parameters.` for any body that does not match the schema it publishes at [nan.builders/openapi.json](https://nan.builders/openapi.json) — a schema stricter than what pi-ai emits in several places. `src/openai-compat-sanitizer.ts` rewrites every outgoing `/chat/completions` payload on the way out, so no pi-ai version or conversation shape can produce an invalid request:
|
|
84
84
|
|
|
85
85
|
- an assistant `content` array carrying a tool call is moved into the top-level `tool_calls` field (NaN's `ContentPart` accepts only `text` and `image_url`);
|
|
86
|
+
- every announced function-type tool call carries a non-empty `id` and a non-empty `function.name` — a call whose `type` is not `function` (a grammar tool) is left untouched — and every `tool` message's `tool_call_id` names the call it answers: a phantom call streamed with `id: ""` is repaired positionally instead of wedging the session on NaN's opaque 400 ([#52](https://github.com/gtrabanco/pi-nan-provider/issues/52)). Fallback ids come from the message position, so a replayed history keeps the gateway's prefix cache warm, and a real id is never rewritten;
|
|
86
87
|
- `reasoning_details` is stripped, and unknown content parts (e.g. `thinking`) are folded into a `text` part so reasoning is not silently lost;
|
|
87
88
|
- fields NaN's schema does not list are removed: `store` always, an empty `tools` array always, and `stream_options` unless the model's `compat.supportsUsageInStreaming` says the gateway reports it;
|
|
88
89
|
- `max_completion_tokens` is renamed to `max_tokens` (the documented field) unless the model's `compat.maxTokensField` opts out ([#34](https://github.com/gtrabanco/pi-nan-provider/issues/34); `qwen3.8-max` is the only catalog model that opts out after the [#36](https://github.com/gtrabanco/pi-nan-provider/issues/36) revert).
|
|
@@ -93,13 +94,13 @@ A caller-supplied `onPayload` hook is preserved and chained after sanitization.
|
|
|
93
94
|
|
|
94
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.
|
|
95
96
|
|
|
96
|
-
The header **
|
|
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.
|
|
97
98
|
|
|
98
99
|
### 🧠 Model-switch safety
|
|
99
100
|
|
|
100
101
|
When you switch models, older pi-ai versions replayed the previous model's reasoning as plain assistant text with **no size bound**, which could overflow a 262K-context model's window; NaN answered with a generic `400 Invalid request. Check your request parameters.` that looked like a provider bug (upstream tracking: [pi-nan-provider#3](https://github.com/gtrabanco/pi-nan-provider/issues/3)). pi-ai 1.3.0 fixed this upstream (`transformMessages` now drops thinking blocks from a different model) and this package requires **pi ≥ 1.4.0** (peer range `^1.4.0`), so the extension-side guard that used to mitigate it was **removed in package 1.4.0** — no action is needed, upstream handles it.
|
|
101
102
|
|
|
102
|
-
A request can still overflow on its own merits — oversized tool outputs, images, or a destination window simply smaller than the content — and NaN answers the same generic 400 instead of naming the overflow, while pi's auto-compaction does not recognize it, so the session would wedge at the ceiling. The provider therefore **re-checks the request size on the way out**: when that generic 400 arrives for a request estimated over the model's window, the error is rewritten into a context-overflow message pi recognizes, so it compacts and retries instead of stalling. A generic 400 on a within-window request is left untouched, so unrelated errors are never mislabelled.
|
|
103
|
+
A request can still overflow on its own merits — oversized tool outputs, images, or a destination window simply smaller than the content — and NaN answers the same generic 400 instead of naming the overflow, while pi's auto-compaction does not recognize it, so the session would wedge at the ceiling. The provider therefore **re-checks the request size on the way out**: when that generic 400 arrives for a request estimated over the model's window, the error is rewritten into a context-overflow message pi recognizes, so it compacts and retries instead of stalling. A generic 400 on a within-window request is left untouched, so unrelated errors are never mislabelled. The two rescue paths stay separate: a payload defect that would provoke the 400 — like the empty tool-call ids of [#52](https://github.com/gtrabanco/pi-nan-provider/issues/52) — is repaired before the request leaves pi (see the sanitizer above), while the size recheck only judges how large the request is.
|
|
103
104
|
|
|
104
105
|
### ⏱️ Intermittent truncated streams (auto-retry, no silent stall)
|
|
105
106
|
|
|
@@ -233,6 +234,8 @@ registering a server that can never connect. To get MCP in the CLI, enable the c
|
|
|
233
234
|
for (const block of result.output) if (block.type === "image") image(block)
|
|
234
235
|
```
|
|
235
236
|
|
|
237
|
+
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.
|
|
238
|
+
|
|
236
239
|
Both models need the "inference" membership tier (403 otherwise); the image endpoints
|
|
237
240
|
are rate-limited separately from chat (20 requests/min, 100 requests/month shared
|
|
238
241
|
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.
|
|
3
|
+
"version": "1.7.2",
|
|
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.
|
|
51
|
-
"@earendil-works/pi-coding-agent": "1.
|
|
50
|
+
"@earendil-works/pi-ai": "1.7.0",
|
|
51
|
+
"@earendil-works/pi-coding-agent": "1.7.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-
|
|
4
|
+
// Source: https://models.dev/api.json (provider "nan"), fetched 2026-11-28T12:10:46.403Z
|
|
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-
|
|
1030
|
+
fetchedAt: "2026-11-28T12:10:46.403Z",
|
|
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: [
|
package/src/attribution.ts
CHANGED
|
@@ -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
|
|
19
|
-
*
|
|
20
|
-
* {@link
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
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()
|
|
93
|
-
*
|
|
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
|
package/src/cache-anomaly.ts
CHANGED
|
@@ -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`.
|
|
31
|
-
*
|
|
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";
|
package/src/http-attempts.ts
CHANGED
|
@@ -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
|
|
6
|
-
* finally succeeds appears as one ordinary turn
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
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
|
|
236
|
-
// n,
|
|
237
|
-
//
|
|
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
|
|
146
|
-
//
|
|
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.
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
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);
|
|
@@ -49,6 +49,16 @@
|
|
|
49
49
|
* accepted. pi-ai emits `tools: []` when the conversation has tool-call
|
|
50
50
|
* history but no active tools; NaN only accepts a real tool list, so the
|
|
51
51
|
* empty array is dropped and a non-empty list is kept.
|
|
52
|
+
* 6. An announced tool call whose ids never arrived (issue #52): a phantom
|
|
53
|
+
* call streamed with an empty `id` (and possibly an empty
|
|
54
|
+
* `function.name`) plus the `tool` message answering it are repaired in
|
|
55
|
+
* one ordered pass — the id comes from the answering `tool_call_id`
|
|
56
|
+
* when that is real, else from the deterministic
|
|
57
|
+
* `call_<name>_<messageIndex>_<callIndex>` fallback; an empty
|
|
58
|
+
* `function.name` becomes `function`; an empty `tool_call_id` binds to
|
|
59
|
+
* the call it answers; a result with nothing to bind to is dropped.
|
|
60
|
+
* Real ids are never rewritten and non-`function` grammar calls are
|
|
61
|
+
* left untouched.
|
|
52
62
|
*
|
|
53
63
|
* This is applied by wrapping the provider's api `stream`/`streamSimple`
|
|
54
64
|
* with an `onPayload` hook in src/provider-factory.ts, so every provider
|
|
@@ -76,7 +86,20 @@ function isObject(value: unknown): value is Record<string, unknown> {
|
|
|
76
86
|
}
|
|
77
87
|
|
|
78
88
|
/** Monotonic counter for deterministic fallback tool-call ids (pi-ai always supplies ids; this is pure defense). */
|
|
79
|
-
|
|
89
|
+
const FALLBACK_TOOL_NAME = "function";
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Deterministic fallback id for a tool call that reached the payload without one.
|
|
93
|
+
*
|
|
94
|
+
* Derived from the message and call positions, never from a counter: a
|
|
95
|
+
* counter mints a different id on every replay of the same history, which
|
|
96
|
+
* changes the request body and invalidates the gateway's server-side prefix
|
|
97
|
+
* cache. Positions are stable while the history only appends, which is how pi
|
|
98
|
+
* replays a session; a compaction legitimately renumbers them.
|
|
99
|
+
*/
|
|
100
|
+
function fallbackToolCallId(messageIndex: number, callIndex: number, name: string): string {
|
|
101
|
+
return `call_${name.length > 0 ? name : FALLBACK_TOOL_NAME}_${messageIndex}_${callIndex}`;
|
|
102
|
+
}
|
|
80
103
|
|
|
81
104
|
/** Normalize a `toolCall` content block into NaN's `tool_calls[].{id,type,function}` shape. */
|
|
82
105
|
function toToolCall(block: ToolCallBlock): Record<string, unknown> {
|
|
@@ -91,27 +114,38 @@ function toToolCall(block: ToolCallBlock): Record<string, unknown> {
|
|
|
91
114
|
argumentsJson = "{}";
|
|
92
115
|
}
|
|
93
116
|
}
|
|
94
|
-
const
|
|
117
|
+
const name = typeof block.name === "string" && block.name.length > 0 ? block.name : FALLBACK_TOOL_NAME;
|
|
95
118
|
return {
|
|
96
|
-
|
|
119
|
+
// The id is repaired by `reconcileToolCalls` once the whole message list is
|
|
120
|
+
// visible: an empty id can only be filled from the result it answers, which
|
|
121
|
+
// is the next message, not this block.
|
|
122
|
+
id: typeof block.id === "string" ? block.id : "",
|
|
97
123
|
type: "function",
|
|
98
124
|
function: {
|
|
99
|
-
name
|
|
125
|
+
name,
|
|
100
126
|
arguments: argumentsJson,
|
|
101
127
|
},
|
|
102
128
|
};
|
|
103
129
|
}
|
|
104
130
|
|
|
105
|
-
/** Merge tool calls, de-duplicating by id and preferring the pre-existing (pi-ai-built) entries. */
|
|
131
|
+
/** Merge tool calls, de-duplicating by a real id and preferring the pre-existing (pi-ai-built) entries. */
|
|
106
132
|
function mergeToolCalls(existing: unknown[], incoming: Array<Record<string, unknown>>): Array<Record<string, unknown>> {
|
|
107
|
-
const
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
133
|
+
const merged: Array<Record<string, unknown>> = [];
|
|
134
|
+
const seenIds = new Set<string>();
|
|
135
|
+
const add = (tc: unknown): void => {
|
|
136
|
+
if (!isObject(tc)) return;
|
|
137
|
+
const id = typeof tc.id === "string" ? tc.id : "";
|
|
138
|
+
// An empty id is not an identity: two anonymous calls are two calls, and
|
|
139
|
+
// dropping either would lose a tool call the model actually made.
|
|
140
|
+
if (id.length > 0) {
|
|
141
|
+
if (seenIds.has(id)) return;
|
|
142
|
+
seenIds.add(id);
|
|
143
|
+
}
|
|
144
|
+
merged.push(tc);
|
|
145
|
+
};
|
|
146
|
+
for (const tc of existing) add(tc);
|
|
147
|
+
for (const tc of incoming) add(tc);
|
|
148
|
+
return merged;
|
|
115
149
|
}
|
|
116
150
|
|
|
117
151
|
/**
|
|
@@ -189,6 +223,114 @@ function sanitizeMessage(message: unknown): unknown {
|
|
|
189
223
|
return out;
|
|
190
224
|
}
|
|
191
225
|
|
|
226
|
+
/**
|
|
227
|
+
* Repair one announced tool call against the result it answers.
|
|
228
|
+
*
|
|
229
|
+
* An id can arrive empty for two reasons: a `toolCall` block carried no id
|
|
230
|
+
* (older payloads), or the gateway streamed a phantom call whose `id` and
|
|
231
|
+
* `name` never landed. Either way the id is filled from the answering
|
|
232
|
+
* `tool_call_id` when that is real, and from the deterministic position
|
|
233
|
+
* fallback otherwise.
|
|
234
|
+
*/
|
|
235
|
+
function repairToolCall(raw: unknown, messageIndex: number, callIndex: number, resultIds: unknown[]): unknown {
|
|
236
|
+
if (!isObject(raw)) return raw;
|
|
237
|
+
if (typeof raw.type === "string" && raw.type !== "function") return raw; // grammar tools keep their shape
|
|
238
|
+
const fn = isObject(raw.function) ? { ...raw.function } : {};
|
|
239
|
+
const rawName = typeof fn.name === "string" ? fn.name : "";
|
|
240
|
+
const name = rawName.length > 0 ? rawName : FALLBACK_TOOL_NAME;
|
|
241
|
+
if (fn.arguments !== undefined && typeof fn.arguments !== "string") {
|
|
242
|
+
try {
|
|
243
|
+
fn.arguments = JSON.stringify(fn.arguments);
|
|
244
|
+
} catch {
|
|
245
|
+
fn.arguments = "{}";
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
const resultId = resultIds[callIndex];
|
|
249
|
+
const id =
|
|
250
|
+
typeof raw.id === "string" && raw.id.length > 0
|
|
251
|
+
? raw.id
|
|
252
|
+
: typeof resultId === "string" && resultId.length > 0
|
|
253
|
+
? resultId
|
|
254
|
+
: fallbackToolCallId(messageIndex, callIndex, name);
|
|
255
|
+
return { ...raw, id, type: "function", function: { ...fn, name } };
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Reconcile announced tool calls with the `tool` messages that answer them, in
|
|
260
|
+
* one ordered pass (issue #52).
|
|
261
|
+
*
|
|
262
|
+
* NaN's gateway, like every OpenAI-compatible one, rejects a payload in which an
|
|
263
|
+
* assistant `tool_calls[].id` or a `tool` message's `tool_call_id` is empty: it
|
|
264
|
+
* answers the opaque `400 Invalid request. Check your request parameters.` and
|
|
265
|
+
* the session wedges for as long as that message stays in history. Both ids are
|
|
266
|
+
* therefore guaranteed non-empty and pairwise equal here.
|
|
267
|
+
*
|
|
268
|
+
* Binding is positional because that is how pi emits them: the results follow
|
|
269
|
+
* their assistant message in the order the calls were announced. A result whose
|
|
270
|
+
* `tool_call_id` is real is never rewritten (an unmatched real id is left alone,
|
|
271
|
+
* as before). A result with an empty id and no announced call to bind to cannot
|
|
272
|
+
* be made valid by rewriting, so it is dropped — the only schema-valid outcome.
|
|
273
|
+
*/
|
|
274
|
+
function reconcileToolCalls(messages: unknown[]): unknown[] {
|
|
275
|
+
const reconciled: unknown[] = [];
|
|
276
|
+
let announced: string[] = [];
|
|
277
|
+
let cursor = 0;
|
|
278
|
+
|
|
279
|
+
messages.forEach((message, index) => {
|
|
280
|
+
if (!isObject(message)) {
|
|
281
|
+
announced = [];
|
|
282
|
+
cursor = 0;
|
|
283
|
+
reconciled.push(message);
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
if (message.role === "assistant") {
|
|
288
|
+
const calls = Array.isArray(message.tool_calls) ? message.tool_calls : [];
|
|
289
|
+
if (calls.length === 0) {
|
|
290
|
+
announced = [];
|
|
291
|
+
cursor = 0;
|
|
292
|
+
reconciled.push(message);
|
|
293
|
+
return;
|
|
294
|
+
}
|
|
295
|
+
// The answers immediately follow; their ids are the preferred repair
|
|
296
|
+
// source, because a real id must win over an invented one.
|
|
297
|
+
const resultIds: unknown[] = [];
|
|
298
|
+
for (let j = index + 1; j < messages.length; j++) {
|
|
299
|
+
const next = messages[j];
|
|
300
|
+
if (!isObject(next) || next.role !== "tool") break;
|
|
301
|
+
resultIds.push(next.tool_call_id);
|
|
302
|
+
}
|
|
303
|
+
const normalized = calls.map((raw, callIndex) => repairToolCall(raw, index, callIndex, resultIds));
|
|
304
|
+
announced = normalized.map((tc) => (isObject(tc) && typeof tc.id === "string" ? tc.id : ""));
|
|
305
|
+
cursor = 0;
|
|
306
|
+
reconciled.push({ ...message, tool_calls: normalized });
|
|
307
|
+
return;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
if (message.role === "tool") {
|
|
311
|
+
const target = announced[cursor];
|
|
312
|
+
cursor += 1;
|
|
313
|
+
const id = message.tool_call_id;
|
|
314
|
+
if (typeof id === "string" && id.length > 0) {
|
|
315
|
+
reconciled.push(message);
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
318
|
+
if (target !== undefined && target.length > 0) {
|
|
319
|
+
reconciled.push({ ...message, tool_call_id: target });
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
// Nothing to bind to: an empty id referencing no call is never valid.
|
|
323
|
+
return;
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
announced = [];
|
|
327
|
+
cursor = 0;
|
|
328
|
+
reconciled.push(message);
|
|
329
|
+
});
|
|
330
|
+
|
|
331
|
+
return reconciled;
|
|
332
|
+
}
|
|
333
|
+
|
|
192
334
|
export interface SanitizerOptions {
|
|
193
335
|
/**
|
|
194
336
|
* Keep `stream_options` in the payload. Set only when the model's effective
|
|
@@ -224,27 +366,11 @@ export function sanitizeOpenAICompatPayload(payload: unknown, options: Sanitizer
|
|
|
224
366
|
|
|
225
367
|
// Patch function-tools call arguments: NaN wants function-call arguments
|
|
226
368
|
// serialized as a JSON string under `function.arguments`. pi-ai already does
|
|
227
|
-
// this, but a hand-built / older-version payload may not. Normalize each
|
|
369
|
+
// this, but a hand-built / older-version payload may not. Normalize each, and
|
|
370
|
+
// reconcile every call with the result that answers it (issue #52): an empty
|
|
371
|
+
// `tool_calls[].id` or `tool_call_id` is an opaque 400 at the gateway.
|
|
228
372
|
if (Array.isArray(out.messages)) {
|
|
229
|
-
out.messages = out.messages
|
|
230
|
-
if (!isObject(m) || m.role !== "assistant") return m;
|
|
231
|
-
if (!Array.isArray(m.tool_calls)) return m;
|
|
232
|
-
const normalized = m.tool_calls.map((tc) => {
|
|
233
|
-
if (!isObject(tc)) return tc;
|
|
234
|
-
if (typeof tc.type === "string" && tc.type !== "function") return tc;
|
|
235
|
-
const fn = isObject(tc.function) ? tc.function : {};
|
|
236
|
-
let args = fn.arguments;
|
|
237
|
-
if (args !== undefined && typeof args !== "string") {
|
|
238
|
-
try {
|
|
239
|
-
args = JSON.stringify(args);
|
|
240
|
-
} catch {
|
|
241
|
-
args = "{}";
|
|
242
|
-
}
|
|
243
|
-
}
|
|
244
|
-
return { ...tc, type: "function", function: { ...fn, ...(args !== undefined ? { arguments: args } : {}) } };
|
|
245
|
-
});
|
|
246
|
-
return { ...m, tool_calls: normalized };
|
|
247
|
-
});
|
|
373
|
+
out.messages = reconcileToolCalls(out.messages);
|
|
248
374
|
}
|
|
249
375
|
|
|
250
376
|
// Top-level fields absent from NaN's schema.
|
package/src/provider-factory.ts
CHANGED
|
@@ -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
|
|
207
|
-
//
|
|
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
|