@gtrabanco/pi-nan-provider 1.6.3 → 1.6.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AGENTS.md CHANGED
@@ -350,6 +350,31 @@ Since 1.0.0 the package version **aligns its MAJOR.MINOR with the pi release lin
350
350
  only when estimated over the window). Wired in `src/provider-factory.ts` after
351
351
  the sanitizer. Regression tests: `test/issue-3-model-switch-overflow.test.ts`,
352
352
  `test/context-overflow-classifier.test.ts`; issue #3.
353
+ - **The #52 wedge is a payload defect, not an under-counting estimator** (verified
354
+ 2026-11-26 against the archived transcript and attempt log). A
355
+ `mimo-v2.6-flash` session sat on the opaque 400 for two hours; the turn before
356
+ the first 400 reports `input` 2,075 + `cacheRead` 559,232 = **561,307 prompt
357
+ tokens** against a **1,048,576** window, while `estimateRequestTokens` answers
358
+ 625,484 for the same 2,170,428 payload bytes. Real ratio = 3.867 bytes/token,
359
+ so the 3.47 divisor **over**-estimates by 11.4 % — the issue's "systematically
360
+ underestimated" is backwards, and its ÷2.0 proposal would fabricate 1,085,214
361
+ tokens for a request at 53.5 % of the window (a forced compaction plus a false
362
+ cause on the error text). The real cause: the gateway streamed
363
+ `{"type":"toolCall","id":"","name":"","arguments":{}}`, pi persisted pi's
364
+ `"Tool not found"` result with `toolCallId: ""`, and pi-ai copies both ids
365
+ verbatim onto the wire (`api/openai-completions.js:1015-1022` for
366
+ `tool_calls`, `:1073-1077` for `role:"tool"`) — so every replay of the history
367
+ was rejected until a compaction removed the pair. `src/openai-compat-sanitizer.ts`
368
+ now reconciles announced calls with their results in one ordered pass
369
+ (`reconcileToolCalls`): empty id ← the answering `tool_call_id`, else a
370
+ deterministic `call_<name>_<messageIndex>_<callIndex>` fallback (never a
371
+ counter — a request-varying id invalidates the prefix cache); empty
372
+ `function.name` → `function`; empty `tool_call_id` ← the announced call; a
373
+ result with nothing to bind to is dropped. Real ids, `type !== "function"`
374
+ grammar calls and unrelated fields are untouched. The overflow thresholds are
375
+ unchanged on purpose. Regression tests: `test/issue-52-empty-tool-call-ids.test.ts`
376
+ (the repair, the deterministic ids, the trailing invariants and the pinned
377
+ measurement); `test/openai-compat-sanitizer.test.ts` stays byte-identical.
353
378
  - Relative imports inside this package use `.ts` extensions (pi's official
354
379
  extension examples do the same; pi transpiles extension sources).
355
380
  - pi 0.87 breaking changes NOT used by this package: `ContextEditEntry` added to
package/README.es.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # @gtrabanco/𝜋-nan-provider
2
2
 
