@gtrabanco/pi-nan-provider 1.5.1 → 1.5.3
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 +26 -2
- package/CONTRIBUTING.md +10 -1
- package/README.es.md +43 -1
- package/README.md +42 -1
- package/package.json +1 -1
- package/scripts/generate-models.ts +19 -3
- package/scripts/manual-overrides.ts +15 -1
- package/scripts/models.generated.ts +5 -5
- package/src/cache-anomaly.ts +277 -0
- package/src/debug-command.ts +124 -0
- package/src/debug-report.ts +601 -0
- package/src/index.ts +2 -0
- package/src/openai-compat-sanitizer.ts +20 -2
- package/src/provider-factory.ts +43 -4
- package/src/zip.ts +114 -0
package/AGENTS.md
CHANGED
|
@@ -174,8 +174,8 @@ Since 1.0.0 the package version **aligns its MAJOR.MINOR with the pi release lin
|
|
|
174
174
|
The `ExtensionAPI` interface does not include `modelRegistry`; it exists only on
|
|
175
175
|
`ExtensionContext` (the `ctx` passed to command/event handlers). At factory time,
|
|
176
176
|
stored credentials are resolved via `readStoredCredential("nan")` from
|
|
177
|
-
`@earendil-works/pi-coding-agent`. Command-time paths (`/nan-mcp`, `/nan-usage
|
|
178
|
-
`ctx.modelRegistry`.
|
|
177
|
+
`@earendil-works/pi-coding-agent`. Command-time paths (`/nan-mcp`, `/nan-usage`,
|
|
178
|
+
`/nan-debug`) use `ctx.modelRegistry`.
|
|
179
179
|
- models.json overrides compose **above** registered native providers.
|
|
180
180
|
- Capability values that diverge from models.dev are recorded as build-time
|
|
181
181
|
`MANUAL_OVERRIDES` (mandatory provenance note) in `scripts/manual-overrides.ts`,
|
|
@@ -490,3 +490,27 @@ Since 1.0.0 the package version **aligns its MAJOR.MINOR with the pi release lin
|
|
|
490
490
|
the network phase already persists correct merged data. Option (a) of the
|
|
491
491
|
reporter (version-stamping persisted entries) is NOT implementable
|
|
492
492
|
provider-side: the store write path belongs to pi-ai.
|
|
493
|
+
|
|
494
|
+
- **Cache-anomaly evidence + `/nan-debug` (issue #35, verified 2026-11-11 on
|
|
495
|
+
pi-ai 1.5.1):** pi-ai's `StreamOptions.onResponse(response, model)` is the
|
|
496
|
+
only response-header surface (`ProviderResponse = { status, headers }`,
|
|
497
|
+
called by openai-completions right after the HTTP response). The gateway
|
|
498
|
+
`id`/`created` pair comes from raw `onProviderStreamEvent` chunks: pi-ai copies
|
|
499
|
+
only `chunk.id` into `AssistantMessage.responseId`, and `created` is never
|
|
500
|
+
persisted. `src/cache-anomaly.ts` wraps the provider api outermost
|
|
501
|
+
(`withCacheAnomalyCapture`), compares each completed stream against the
|
|
502
|
+
previous one **per model**, and on the #17 signature (same `id` + `created`)
|
|
503
|
+
appends one record to `<agentDir>/nan-cache-anomalies.jsonl`. Bursts record
|
|
504
|
+
the first pair once; a differing signature resets the baseline. The record is
|
|
505
|
+
local-only (model, id/created, both `cf-ray`, ISO timestamps, payload
|
|
506
|
+
SHA-256); no content, credentials or paths. `--window`'s usage fetch is the
|
|
507
|
+
only network path in `/nan-debug` and stays behind the explicit flag.
|
|
508
|
+
`src/debug-report.ts` reads `<agentDir>/sessions/**/*.jsonl` (filename date
|
|
509
|
+
prefix, else mtime), extracts only assistant `provider: "nan"` turns, and
|
|
510
|
+
renders the 2026-11-10 report shape plus `turns.jsonl`. The zip is built by
|
|
511
|
+
`src/zip.ts` (store method, sorted entries, fixed 1980-01-01 timestamps)
|
|
512
|
+
because `Bun.Archive` is Bun-only and pi also runs on Node. Session/worktree
|
|
513
|
+
labels are MD5[:12]; `errorMessage` maps to
|
|
514
|
+
`overflow|rate_limited|invalid_request|transport|other`.
|
|
515
|
+
Regression tests: `test/issue-35-cache-anomaly-capture.test.ts`,
|
|
516
|
+
`test/issue-35-debug-report.test.ts`, `test/issue-35-nan-debug-command.test.ts`.
|
package/CONTRIBUTING.md
CHANGED
|
@@ -1,6 +1,15 @@
|
|
|
1
1
|
# Contributing to @gtrabanco/pi-nan-provider
|
|
2
2
|
|
|
3
|
-
Thanks for contributing! Read [`AGENTS.md`](AGENTS.md) first — it contains the binding rules for this repo (the One Rule, no fabricated model metadata, one shared provider implementation, verified pi API facts,
|
|
3
|
+
Thanks for contributing! Read [`AGENTS.md`](AGENTS.md) first — it contains the binding rules for this repo (the One Rule, no fabricated model metadata, one shared provider implementation, verified pi API facts, the versioning policy, and AI content policies). This document covers the mechanics.
|
|
4
|
+
|
|
5
|
+
## AI-generated contributions
|
|
6
|
+
|
|
7
|
+
**Changes made with AI are welcome.** Whether you wrote a feature, fixed a bug, or improved docs using an AI assistant, the only requirement is transparency:
|
|
8
|
+
|
|
9
|
+
- **Code and committed files** (source, tests, docs, configs): never add AI authorship stamps or metadata inside the code itself (no `// Generated by AI`, no `Author: AI`, no co-author fields). Clean, direct code only.
|
|
10
|
+
- **GitHub PRs and comments**: when a PR description, comment, or issue body is generated (wholly or substantially) by AI, append a sign-off line in the language of the conversation, e.g. "Automatically generated using AI" or similar. People have the right to know whether they are talking to another person, a person steering an AI, or an autonomous AI — so always disclose when content was AI-generated.
|
|
11
|
+
|
|
12
|
+
Full policy is in [`AGENTS.md`](AGENTS.md) under *AI-generated content must be signed*.
|
|
4
13
|
|
|
5
14
|
## Setup
|
|
6
15
|
|
package/README.es.md
CHANGED
|
@@ -350,6 +350,48 @@ Los errores siguen siendo accionables: `401` → ejecuta `/login nan` o corrige
|
|
|
350
350
|
|
|
351
351
|
---
|
|
352
352
|
|
|
353
|
+
## 🧾 Evidencia de anomalías de caché: `/nan-debug`
|
|
354
|
+
|
|
355
|
+
La caché de respuestas del gateway de NaN puede devolver el mismo `id` y
|
|
356
|
+
`created` en peticiones seguidas (la firma del issue #17). NaN pidió el `model`
|
|
357
|
+
y el `cf-ray` de un par de llamadas si vuelve a pasar; los transcripts de pi no
|
|
358
|
+
guardan cabeceras de respuesta, así que el proveedor las captura.
|
|
359
|
+
|
|
360
|
+
Cuando dos streams del mismo modelo devuelven el mismo `id` + `created`, se
|
|
361
|
+
añade una línea JSON a `<agentDir>/nan-cache-anomalies.jsonl` — `model`, el par
|
|
362
|
+
`id`/`created`, los dos `cf-ray`, timestamps ISO y un SHA-256 del payload de la
|
|
363
|
+
petición. Es **solo local**: ni contenido de prompt/respuesta, ni credenciales,
|
|
364
|
+
ni rutas, ni subida remota. Un fallo de escritura nunca rompe un stream.
|
|
365
|
+
|
|
366
|
+
`/nan-debug` convierte ese fichero y tus transcripts en un paquete de evidencia
|
|
367
|
+
redactado y reproducible para NaN:
|
|
368
|
+
|
|
369
|
+
```text
|
|
370
|
+
/nan-debug # últimos 7 días, escribe <agentDir>/nan-debug-report/
|
|
371
|
+
/nan-debug cache --window 2 # etiqueta de tema + ventana de 2 días
|
|
372
|
+
/nan-debug --window 2 --emit # además escribe <agentDir>/nan-debug-report.zip
|
|
373
|
+
/nan-debug cache --out ~/evidence --emit
|
|
374
|
+
```
|
|
375
|
+
|
|
376
|
+
- `--window N` (1–90 días) consulta además `GET /v1/usage` para el mismo periodo
|
|
377
|
+
con tu clave guardada y escribe `usage_window.json`; sin el flag no se hace
|
|
378
|
+
ninguna petición. Esa llamada en vivo consume el límite de peticiones.
|
|
379
|
+
- El zip se escribe **solo** con `--emit`; la ejecución por defecto escribe el
|
|
380
|
+
informe local e imprime un resumen.
|
|
381
|
+
- `--out <ruta>` escribe el informe donde lo indiques (y, con `--emit`,
|
|
382
|
+
`<ruta>.zip`); un `~/` inicial se expande a tu directorio home, así que los
|
|
383
|
+
ejemplos de arriba escriben donde dicen. Un token de flag nunca se acepta
|
|
384
|
+
como ruta.
|
|
385
|
+
- El informe contiene `README.md`, `anonymized_usage.jsonl` (totales por
|
|
386
|
+
fecha/sesión/modelo, conteo de `stopReason`, tasa de acierto de caché),
|
|
387
|
+
`turns.jsonl` (uso por turno, `stopReason`, clase de error, `responseId`),
|
|
388
|
+
`anomalies.jsonl` (par de `cf-ray`) y `metadata.json` (versiones de paquete,
|
|
389
|
+
pi-ai y pi; procedencia del catálogo).
|
|
390
|
+
- Las etiquetas de sesión y worktree son MD5 truncado a 12 caracteres;
|
|
391
|
+
`errorMessage` se reduce a `overflow | rate_limited | invalid_request |
|
|
392
|
+
transport | other`; el contenido de prompt/respuesta y las credenciales nunca
|
|
393
|
+
se recogen. Entradas idénticas producen bytes de zip idénticos.
|
|
394
|
+
|
|
353
395
|
## 📊 Modelos
|
|
354
396
|
|
|
355
397
|
Catálogo base (verificado contra [docs de NaN](https://nan.builders/docs/models) y [OpenAPI](https://nan.builders/openapi.json)).
|
|
@@ -412,7 +454,7 @@ El parámetro `reasoning_effort` de NaN controla cuánto piensa el modelo antes
|
|
|
412
454
|
| `mimo-v2.6-flash` | `none` | Los docs lo llamaban "profundidad no ajustable", pero el gateway en vivo (2026-10-14) muestra que `none` da 0 tokens de razonamiento con respuesta completa mientras `low` da 22 y omitirlo 17 — así que `thinking: "off"` envía `reasoning_effort: "none"` vía el `thinkingLevelMap` del catálogo |
|
|
413
455
|
|
|
414
456
|
> [!NOTE]
|
|
415
|
-
> `maxTokens` NO limita la fase de razonamiento en los modelos de NaN. La fase de razonamiento corre hasta completarse (o se corta en el límite de stream solo-razonamiento de NaN: 45.000 caracteres de razonamiento, o 420 s sin salida visible) independientemente de `maxTokens` — medido: `max_tokens=512` en deepseek-v4-flash aún consumió 13,376 tokens de completación, todos de razonamiento (26x el techo). Este es un comportamiento del gateway confirmado por el issue #16 (medido 2026-09-27).
|
|
457
|
+
> `maxTokens` NO limita la fase de razonamiento en los modelos de NaN. La fase de razonamiento corre hasta completarse (o se corta en el límite de stream solo-razonamiento de NaN: 45.000 caracteres de razonamiento, o 420 s sin salida visible) independientemente de `maxTokens` — medido: `max_tokens=512` en deepseek-v4-flash aún consumió 13,376 tokens de completación, todos de razonamiento (26x el techo). Este es un comportamiento del gateway confirmado por el issue #16 (medido 2026-09-27) y por NaN para `qwen3.8-flash` (issue #34, 2026-11-11 — el exceso además factura contra la cuota). Como límite provisional para `qwen3.8-flash` el catálogo envía `max_completion_tokens`, que NaN confirmó que SÍ se respeta; sobrevive porque la compat de ese modelo desactiva el renombrado a `max_tokens` del sanitizador de esquema (su OpenAPI publicado solo documenta `max_tokens`). Retira ese override cuando NaN publique el arreglo en su gateway — `test/issue-34-max-completion-tokens.test.ts` es el tripwire. Solo el razonamiento aún puede agotar el presupuesto completo y cerrar el turno con contenido vacío; ese corte lleva el marcador `reasoning_only_stream` de NaN y pi-ai reintenta el turno (issue #21).
|
|
416
458
|
|
|
417
459
|
## 🚀 Desarrollo
|
|
418
460
|
|
package/README.md
CHANGED
|
@@ -345,6 +345,47 @@ Failures stay actionable: `401` → run `/login nan` or fix `NAN_API_KEY`, `404`
|
|
|
345
345
|
|
|
346
346
|
---
|
|
347
347
|
|
|
348
|
+
## 🧾 Cache anomaly evidence: `/nan-debug`
|
|
349
|
+
|
|
350
|
+
NaN's gateway response cache can replay the same completion `id` and `created`
|
|
351
|
+
timestamp for back-to-back requests (the issue #17 signature). NaN asked for the
|
|
352
|
+
`model` and the `cf-ray` of a couple of calls when it recurs; pi transcripts do
|
|
353
|
+
not keep response headers, so the provider captures them itself.
|
|
354
|
+
|
|
355
|
+
When two streams for the same model return the same `id` + `created`, one JSON
|
|
356
|
+
line is appended to `<agentDir>/nan-cache-anomalies.jsonl` —
|
|
357
|
+
`model`, the `id`/`created` pair, both `cf-ray` values, ISO timestamps and a
|
|
358
|
+
SHA-256 of the request payload. It is **local-only**: no prompt or response
|
|
359
|
+
content, no credentials, no paths, no upload. A write failure never breaks a
|
|
360
|
+
stream.
|
|
361
|
+
|
|
362
|
+
`/nan-debug` turns that file plus your session transcripts into a redacted,
|
|
363
|
+
reproducible evidence package for NaN:
|
|
364
|
+
|
|
365
|
+
```text
|
|
366
|
+
/nan-debug # last 7 days, writes <agentDir>/nan-debug-report/
|
|
367
|
+
/nan-debug cache --window 2 # topic label + a 2-day window
|
|
368
|
+
/nan-debug --window 2 --emit # also writes <agentDir>/nan-debug-report.zip
|
|
369
|
+
/nan-debug cache --out ~/evidence --emit
|
|
370
|
+
```
|
|
371
|
+
|
|
372
|
+
- `--window N` (1–90 days) also fetches `GET /v1/usage` for the same period with
|
|
373
|
+
your stored key and writes `usage_window.json`; without the flag nothing is
|
|
374
|
+
fetched. That live call counts against your quota's request rate.
|
|
375
|
+
- The zip is written **only** with `--emit`; the default run writes the local
|
|
376
|
+
report and prints a preview.
|
|
377
|
+
- `--out <path>` writes the report anywhere you name it (and, with `--emit`,
|
|
378
|
+
`<path>.zip`); a leading `~/` expands to your home directory, so the examples
|
|
379
|
+
above write where they say. A flag token is never accepted as the path.
|
|
380
|
+
- The report contains `README.md`, `anonymized_usage.jsonl` (per date/session/
|
|
381
|
+
model totals, stop-reason counts, cache-hit rate), `turns.jsonl` (per-turn
|
|
382
|
+
usage, stop reason, error class, response id), `anomalies.jsonl` (`cf-ray`
|
|
383
|
+
pair) and `metadata.json` (package/pi-ai/pi versions, catalog provenance).
|
|
384
|
+
- Session and worktree labels are MD5-truncated to 12 chars; `errorMessage` is
|
|
385
|
+
reduced to `overflow | rate_limited | invalid_request | transport | other`;
|
|
386
|
+
prompt/response content and credentials are never collected. Identical inputs
|
|
387
|
+
produce byte-identical zip bytes.
|
|
388
|
+
|
|
348
389
|
## 📊 Models
|
|
349
390
|
|
|
350
391
|
Baseline catalog (verified against [NaN docs](https://nan.builders/docs/models) and [OpenAPI](https://nan.builders/openapi.json)).
|
|
@@ -404,7 +445,7 @@ NaN's `reasoning_effort` parameter controls how much the model thinks before ans
|
|
|
404
445
|
| `kimi-k3.1-pro`, `qwen3.8-max`, `deepseek-v4-pro`, `hy4` | *(no mapping declared)* | External-provider models launched 2026-11-10; how the gateway translates `reasoning_effort` for them is unmeasured, so the catalog declares no effort values and no `thinkingLevelMap` (`thinking: "off"` sends no parameter) |
|
|
405
446
|
| `mimo-v2.6-flash` | `none` | The docs called this "depth not adjustable", but the live gateway (2026-10-14) shows `none` gives 0 reasoning tokens with a full answer while `low` gives 22 and omitting the parameter 17 — so `thinking: "off"` sends `reasoning_effort: "none"` via the catalog's `thinkingLevelMap` |
|
|
406
447
|
> [!NOTE]
|
|
407
|
-
> `maxTokens` does NOT bound the reasoning phase on NaN models. The reasoning phase runs to completion (or is cut at NaN's reasoning-only stream limit: 45,000 reasoning characters, or 420 s without visible output) regardless of `maxTokens` — measured: `max_tokens=512` on deepseek-v4-flash still consumed 13,376 completion tokens, all reasoning (26x the ceiling). This is gateway behavior confirmed by issue #16 (measured 2026-09-27).
|
|
448
|
+
> `maxTokens` does NOT bound the reasoning phase on NaN models. The reasoning phase runs to completion (or is cut at NaN's reasoning-only stream limit: 45,000 reasoning characters, or 420 s without visible output) regardless of `maxTokens` — measured: `max_tokens=512` on deepseek-v4-flash still consumed 13,376 completion tokens, all reasoning (26x the ceiling). This is gateway behavior confirmed by issue #16 (measured 2026-09-27) and by NaN for `qwen3.8-flash` (issue #34, 2026-11-11 — the excess also bills against the quota). As an interim bound for `qwen3.8-flash` the catalog sends `max_completion_tokens` instead, which NaN confirmed IS respected; it survives because that model's compat opts out of the schema sanitizer's rename to `max_tokens` (its published OpenAPI schema still documents only `max_tokens`). Remove that override once NaN ships their gateway fix — `test/issue-34-max-completion-tokens.test.ts` is the tripwire. Reasoning alone can still consume the whole budget and end the turn with empty content; that closure carries NaN's `reasoning_only_stream` marker and pi-ai retries the turn (issue #21).
|
|
408
449
|
|
|
409
450
|
|
|
410
451
|
---
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@gtrabanco/pi-nan-provider",
|
|
3
|
-
"version": "1.5.
|
|
3
|
+
"version": "1.5.3",
|
|
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",
|
|
@@ -63,6 +63,17 @@ const MODELS_DEV_API_URL = "https://models.dev/api.json";
|
|
|
63
63
|
const SOURCE_PROVIDER_ID = "nan";
|
|
64
64
|
const FETCH_TIMEOUT_MS = 15_000;
|
|
65
65
|
|
|
66
|
+
/**
|
|
67
|
+
* Per-entry compat: the LiteLLM-confirmed NAN_COMPAT shared by every NaN
|
|
68
|
+
* model, with any per-model MANUAL_OVERRIDES.maxTokensField applied. The
|
|
69
|
+
* strict-schema sanitizer reads `compat.maxTokensField` at request time to
|
|
70
|
+
* decide whether `max_completion_tokens` survives to the wire (issue #34),
|
|
71
|
+
* so the generated entry is the single place that value can come from.
|
|
72
|
+
*/
|
|
73
|
+
function buildCompat(override: ManualModelOverride | undefined): typeof NAN_COMPAT {
|
|
74
|
+
return override?.maxTokensField ? { ...NAN_COMPAT, maxTokensField: override.maxTokensField } : { ...NAN_COMPAT };
|
|
75
|
+
}
|
|
76
|
+
|
|
66
77
|
/**
|
|
67
78
|
* Official community chat models per https://nan.builders/docs/models
|
|
68
79
|
* (checked 2026-09-29). Each MUST reach the catalog — from models.dev or from a MANUAL_ONLY entry —
|
|
@@ -131,7 +142,12 @@ const NAN_COMPAT = {
|
|
|
131
142
|
// silently synthesizes stop/toolUse and the turn stalls mid-answer
|
|
132
143
|
// (observed 2026-09-13 on glm5.3-flash; issue #2).
|
|
133
144
|
supportsFinishReason: true,
|
|
134
|
-
|
|
145
|
+
// The request field is the classic `max_tokens` for every model by default.
|
|
146
|
+
// Typed as the `"max_tokens" | "max_completion_tokens"` union so a per-model
|
|
147
|
+
// MANUAL_OVERRIDES entry (issue #34: qwen3.8-flash sends
|
|
148
|
+
// `max_completion_tokens`) can override it without widening the value away
|
|
149
|
+
// from the confirmed string.
|
|
150
|
+
maxTokensField: "max_tokens" as "max_tokens" | "max_completion_tokens",
|
|
135
151
|
};
|
|
136
152
|
|
|
137
153
|
const NAN_COMPAT_NOTE =
|
|
@@ -216,7 +232,7 @@ function buildManualOnlyModelEntry(
|
|
|
216
232
|
maxTokens: override?.maxTokens ?? 131_072,
|
|
217
233
|
reasoningEffortValues,
|
|
218
234
|
...(override?.thinkingLevelMap ? { thinkingLevelMap: { ...override.thinkingLevelMap } } : {}),
|
|
219
|
-
compat:
|
|
235
|
+
compat: buildCompat(override),
|
|
220
236
|
notes: [
|
|
221
237
|
NAN_COMPAT_NOTE,
|
|
222
238
|
`manual-only: "${modelId}" not yet on models.dev provider nan (${detail}).`,
|
|
@@ -276,7 +292,7 @@ function convertModel(modelId: string, m: ModelsDevModel): GeneratedModel | { sk
|
|
|
276
292
|
maxTokens: override?.maxTokens ?? maxTokens,
|
|
277
293
|
reasoningEffortValues,
|
|
278
294
|
...(override?.thinkingLevelMap ? { thinkingLevelMap: { ...override.thinkingLevelMap } } : {}),
|
|
279
|
-
compat:
|
|
295
|
+
compat: buildCompat(override),
|
|
280
296
|
notes: [
|
|
281
297
|
NAN_COMPAT_NOTE,
|
|
282
298
|
...(override ? [override.note] : []),
|
|
@@ -44,6 +44,18 @@ export interface ManualModelOverride {
|
|
|
44
44
|
* supplies the effort value that NaN understands (e.g. "none" or "minimal").
|
|
45
45
|
*/
|
|
46
46
|
thinkingLevelMap?: Partial<Record<string, string | null>>;
|
|
47
|
+
/**
|
|
48
|
+
* Compat max-tokens request field override, applied over NAN_COMPAT.
|
|
49
|
+
* The default for every NaN model is the classic `max_tokens` field
|
|
50
|
+
* (LiteLLM-confirmed); a model where `max_tokens` does not bound the
|
|
51
|
+
* reasoning phase sends `max_completion_tokens` instead. The strict-schema
|
|
52
|
+
* sanitizer renames `max_completion_tokens` back to `max_tokens` by default
|
|
53
|
+
* (NaN's published OpenAPI schema only documents `max_tokens`), so a model
|
|
54
|
+
* carrying `"max_completion_tokens"` here is also exempted from that rename
|
|
55
|
+
* at request time (SanitizerOptions.preserveMaxCompletionTokens, wired from
|
|
56
|
+
* the model's effective compat in src/provider-factory.ts).
|
|
57
|
+
*/
|
|
58
|
+
maxTokensField?: "max_tokens" | "max_completion_tokens";
|
|
47
59
|
/** Required provenance note; emitted verbatim onto the generated entry. */
|
|
48
60
|
note: string;
|
|
49
61
|
}
|
|
@@ -243,8 +255,10 @@ export const MANUAL_OVERRIDES: Record<string, ManualModelOverride> = {
|
|
|
243
255
|
},
|
|
244
256
|
"qwen3.8-flash": {
|
|
245
257
|
contextWindow: 1_048_576,
|
|
258
|
+
maxTokensField: "max_completion_tokens",
|
|
246
259
|
note:
|
|
247
|
-
"contextWindow 1,048,576: NaN docs state '1M token context (1,048,576 tokens)' and 'Max answer 131K tokens' (https://nan.builders/docs/models, checked 2026-10-14) — models.dev still lists 262,144. The earlier override was withdrawn 2026-09-07 when the docs read '262K token context, the model's native window'; the docs now state 1M and they are the source of truth (maintainer instruction: docs win over models.dev, which a user updates later). maxTokens stays 131,072, which models.dev already matches and the docs confirm as the 131K max answer."
|
|
260
|
+
"contextWindow 1,048,576: NaN docs state '1M token context (1,048,576 tokens)' and 'Max answer 131K tokens' (https://nan.builders/docs/models, checked 2026-10-14) — models.dev still lists 262,144. The earlier override was withdrawn 2026-09-07 when the docs read '262K token context, the model's native window'; the docs now state 1M and they are the source of truth (maintainer instruction: docs win over models.dev, which a user updates later). maxTokens stays 131,072, which models.dev already matches and the docs confirm as the 131K max answer. " +
|
|
261
|
+
"maxTokensField 'max_completion_tokens' (issue #34, NaN maintainer confirmation received 2026-11-11, quoted verbatim in the issue): on this model max_tokens does NOT bound the reasoning phase, the excess bills against the quota (it explained the 796M tokens against the 500M cap in the 2026-09-27 /v1/usage survey), and max_completion_tokens IS respected as the interim bound. The published OpenAPI schema still documents only max_tokens, so the strict-schema sanitizer exempts this model from its max_completion_tokens→max_tokens rename at request time (SanitizerOptions.preserveMaxCompletionTokens, wired from compat.maxTokensField in src/provider-factory.ts). REVERT: once NaN ships their prepared gateway fix, remove this override — test/issue-34-max-completion-tokens.test.ts fails on purpose until it is removed; accepting max_completion_tokens on the other flash models is unverified live (permission-gated probe needed), so the scope stays this one model.",
|
|
248
262
|
},
|
|
249
263
|
"deepseek-v4-flash": {
|
|
250
264
|
input: ["text", "image"],
|
|
@@ -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-12T01:10:06.135Z
|
|
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.
|
|
@@ -614,11 +614,11 @@ export const NAN_GENERATED_MODELS: readonly GeneratedModelEntry[] = [
|
|
|
614
614
|
"supportsReasoningEffort": true,
|
|
615
615
|
"supportsUsageInStreaming": true,
|
|
616
616
|
"supportsFinishReason": true,
|
|
617
|
-
"maxTokensField": "
|
|
617
|
+
"maxTokensField": "max_completion_tokens"
|
|
618
618
|
},
|
|
619
619
|
"notes": [
|
|
620
620
|
"compat matches the maintainer's working ~/.pi/agent/models.json LiteLLM config for api.nan.builders (2026-09-04): supportsDeveloperRole false, supportsReasoningEffort true, maxTokensField max_tokens. NaN's docs example sets only supportsDeveloperRole: true and is not battle-tested. supportsFinishReason true (2026-09-13, issue #2): the LiteLLM gateway intermittently closes SSE streams before emitting finish_reason; with true pi-ai raises 'Stream ended without finish_reason', which matches pi-ai's retryable-provider pattern ('ended without') and is retried automatically, whereas false silently synthesized stop/toolUse and stalled the turn mid-answer. supportsUsageInStreaming true (2026-09-16, issue #7): NaN's published schema is silent about stream_options, but the live gateway honors it — two identical streaming calls per model, differing only in stream_options: { include_usage: true }, returned 0 usage chunks without it and exactly 1 with it (prompt/completion/reasoning/cached token counts) on deepseek-v4-flash, glm5.3-flash, qwen3.6, mimo-v2.5 and gemma4, and a real pi session then recorded token counts where it recorded zeros. pi-ai only sends stream_options when this is not false, and the sanitizer forwards it when the model declares true, so chat models opt in by default and usage is reported (issue #4). A model that does not report streaming usage can still opt out per model with a models.json compat override (supportsUsageInStreaming: false); the sanitizer then strips stream_options and the payload stays strict.",
|
|
621
|
-
"contextWindow 1,048,576: NaN docs state '1M token context (1,048,576 tokens)' and 'Max answer 131K tokens' (https://nan.builders/docs/models, checked 2026-10-14) — models.dev still lists 262,144. The earlier override was withdrawn 2026-09-07 when the docs read '262K token context, the model's native window'; the docs now state 1M and they are the source of truth (maintainer instruction: docs win over models.dev, which a user updates later). maxTokens stays 131,072, which models.dev already matches and the docs confirm as the 131K max answer."
|
|
621
|
+
"contextWindow 1,048,576: NaN docs state '1M token context (1,048,576 tokens)' and 'Max answer 131K tokens' (https://nan.builders/docs/models, checked 2026-10-14) — models.dev still lists 262,144. The earlier override was withdrawn 2026-09-07 when the docs read '262K token context, the model's native window'; the docs now state 1M and they are the source of truth (maintainer instruction: docs win over models.dev, which a user updates later). maxTokens stays 131,072, which models.dev already matches and the docs confirm as the 131K max answer. maxTokensField 'max_completion_tokens' (issue #34, NaN maintainer confirmation received 2026-11-11, quoted verbatim in the issue): on this model max_tokens does NOT bound the reasoning phase, the excess bills against the quota (it explained the 796M tokens against the 500M cap in the 2026-09-27 /v1/usage survey), and max_completion_tokens IS respected as the interim bound. The published OpenAPI schema still documents only max_tokens, so the strict-schema sanitizer exempts this model from its max_completion_tokens→max_tokens rename at request time (SanitizerOptions.preserveMaxCompletionTokens, wired from compat.maxTokensField in src/provider-factory.ts). REVERT: once NaN ships their prepared gateway fix, remove this override — test/issue-34-max-completion-tokens.test.ts fails on purpose until it is removed; accepting max_completion_tokens on the other flash models is unverified live (permission-gated probe needed), so the scope stays this one model."
|
|
622
622
|
],
|
|
623
623
|
"extras": {
|
|
624
624
|
"id": "qwen3.8-flash",
|
|
@@ -703,7 +703,7 @@ export const NAN_GENERATED_MODELS: readonly GeneratedModelEntry[] = [
|
|
|
703
703
|
export const GENERATED_CATALOG_META = {
|
|
704
704
|
source: "https://models.dev/api.json",
|
|
705
705
|
modelsDevProvider: "nan",
|
|
706
|
-
fetchedAt: "2026-11-
|
|
706
|
+
fetchedAt: "2026-11-12T01:10:06.135Z",
|
|
707
707
|
modelCount: 11,
|
|
708
708
|
models: ["deepseek-v4-flash","deepseek-v4-pro","gemma4","glm5.3","glm5.3-flash","hy4","kimi-k3.1-pro","mimo-v2.6-flash","qwen3.6","qwen3.8-flash","qwen3.8-max"],
|
|
709
709
|
notes: [
|
|
@@ -730,7 +730,7 @@ export const GENERATED_CATALOG_META = {
|
|
|
730
730
|
"thinkingLevelMap { off: \"none\" } (live re-probe 2026-10-14): the docs list this model as 'accepted, depth not adjustable', but the gateway makes the parameter effective at the off end — `none` gave 0 reasoning tokens / a full answer, while `low` gave 22 reasoning tokens and omitting the parameter gave 17. Measured behavior wins over the docs, so `thinking: off` now sends reasoning_effort:\"none\" and actually disables reasoning. No other level was sampled, so only `off` is mapped.",
|
|
731
731
|
"manual-only: \"mimo-v2.6-flash\" skipped: models.dev provider \"nan\" now lists it, so the manual-only entry is not emitted and the models.dev values are used (omnimodal model (text, image, audio input) served by NaN; limits and modalities from https://nan.builders/docs/models#mimo-v2-6-flash (checked 2026-09-25, quotas re-checked 2026-09-29): 1,048,576 context / 131,072 max output / 1.0B monthly quota per member. Tool calling: yes. Streaming: yes. Input modalities (pi-representable): text, image (audio not representable in pi's Model type). Fallback entry: emitted only while models.dev provider nan does not list the model — models.dev started listing it on 2026-09-29, so the generator then keeps the models.dev values and attaches this note to that entry instead of emitting a second one.)",
|
|
732
732
|
"thinkingLevelMap { off: \"none\" } (issue #16): NaN docs state that with no reasoning_effort parameter every model uses its own default and that default is reasoning ON for qwen3.6 (16,384-token budget), while `none` and `minimal` skip the reasoning phase entirely (https://nan.builders/docs/models#controlling-reasoning, checked 2026-10-01). pi maps reasoning:\"off\" to reasoningEffort:undefined, so without this map `thinking: off` sent no parameter and the model reasoned anyway; the map sends reasoning_effort:\"none\" and actually disables reasoning.",
|
|
733
|
-
"contextWindow 1,048,576: NaN docs state '1M token context (1,048,576 tokens)' and 'Max answer 131K tokens' (https://nan.builders/docs/models, checked 2026-10-14) — models.dev still lists 262,144. The earlier override was withdrawn 2026-09-07 when the docs read '262K token context, the model's native window'; the docs now state 1M and they are the source of truth (maintainer instruction: docs win over models.dev, which a user updates later). maxTokens stays 131,072, which models.dev already matches and the docs confirm as the 131K max answer.",
|
|
733
|
+
"contextWindow 1,048,576: NaN docs state '1M token context (1,048,576 tokens)' and 'Max answer 131K tokens' (https://nan.builders/docs/models, checked 2026-10-14) — models.dev still lists 262,144. The earlier override was withdrawn 2026-09-07 when the docs read '262K token context, the model's native window'; the docs now state 1M and they are the source of truth (maintainer instruction: docs win over models.dev, which a user updates later). maxTokens stays 131,072, which models.dev already matches and the docs confirm as the 131K max answer. maxTokensField 'max_completion_tokens' (issue #34, NaN maintainer confirmation received 2026-11-11, quoted verbatim in the issue): on this model max_tokens does NOT bound the reasoning phase, the excess bills against the quota (it explained the 796M tokens against the 500M cap in the 2026-09-27 /v1/usage survey), and max_completion_tokens IS respected as the interim bound. The published OpenAPI schema still documents only max_tokens, so the strict-schema sanitizer exempts this model from its max_completion_tokens→max_tokens rename at request time (SanitizerOptions.preserveMaxCompletionTokens, wired from compat.maxTokensField in src/provider-factory.ts). REVERT: once NaN ships their prepared gateway fix, remove this override — test/issue-34-max-completion-tokens.test.ts fails on purpose until it is removed; accepting max_completion_tokens on the other flash models is unverified live (permission-gated probe needed), so the scope stays this one model.",
|
|
734
734
|
"manual-only: \"qwen3.8-max\" not yet on models.dev provider nan (NaN external-provider model launched 2026-11-10, listed by the live GET /v1/models but absent from models.dev provider nan and the NaN docs).",
|
|
735
735
|
"NaN external-provider model launched 2026-11-10. contextWindow 1,000,000: NaN pricing page card says '1M context' (maintainer screenshot, 2026-11-10); the first-party vendor value on models.dev provider alibaba (qwen3.8-max) is 1,000,000, the smaller of it and NaN's 1M = 1,048,576 convention (https://nan.builders/docs/pi), so the vendor value is used. maxTokens 32,768: https://nan.builders/docs/pi declares 32768 for every 1M-context NaN model (vendor limit 131,072 on models.dev provider alibaba). input text+image per models.dev provider alibaba (qwen3.8-max), reasoning model per the vendor. Existence: live GET https://api.nan.builders/v1/models (checked 2026-11-10); the docs https://nan.builders/docs/models, https://nan.builders/docs/pi and https://nan.builders/openapi.json do not list it yet. reasoningEffortValues [] and no thinkingLevelMap: the gateway's reasoning_effort handling for external providers is unmeasured. cost 0 per maintainer decision."
|
|
736
736
|
],
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* NaN gateway cache-anomaly evidence capture (issue #35).
|
|
3
|
+
*
|
|
4
|
+
* Issue #17 identified NaN's gateway response cache: identical requests sent
|
|
5
|
+
* back-to-back can return the same completion `id` AND the same `created`
|
|
6
|
+
* timestamp — a replayed cache entry, not a new generation. NaN could not
|
|
7
|
+
* reproduce it and asked for "modelo y cf-ray de un par de llamadas". pi's
|
|
8
|
+
* session JSONL records usage and response ids but no response headers, so the
|
|
9
|
+
* provider is the only surface that can keep the `cf-ray` of both calls.
|
|
10
|
+
*
|
|
11
|
+
* This module:
|
|
12
|
+
* - reads `cf-ray` from pi-ai's `onResponse` hook (the only header surface),
|
|
13
|
+
* - reads the raw gateway `id`/`created` pair from `onProviderStreamEvent`
|
|
14
|
+
* chunks (pi-ai only persists `id` as `AssistantMessage.responseId`),
|
|
15
|
+
* - compares each completed stream with the previous one for the same model,
|
|
16
|
+
* and when both `id` and `created` repeat, appends one JSONL record to
|
|
17
|
+
* `<agentDir>/nan-cache-anomalies.jsonl`.
|
|
18
|
+
*
|
|
19
|
+
* The record deliberately carries no prompt or response content, no
|
|
20
|
+
* credentials and no paths: only the model, the gateway pair, both `cf-ray`
|
|
21
|
+
* values, ISO timestamps and a SHA-256 fingerprint of the request payload
|
|
22
|
+
* (used to say whether the duplicate arrived for the same payload). It is
|
|
23
|
+
* local-only — nothing is uploaded.
|
|
24
|
+
*
|
|
25
|
+
* A missing `onResponse` (older pi-ai or a host that does not call it) simply
|
|
26
|
+
* leaves `cf_ray` null; detection still works on `id`+`created`. Every write is
|
|
27
|
+
* best-effort: a full disk must never break a stream.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
import { createHash } from "node:crypto";
|
|
31
|
+
import { appendFileSync, mkdirSync } from "node:fs";
|
|
32
|
+
import { dirname, join } from "node:path";
|
|
33
|
+
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
34
|
+
import type { AssistantMessage, ProviderStreams } from "@earendil-works/pi-ai";
|
|
35
|
+
|
|
36
|
+
/** Default file name inside pi's agent dir. */
|
|
37
|
+
export const CACHE_ANOMALY_FILE = "nan-cache-anomalies.jsonl";
|
|
38
|
+
|
|
39
|
+
/** The only anomaly kind captured here (issue #17 signature). */
|
|
40
|
+
export const CACHE_ANOMALY_KIND = "duplicate_id_created";
|
|
41
|
+
|
|
42
|
+
export interface CacheAnomalyRequest {
|
|
43
|
+
/** Cloudflare trace id (`cf-ray`) of the response, when the host exposed it. */
|
|
44
|
+
cf_ray: string | null;
|
|
45
|
+
/** ISO timestamp of when the response headers were observed. */
|
|
46
|
+
observed_at: string;
|
|
47
|
+
/** SHA-256 of the outgoing request payload, null when unavailable. */
|
|
48
|
+
payload_sha256: string | null;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* One persisted anomaly. Both requests returned the same gateway `id` and
|
|
53
|
+
* `created`; `requests` carries each call's `cf-ray` and timestamp.
|
|
54
|
+
*/
|
|
55
|
+
export interface CacheAnomalyRecord {
|
|
56
|
+
detected_at: string;
|
|
57
|
+
kind: typeof CACHE_ANOMALY_KIND;
|
|
58
|
+
model: string;
|
|
59
|
+
id: string;
|
|
60
|
+
created: number;
|
|
61
|
+
/** Whether both streams sent the same request payload. */
|
|
62
|
+
payload_match: boolean;
|
|
63
|
+
requests: [CacheAnomalyRequest, CacheAnomalyRequest];
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface CacheAnomalySink {
|
|
67
|
+
record(record: CacheAnomalyRecord): void;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The anomaly file path for the current pi agent dir. */
|
|
71
|
+
export function defaultCacheAnomalyPath(): string {
|
|
72
|
+
return join(getAgentDir(), CACHE_ANOMALY_FILE);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* File sink: append one JSON line per anomaly, creating the agent dir if
|
|
77
|
+
* needed. Never throws — the first failure warns once, then stays quiet so a
|
|
78
|
+
* broken disk cannot spam the console or break a turn.
|
|
79
|
+
*/
|
|
80
|
+
export function createCacheAnomalyFileSink(filePath?: string): CacheAnomalySink {
|
|
81
|
+
let warned = false;
|
|
82
|
+
return {
|
|
83
|
+
record(record) {
|
|
84
|
+
try {
|
|
85
|
+
const target = filePath ?? defaultCacheAnomalyPath();
|
|
86
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
87
|
+
appendFileSync(target, `${JSON.stringify(record)}\n`);
|
|
88
|
+
} catch (error) {
|
|
89
|
+
if (warned) return;
|
|
90
|
+
warned = true;
|
|
91
|
+
console.warn(
|
|
92
|
+
`[pi-nan-provider] could not persist cache-anomaly evidence (${error instanceof Error ? error.message : String(error)}); streams continue.`,
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
},
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export interface CacheAnomalyCaptureOptions {
|
|
100
|
+
sink: CacheAnomalySink;
|
|
101
|
+
/** Injectable clock for deterministic tests. */
|
|
102
|
+
now?: () => Date;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
interface Observation {
|
|
106
|
+
cfRay: string | null;
|
|
107
|
+
observedAt: string;
|
|
108
|
+
payloadSha: string | null;
|
|
109
|
+
id?: string;
|
|
110
|
+
created?: number;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
interface LastResponse {
|
|
114
|
+
id: string;
|
|
115
|
+
created: number;
|
|
116
|
+
cfRay: string | null;
|
|
117
|
+
observedAt: string;
|
|
118
|
+
payloadSha: string | null;
|
|
119
|
+
/** Set once the duplicate pair was reported; suppresses burst cascades. */
|
|
120
|
+
recorded: boolean;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function isObject(value: unknown): value is Record<string, unknown> {
|
|
124
|
+
return typeof value === "object" && value !== null;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Case-insensitive header lookup (undici lowercases `Headers`, proxies may not). */
|
|
128
|
+
function headerValue(headers: Record<string, string> | undefined, name: string): string | null {
|
|
129
|
+
if (!headers) return null;
|
|
130
|
+
const wanted = name.toLowerCase();
|
|
131
|
+
for (const [key, value] of Object.entries(headers)) {
|
|
132
|
+
if (key.toLowerCase() === wanted && typeof value === "string" && value.length > 0) return value;
|
|
133
|
+
}
|
|
134
|
+
return null;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** SHA-256 of the payload; null when it cannot be serialized. */
|
|
138
|
+
export function fingerprintPayload(payload: unknown): string | null {
|
|
139
|
+
try {
|
|
140
|
+
return createHash("sha256").update(JSON.stringify(payload) ?? "").digest("hex");
|
|
141
|
+
} catch {
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** Extract `id`/`created` from a raw openai-completions chunk. */
|
|
147
|
+
export function gatewayPairFromChunk(chunk: unknown): { id?: string; created?: number } {
|
|
148
|
+
if (!isObject(chunk)) return {};
|
|
149
|
+
const id = typeof chunk.id === "string" && chunk.id.length > 0 ? chunk.id : undefined;
|
|
150
|
+
const rawCreated = chunk.created;
|
|
151
|
+
const created =
|
|
152
|
+
typeof rawCreated === "number" && Number.isFinite(rawCreated)
|
|
153
|
+
? rawCreated
|
|
154
|
+
: typeof rawCreated === "string" && /^\d+$/.test(rawCreated)
|
|
155
|
+
? Number(rawCreated)
|
|
156
|
+
: undefined;
|
|
157
|
+
return { ...(id ? { id } : {}), ...(created !== undefined ? { created } : {}) };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Wrap an api so completed streams are compared pairwise per model. Only the
|
|
162
|
+
* hooks are added; the stream, its events and its terminal message are
|
|
163
|
+
* untouched. Any caller-supplied `onResponse`, `onPayload` and
|
|
164
|
+
* `onProviderStreamEvent` are preserved and chained after the observation.
|
|
165
|
+
*/
|
|
166
|
+
export function withCacheAnomalyCapture(api: ProviderStreams, options: CacheAnomalyCaptureOptions): ProviderStreams {
|
|
167
|
+
const now = options.now ?? (() => new Date());
|
|
168
|
+
const lastByModel = new Map<string, LastResponse>();
|
|
169
|
+
|
|
170
|
+
const observe = <T extends object | undefined>(
|
|
171
|
+
run: (streamOptions: T) => ReturnType<ProviderStreams["stream"]>,
|
|
172
|
+
modelId: string,
|
|
173
|
+
streamOptions: T,
|
|
174
|
+
): ReturnType<ProviderStreams["stream"]> => {
|
|
175
|
+
const state: Observation = { cfRay: null, observedAt: now().toISOString(), payloadSha: null };
|
|
176
|
+
const opts = { ...((streamOptions ?? {}) as Record<string, unknown>) };
|
|
177
|
+
|
|
178
|
+
const userOnResponse = opts.onResponse;
|
|
179
|
+
opts.onResponse = async (response: unknown, model: unknown) => {
|
|
180
|
+
if (isObject(response)) {
|
|
181
|
+
state.cfRay = headerValue(response.headers as Record<string, string> | undefined, "cf-ray");
|
|
182
|
+
state.observedAt = now().toISOString();
|
|
183
|
+
}
|
|
184
|
+
if (typeof userOnResponse === "function") {
|
|
185
|
+
return (userOnResponse as (r: unknown, m: unknown) => unknown)(response, model);
|
|
186
|
+
}
|
|
187
|
+
return undefined;
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
const userOnPayload = opts.onPayload;
|
|
191
|
+
opts.onPayload = async (payload: unknown, model: unknown) => {
|
|
192
|
+
state.payloadSha = fingerprintPayload(payload);
|
|
193
|
+
if (typeof userOnPayload === "function") {
|
|
194
|
+
return (userOnPayload as (p: unknown, m: unknown) => unknown)(payload, model);
|
|
195
|
+
}
|
|
196
|
+
return undefined;
|
|
197
|
+
};
|
|
198
|
+
|
|
199
|
+
const userOnStreamEvent = opts.onProviderStreamEvent;
|
|
200
|
+
opts.onProviderStreamEvent = async (chunk: unknown, model: unknown) => {
|
|
201
|
+
const pair = gatewayPairFromChunk(chunk);
|
|
202
|
+
if (pair.id) state.id = pair.id;
|
|
203
|
+
if (pair.created !== undefined) state.created = pair.created;
|
|
204
|
+
if (typeof userOnStreamEvent === "function") {
|
|
205
|
+
return (userOnStreamEvent as (c: unknown, m: unknown) => unknown)(chunk, model);
|
|
206
|
+
}
|
|
207
|
+
return undefined;
|
|
208
|
+
};
|
|
209
|
+
|
|
210
|
+
const stream = run(opts as T);
|
|
211
|
+
|
|
212
|
+
const complete = (message: AssistantMessage | undefined) => {
|
|
213
|
+
// pi-ai persists only the id; keep it as a fallback when the raw
|
|
214
|
+
// chunks did not carry one.
|
|
215
|
+
const id = state.id ?? message?.responseId;
|
|
216
|
+
if (!id || state.created === undefined) return;
|
|
217
|
+
|
|
218
|
+
const current: LastResponse = {
|
|
219
|
+
id,
|
|
220
|
+
created: state.created,
|
|
221
|
+
cfRay: state.cfRay,
|
|
222
|
+
observedAt: state.observedAt,
|
|
223
|
+
payloadSha: state.payloadSha,
|
|
224
|
+
recorded: false,
|
|
225
|
+
};
|
|
226
|
+
const previous = lastByModel.get(modelId);
|
|
227
|
+
if (previous && previous.id === current.id && previous.created === current.created) {
|
|
228
|
+
if (!previous.recorded) {
|
|
229
|
+
const record: CacheAnomalyRecord = {
|
|
230
|
+
detected_at: now().toISOString(),
|
|
231
|
+
kind: CACHE_ANOMALY_KIND,
|
|
232
|
+
model: modelId,
|
|
233
|
+
id: current.id,
|
|
234
|
+
created: current.created,
|
|
235
|
+
payload_match:
|
|
236
|
+
previous.payloadSha !== null &&
|
|
237
|
+
current.payloadSha !== null &&
|
|
238
|
+
previous.payloadSha === current.payloadSha,
|
|
239
|
+
requests: [
|
|
240
|
+
{
|
|
241
|
+
cf_ray: previous.cfRay,
|
|
242
|
+
observed_at: previous.observedAt,
|
|
243
|
+
payload_sha256: previous.payloadSha,
|
|
244
|
+
},
|
|
245
|
+
{
|
|
246
|
+
cf_ray: current.cfRay,
|
|
247
|
+
observed_at: current.observedAt,
|
|
248
|
+
payload_sha256: current.payloadSha,
|
|
249
|
+
},
|
|
250
|
+
],
|
|
251
|
+
};
|
|
252
|
+
try {
|
|
253
|
+
options.sink.record(record);
|
|
254
|
+
} catch {
|
|
255
|
+
// Evidence capture is best-effort; never break the turn.
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
lastByModel.set(modelId, { ...previous, recorded: true });
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
lastByModel.set(modelId, current);
|
|
262
|
+
};
|
|
263
|
+
|
|
264
|
+
stream.result().then(complete, () => {
|
|
265
|
+
// A failed stream has no gateway pair worth comparing.
|
|
266
|
+
});
|
|
267
|
+
return stream;
|
|
268
|
+
};
|
|
269
|
+
|
|
270
|
+
return {
|
|
271
|
+
...api,
|
|
272
|
+
stream: (model, context, streamOptions) =>
|
|
273
|
+
observe((next) => api.stream(model, context, next), model.id, streamOptions),
|
|
274
|
+
streamSimple: (model, context, streamOptions) =>
|
|
275
|
+
observe((next) => api.streamSimple(model, context, next), model.id, streamOptions),
|
|
276
|
+
};
|
|
277
|
+
}
|