@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.
@@ -0,0 +1,615 @@
1
+ /**
2
+ * Provider-level HTTP attempt evidence (issue #49).
3
+ *
4
+ * pi's transcript only keeps the terminal outcome of a logical request: pi-ai
5
+ * retries 429/408/409/5xx inside `retryProviderRequest`, a retried request that
6
+ * finally succeeds appears as one ordinary turn, and `onResponse` fires only
7
+ * after the retry loop resolves — so a rejected attempt leaves no `cf-ray`, no
8
+ * status and no timing anywhere. Support asked for exactly that evidence (the
9
+ * reference CSV in issue #49 has one row per HTTP attempt).
10
+ *
11
+ * `createProvider` exposes no `fetch` option (pi-ai 1.6.0, `CreateProviderOptions`),
12
+ * but `StreamOptions.fetch` is forwarded to the OpenAI client
13
+ * (`dist/api/openai-completions.js:createClient`). Wrapping the provider's api
14
+ * and injecting that field is the one tap that sees every attempt of a logical
15
+ * request — success or failure — without touching content.
16
+ *
17
+ * Contract:
18
+ * - one `attempt` record per fetch call, written when the fetch settles:
19
+ * status, whitelisted headers, millisecond timestamps, latency, attempt
20
+ * number, process-scoped inflight/60 s counters, payload size and the
21
+ * request parameters actually sent;
22
+ * - one `response` record per completed logical request, carrying the
23
+ * gateway `response_id`/`created`, the terminal status and the attempt
24
+ * count — never any prompt or response body;
25
+ * - no content, no credentials, no URLs and no payload fingerprint: header
26
+ * values are whitelisted by name, everything else is dropped;
27
+ * - local-only and best-effort: a full disk warns once and never breaks a
28
+ * stream; the file keeps the newest `HTTP_ATTEMPTS_MAX_LINES` lines.
29
+ */
30
+
31
+ import { randomUUID } from "node:crypto";
32
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
33
+ import { dirname, join } from "node:path";
34
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
35
+ import type { AssistantMessage, ProviderStreams } from "@earendil-works/pi-ai";
36
+
37
+ /** Default file name inside pi's agent dir. */
38
+ export const HTTP_ATTEMPTS_FILE = "nan-http-attempts.jsonl";
39
+
40
+ /** Lines kept after a compact: newest first-in, oldest dropped. */
41
+ export const HTTP_ATTEMPTS_MAX_LINES = 50_000;
42
+
43
+ /** Response headers support correlates on; everything else is dropped. */
44
+ const HEADER_WHITELIST = new Set([
45
+ "cf-ray",
46
+ "retry-after",
47
+ "retry-after-ms",
48
+ "x-request-id",
49
+ "request-id",
50
+ "x-should-retry",
51
+ "openai-processing-ms",
52
+ ]);
53
+
54
+ /** Header families (OpenAI/Anthropic style rate-limit telemetry). */
55
+ const HEADER_PREFIXES = ["x-ratelimit-", "ratelimit-", "x-rate-limit-"];
56
+
57
+ /** Cap applied to every retained header value. */
58
+ const HEADER_VALUE_MAX_CHARS = 200;
59
+
60
+ /** The request parameters the reference CSV carries per row. */
61
+ export interface HttpAttemptRequestParams {
62
+ reasoning_effort: string | null;
63
+ max_tokens: number | null;
64
+ /** Which request field actually carried the token budget, when any. */
65
+ max_tokens_field: "max_tokens" | "max_completion_tokens" | null;
66
+ stream: boolean | null;
67
+ }
68
+
69
+ /** One HTTP attempt (one fetch call), written when the fetch settles. */
70
+ export interface HttpAttemptRecord {
71
+ kind: "attempt";
72
+ /** Opaque id shared by every attempt of the same logical request. */
73
+ request_id: string;
74
+ /** 1-based attempt number within the logical request. */
75
+ attempt_n: number;
76
+ model: string;
77
+ started_at: string;
78
+ /** When the response headers arrived (or the fetch rejected). */
79
+ ended_at: string;
80
+ /** Start → response headers; the early-rejection signal (not the full body read). */
81
+ time_to_header_ms: number;
82
+ status: number | null;
83
+ /** Whitelisted response headers only. */
84
+ headers: Record<string, string>;
85
+ payload_bytes: number | null;
86
+ request: HttpAttemptRequestParams | null;
87
+ /** Attempts open in this process at the moment this one started (not key-wide). */
88
+ inflight_process_at_start: number;
89
+ inflight_same_model_at_start: number;
90
+ /** Attempts started in this process in the previous 60 s, this one included. */
91
+ starts_last_60s_process: number;
92
+ starts_last_60s_same_model: number;
93
+ /** Gateway `error.type` from a non-2xx error body; null otherwise. */
94
+ error_type: string | null;
95
+ /** Gateway `error.code` from a non-2xx error body; null otherwise. */
96
+ error_code: string | null;
97
+ /** Fetch-rejection class (`error.name`), null when a response arrived. */
98
+ transport_error: string | null;
99
+ }
100
+
101
+ /** One completed logical request, joining the gateway id back to the turn. */
102
+ export interface HttpResponseRecord {
103
+ kind: "response";
104
+ request_id: string;
105
+ model: string;
106
+ response_id: string | null;
107
+ created: number | null;
108
+ /** Status of the terminal attempt. */
109
+ status: number | null;
110
+ /** Total attempts this logical request made. */
111
+ attempts: number;
112
+ ended_at: string;
113
+ /** First attempt start → completion (retries and backoff included). */
114
+ duration_ms: number | null;
115
+ request: HttpAttemptRequestParams | null;
116
+ /** Token counts the gateway reported for the completed request. */
117
+ usage: {
118
+ prompt_tokens: number;
119
+ completion_tokens: number;
120
+ reasoning_tokens: number;
121
+ cache_read_tokens: number;
122
+ } | null;
123
+ /** Raw OpenAI `finish_reason` from the last chunk; null when absent. */
124
+ finish_reason: string | null;
125
+ /** Gateway error type when the error arrived inside a 200 SSE stream. */
126
+ error_type: string | null;
127
+ error_code: string | null;
128
+ }
129
+
130
+ export type HttpAttemptEntry = HttpAttemptRecord | HttpResponseRecord;
131
+
132
+ export interface HttpAttemptSink {
133
+ record(entry: HttpAttemptEntry): void;
134
+ }
135
+
136
+ /** The attempts file path for the current pi agent dir. */
137
+ export function defaultHttpAttemptPath(): string {
138
+ return join(getAgentDir(), HTTP_ATTEMPTS_FILE);
139
+ }
140
+
141
+ function countLines(text: string): number {
142
+ if (text.length === 0) return 0;
143
+ const lines = text.split("\n").length;
144
+ return text.endsWith("\n") ? lines - 1 : lines;
145
+ }
146
+
147
+ /**
148
+ * File sink: append one JSON line per record, keeping the file bounded by
149
+ * `maxLines` (the compact keeps the newest lines). Never throws — the first
150
+ * failure warns once, then stays quiet so a broken disk cannot spam the console
151
+ * or break a turn.
152
+ */
153
+ export function createHttpAttemptFileSink(
154
+ filePath?: string,
155
+ options: { maxLines?: number } = {},
156
+ ): HttpAttemptSink {
157
+ const maxLines = options.maxLines ?? HTTP_ATTEMPTS_MAX_LINES;
158
+ let warned = false;
159
+ let counted = false;
160
+ let lines = 0;
161
+
162
+ const warnOnce = (error: unknown): void => {
163
+ if (warned) return;
164
+ warned = true;
165
+ console.warn(
166
+ `[pi-nan-provider] could not persist HTTP attempt evidence (${error instanceof Error ? error.message : String(error)}); streams continue.`,
167
+ );
168
+ };
169
+
170
+ const compact = (path: string): void => {
171
+ try {
172
+ const kept = readFileSync(path, "utf8")
173
+ .split("\n")
174
+ .filter((line) => line.length > 0)
175
+ .slice(-maxLines);
176
+ writeFileSync(path, kept.length > 0 ? `${kept.join("\n")}\n` : "");
177
+ lines = kept.length;
178
+ } catch {
179
+ // Best-effort: a failed compact is retried on the next overflow.
180
+ }
181
+ };
182
+
183
+ return {
184
+ record(entry) {
185
+ try {
186
+ const path = filePath ?? defaultHttpAttemptPath();
187
+ mkdirSync(dirname(path), { recursive: true });
188
+ if (!counted) {
189
+ counted = true;
190
+ lines = existsSync(path) ? countLines(readFileSync(path, "utf8")) : 0;
191
+ }
192
+ appendFileSync(path, `${JSON.stringify(entry)}\n`);
193
+ lines += 1;
194
+ if (lines > maxLines) compact(path);
195
+ } catch (error) {
196
+ warnOnce(error);
197
+ }
198
+ },
199
+ };
200
+ }
201
+
202
+ /** Structural check: a record with a valid kind but missing fields would crash the report. */
203
+ function isAttemptRecord(entry: Record<string, unknown>): entry is Record<string, unknown> & HttpAttemptRecord {
204
+ return (
205
+ typeof entry.request_id === "string" &&
206
+ typeof entry.model === "string" &&
207
+ typeof entry.attempt_n === "number" &&
208
+ typeof entry.started_at === "string" &&
209
+ typeof entry.ended_at === "string" &&
210
+ typeof entry.time_to_header_ms === "number" &&
211
+ (entry.status === null || typeof entry.status === "number") &&
212
+ typeof entry.headers === "object" &&
213
+ entry.headers !== null
214
+ );
215
+ }
216
+
217
+ function isResponseRecord(entry: Record<string, unknown>): entry is Record<string, unknown> & HttpResponseRecord {
218
+ return (
219
+ typeof entry.request_id === "string" &&
220
+ typeof entry.model === "string" &&
221
+ typeof entry.attempts === "number" &&
222
+ typeof entry.ended_at === "string" &&
223
+ (entry.duration_ms === null || typeof entry.duration_ms === "number") &&
224
+ (entry.status === null || typeof entry.status === "number")
225
+ );
226
+ }
227
+
228
+ /**
229
+ * Read the sidecar. Malformed lines, unknown record kinds and structurally
230
+ * incomplete rows are skipped; a missing file yields an empty list.
231
+ */
232
+ export function readHttpAttempts(filePath?: string): HttpAttemptEntry[] {
233
+ const entries: HttpAttemptEntry[] = [];
234
+ try {
235
+ const path = filePath ?? defaultHttpAttemptPath();
236
+ if (!existsSync(path)) return entries;
237
+ for (const line of readFileSync(path, "utf8").split("\n")) {
238
+ if (line.trim().length === 0) continue;
239
+ try {
240
+ const entry = JSON.parse(line) as unknown;
241
+ if (!isObject(entry)) continue;
242
+ if (entry.kind === "attempt" && isAttemptRecord(entry)) {
243
+ entries.push(entry as unknown as HttpAttemptRecord);
244
+ } else if (entry.kind === "response" && isResponseRecord(entry)) {
245
+ entries.push(entry as unknown as HttpResponseRecord);
246
+ }
247
+ } catch {
248
+ // A corrupted line must not break the collector.
249
+ }
250
+ }
251
+ } catch {
252
+ // Unreadable sidecar = no evidence, never a crash.
253
+ }
254
+ return entries;
255
+ }
256
+
257
+ function keepHeader(name: string): boolean {
258
+ const lower = name.toLowerCase();
259
+ return HEADER_WHITELIST.has(lower) || HEADER_PREFIXES.some((prefix) => lower.startsWith(prefix));
260
+ }
261
+
262
+ /**
263
+ * Keep only the whitelisted response headers, lowercased and value-capped.
264
+ * Accepts a `Headers` instance (undici/bun) or a plain record (injected test
265
+ * fetches); anything else yields an empty record.
266
+ */
267
+ export function pickResponseHeaders(headers: unknown): Record<string, string> {
268
+ const kept: Record<string, string> = {};
269
+ const add = (rawName: string, rawValue: unknown): void => {
270
+ if (typeof rawValue !== "string" || rawValue.length === 0) return;
271
+ if (!keepHeader(rawName)) return;
272
+ kept[rawName.toLowerCase()] = rawValue.slice(0, HEADER_VALUE_MAX_CHARS);
273
+ };
274
+
275
+ if (typeof Headers !== "undefined" && headers instanceof Headers) {
276
+ headers.forEach((value, name) => add(name, value));
277
+ } else if (typeof headers === "object" && headers !== null) {
278
+ for (const [name, value] of Object.entries(headers as Record<string, unknown>)) add(name, value);
279
+ }
280
+
281
+ return Object.fromEntries(Object.entries(kept).sort(([a], [b]) => a.localeCompare(b)));
282
+ }
283
+
284
+ function isObject(value: unknown): value is Record<string, unknown> {
285
+ return typeof value === "object" && value !== null;
286
+ }
287
+
288
+ /** Cap on the error body read; gateway error bodies are small, this bounds memory. */
289
+ const MAX_ERROR_BODY_BYTES = 8_192;
290
+
291
+ /**
292
+ * Read only the `type`/`code` of a non-2xx gateway error body. The response is
293
+ * cloned (never consumed) and at most `MAX_ERROR_BODY_BYTES` are read, so the
294
+ * error message, the body and any user content are never stored. Returns nulls
295
+ * when the body is not a JSON error or cannot be read.
296
+ */
297
+ async function readGatewayErrorFields(response: Response): Promise<{ type: string | null; code: string | null }> {
298
+ const empty = { type: null, code: null };
299
+ const body = response.clone().body;
300
+ if (!body) return empty;
301
+ let text = "";
302
+ let bytes = 0;
303
+ try {
304
+ const reader = body.getReader();
305
+ const decoder = new TextDecoder();
306
+ for (;;) {
307
+ const { done, value } = await reader.read();
308
+ if (done) break;
309
+ if (value) {
310
+ bytes += value.byteLength;
311
+ text += decoder.decode(value, { stream: true });
312
+ }
313
+ if (bytes >= MAX_ERROR_BODY_BYTES) {
314
+ await reader.cancel().catch(() => undefined);
315
+ break;
316
+ }
317
+ }
318
+ if (bytes < MAX_ERROR_BODY_BYTES) text += decoder.decode();
319
+ } catch {
320
+ return empty;
321
+ }
322
+ const start = text.indexOf("{");
323
+ const end = text.lastIndexOf("}");
324
+ if (start === -1 || end <= start) return empty;
325
+ try {
326
+ const parsed = JSON.parse(text.slice(start, end + 1)) as unknown;
327
+ if (!isObject(parsed)) return empty;
328
+ // Same two shapes the transcript parser accepts: wrapped or inner object.
329
+ const error = isObject(parsed.error) ? parsed.error : parsed;
330
+ return { type: asString(error.type), code: asString(error.code) };
331
+ } catch {
332
+ return empty;
333
+ }
334
+ }
335
+
336
+ function asString(value: unknown): string | null {
337
+ return typeof value === "string" && value.length > 0 ? value : null;
338
+ }
339
+
340
+ function asNumber(value: unknown): number | null {
341
+ return typeof value === "number" && Number.isFinite(value) ? value : null;
342
+ }
343
+
344
+ function numberOrZero(value: unknown): number {
345
+ return typeof value === "number" && Number.isFinite(value) ? value : 0;
346
+ }
347
+
348
+ /** The request parameters and serialized size of the final outgoing payload. */
349
+ function readRequestParams(payload: unknown): {
350
+ bytes: number | null;
351
+ params: HttpAttemptRequestParams;
352
+ } {
353
+ const body = isObject(payload) ? payload : {};
354
+ const params: HttpAttemptRequestParams = {
355
+ reasoning_effort: asString(body.reasoning_effort),
356
+ max_tokens: asNumber(body.max_completion_tokens) ?? asNumber(body.max_tokens),
357
+ max_tokens_field:
358
+ body.max_completion_tokens !== undefined
359
+ ? "max_completion_tokens"
360
+ : body.max_tokens !== undefined
361
+ ? "max_tokens"
362
+ : null,
363
+ stream: typeof body.stream === "boolean" ? body.stream : null,
364
+ };
365
+ let bytes: number | null = null;
366
+ try {
367
+ bytes = new TextEncoder().encode(JSON.stringify(payload) ?? "").length;
368
+ } catch {
369
+ bytes = null;
370
+ }
371
+ return { bytes, params };
372
+ }
373
+
374
+ export interface HttpAttemptCaptureOptions {
375
+ sink: HttpAttemptSink;
376
+ /** Injectable clock for deterministic tests. */
377
+ now?: () => Date;
378
+ /** Injectable logical-request id generator (default: `randomUUID`). */
379
+ requestId?: () => string;
380
+ }
381
+
382
+ interface OpenAttempt {
383
+ model: string;
384
+ start: number;
385
+ end: number | undefined;
386
+ }
387
+
388
+ /** Window used for the 60 s start counters. */
389
+ const START_WINDOW_MS = 60_000;
390
+
391
+ /**
392
+ * Wrap an api so every HTTP attempt is observed. Only the `fetch` option and
393
+ * the observation hooks are added; the stream, its events and its terminal
394
+ * message are untouched. Caller-supplied hooks are preserved and chained after
395
+ * the observation.
396
+ */
397
+ export function withHttpAttemptCapture(api: ProviderStreams, options: HttpAttemptCaptureOptions): ProviderStreams {
398
+ const now = options.now ?? (() => new Date());
399
+ const nextRequestId = options.requestId ?? (() => randomUUID());
400
+ const open: OpenAttempt[] = [];
401
+ const starts: Array<{ model: string; at: number }> = [];
402
+
403
+ const countOpen = (at: number, model: string): { all: number; sameModel: number } => {
404
+ let all = 0;
405
+ let sameModel = 0;
406
+ for (const attempt of open) {
407
+ if (attempt.start <= at && attempt.end === undefined) {
408
+ all += 1;
409
+ if (attempt.model === model) sameModel += 1;
410
+ }
411
+ }
412
+ return { all, sameModel };
413
+ };
414
+
415
+ /** Drop start records older than the window so memory stays bounded. */
416
+ const pruneStarts = (at: number): void => {
417
+ let keepFrom = 0;
418
+ while (keepFrom < starts.length && starts[keepFrom]!.at < at - START_WINDOW_MS * 5) keepFrom += 1;
419
+ if (keepFrom > 0) starts.splice(0, keepFrom);
420
+ // Concurrent attempts all settle; drop the closed ones older than the window.
421
+ for (let i = open.length - 1; i >= 0; i -= 1) {
422
+ const attempt = open[i]!;
423
+ if (attempt.end !== undefined && attempt.end < at - START_WINDOW_MS * 5) open.splice(i, 1);
424
+ }
425
+ };
426
+
427
+ const observe = <T extends object | undefined>(
428
+ run: (streamOptions: T) => ReturnType<ProviderStreams["stream"]>,
429
+ modelId: string,
430
+ streamOptions: T,
431
+ ): ReturnType<ProviderStreams["stream"]> => {
432
+ const requestId = nextRequestId();
433
+ const opts = { ...((streamOptions ?? {}) as Record<string, unknown>) };
434
+ const state: {
435
+ payloadBytes: number | null;
436
+ request: HttpAttemptRequestParams | null;
437
+ id: string | null;
438
+ created: number | null;
439
+ attempts: number;
440
+ lastStatus: number | null;
441
+ firstStart: number | null;
442
+ finishReason: string | null;
443
+ streamErrorType: string | null;
444
+ streamErrorCode: string | null;
445
+ } = {
446
+ payloadBytes: null,
447
+ request: null,
448
+ id: null,
449
+ created: null,
450
+ attempts: 0,
451
+ lastStatus: null,
452
+ firstStart: null,
453
+ finishReason: null,
454
+ streamErrorType: null,
455
+ streamErrorCode: null,
456
+ };
457
+
458
+ const userOnPayload = opts.onPayload;
459
+ opts.onPayload = async (payload: unknown, model: unknown) => {
460
+ const measured = readRequestParams(payload);
461
+ state.payloadBytes = measured.bytes;
462
+ state.request = measured.params;
463
+ if (typeof userOnPayload === "function") {
464
+ return (userOnPayload as (p: unknown, m: unknown) => unknown)(payload, model);
465
+ }
466
+ return undefined;
467
+ };
468
+
469
+ const userOnStreamEvent = opts.onProviderStreamEvent;
470
+ opts.onProviderStreamEvent = async (chunk: unknown, model: unknown) => {
471
+ if (isObject(chunk)) {
472
+ const id = asString(chunk.id);
473
+ if (id) state.id = id;
474
+ const created = asNumber(chunk.created);
475
+ if (created !== null) state.created = created;
476
+ const choices = chunk.choices;
477
+ if (Array.isArray(choices) && isObject(choices[0]) && typeof choices[0].finish_reason === "string") {
478
+ state.finishReason = choices[0].finish_reason;
479
+ }
480
+ if (isObject(chunk.error)) {
481
+ state.streamErrorType = asString(chunk.error.type);
482
+ state.streamErrorCode = asString(chunk.error.code);
483
+ }
484
+ }
485
+ if (typeof userOnStreamEvent === "function") {
486
+ return (userOnStreamEvent as (c: unknown, m: unknown) => unknown)(chunk, model);
487
+ }
488
+ return undefined;
489
+ };
490
+
491
+ const baseFetch = (opts.fetch as typeof fetch | undefined) ?? globalThis.fetch;
492
+ const tapFetch = (async (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => {
493
+ const at = now().getTime();
494
+ pruneStarts(at);
495
+ if (state.firstStart === null) state.firstStart = at;
496
+ const concurrent = countOpen(at, modelId);
497
+ const recentStarts = starts.filter((start) => start.at >= at - START_WINDOW_MS).length + 1;
498
+ const recentSameModel =
499
+ starts.filter((start) => start.at >= at - START_WINDOW_MS && start.model === modelId).length + 1;
500
+ const tracked: OpenAttempt = { model: modelId, start: at, end: undefined };
501
+ const attempt_n = (state.attempts += 1);
502
+ open.push(tracked);
503
+ starts.push({ model: modelId, at });
504
+
505
+ const record = (
506
+ endedMs: number,
507
+ status: number | null,
508
+ headers: Record<string, string>,
509
+ errorType: string | null,
510
+ errorCode: string | null,
511
+ transportError: string | null,
512
+ ): void => {
513
+ // The HTTP attempt ends when the headers arrive; the body read below is
514
+ // instrumentation, so it must not inflate the concurrency counters.
515
+ tracked.end = endedMs;
516
+ state.lastStatus = status;
517
+ const entry: HttpAttemptRecord = {
518
+ kind: "attempt",
519
+ request_id: requestId,
520
+ attempt_n,
521
+ model: modelId,
522
+ started_at: new Date(at).toISOString(),
523
+ ended_at: new Date(endedMs).toISOString(),
524
+ time_to_header_ms: Math.max(0, endedMs - at),
525
+ status,
526
+ headers,
527
+ payload_bytes: state.payloadBytes,
528
+ request: state.request,
529
+ inflight_process_at_start: concurrent.all,
530
+ inflight_same_model_at_start: concurrent.sameModel,
531
+ starts_last_60s_process: recentStarts,
532
+ starts_last_60s_same_model: recentSameModel,
533
+ error_type: errorType,
534
+ error_code: errorCode,
535
+ transport_error: transportError,
536
+ };
537
+ try {
538
+ options.sink.record(entry);
539
+ } catch {
540
+ // Evidence capture is best-effort; never break the turn.
541
+ }
542
+ };
543
+
544
+ try {
545
+ const response = await baseFetch(input, init);
546
+ const headerMs = now().getTime();
547
+ const gatewayError = response.status >= 400 ? await readGatewayErrorFields(response) : null;
548
+ record(
549
+ headerMs,
550
+ response.status,
551
+ pickResponseHeaders(response.headers),
552
+ gatewayError?.type ?? null,
553
+ gatewayError?.code ?? null,
554
+ null,
555
+ );
556
+ return response;
557
+ } catch (error) {
558
+ const name = isObject(error) && typeof error.name === "string" && error.name.length > 0 ? error.name : "Error";
559
+ record(now().getTime(), null, {}, null, null, name);
560
+ throw error;
561
+ }
562
+ }) as typeof fetch;
563
+ opts.fetch = tapFetch;
564
+
565
+ const stream = run(opts as T);
566
+
567
+ stream.result().then(
568
+ (message: AssistantMessage | undefined) => {
569
+ const ended = now();
570
+ // pi-ai persists only the id; prefer the raw chunk, fall back to it.
571
+ const responseId = state.id ?? asString(message?.responseId);
572
+ const usage = isObject(message?.usage)
573
+ ? {
574
+ prompt_tokens: numberOrZero(message?.usage.input),
575
+ completion_tokens: numberOrZero(message?.usage.output),
576
+ reasoning_tokens: numberOrZero(message?.usage.reasoning),
577
+ cache_read_tokens: numberOrZero(message?.usage.cacheRead),
578
+ }
579
+ : null;
580
+ const entry: HttpResponseRecord = {
581
+ kind: "response",
582
+ request_id: requestId,
583
+ model: modelId,
584
+ response_id: responseId,
585
+ created: state.created,
586
+ status: state.lastStatus,
587
+ attempts: state.attempts,
588
+ ended_at: ended.toISOString(),
589
+ duration_ms: state.firstStart === null ? null : Math.max(0, ended.getTime() - state.firstStart),
590
+ request: state.request,
591
+ usage,
592
+ finish_reason: state.finishReason,
593
+ error_type: state.streamErrorType,
594
+ error_code: state.streamErrorCode,
595
+ };
596
+ try {
597
+ options.sink.record(entry);
598
+ } catch {
599
+ // Evidence capture is best-effort; never break the turn.
600
+ }
601
+ },
602
+ () => undefined,
603
+ );
604
+
605
+ return stream;
606
+ };
607
+
608
+ return {
609
+ ...api,
610
+ stream: (model, context, streamOptions) =>
611
+ observe((next) => api.stream(model, context, next), model.id, streamOptions),
612
+ streamSimple: (model, context, streamOptions) =>
613
+ observe((next) => api.streamSimple(model, context, next), model.id, streamOptions),
614
+ };
615
+ }