3
3
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
4
- [![Version](https://img.shields.io/badge/version-1.6.3-blue)](https://github.com/gtrabanco/pi-nan-provider/releases)
4
+ [![Version](https://img.shields.io/badge/version-1.6.4-blue)](https://github.com/gtrabanco/pi-nan-provider/releases)
5
5
  [![Built with NaN](https://nan.builders/badge/built-with-nan-compact.svg)](https://cloud.nan.builders/r/7GK06FX8)
6
6
 
7
7
  [NaN Builders](https://cloud.nan.builders/r/7GK06FX8) model provider + MCP nativo para [pi](https://github.com/earendil-works/pi).
@@ -18,7 +18,7 @@ Registra el proveedor `nan` vía `pi.registerProvider()` usando la API OpenAI-co
18
18
  | **Catálogo de modelos en dos capas** | Fallback generado en build-time (pi arranca aunque no haya red) fusionado con la lista en vivo `GET /v1/models`; después `filterModels` oculta lo que tu clave no pueda usar. |
19
19
  | **Overlay de catálogo en tiempo de lectura** | Los datos de capacidad se reaplican desde el catálogo generado en cada lectura de `getModels()` / `getAllModels()`, así que un `models-store.json` escrito por una versión anterior del paquete no puede eclipsarlos ([#19](https://github.com/gtrabanco/pi-nan-provider/issues/19)) ni volver a registrar ids no-chat como modelos de chat ([#32](https://github.com/gtrabanco/pi-nan-provider/issues/32)). La store decide *qué* ids existen; el catálogo generado decide *qué pueden hacer*. |
20
20
  | **Guardia de endpoints no-chat** | `NON_CHAT_MODEL_IDS` mantiene los ids de embedding / rerank / TTS / STT / imagen / vídeo fuera del selector de chat de pi. |
21
- | **Sanitizador de payloads estricto** | Cuerpo de `/chat/completions` reescrito para cumplir [el esquema publicado de NaN](https://nan.builders/openapi.json) antes de salir de pi, sea cual sea la versión de pi-ai incluida. |
21
+ | **Sanitizador de payloads estricto** | Cuerpo de `/chat/completions` reescrito para cumplir [el esquema publicado de NaN](https://nan.builders/openapi.json) antes de salir de pi, sea cual sea la versión de pi-ai incluida — incluidos los ids de tool call y de resultado, de modo que una tool call fantasma emitida con `id: ""` no puede bloquear la sesión ([#52](https://github.com/gtrabanco/pi-nan-provider/issues/52)). |
22
22
  | **Rescate de desbordamiento de contexto** | El `400 Invalid request` genérico de NaN se reclasifica como desbordamiento cuando la petición se estima por encima de la ventana del modelo ([#3](https://github.com/gtrabanco/pi-nan-provider/issues/3)), y un `524` de caché fría por encima de `NAN_COLD_CACHE_CEILING_TOKENS` también ([#18](https://github.com/gtrabanco/pi-nan-provider/issues/18)) — pi compacta y reintenta en vez de quedarse colgado. |
23
23
  | **Reintento de streams truncados** | `supportsFinishReason: true` convierte un stream SSE cerrado antes de `finish_reason` en un error reintentable en vez de un stall silencioso ([#2](https://github.com/gtrabanco/pi-nan-provider/issues/2)). |
24
24
  | **Uso de tokens en streaming** | `stream_options.include_usage` activo por defecto, así que pi reporta recuentos reales de entrada/salida/razonamiento/caché ([#4](https://github.com/gtrabanco/pi-nan-provider/issues/4), [#7](https://github.com/gtrabanco/pi-nan-provider/issues/7)). |
@@ -83,6 +83,7 @@ El registro es síncrono a propósito: el catálogo de fallback está disponible
83
83
  NaN responde HTTP 400 `Invalid request. Check your request parameters.` con cualquier cuerpo que no cumpla el esquema que publica en [nan.builders/openapi.json](https://nan.builders/openapi.json) — un esquema más estricto que lo que pi-ai emite en varios sitios. `src/openai-compat-sanitizer.ts` reescribe cada cuerpo saliente de `/chat/completions`, así que ninguna versión de pi-ai ni ninguna forma de conversación pueden producir una petición inválida:
84
84
 
85
85
  - un array `content` de asistente que lleva una tool call se mueve al campo superior `tool_calls` (el `ContentPart` de NaN solo acepta `text` y `image_url`);
86
+ - tool call anunciada de tipo `function` lleva un `id` no vacío y un `function.name` no vacío — una llamada cuyo `type` no es `function` (una grammar tool) se deja intacta — y el `tool_call_id` de cada mensaje `tool` nombra la llamada que responde: una tool call fantasma emitida con `id: ""` se repara posicionalmente en lugar de bloquear la sesión con el 400 opaco de NaN ([#52](https://github.com/gtrabanco/pi-nan-provider/issues/52)). Los ids de relleno salen de la posición del mensaje, así que un historial reenviado mantiene caliente la caché de prefijo del gateway, y un id real nunca se reescribe;
86
87
  - se elimina `reasoning_details`, y las partes de contenido desconocidas (p. ej. `thinking`) se pliegan en una parte `text` para que el razonamiento no se pierda en silencio;
87
88
  - se eliminan los campos que el esquema de NaN no lista: `store` siempre, un array `tools` vacío siempre, y `stream_options` salvo que `compat.supportsUsageInStreaming` del modelo diga que el gateway lo reporta;
88
89
  - `max_completion_tokens` se renombra a `max_tokens` (el campo documentado) salvo que `compat.maxTokensField` del modelo lo desactive ([#34](https://github.com/gtrabanco/pi-nan-provider/issues/34); `qwen3.8-max` es el único modelo del catálogo que lo desactiva tras la reversión del [#36](https://github.com/gtrabanco/pi-nan-provider/issues/36)).
@@ -99,7 +100,7 @@ La cabecera **sigue la opción de telemetría de pi**: con `enableInstallTelemet
99
100
 
100
101
  Al cambiar de modelo, versiones antiguas de pi-ai reenviaban el razonamiento del modelo anterior como texto plano de asistente **sin límite de tamaño**, lo que podía desbordar la ventana de un modelo de 262K; NaN respondía con un `400 Invalid request. Check your request parameters.` genérico que parecía un bug del proveedor (seguimiento upstream: [pi-nan-provider#3](https://github.com/gtrabanco/pi-nan-provider/issues/3)). pi-ai 1.3.0 arregló esto upstream (`transformMessages` ahora descarta los bloques de thinking de otro modelo) y este paquete requiere **pi ≥ 1.4.0** (rango peer `^1.4.0`), así que el guard extension-side que lo mitigaba fue **eliminado en la versión 1.4.0 del paquete** — no hay que hacer nada, upstream lo gestiona.
101
102
 
102
- Una petición puede seguir desbordando por méritos propios — tool outputs enormes, imágenes o una ventana de destino simplemente más pequeña que el contenido — y NaN responde con el mismo 400 genérico en lugar de nombrar el desbordamiento, mientras que la auto-compactación de pi no lo reconoce, así que la sesión se quedaría atascada en el techo. Por eso el proveedor **vuelve a comprobar el tamaño de la petición a la salida**: cuando llega ese 400 genérico para una petición estimada por encima de la ventana del modelo, el error se reescribe como un mensaje de context overflow que pi reconoce, de modo que compacta y reintenta en vez de bloquearse. Un 400 genérico en una petición dentro de la ventana no se toca, así que nunca se etiquetan mal errores no relacionados.
103
+ Una petición puede seguir desbordando por méritos propios — tool outputs enormes, imágenes o una ventana de destino simplemente más pequeña que el contenido — y NaN responde con el mismo 400 genérico en lugar de nombrar el desbordamiento, mientras que la auto-compactación de pi no lo reconoce, así que la sesión se quedaría atascada en el techo. Por eso el proveedor **vuelve a comprobar el tamaño de la petición a la salida**: cuando llega ese 400 genérico para una petición estimada por encima de la ventana del modelo, el error se reescribe como un mensaje de context overflow que pi reconoce, de modo que compacta y reintenta en vez de bloquearse. Un 400 genérico en una petición dentro de la ventana no se toca, así que nunca se etiquetan mal errores no relacionados. Las dos rutas de rescate se mantienen separadas: un defecto de payload que provocaría el 400 — como los ids de tool call vacíos de [#52](https://github.com/gtrabanco/pi-nan-provider/issues/52) — se repara antes de que la petición salga de pi (ver el sanitizador arriba), mientras que la revisión de tamaño solo juzga cuán grande es la petición.
103
104
 
104
105
  ### ⏱️ Streams truncados intermitentes (auto-retry, sin stall silencioso)
105
106
 
package/README.md CHANGED
@@ -1,7 +1,7 @@
1
1
  # @gtrabanco/𝜋-nan-provider
2
2
 
3
3
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
4
- [![Version](https://img.shields.io/badge/version-1.6.3-blue)](https://github.com/gtrabanco/pi-nan-provider/releases)
4
+ [![Version](https://img.shields.io/badge/version-1.6.4-blue)](https://github.com/gtrabanco/pi-nan-provider/releases)
5
5
  [![Built with NaN](https://nan.builders/badge/built-with-nan-compact.svg)](https://cloud.nan.builders/r/7GK06FX8)
6
6
 
7
7
  [NaN Builders](https://cloud.nan.builders/r/7GK06FX8) model provider + a native MCP server for [pi](https://github.com/earendil-works/pi).
@@ -18,7 +18,7 @@ Registers the `nan` provider via `pi.registerProvider()` using NaN's OpenAI-comp
18
18
  | **Two-layer model catalog** | Build-time generated fallback (pi always starts, even offline) merged with the live `GET /v1/models` list; `filterModels` then hides whatever your key cannot call. |
19
19
  | **Read-time catalog overlay** | Capability data is re-applied from the generated catalog on every `getModels()` / `getAllModels()` read, so a `models-store.json` written by an older package version can neither shadow it ([#19](https://github.com/gtrabanco/pi-nan-provider/issues/19)) nor re-register non-chat ids as chat models ([#32](https://github.com/gtrabanco/pi-nan-provider/issues/32)). The store decides *which* ids exist; the generated catalog decides *what they can do*. |
20
20
  | **Non-chat endpoint guard** | `NON_CHAT_MODEL_IDS` keeps embedding / rerank / TTS / STT / image / video ids out of pi's chat picker. |
21
- | **Strict payload sanitizer** | Every `/chat/completions` body is rewritten to match [NaN's published schema](https://nan.builders/openapi.json) before it leaves pi, whatever pi-ai version is bundled. |
21
+ | **Strict payload sanitizer** | Every `/chat/completions` body is rewritten to match [NaN's published schema](https://nan.builders/openapi.json) before it leaves pi, whatever pi-ai version is bundled — including tool-call/result ids, so a phantom call streamed with `id: ""` cannot wedge the session ([#52](https://github.com/gtrabanco/pi-nan-provider/issues/52)). |
22
22
  | **Context-overflow rescue** | NaN's generic `400 Invalid request` is reclassified as an overflow when the request is estimated over the model's window ([#3](https://github.com/gtrabanco/pi-nan-provider/issues/3)), and a cold-cache `524` over `NAN_COLD_CACHE_CEILING_TOKENS` too ([#18](https://github.com/gtrabanco/pi-nan-provider/issues/18)) — pi compacts and retries instead of wedging. |
23
23
  | **Truncated-stream retry** | `supportsFinishReason: true` turns an SSE stream closed before `finish_reason` into a retryable error instead of a silent stall ([#2](https://github.com/gtrabanco/pi-nan-provider/issues/2)). |
24
24
  | **Streaming token usage** | `stream_options.include_usage` is on by default, so pi reports real input/output/reasoning/cache counts ([#4](https://github.com/gtrabanco/pi-nan-provider/issues/4), [#7](https://github.com/gtrabanco/pi-nan-provider/issues/7)). |
@@ -83,6 +83,7 @@ The registration is synchronous on purpose: the generated fallback catalog is av
83
83
  NaN answers HTTP 400 `Invalid request. Check your request parameters.` for any body that does not match the schema it publishes at [nan.builders/openapi.json](https://nan.builders/openapi.json) — a schema stricter than what pi-ai emits in several places. `src/openai-compat-sanitizer.ts` rewrites every outgoing `/chat/completions` payload on the way out, so no pi-ai version or conversation shape can produce an invalid request:
84
84
 
85
85
  - an assistant `content` array carrying a tool call is moved into the top-level `tool_calls` field (NaN's `ContentPart` accepts only `text` and `image_url`);
86
+ - every announced function-type tool call carries a non-empty `id` and a non-empty `function.name` — a call whose `type` is not `function` (a grammar tool) is left untouched — and every `tool` message's `tool_call_id` names the call it answers: a phantom call streamed with `id: ""` is repaired positionally instead of wedging the session on NaN's opaque 400 ([#52](https://github.com/gtrabanco/pi-nan-provider/issues/52)). Fallback ids come from the message position, so a replayed history keeps the gateway's prefix cache warm, and a real id is never rewritten;
86
87
  - `reasoning_details` is stripped, and unknown content parts (e.g. `thinking`) are folded into a `text` part so reasoning is not silently lost;
87
88
  - fields NaN's schema does not list are removed: `store` always, an empty `tools` array always, and `stream_options` unless the model's `compat.supportsUsageInStreaming` says the gateway reports it;
88
89
  - `max_completion_tokens` is renamed to `max_tokens` (the documented field) unless the model's `compat.maxTokensField` opts out ([#34](https://github.com/gtrabanco/pi-nan-provider/issues/34); `qwen3.8-max` is the only catalog model that opts out after the [#36](https://github.com/gtrabanco/pi-nan-provider/issues/36) revert).
@@ -99,7 +100,7 @@ The header **follows pi's telemetry setting**: with `enableInstallTelemetry: fal
99
100
 
100
101
  When you switch models, older pi-ai versions replayed the previous model's reasoning as plain assistant text with **no size bound**, which could overflow a 262K-context model's window; NaN answered with a generic `400 Invalid request. Check your request parameters.` that looked like a provider bug (upstream tracking: [pi-nan-provider#3](https://github.com/gtrabanco/pi-nan-provider/issues/3)). pi-ai 1.3.0 fixed this upstream (`transformMessages` now drops thinking blocks from a different model) and this package requires **pi ≥ 1.4.0** (peer range `^1.4.0`), so the extension-side guard that used to mitigate it was **removed in package 1.4.0** — no action is needed, upstream handles it.
101
102
 
102
- A request can still overflow on its own merits — oversized tool outputs, images, or a destination window simply smaller than the content — and NaN answers the same generic 400 instead of naming the overflow, while pi's auto-compaction does not recognize it, so the session would wedge at the ceiling. The provider therefore **re-checks the request size on the way out**: when that generic 400 arrives for a request estimated over the model's window, the error is rewritten into a context-overflow message pi recognizes, so it compacts and retries instead of stalling. A generic 400 on a within-window request is left untouched, so unrelated errors are never mislabelled.
103
+ A request can still overflow on its own merits — oversized tool outputs, images, or a destination window simply smaller than the content — and NaN answers the same generic 400 instead of naming the overflow, while pi's auto-compaction does not recognize it, so the session would wedge at the ceiling. The provider therefore **re-checks the request size on the way out**: when that generic 400 arrives for a request estimated over the model's window, the error is rewritten into a context-overflow message pi recognizes, so it compacts and retries instead of stalling. A generic 400 on a within-window request is left untouched, so unrelated errors are never mislabelled. The two rescue paths stay separate: a payload defect that would provoke the 400 — like the empty tool-call ids of [#52](https://github.com/gtrabanco/pi-nan-provider/issues/52) — is repaired before the request leaves pi (see the sanitizer above), while the size recheck only judges how large the request is.
103
104
 
104
105
  ### ⏱️ Intermittent truncated streams (auto-retry, no silent stall)
105
106
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gtrabanco/pi-nan-provider",
3
- "version": "1.6.3",
3
+ "version": "1.6.4",
4
4
  "description": "NaN Builders (api.nan.builders) model provider for pi - OpenAI-compatible registration with a models.dev-generated fallback, tier-aware live catalog, and an optional community media MCP bridge",
5
5
  "keywords": [
6
6
  "pi",
@@ -1,7 +1,7 @@
1
1
  // This file is auto-generated by scripts/generate-models.ts
2
2
  // Do not edit manually — run `bun run generate-models` to update.
3
3
  //
4
- // Source: https://models.dev/api.json (provider "nan"), fetched 2026-11-25T10:55:49.540Z
4
+ // Source: https://models.dev/api.json (provider "nan"), fetched 2026-11-27T00:10:03.719Z
5
5
  // Provenance: every contextWindow/maxTokens/input/cost value traces to
6
6
  // models.dev or to the per-entry notes below. Nothing is invented; entries
7
7
  // models.dev documents incompletely are omitted and flagged instead.
@@ -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-25T10:55:49.540Z",
1030
+ fetchedAt: "2026-11-27T00:10:03.719Z",
1031
1031
  modelCount: 13,
1032
1032
  models: ["deepseek-v4-flash","deepseek-v4-pro","gemma4","glm5.3","glm5.3-flash","hy4","hy4-flash","kimi-k3.1-pro","mimo-v2.6-flash","qwen3.6","qwen3.8-flash","qwen3.8-max","qwen4-max"],
1033
1033
  notes: [
@@ -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
- let anonymousToolCallSeq = 0;
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 fallbackName = typeof block.name === "string" && block.name.length > 0 ? block.name : "function";
117
+ const name = typeof block.name === "string" && block.name.length > 0 ? block.name : FALLBACK_TOOL_NAME;
95
118
  return {
96
- id: typeof block.id === "string" && block.id.length > 0 ? block.id : `call_${fallbackName}_${++anonymousToolCallSeq}`,
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: fallbackName,
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 byId = new Map<string, Record<string, unknown>>();
108
- for (const tc of existing) {
109
- if (isObject(tc) && typeof tc.id === "string") byId.set(tc.id, tc);
110
- }
111
- for (const tc of incoming) {
112
- if (typeof tc.id === "string" && !byId.has(tc.id)) byId.set(tc.id, tc);
113
- }
114
- return [...byId.values()];
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.map((m) => {
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.