@gtrabanco/pi-nan-provider 1.6.1 → 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.
@@ -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.
@@ -41,6 +41,7 @@ import { withContextOverflowClassification } from "./context-overflow-classifier
41
41
  import { withReasoningOnlyStreamGuard } from "./reasoning-only-stream-guard.ts";
42
42
  import { createCacheAnomalyFileSink, withCacheAnomalyCapture, type CacheAnomalySink } from "./cache-anomaly.ts";
43
43
  import { createResponseRayFileSink, type ResponseRaySink } from "./response-rays.ts";
44
+ import { createHttpAttemptFileSink, withHttpAttemptCapture, type HttpAttemptSink } from "./http-attempts.ts";
44
45
  import { NAN_IMAGE_API, baselineImageModels, createNanImagesApi } from "./images.ts";
45
46
  import {
46
47
  baselineModels,
@@ -77,6 +78,8 @@ export interface NanCompatibleProviderOptions {
77
78
  cacheAnomalySink?: CacheAnomalySink;
78
79
  /** Sink for the per-response cf-ray sidecar (issue #35 S11); defaults to the agent-dir JSONL file. */
79
80
  responseRaySink?: ResponseRaySink;
81
+ /** Sink for the HTTP attempt sidecar (issue #49); defaults to the agent-dir JSONL file. */
82
+ httpAttemptSink?: HttpAttemptSink;
80
83
  }
81
84
 
82
85
  /**
@@ -306,18 +309,25 @@ export async function createNanCompatibleProvider(
306
309
  // middle → guard (marker detection), innermost → sanitizer (payload).
307
310
  // The guard's onProviderStreamEvent hook sees the raw response chunks
308
311
  // (NOT onPayload, which only receives the outgoing request params).
309
- // Outermost: cache-anomaly evidence capture (issue #35). It only adds
310
- // observation hooks (onResponse for `cf-ray`, onProviderStreamEvent for
311
- // the raw id/created pair) and never rewrites the stream. Since S11 it
312
- // also appends every observed cf-ray to the response-ray sidecar.
313
- api: withCacheAnomalyCapture(
314
- withContextOverflowClassification(
315
- withReasoningOnlyStreamGuard(wrapApiForStrictSanitization(apiFactory())),
312
+ // Outermost: the HTTP attempt tap (issue #49) injects `options.fetch`
313
+ // and observes every attempt, including the retries pi-ai hides and the
314
+ // 429s that never reach `onResponse`. It only adds the fetch wrapper and
315
+ // observation hooks; the stream is untouched.
316
+ // Next: cache-anomaly evidence capture (issue #35), which adds the
317
+ // `cf-ray`/id/created observation and the response-ray sidecar.
318
+ // Then: classifier (error rewrites), guard (marker detection), sanitizer
319
+ // (payload) — innermost.
320
+ api: withHttpAttemptCapture(
321
+ withCacheAnomalyCapture(
322
+ withContextOverflowClassification(
323
+ withReasoningOnlyStreamGuard(wrapApiForStrictSanitization(apiFactory())),
324
+ ),
325
+ {
326
+ sink: options.cacheAnomalySink ?? createCacheAnomalyFileSink(),
327
+ raySink: options.responseRaySink ?? createResponseRayFileSink(),
328
+ },
316
329
  ),
317
- {
318
- sink: options.cacheAnomalySink ?? createCacheAnomalyFileSink(),
319
- raySink: options.responseRaySink ?? createResponseRayFileSink(),
320
- },
330
+ { sink: options.httpAttemptSink ?? createHttpAttemptFileSink() },
321
331
  ),
322
332
  }),
323
333
  overlayMap,