@gtrabanco/pi-nan-provider 1.5.2 → 1.5.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.
@@ -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
- maxTokensField: "max_tokens" as const,
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: { ...NAN_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: { ...NAN_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-10T15:52:24.186Z
4
+ // Source: https://models.dev/api.json (provider "nan"), fetched 2026-11-12T22:42:17.308Z
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": "max_tokens"
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-10T15:52:24.186Z",
706
+ fetchedAt: "2026-11-12T22:42:17.308Z",
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
+ }
@@ -0,0 +1,124 @@
1
+ /**
2
+ * `/nan-debug` command (issue #35) — deterministic, redacted evidence
3
+ * collection following the `/nan-usage` precedent.
4
+ *
5
+ * Flow: parse → collect → write the redacted report locally → notify a preview.
6
+ * The shareable zip is written only with `--emit` (the explicit confirmation
7
+ * the issue asks for). `/v1/usage` is consulted only with `--window`, and it
8
+ * stays permission-gated: the user invoked the command with that flag.
9
+ */
10
+
11
+ import { join } from "node:path";
12
+ import { homedir as osHomedir } from "node:os";
13
+ import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
14
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
15
+ import { NAN_API_KEY_ENV, resolveStoredNanApiKey, tryResolveNanApiKeyViaRegistry } from "./mcp/api-key.ts";
16
+ import {
17
+ DEBUG_USAGE_LINE,
18
+ NAN_DEBUG_REPORT_DIR,
19
+ NAN_DEBUG_ZIP,
20
+ buildDebugReport,
21
+ fetchDebugUsageWindow,
22
+ parseDebugArgs,
23
+ renderDebugReport,
24
+ writeDebugReport,
25
+ writeDebugZip,
26
+ type FetchUsageWindow,
27
+ } from "./debug-report.ts";
28
+
29
+ export interface NanDebugCommandDeps {
30
+ /** Injectable for tests; defaults to pi's agent dir. */
31
+ agentDir?: string;
32
+ /** Injectable clock for deterministic tests. */
33
+ now?: () => Date;
34
+ /** Injectable `GET /v1/usage` client for tests; defaults to the live call. */
35
+ fetchUsage?: FetchUsageWindow;
36
+ /** Injectable key resolution for tests. */
37
+ resolveApiKey?: (ctx: ExtensionCommandContext) => Promise<string | undefined>;
38
+ /** Injectable home directory for tests; defaults to the OS home. */
39
+ homedir?: string;
40
+ }
41
+
42
+ async function defaultResolveApiKey(ctx: ExtensionCommandContext): Promise<string | undefined> {
43
+ const registryKey = await tryResolveNanApiKeyViaRegistry(ctx.modelRegistry);
44
+ return registryKey ?? resolveStoredNanApiKey() ?? (process.env[NAN_API_KEY_ENV] || undefined);
45
+ }
46
+
47
+ /**
48
+ * Expand a leading `~` (or `~/`) against the home directory so the README
49
+ * example `--out ~/evidence` writes where it says (EV-2026-11-11 A2).
50
+ * Every other path passes through untouched.
51
+ */
52
+ function expandHomePath(value: string, home: string): string {
53
+ if (value === "~") return home;
54
+ if (value.startsWith("~/")) return join(home, value.slice(2));
55
+ return value;
56
+ }
57
+
58
+ export function registerNanDebugCommand(pi: ExtensionAPI, deps: NanDebugCommandDeps = {}): void {
59
+ pi.registerCommand("nan-debug", {
60
+ description:
61
+ "Collect a redacted NaN evidence report locally; --emit writes the shareable zip (/nan-debug help)",
62
+ handler: async (args: string, ctx: ExtensionCommandContext) => {
63
+ if (args.trim().toLowerCase() === "help") {
64
+ ctx.ui.notify(DEBUG_USAGE_LINE, "info");
65
+ return;
66
+ }
67
+
68
+ const parsed = parseDebugArgs(args);
69
+ if (!parsed.ok) {
70
+ ctx.ui.notify(parsed.error, "warning");
71
+ return;
72
+ }
73
+
74
+ const now = deps.now?.() ?? new Date();
75
+ const agentDir = deps.agentDir ?? getAgentDir();
76
+ const apiKey = parsed.args.windowProvided
77
+ ? await (deps.resolveApiKey ?? defaultResolveApiKey)(ctx)
78
+ : undefined;
79
+
80
+ let rendered;
81
+ try {
82
+ const report = await buildDebugReport({
83
+ agentDir,
84
+ now,
85
+ windowDays: parsed.args.windowDays,
86
+ topic: parsed.args.topic,
87
+ apiKey,
88
+ includeUsage: parsed.args.windowProvided,
89
+ fetchUsage: parsed.args.windowProvided ? (deps.fetchUsage ?? fetchDebugUsageWindow) : undefined,
90
+ });
91
+ rendered = renderDebugReport(report);
92
+ } catch (error) {
93
+ ctx.ui.notify(
94
+ `nan-debug failed to collect the report: ${error instanceof Error ? error.message : String(error)}`,
95
+ "warning",
96
+ );
97
+ return;
98
+ }
99
+
100
+ const explicitZipTarget = parsed.args.out ? expandHomePath(parsed.args.out, deps.homedir ?? osHomedir()) : undefined;
101
+ const explicitZip = explicitZipTarget?.endsWith(".zip") ? explicitZipTarget : undefined;
102
+ const outDir = explicitZip
103
+ ? explicitZip.replace(/\.zip$/, "")
104
+ : (explicitZipTarget ?? join(agentDir, NAN_DEBUG_REPORT_DIR));
105
+ const zipPath = explicitZip ?? (explicitZipTarget ? `${explicitZipTarget}.zip` : join(agentDir, NAN_DEBUG_ZIP));
106
+
107
+ try {
108
+ writeDebugReport(rendered.files, outDir);
109
+ if (parsed.args.emit) writeDebugZip(rendered.files, zipPath);
110
+ } catch (error) {
111
+ ctx.ui.notify(
112
+ `nan-debug wrote nothing: ${error instanceof Error ? error.message : String(error)}`,
113
+ "warning",
114
+ );
115
+ return;
116
+ }
117
+
118
+ const message = parsed.args.emit
119
+ ? `${rendered.preview}\n→ zip written to ${zipPath}`
120
+ : `${rendered.preview}\n→ local report: ${outDir}`;
121
+ ctx.ui.notify(message, "info");
122
+ },
123
+ });
124
+ }