narrarium-engine 0.1.12 → 0.1.13

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.
@@ -7,7 +7,7 @@ import { redactSecrets } from "./redact.js";
7
7
  import { effectiveAiBase, endpointOrigin } from "./request.js";
8
8
  import { candidateBoundary, planAttempts } from "./routing.js";
9
9
  import { isEmptyToolArguments, splitReasoningBlock, structuredFromReply } from "./structured.js";
10
- import { AiFallbackBlockedError, AiProviderError, AiReplyRejectedError } from "./types.js";
10
+ import { AiFallbackBlockedError, AiProviderError, AiReplyRejectedError, AiStreamInterruptedError, MAX_PARTIAL_CHARACTERS, TRANSPORT_TAIL_CHARACTERS } from "./types.js";
11
11
  // The deadlines of a call: how long a provider has to begin answering, the least it is given, and the most a call may take.
12
12
  export { DEFAULT_REQUEST_TIMEOUT_MS, MIN_REQUEST_TIMEOUT_MS, TOTAL_REQUEST_CAP_MS } from "./deadlines.js";
13
13
  /**
@@ -58,6 +58,7 @@ function fallbackTarget(candidate) {
58
58
  * What failed attempts cost is added to the final response (or error), so budgets never under-count.
59
59
  */
60
60
  export function createFetchAi(config, options = {}) {
61
+ const refusals = options.usageOptionRefusals ?? new Set();
61
62
  return {
62
63
  async complete(request) {
63
64
  let startedAt = Date.now();
@@ -124,7 +125,7 @@ export function createFetchAi(config, options = {}) {
124
125
  try {
125
126
  if (!attempt.built)
126
127
  throw attempt.buildError;
127
- const response = await callCandidate(config, attempt, attempt.built, request, options, deadlines, secrets, trace);
128
+ const response = await callCandidate(config, attempt, attempt.built, request, options, deadlines, secrets, trace, refusals);
128
129
  notify(options.onAttemptEnd, {
129
130
  ...identity,
130
131
  outcome: "ok",
@@ -135,6 +136,7 @@ export function createFetchAi(config, options = {}) {
135
136
  currency: response.currency,
136
137
  text: response.text,
137
138
  ...replyTrace(trace, Boolean(request.json)),
139
+ ...(trace.transport ? { transport: trace.transport } : {}),
138
140
  durationMs: Date.now() - attemptStarted,
139
141
  });
140
142
  return withSpent(response, spent);
@@ -150,7 +152,7 @@ export function createFetchAi(config, options = {}) {
150
152
  }
151
153
  addSpent(spent, error);
152
154
  lastError = error;
153
- request.onText?.("");
155
+ notify(request.onText, "");
154
156
  }
155
157
  }
156
158
  const notes = [];
@@ -247,17 +249,28 @@ function failedAttempt(identity, error, cancelled, timeoutMs, durationMs, secret
247
249
  ...(timedOut ? { timeoutMs: provider?.timeout?.ms ?? timeoutMs } : {}),
248
250
  ...(timedOut && provider?.timeout ? { timeoutPhase: provider.timeout.phase } : {}),
249
251
  ...reply,
252
+ ...(provider?.transport ? { transport: provider.transport } : {}),
253
+ ...(provider?.partialText ? { partialText: provider.partialText } : {}),
250
254
  durationMs,
251
255
  };
252
256
  }
257
+ /** A count of tokens: a number that is not negative. */
258
+ function tokenCount(value) {
259
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
260
+ }
261
+ /**
262
+ * The tokens a provider reports (`usage`): OpenAI's `prompt_tokens` and `completion_tokens`, or the `input_tokens` and `output_tokens` that other providers and the Responses API use; the tokens
263
+ * served from the cache by whichever field says it (`prompt_tokens_details.cached_tokens`, `input_tokens_details.cached_tokens`, `prompt_cache_hit_tokens`, `cache_read_input_tokens`).
264
+ */
253
265
  function normalizeUsage(value) {
254
266
  if (!value || typeof value !== "object")
255
267
  return undefined;
256
268
  const usage = value;
269
+ const details = (usage.prompt_tokens_details ?? usage.input_tokens_details);
257
270
  return {
258
- inputTokens: usage.prompt_tokens ?? 0,
259
- outputTokens: usage.completion_tokens ?? 0,
260
- cachedInputTokens: usage.prompt_tokens_details?.cached_tokens ?? 0,
271
+ inputTokens: tokenCount(usage.prompt_tokens) ?? tokenCount(usage.input_tokens) ?? 0,
272
+ outputTokens: tokenCount(usage.completion_tokens) ?? tokenCount(usage.output_tokens) ?? 0,
273
+ cachedInputTokens: tokenCount(details?.cached_tokens) ?? tokenCount(usage.prompt_cache_hit_tokens) ?? tokenCount(usage.cache_read_input_tokens) ?? 0,
261
274
  };
262
275
  }
263
276
  /**
@@ -285,7 +298,8 @@ function parseRetryAfter(value) {
285
298
  const date = Date.parse(text);
286
299
  return Number.isNaN(date) ? undefined : Math.min(MAX_RETRY_AFTER_MS, Math.max(0, date - Date.now()));
287
300
  }
288
- const TRANSIENT_STATUSES = new Set([408, 429, 502, 503, 504]);
301
+ /** The statuses that depend on the moment: a timeout, a rate limit, a gateway that cannot reach the model or that gave up waiting for it, and the origin errors (520-524) that Cloudflare says for the same. */
302
+ const TRANSIENT_STATUSES = new Set([408, 429, 502, 503, 504, 520, 521, 522, 523, 524]);
289
303
  /**
290
304
  * What a refusal of the thinking parameter says: the name of the one that the level travels in, in the provider's message or in the `param` of its error
291
305
  * object (some providers say only `"param": "reasoning_effort"`): the OpenAI field, or the chat-template argument (`chat_template_kwargs`, `reasoning_strength`).
@@ -317,7 +331,9 @@ async function providerError(response, provider, model, redact, sent) {
317
331
  detail = typeof message === "string" ? message : raw;
318
332
  }
319
333
  catch {
320
- detail = raw;
334
+ // A gateway in front of the provider answers with a page of its own (Cloudflare's 524, an nginx 502): its title says what it is, its markup says nothing.
335
+ const page = /^\s*<(?:!doctype\s+html|html)\b/i.test(raw) ? /<title[^>]*>([^<]{1,200})<\/title>/i.exec(raw)?.[1]?.replace(/\s+/g, " ").trim() : undefined;
336
+ detail = /^\s*<(?:!doctype\s+html|html)\b/i.test(raw) ? `an HTML page from a gateway or a proxy${page ? ` ("${page}")` : ""}, not an answer of the provider` : raw;
321
337
  }
322
338
  }
323
339
  catch {
@@ -343,10 +359,11 @@ class StreamReadError extends Error {
343
359
  }
344
360
  }
345
361
  /**
346
- * Reads server-sent events; resolves `true` when the provider closed the stream with `[DONE]`. An event is its `data:`
347
- * lines joined with a newline, ended by a blank line; a value that is complete as it stands (one JSON object, or
348
- * `[DONE]`) is delivered at once, so servers that leave out the blank lines still stream.
349
- * Every piece that arrives starts the idle deadline again, a comment (`: keep-alive`) too, and no read can hold the call past
362
+ * Reads server-sent events; resolves `true` when the provider closed the stream with `[DONE]`. A line ends with a line feed, a carriage return or both (the specification allows
363
+ * the three, and a pair cut between two chunks is one end). An event is its `data:` lines joined with a newline, ended by a blank line, and it may be named by an `event:` line;
364
+ * a value that is complete as it stands (one JSON object, or `[DONE]`) is delivered at once, so servers that leave out the blank lines still stream. Lines that are
365
+ * neither (`: keep-alive` comments, `id:`, `retry:`) are ignored, and the text of a character that a chunk cuts in two is kept until the rest comes.
366
+ * Every piece that arrives starts the idle deadline again, a comment too, and no read can hold the call past
350
367
  * a deadline or the author's cancel. However it ends, but by the end of the stream, the reader is released.
351
368
  */
352
369
  async function readEventStream(response, clock, hooks) {
@@ -354,8 +371,13 @@ async function readEventStream(response, clock, hooks) {
354
371
  throw new AiProviderError("The provider returned an empty stream.", undefined, true, { transient: true });
355
372
  const reader = response.body.getReader();
356
373
  const decoder = new TextDecoder();
374
+ /** The line that is being read: what has arrived of it. */
357
375
  let buffer = "";
376
+ /** The last line ended with a carriage return: a line feed that opens the next chunk is the other half of the same end. */
377
+ let skipLineFeed = false;
358
378
  let pending = [];
379
+ /** The name that the `event:` line of the event being read gave it. */
380
+ let named = "";
359
381
  let exhausted = false;
360
382
  const complete = (value) => {
361
383
  const text = value.trim();
@@ -373,9 +395,15 @@ async function readEventStream(response, clock, hooks) {
373
395
  };
374
396
  const flush = () => {
375
397
  const lines = pending;
398
+ const event = named;
376
399
  pending = [];
377
- if (!lines.length)
400
+ named = "";
401
+ if (!lines.length) {
402
+ // An `event: error` with no data at all still says that the provider failed.
403
+ if (event === "error")
404
+ hooks.onData("", event);
378
405
  return false;
406
+ }
379
407
  const joined = lines.join("\n").trim();
380
408
  if (joined === "[DONE]")
381
409
  return true;
@@ -386,23 +414,59 @@ async function readEventStream(response, clock, hooks) {
386
414
  if (single === "[DONE]")
387
415
  return true;
388
416
  if (single)
389
- hooks.onData(single);
417
+ hooks.onData(single, event);
390
418
  }
391
419
  return false;
392
420
  }
393
- if (joined)
394
- hooks.onData(joined);
421
+ if (joined || event === "error")
422
+ hooks.onData(joined, event);
395
423
  return false;
396
424
  };
397
425
  const takeLine = (line) => {
398
- const clean = line.replace(/\r$/, "");
399
- if (!clean)
426
+ if (!line)
400
427
  return flush();
401
- if (!clean.startsWith("data:"))
428
+ if (line.startsWith("event:")) {
429
+ named = line.slice(6).trim().toLowerCase();
430
+ return false;
431
+ }
432
+ if (!line.startsWith("data:"))
402
433
  return false;
403
- pending.push(clean.slice(5).trimStart());
434
+ pending.push(line.slice(5).trimStart());
404
435
  return complete(pending.join("\n")) ? flush() : false;
405
436
  };
437
+ /** Splits what arrived into lines and takes them; `true` when the end marker was among them. */
438
+ const feed = (decoded) => {
439
+ let text = decoded;
440
+ if (skipLineFeed) {
441
+ skipLineFeed = false;
442
+ if (text.charCodeAt(0) === 10)
443
+ text = text.slice(1);
444
+ }
445
+ buffer += text;
446
+ let start = 0;
447
+ for (let at = 0; at < buffer.length; at += 1) {
448
+ const code = buffer.charCodeAt(at);
449
+ if (code !== 10 && code !== 13)
450
+ continue;
451
+ const line = buffer.slice(start, at);
452
+ if (code === 13) {
453
+ if (at + 1 < buffer.length) {
454
+ if (buffer.charCodeAt(at + 1) === 10)
455
+ at += 1;
456
+ }
457
+ else {
458
+ skipLineFeed = true;
459
+ }
460
+ }
461
+ start = at + 1;
462
+ if (takeLine(line)) {
463
+ buffer = "";
464
+ return true;
465
+ }
466
+ }
467
+ buffer = buffer.slice(start);
468
+ return false;
469
+ };
406
470
  try {
407
471
  for (;;) {
408
472
  let piece;
@@ -418,19 +482,15 @@ async function readEventStream(response, clock, hooks) {
418
482
  break;
419
483
  }
420
484
  clock.activity();
421
- hooks.onBytes(piece.value.byteLength);
422
- buffer += decoder.decode(piece.value, { stream: true });
423
- let newline = buffer.indexOf("\n");
424
- while (newline >= 0) {
425
- const line = buffer.slice(0, newline);
426
- buffer = buffer.slice(newline + 1);
427
- if (takeLine(line))
428
- return true;
429
- newline = buffer.indexOf("\n");
430
- }
485
+ const decoded = decoder.decode(piece.value, { stream: true });
486
+ hooks.onChunk(piece.value.byteLength, decoded);
487
+ if (feed(decoded))
488
+ return true;
431
489
  hooks.onPiece();
432
490
  }
433
- buffer += decoder.decode();
491
+ const rest = decoder.decode();
492
+ if (rest && feed(rest))
493
+ return true;
434
494
  if (buffer.trim() && takeLine(buffer))
435
495
  return true;
436
496
  return flush();
@@ -445,7 +505,7 @@ async function readEventStream(response, clock, hooks) {
445
505
  * Reads the whole body of a reply that is one JSON value. Like the stream reader it starts the idle deadline again at every piece, cannot
446
506
  * be held past a deadline or the author's cancel, and releases the body however it ends (`response.json()` would keep it locked).
447
507
  */
448
- async function readJsonBody(response, clock, onBytes) {
508
+ async function readJsonBody(response, clock, onChunk) {
449
509
  if (!response.body)
450
510
  return clock.guard(response.json());
451
511
  const reader = response.body.getReader();
@@ -466,8 +526,9 @@ async function readJsonBody(response, clock, onBytes) {
466
526
  break;
467
527
  }
468
528
  clock.activity();
469
- onBytes(piece.value.byteLength);
470
- body += decoder.decode(piece.value, { stream: true });
529
+ const decoded = decoder.decode(piece.value, { stream: true });
530
+ onChunk(piece.value.byteLength, decoded);
531
+ body += decoded;
471
532
  }
472
533
  body += decoder.decode();
473
534
  return JSON.parse(body);
@@ -503,10 +564,13 @@ export function classifyFinishReason(reason, ended) {
503
564
  const PERMANENT_STREAM_ERROR = /authenticat|unauthori[sz]ed|forbidden|permission|invalid[_ -]?(?:request|api[_ -]?key|argument|parameter)|bad[_ -]?request/i;
504
565
  const TRANSIENT_STREAM_ERROR = /overload|rate[_ -]?limit|too many requests|temporar|unavailable|busy|try again|time[ds]? ?out|capacity/i;
505
566
  /**
506
- * A failure the provider reported inside the stream (`{"error": {...}}` or `{"error": "..."}`), or `null` when the
507
- * chunk carries none. It is retried unless its status or code says authentication or an invalid request.
567
+ * A failure the provider reported inside the stream (`{"error": {...}}`, `{"error": "..."}`, or an `event: error`), or `null` when the
568
+ * chunk carries none. It is retried unless its status or code says authentication or an invalid request. `started`: the model had already written something, so the provider was answering
569
+ * when it failed and the reply stopped halfway: that is a failure of the moment (`AiStreamInterruptedError`, `transient`), whatever the runtime calls it (a 500, a crash, no status at all),
570
+ * as long as it is not one of those that never change. A failure before any of the reply is the provider refusing or failing at the start: it is `transient` only when its status or
571
+ * its words say it depends on the moment (a deterministic failure, `context too long`, would be the same every time).
508
572
  */
509
- function streamError(value, label, details, redact) {
573
+ function streamError(value, label, details, redact, started) {
510
574
  const source = value && typeof value === "object" ? value : null;
511
575
  const message = typeof value === "string" ? value.trim() : typeof source?.message === "string" ? source.message.trim() : "";
512
576
  if (!source && !message)
@@ -518,14 +582,22 @@ function streamError(value, label, details, redact) {
518
582
  const permanent = (status !== undefined && status >= 400 && status < 500 && status !== 408 && status !== 409 && status !== 429) || PERMANENT_STREAM_ERROR.test(words);
519
583
  const transient = !permanent && ((status !== undefined && TRANSIENT_STATUSES.has(status)) || TRANSIENT_STREAM_ERROR.test(`${message} ${words}`));
520
584
  const detail = redact(message || (source && Object.keys(source).length ? JSON.stringify(source) : "no details")).replace(/\s+/g, " ").slice(0, 400);
521
- return new AiProviderError(redact(`${label}: the provider reported an error during the reply — ${detail}`), status, !permanent, { ...details, ...(transient ? { transient: true } : {}) });
585
+ const said = redact(`${label}: the provider reported an error during the reply — ${detail}`);
586
+ if (started && !permanent)
587
+ return new AiStreamInterruptedError(said, "provider-error", status, details);
588
+ return new AiProviderError(said, status, !permanent, { ...details, ...(transient ? { transient: true } : {}) });
522
589
  }
523
- /** Characters of reasoning a reply carried. Only the count is kept, never the reasoning itself. */
590
+ /**
591
+ * Characters of reasoning a reply carried. Only the count is kept, never the reasoning itself. The reasoning is in `reasoning_content` (llama.cpp, DeepSeek, older vLLM) or in `reasoning`
592
+ * (newer vLLM, OpenRouter); a runtime that is moving from the first to the second sends the same words under both names, and they are counted once.
593
+ */
524
594
  function reasoningLength(source) {
525
595
  if (!source || typeof source !== "object")
526
596
  return 0;
527
597
  const { reasoning_content: content, reasoning } = source;
528
- return (typeof content === "string" ? content.length : 0) + (typeof reasoning === "string" ? reasoning.length : 0);
598
+ const first = typeof content === "string" ? content : "";
599
+ const second = typeof reasoning === "string" ? reasoning : "";
600
+ return first === second ? first.length : first.length + second.length;
529
601
  }
530
602
  /** The function calls of a message (`tool_calls`) whose arguments are text, in their order. */
531
603
  function callsOf(value) {
@@ -559,7 +631,44 @@ function chosenArguments(calls, wanted) {
559
631
  }
560
632
  return firstWithArguments ?? first ?? "";
561
633
  }
562
- async function callCandidate(config, attempt, built, request, options, deadlines, secrets, trace) {
634
+ /** What of the end of a stream is kept to cut the reported tail from: longer than the tail, so that a credential that the cut would divide has been replaced whole before it is. */
635
+ const TAIL_WINDOW_CHARACTERS = TRANSPORT_TAIL_CHARACTERS * 3;
636
+ /** The headers in which a provider or its gateway puts the id of a request: it is what they look a call up by in their logs. */
637
+ const REQUEST_ID_HEADERS = ["x-llmproxy-request-id", "x-request-id", "request-id", "x-ms-request-id", "apim-request-id"];
638
+ /** The most addresses a set of refusals of `stream_options` keeps. */
639
+ const MAX_REMEMBERED_REFUSALS = 200;
640
+ /** The id that a response carries for its request, when it is one (letters, digits and a few signs: never anything a key could be). */
641
+ function requestIdOf(headers) {
642
+ for (const name of REQUEST_ID_HEADERS) {
643
+ const value = headers?.get?.(name)?.trim();
644
+ if (value && /^[A-Za-z0-9._:-]{1,100}$/.test(value))
645
+ return value;
646
+ }
647
+ return undefined;
648
+ }
649
+ /** The text of a reasoning field in a piece of a stream, with the closing quote when the piece has it (a window of a stream may end, or begin, inside one). */
650
+ const REASONING_FIELD = /("(?:reasoning_content|reasoning)"\s*:\s*")(?:[^"\\]|\\.)*("?)/g;
651
+ /**
652
+ * The end of a stream as the diagnostics keep it: what arrived, without the words of the model's reasoning (the engine never keeps them: only their count). `whole`: the window holds the
653
+ * beginning of the stream. A window that begins somewhere inside the stream may begin inside a reasoning field, which cannot be told, so its first line (which may be cut) is dropped.
654
+ */
655
+ function streamTail(window, whole) {
656
+ let text = window;
657
+ if (!whole) {
658
+ const at = text.search(/\r\n|\r|\n/);
659
+ text = at < 0 ? "" : text.slice(at + (text.startsWith("\r\n", at) ? 2 : 1));
660
+ }
661
+ return text.replace(REASONING_FIELD, "$1…$2");
662
+ }
663
+ /** A refusal of `stream_options`: a 400 or a 422 whose message names the option (or `include_usage`). */
664
+ function refusesUsageOption(failure, label) {
665
+ return (failure.status === 400 || failure.status === 422) && /stream[_ -]?options|include[_ -]?usage/i.test(failure.message.replace(label, ""));
666
+ }
667
+ function withoutUsageOption(body) {
668
+ const { stream_options: _refused, ...rest } = body;
669
+ return rest;
670
+ }
671
+ async function callCandidate(config, attempt, built, request, options, deadlines, secrets, trace, refusals) {
563
672
  const { candidate } = attempt;
564
673
  const { integration, model } = candidate;
565
674
  const label = `${integration.provider} ${model}`;
@@ -579,14 +688,27 @@ async function callCandidate(config, attempt, built, request, options, deadlines
579
688
  let wholeArguments = "";
580
689
  /** The response ended properly: a stream that closed with `[DONE]`, or a complete JSON body. */
581
690
  let ended = true;
691
+ /** How the stream ended, once it has: what the diagnostics say unless a failure tells better. */
692
+ let streamEnd;
582
693
  let bytes = 0;
694
+ let chunks = 0;
583
695
  let events = 0;
696
+ let lastChunkAt;
697
+ /** The end of what arrived, as it came (see `TAIL_WINDOW_CHARACTERS`), and how many characters arrived in all. */
698
+ let tailWindow = "";
699
+ let tailCharacters = 0;
700
+ let status;
701
+ let requestId;
702
+ /** The request that is answered asks the provider for the tokens of the stream (`stream_options.include_usage`). */
703
+ let usageRequested = Boolean(built.body.stream_options);
584
704
  let lastProgressAt;
585
705
  let response;
586
706
  /** Where the call is, to say what went wrong when something does. */
587
707
  let stage = "send";
588
708
  const callArguments = () => wholeArguments || chosenArguments(calls.values(), wanted);
589
- /** What the attempt used: the provider's count, else an estimate once the model has started to answer. */
709
+ /** The model has written something of the reply (its text, its reasoning or the call of its function): the provider is answering. */
710
+ const started = () => Boolean(text || reasoningCharacters || calls.size || wholeArguments);
711
+ /** What an attempt used: the provider's count, else an estimate once the model has started to answer. */
590
712
  const measure = () => {
591
713
  if (usage && usage.inputTokens + usage.outputTokens > 0)
592
714
  return { usage, usageKnown: true };
@@ -598,8 +720,30 @@ async function callCandidate(config, attempt, built, request, options, deadlines
598
720
  usageKnown: false,
599
721
  };
600
722
  };
601
- const details = (extra = {}) => {
723
+ /** What the transport saw: the numbers of the response, the end of what arrived and how it ended (`end`, else how the stream ended). Nothing of it is a key. */
724
+ const transport = (end = streamEnd, withTail = true) => {
725
+ const tail = withTail ? redact(streamTail(tailWindow, tailCharacters <= TAIL_WINDOW_CHARACTERS)).slice(-TRANSPORT_TAIL_CHARACTERS) : "";
726
+ const shown = redact(finishReason).replace(/\s+/g, " ").trim().slice(0, 60);
727
+ return {
728
+ ...(status !== undefined ? { status } : {}),
729
+ streamed: trace.streamed,
730
+ bytes,
731
+ chunks,
732
+ events,
733
+ ...(lastChunkAt !== undefined ? { lastChunkAfterMs: Math.max(0, lastChunkAt - trace.startedAt), lastChunkAt: new Date(lastChunkAt).toISOString(), silentMs: Math.max(0, Date.now() - lastChunkAt) } : {}),
734
+ ...(tail ? { tail } : {}),
735
+ ...(shown ? { finishReason: shown } : {}),
736
+ usageReceived: Boolean(usage && usage.inputTokens + usage.outputTokens > 0),
737
+ usageRequested,
738
+ ...(end ? { end } : {}),
739
+ ...(requestId ? { requestId } : {}),
740
+ };
741
+ };
742
+ const details = (extra = {}, end) => {
602
743
  const measured = measure();
744
+ // The reply that had arrived: its text without a reasoning block, else the arguments of its function.
745
+ const written = splitReasoningBlock(text).reply;
746
+ const partial = written.trim() ? written : callArguments();
603
747
  return {
604
748
  usage: measured.usage,
605
749
  cost: estimateCost(measured.usage, candidate.pricing),
@@ -608,13 +752,15 @@ async function callCandidate(config, attempt, built, request, options, deadlines
608
752
  model,
609
753
  provider: integration.provider,
610
754
  integrationId: integration.id,
755
+ ...(status !== undefined || bytes > 0 ? { transport: transport(end) } : {}),
756
+ ...(partial ? { partialText: redact(partial.slice(0, MAX_PARTIAL_CHARACTERS)) } : {}),
611
757
  ...extra,
612
758
  };
613
759
  };
614
760
  /** A stream that no model's answer explains: stopped, with what it used and what to do. */
615
761
  const runaway = (what) => new AiProviderError(redact(`${label}: ${what}. Nothing was applied: the provider may have used tokens. Lower the thinking effort of the model or choose another one.`), undefined, false, details());
616
762
  const timeoutError = (expired, answering) => new AiProviderError(redact(timeoutMessage(label, expired, deadlines, integration.name)), undefined, true, {
617
- ...(answering ? details() : {}),
763
+ ...(answering ? details({}, "timeout") : {}),
618
764
  transient: true,
619
765
  timedOut: true,
620
766
  timeout: { phase: expired.phase, ms: expired.ms, ...(expired.phase === "start" && deadlines.raisedFrom !== undefined ? { raisedFrom: deadlines.raisedFrom } : {}) },
@@ -651,18 +797,29 @@ async function callCandidate(config, attempt, built, request, options, deadlines
651
797
  call.arguments += fn.arguments;
652
798
  }
653
799
  };
654
- const take = (data) => {
655
- let chunk;
800
+ const take = (data, event = "") => {
801
+ let parsed;
656
802
  try {
657
- chunk = JSON.parse(data);
803
+ parsed = JSON.parse(data);
658
804
  }
659
805
  catch {
660
- return;
806
+ parsed = undefined;
807
+ }
808
+ let chunk;
809
+ if (event === "error") {
810
+ // An `event: error`: whatever its data is (an error object, a message, nothing), the provider is reporting a failure.
811
+ const inner = parsed && typeof parsed === "object" && "error" in parsed ? parsed.error : parsed;
812
+ chunk = { error: inner || data.trim() || "the provider sent an error event without details" };
813
+ }
814
+ else {
815
+ if (parsed === undefined)
816
+ return;
817
+ chunk = parsed;
661
818
  }
662
819
  if (!chunk || typeof chunk !== "object")
663
820
  return;
664
821
  if (chunk.error) {
665
- const failure = streamError(chunk.error, label, details(), redact);
822
+ const failure = streamError(chunk.error, label, details({}, "error"), redact, started());
666
823
  if (failure)
667
824
  throw failure;
668
825
  }
@@ -676,7 +833,7 @@ async function callCandidate(config, attempt, built, request, options, deadlines
676
833
  text += delta.content;
677
834
  // The text of a structured reply is no prose for the listener: its progress is `onProgress`.
678
835
  if (!structured)
679
- request.onText?.(text);
836
+ notify(request.onText, text);
680
837
  }
681
838
  addCalls(delta?.tool_calls);
682
839
  // Some providers end the stream with the whole message instead of (or after) the pieces.
@@ -690,28 +847,42 @@ async function callCandidate(config, attempt, built, request, options, deadlines
690
847
  const reason = choices.find((choice) => typeof choice?.finish_reason === "string" && choice.finish_reason)?.finish_reason;
691
848
  if (reason)
692
849
  finishReason = reason;
693
- if (chunk.usage)
694
- usage = normalizeUsage(chunk.usage);
850
+ // The usage comes in whichever chunk the provider puts it (the last one with no choice, the one that finishes the reply, or every one); a count of zero does not replace one that was read.
851
+ if (chunk.usage) {
852
+ const next = normalizeUsage(chunk.usage);
853
+ if (next && (next.inputTokens + next.outputTokens > 0 || !usage))
854
+ usage = next;
855
+ }
695
856
  };
696
- const countBytes = (count, what) => {
857
+ const chunkArrived = (count, decoded, what) => {
697
858
  bytes += count;
859
+ chunks += 1;
860
+ lastChunkAt = Date.now();
861
+ tailCharacters += decoded.length;
862
+ tailWindow = decoded.length >= TAIL_WINDOW_CHARACTERS ? decoded.slice(-TAIL_WINDOW_CHARACTERS) : (tailWindow + decoded).slice(-TAIL_WINDOW_CHARACTERS);
698
863
  trace.firstByteMs ??= elapsed();
699
864
  if (bytes > MAX_STREAM_TRANSPORT_BYTES)
700
865
  throw runaway(`the ${what} passed the safety limit of ${MAX_STREAM_TRANSPORT_BYTES / 1_000_000} MB (a model that loops while reasoning looks like this)`);
701
866
  };
702
867
  const hooks = {
703
- onData: (data) => {
868
+ onData: (data, event) => {
704
869
  events += 1;
705
- take(data);
870
+ take(data, event);
706
871
  },
707
- onBytes: (count) => countBytes(count, "stream"),
872
+ onChunk: (count, decoded) => chunkArrived(count, decoded, "stream"),
708
873
  onPiece: reportProgress,
709
874
  };
710
- try {
875
+ // What is sent: an address that refused `stream_options` before is not asked it again.
876
+ let body = built.body;
877
+ if (usageRequested && refusals.has(built.url)) {
878
+ body = withoutUsageOption(body);
879
+ usageRequested = false;
880
+ }
881
+ const send = () => {
711
882
  const sent = Promise.resolve(fetchImpl(built.url, {
712
883
  method: "POST",
713
884
  headers: built.headers,
714
- body: JSON.stringify(built.body),
885
+ body: JSON.stringify(body),
715
886
  signal: clock.signal,
716
887
  }));
717
888
  // A reply that comes after the call was given up is dropped, and its body let go.
@@ -719,11 +890,29 @@ async function callCandidate(config, attempt, built, request, options, deadlines
719
890
  if (clock.interrupted())
720
891
  discardBody(late);
721
892
  }, () => undefined);
722
- response = await clock.guard(sent);
723
- stage = "other";
724
- if (!response.ok) {
893
+ return clock.guard(sent);
894
+ };
895
+ try {
896
+ for (;;) {
897
+ stage = "send";
898
+ response = await send();
899
+ stage = "other";
900
+ status = response.status;
901
+ requestId = requestIdOf(response.headers);
902
+ if (response.ok)
903
+ break;
725
904
  trace.firstByteMs ??= elapsed();
726
905
  const failure = await clock.guard(providerError(response, integration.provider, model, redact, built.thinking ? { integration: integration.name, parameter: built.reasoningParameter ?? "reasoning_effort" } : undefined));
906
+ failure.transport = transport();
907
+ // A provider that refuses `stream_options` is asked again, at once, without it, and is not asked it again: its replies carry no token count, which is then an estimate.
908
+ if (usageRequested && refusesUsageOption(failure, label)) {
909
+ if (refusals.size >= MAX_REMEMBERED_REFUSALS)
910
+ refusals.delete(refusals.values().next().value);
911
+ refusals.add(built.url);
912
+ usageRequested = false;
913
+ body = withoutUsageOption(body);
914
+ continue;
915
+ }
727
916
  // A provider that cannot stream says so with a 400: tell where to switch streaming off.
728
917
  if (built.stream && (failure.status === 400 || failure.status === 422) && /stream/i.test(failure.message.replace(label, ""))) {
729
918
  failure.message = redact(`${failure.message}${/[.!?]$/.test(failure.message) ? "" : "."} If this provider cannot stream its replies, set "Streaming" of the integration "${integration.name}" to "off".`);
@@ -739,13 +928,14 @@ async function callCandidate(config, attempt, built, request, options, deadlines
739
928
  if (streamed) {
740
929
  stage = "stream";
741
930
  ended = await readEventStream(response, clock, hooks);
931
+ streamEnd = ended ? "done" : "closed";
742
932
  }
743
933
  else {
744
934
  stage = "json";
745
935
  trace.firstByteMs ??= elapsed();
746
- const payload = await readJsonBody(response, clock, (count) => countBytes(count, "reply"));
936
+ const payload = await readJsonBody(response, clock, (count, decoded) => chunkArrived(count, decoded, "reply"));
747
937
  if (payload?.error) {
748
- const failure = streamError(payload.error, label, details(), redact);
938
+ const failure = streamError(payload.error, label, details(), redact, false);
749
939
  if (failure)
750
940
  throw failure;
751
941
  }
@@ -759,7 +949,7 @@ async function callCandidate(config, attempt, built, request, options, deadlines
759
949
  usage = normalizeUsage(payload?.usage);
760
950
  // A plain reply that came whole still reaches the listener of the text, once.
761
951
  if (!structured && text)
762
- request.onText?.(text);
952
+ notify(request.onText, text);
763
953
  }
764
954
  stage = "other";
765
955
  const outcome = classifyFinishReason(finishReason, ended);
@@ -770,12 +960,15 @@ async function callCandidate(config, attempt, built, request, options, deadlines
770
960
  trace.finishReason = shown;
771
961
  trace.replyCharacters = read.reply.trim().length + (isEmptyToolArguments(readArguments) ? 0 : readArguments.trim().length);
772
962
  trace.reasoningCharacters = reasoningCharacters + read.reasoningCharacters;
963
+ // The record of an attempt that worked carries numbers only: the end of the stream is for the one that failed.
964
+ trace.transport = transport(undefined, false);
965
+ // A reply that stops halfway (the stream closed too early, or the provider ended it with an error or an abort) is a failure of the moment, and what had arrived goes with it.
773
966
  if (outcome === "incomplete")
774
- throw new AiProviderError(`${label}: the stream ended before the reply was complete.`, undefined, true, details({ transient: true }));
967
+ throw new AiStreamInterruptedError(`${label}: the stream ended before the reply was complete.`, "ended", undefined, details());
775
968
  if (outcome === "unexpected")
776
- throw new AiProviderError(`${label}: unexpected finish reason "${shown}" and the stream did not end with [DONE]: the reply may be incomplete.`, undefined, true, details());
969
+ throw new AiStreamInterruptedError(`${label}: unexpected finish reason "${shown}" and the stream did not end with [DONE]: the reply may be incomplete.`, "ended", undefined, details());
777
970
  if (outcome === "failed")
778
- throw new AiProviderError(`${label}: the provider ended the reply with the finish reason "${shown}".`, undefined, true, details());
971
+ throw new AiStreamInterruptedError(`${label}: the provider ended the reply with the finish reason "${shown}".`, /abort|cancel/i.test(shown) ? "provider-abort" : "provider-error", undefined, details({}, "error"));
779
972
  if (outcome === "filtered")
780
973
  throw new AiProviderError(`${label}: the provider filtered the reply content (${shown}).`, undefined, false, details());
781
974
  // Some local servers leave the reasoning in the content as a leading <think> block: it is not the reply.
@@ -839,10 +1032,10 @@ async function callCandidate(config, attempt, built, request, options, deadlines
839
1032
  if (stage === "send")
840
1033
  throw new AiProviderError(redact(`${label}: ${error instanceof Error ? error.message : String(error)}`), undefined, true, { transient: true });
841
1034
  if (stage === "stream" && error instanceof StreamReadError) {
842
- throw new AiProviderError(redact(`${label}: the connection with the provider was lost while it was answering, so the reply could not be read. Nothing was applied. If this happens every time, check the proxy or the tunnel between this app and the provider.`), undefined, true, details({ transient: true }));
1035
+ throw new AiStreamInterruptedError(redact(`${label}: the connection with the provider was lost while it was answering, so the reply could not be read. Nothing was applied. If this happens every time, check the proxy or the tunnel between this app and the provider.`), "lost", undefined, details({}, "reset"));
843
1036
  }
844
1037
  if (stage === "stream" || stage === "json")
845
- throw new AiProviderError(redact(`${label}: the reply could not be read.`), undefined, true, details({ transient: true }));
1038
+ throw new AiProviderError(redact(`${label}: the reply could not be read.`), undefined, true, details({ transient: true }, stage === "stream" ? "reset" : undefined));
846
1039
  throw error;
847
1040
  }
848
1041
  finally {