narrarium-engine 0.1.12 → 0.1.14

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.
Files changed (73) hide show
  1. package/README.md +69 -5
  2. package/dist/ai/deadlines.d.ts.map +1 -1
  3. package/dist/ai/deadlines.js +25 -8
  4. package/dist/ai/deadlines.js.map +1 -1
  5. package/dist/ai/fetch-client.d.ts +19 -1
  6. package/dist/ai/fetch-client.d.ts.map +1 -1
  7. package/dist/ai/fetch-client.js +289 -74
  8. package/dist/ai/fetch-client.js.map +1 -1
  9. package/dist/ai/types.d.ts +71 -0
  10. package/dist/ai/types.d.ts.map +1 -1
  11. package/dist/ai/types.js +19 -0
  12. package/dist/ai/types.js.map +1 -1
  13. package/dist/autopilot/calls/index.d.ts +8 -0
  14. package/dist/autopilot/calls/index.d.ts.map +1 -0
  15. package/dist/autopilot/calls/index.js +8 -0
  16. package/dist/autopilot/calls/index.js.map +1 -0
  17. package/dist/autopilot/calls/memory-store.d.ts +38 -0
  18. package/dist/autopilot/calls/memory-store.d.ts.map +1 -0
  19. package/dist/autopilot/calls/memory-store.js +279 -0
  20. package/dist/autopilot/calls/memory-store.js.map +1 -0
  21. package/dist/autopilot/calls/port.d.ts +76 -0
  22. package/dist/autopilot/calls/port.d.ts.map +1 -0
  23. package/dist/autopilot/calls/port.js +28 -0
  24. package/dist/autopilot/calls/port.js.map +1 -0
  25. package/dist/autopilot/calls/recorder.d.ts +120 -0
  26. package/dist/autopilot/calls/recorder.d.ts.map +1 -0
  27. package/dist/autopilot/calls/recorder.js +400 -0
  28. package/dist/autopilot/calls/recorder.js.map +1 -0
  29. package/dist/autopilot/calls/retention.d.ts +27 -0
  30. package/dist/autopilot/calls/retention.d.ts.map +1 -0
  31. package/dist/autopilot/calls/retention.js +33 -0
  32. package/dist/autopilot/calls/retention.js.map +1 -0
  33. package/dist/autopilot/calls/run-calls.d.ts +106 -0
  34. package/dist/autopilot/calls/run-calls.d.ts.map +1 -0
  35. package/dist/autopilot/calls/run-calls.js +251 -0
  36. package/dist/autopilot/calls/run-calls.js.map +1 -0
  37. package/dist/autopilot/calls/types.d.ts +232 -0
  38. package/dist/autopilot/calls/types.d.ts.map +1 -0
  39. package/dist/autopilot/calls/types.js +53 -0
  40. package/dist/autopilot/calls/types.js.map +1 -0
  41. package/dist/autopilot/calls/utf8.d.ts +19 -0
  42. package/dist/autopilot/calls/utf8.d.ts.map +1 -0
  43. package/dist/autopilot/calls/utf8.js +91 -0
  44. package/dist/autopilot/calls/utf8.js.map +1 -0
  45. package/dist/autopilot/errors.d.ts.map +1 -1
  46. package/dist/autopilot/errors.js +60 -1
  47. package/dist/autopilot/errors.js.map +1 -1
  48. package/dist/autopilot/runner.d.ts +10 -0
  49. package/dist/autopilot/runner.d.ts.map +1 -1
  50. package/dist/autopilot/runner.js +109 -7
  51. package/dist/autopilot/runner.js.map +1 -1
  52. package/dist/autopilot/session.d.ts +12 -0
  53. package/dist/autopilot/session.d.ts.map +1 -1
  54. package/dist/autopilot/session.js +4 -0
  55. package/dist/autopilot/session.js.map +1 -1
  56. package/dist/autopilot/types.d.ts +60 -3
  57. package/dist/autopilot/types.d.ts.map +1 -1
  58. package/dist/autopilot/types.js.map +1 -1
  59. package/dist/index.d.ts +1 -0
  60. package/dist/index.d.ts.map +1 -1
  61. package/dist/index.js +1 -0
  62. package/dist/index.js.map +1 -1
  63. package/dist/server/client.d.ts +42 -1
  64. package/dist/server/client.d.ts.map +1 -1
  65. package/dist/server/client.js +69 -1
  66. package/dist/server/client.js.map +1 -1
  67. package/dist/server/protocol.d.ts +44 -0
  68. package/dist/server/protocol.d.ts.map +1 -1
  69. package/dist/server/protocol.js +19 -0
  70. package/dist/server/protocol.js.map +1 -1
  71. package/dist/version.d.ts +1 -1
  72. package/dist/version.js +1 -1
  73. package/package.json +1 -1
@@ -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();
@@ -100,7 +101,7 @@ export function createFetchAi(config, options = {}) {
100
101
  // The first candidate runs for its own deadlines whatever the total; a later one runs for the routing time that is left.
101
102
  const deadlines = resolveDeadlines(integration, options, tried > 0 && maxTotal !== undefined ? maxTotal - (Date.now() - startedAt) : undefined);
102
103
  const identity = { attemptId: randomId("attempt"), label: request.label, capability: request.capability, provider: integration.provider, model: candidate.model, integrationId: integration.id, index: attempt.index };
103
- notify(options.onAttempt, {
104
+ const attemptReport = {
104
105
  ...identity,
105
106
  // Copies: a listener can never change what is sent.
106
107
  messages: reportedMessages(attempt.built, request),
@@ -116,7 +117,9 @@ export function createFetchAi(config, options = {}) {
116
117
  ...(attempt.built?.reasoningParameter ? { reasoningParameter: attempt.built.reasoningParameter } : {}),
117
118
  ...(skipped.length ? { skipped: skipped.map((entry) => ({ ...entry })) } : {}),
118
119
  ...(attempt.built?.notes?.length ? { notes: [...attempt.built.notes] } : {}),
119
- });
120
+ };
121
+ notify(options.onAttempt, attemptReport);
122
+ notify(request.onAttempt, attemptReport);
120
123
  const attemptStarted = Date.now();
121
124
  const trace = { startedAt: attemptStarted, streamed: false, toolSeen: false };
122
125
  lastSent = candidate;
@@ -124,8 +127,8 @@ export function createFetchAi(config, options = {}) {
124
127
  try {
125
128
  if (!attempt.built)
126
129
  throw attempt.buildError;
127
- const response = await callCandidate(config, attempt, attempt.built, request, options, deadlines, secrets, trace);
128
- notify(options.onAttemptEnd, {
130
+ const response = await callCandidate(config, attempt, attempt.built, request, options, deadlines, secrets, trace, refusals);
131
+ const endReport = {
129
132
  ...identity,
130
133
  outcome: "ok",
131
134
  usage: response.usage,
@@ -135,13 +138,18 @@ export function createFetchAi(config, options = {}) {
135
138
  currency: response.currency,
136
139
  text: response.text,
137
140
  ...replyTrace(trace, Boolean(request.json)),
141
+ ...(trace.transport ? { transport: trace.transport } : {}),
138
142
  durationMs: Date.now() - attemptStarted,
139
- });
143
+ };
144
+ notify(options.onAttemptEnd, endReport);
145
+ notify(request.onAttemptEnd, endReport);
140
146
  return withSpent(response, spent);
141
147
  }
142
148
  catch (error) {
143
149
  const cancelled = Boolean(request.signal?.aborted) && isAbortError(error);
144
- notify(options.onAttemptEnd, failedAttempt(identity, error, cancelled, deadlines.startMs, Date.now() - attemptStarted, secrets, replyTrace(trace, Boolean(request.json))));
150
+ const failedReport = failedAttempt(identity, error, cancelled, deadlines.startMs, Date.now() - attemptStarted, secrets, replyTrace(trace, Boolean(request.json)));
151
+ notify(options.onAttemptEnd, failedReport);
152
+ notify(request.onAttemptEnd, failedReport);
145
153
  if (cancelled)
146
154
  throw error;
147
155
  if (error instanceof AiProviderError && !error.target) {
@@ -150,7 +158,8 @@ export function createFetchAi(config, options = {}) {
150
158
  }
151
159
  addSpent(spent, error);
152
160
  lastError = error;
153
- request.onText?.("");
161
+ notify(request.onText, "");
162
+ notify(request.onStructuredText, "");
154
163
  }
155
164
  }
156
165
  const notes = [];
@@ -247,17 +256,28 @@ function failedAttempt(identity, error, cancelled, timeoutMs, durationMs, secret
247
256
  ...(timedOut ? { timeoutMs: provider?.timeout?.ms ?? timeoutMs } : {}),
248
257
  ...(timedOut && provider?.timeout ? { timeoutPhase: provider.timeout.phase } : {}),
249
258
  ...reply,
259
+ ...(provider?.transport ? { transport: provider.transport } : {}),
260
+ ...(provider?.partialText ? { partialText: provider.partialText } : {}),
250
261
  durationMs,
251
262
  };
252
263
  }
264
+ /** A count of tokens: a number that is not negative. */
265
+ function tokenCount(value) {
266
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
267
+ }
268
+ /**
269
+ * 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
270
+ * 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`).
271
+ */
253
272
  function normalizeUsage(value) {
254
273
  if (!value || typeof value !== "object")
255
274
  return undefined;
256
275
  const usage = value;
276
+ const details = (usage.prompt_tokens_details ?? usage.input_tokens_details);
257
277
  return {
258
- inputTokens: usage.prompt_tokens ?? 0,
259
- outputTokens: usage.completion_tokens ?? 0,
260
- cachedInputTokens: usage.prompt_tokens_details?.cached_tokens ?? 0,
278
+ inputTokens: tokenCount(usage.prompt_tokens) ?? tokenCount(usage.input_tokens) ?? 0,
279
+ outputTokens: tokenCount(usage.completion_tokens) ?? tokenCount(usage.output_tokens) ?? 0,
280
+ cachedInputTokens: tokenCount(details?.cached_tokens) ?? tokenCount(usage.prompt_cache_hit_tokens) ?? tokenCount(usage.cache_read_input_tokens) ?? 0,
261
281
  };
262
282
  }
263
283
  /**
@@ -285,7 +305,8 @@ function parseRetryAfter(value) {
285
305
  const date = Date.parse(text);
286
306
  return Number.isNaN(date) ? undefined : Math.min(MAX_RETRY_AFTER_MS, Math.max(0, date - Date.now()));
287
307
  }
288
- const TRANSIENT_STATUSES = new Set([408, 429, 502, 503, 504]);
308
+ /** 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. */
309
+ const TRANSIENT_STATUSES = new Set([408, 429, 502, 503, 504, 520, 521, 522, 523, 524]);
289
310
  /**
290
311
  * 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
312
  * object (some providers say only `"param": "reasoning_effort"`): the OpenAI field, or the chat-template argument (`chat_template_kwargs`, `reasoning_strength`).
@@ -317,7 +338,9 @@ async function providerError(response, provider, model, redact, sent) {
317
338
  detail = typeof message === "string" ? message : raw;
318
339
  }
319
340
  catch {
320
- detail = raw;
341
+ // 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.
342
+ const page = /^\s*<(?:!doctype\s+html|html)\b/i.test(raw) ? /<title[^>]*>([^<]{1,200})<\/title>/i.exec(raw)?.[1]?.replace(/\s+/g, " ").trim() : undefined;
343
+ 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
344
  }
322
345
  }
323
346
  catch {
@@ -343,10 +366,11 @@ class StreamReadError extends Error {
343
366
  }
344
367
  }
345
368
  /**
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
369
+ * 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
370
+ * 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;
371
+ * 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
372
+ * 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.
373
+ * Every piece that arrives starts the idle deadline again, a comment too, and no read can hold the call past
350
374
  * a deadline or the author's cancel. However it ends, but by the end of the stream, the reader is released.
351
375
  */
352
376
  async function readEventStream(response, clock, hooks) {
@@ -354,8 +378,13 @@ async function readEventStream(response, clock, hooks) {
354
378
  throw new AiProviderError("The provider returned an empty stream.", undefined, true, { transient: true });
355
379
  const reader = response.body.getReader();
356
380
  const decoder = new TextDecoder();
381
+ /** The line that is being read: what has arrived of it. */
357
382
  let buffer = "";
383
+ /** The last line ended with a carriage return: a line feed that opens the next chunk is the other half of the same end. */
384
+ let skipLineFeed = false;
358
385
  let pending = [];
386
+ /** The name that the `event:` line of the event being read gave it. */
387
+ let named = "";
359
388
  let exhausted = false;
360
389
  const complete = (value) => {
361
390
  const text = value.trim();
@@ -373,9 +402,15 @@ async function readEventStream(response, clock, hooks) {
373
402
  };
374
403
  const flush = () => {
375
404
  const lines = pending;
405
+ const event = named;
376
406
  pending = [];
377
- if (!lines.length)
407
+ named = "";
408
+ if (!lines.length) {
409
+ // An `event: error` with no data at all still says that the provider failed.
410
+ if (event === "error")
411
+ hooks.onData("", event);
378
412
  return false;
413
+ }
379
414
  const joined = lines.join("\n").trim();
380
415
  if (joined === "[DONE]")
381
416
  return true;
@@ -386,23 +421,59 @@ async function readEventStream(response, clock, hooks) {
386
421
  if (single === "[DONE]")
387
422
  return true;
388
423
  if (single)
389
- hooks.onData(single);
424
+ hooks.onData(single, event);
390
425
  }
391
426
  return false;
392
427
  }
393
- if (joined)
394
- hooks.onData(joined);
428
+ if (joined || event === "error")
429
+ hooks.onData(joined, event);
395
430
  return false;
396
431
  };
397
432
  const takeLine = (line) => {
398
- const clean = line.replace(/\r$/, "");
399
- if (!clean)
433
+ if (!line)
400
434
  return flush();
401
- if (!clean.startsWith("data:"))
435
+ if (line.startsWith("event:")) {
436
+ named = line.slice(6).trim().toLowerCase();
402
437
  return false;
403
- pending.push(clean.slice(5).trimStart());
438
+ }
439
+ if (!line.startsWith("data:"))
440
+ return false;
441
+ pending.push(line.slice(5).trimStart());
404
442
  return complete(pending.join("\n")) ? flush() : false;
405
443
  };
444
+ /** Splits what arrived into lines and takes them; `true` when the end marker was among them. */
445
+ const feed = (decoded) => {
446
+ let text = decoded;
447
+ if (skipLineFeed) {
448
+ skipLineFeed = false;
449
+ if (text.charCodeAt(0) === 10)
450
+ text = text.slice(1);
451
+ }
452
+ buffer += text;
453
+ let start = 0;
454
+ for (let at = 0; at < buffer.length; at += 1) {
455
+ const code = buffer.charCodeAt(at);
456
+ if (code !== 10 && code !== 13)
457
+ continue;
458
+ const line = buffer.slice(start, at);
459
+ if (code === 13) {
460
+ if (at + 1 < buffer.length) {
461
+ if (buffer.charCodeAt(at + 1) === 10)
462
+ at += 1;
463
+ }
464
+ else {
465
+ skipLineFeed = true;
466
+ }
467
+ }
468
+ start = at + 1;
469
+ if (takeLine(line)) {
470
+ buffer = "";
471
+ return true;
472
+ }
473
+ }
474
+ buffer = buffer.slice(start);
475
+ return false;
476
+ };
406
477
  try {
407
478
  for (;;) {
408
479
  let piece;
@@ -418,19 +489,15 @@ async function readEventStream(response, clock, hooks) {
418
489
  break;
419
490
  }
420
491
  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
- }
492
+ const decoded = decoder.decode(piece.value, { stream: true });
493
+ hooks.onChunk(piece.value.byteLength, decoded);
494
+ if (feed(decoded))
495
+ return true;
431
496
  hooks.onPiece();
432
497
  }
433
- buffer += decoder.decode();
498
+ const rest = decoder.decode();
499
+ if (rest && feed(rest))
500
+ return true;
434
501
  if (buffer.trim() && takeLine(buffer))
435
502
  return true;
436
503
  return flush();
@@ -445,7 +512,7 @@ async function readEventStream(response, clock, hooks) {
445
512
  * 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
513
  * be held past a deadline or the author's cancel, and releases the body however it ends (`response.json()` would keep it locked).
447
514
  */
448
- async function readJsonBody(response, clock, onBytes) {
515
+ async function readJsonBody(response, clock, onChunk) {
449
516
  if (!response.body)
450
517
  return clock.guard(response.json());
451
518
  const reader = response.body.getReader();
@@ -466,8 +533,9 @@ async function readJsonBody(response, clock, onBytes) {
466
533
  break;
467
534
  }
468
535
  clock.activity();
469
- onBytes(piece.value.byteLength);
470
- body += decoder.decode(piece.value, { stream: true });
536
+ const decoded = decoder.decode(piece.value, { stream: true });
537
+ onChunk(piece.value.byteLength, decoded);
538
+ body += decoded;
471
539
  }
472
540
  body += decoder.decode();
473
541
  return JSON.parse(body);
@@ -503,10 +571,13 @@ export function classifyFinishReason(reason, ended) {
503
571
  const PERMANENT_STREAM_ERROR = /authenticat|unauthori[sz]ed|forbidden|permission|invalid[_ -]?(?:request|api[_ -]?key|argument|parameter)|bad[_ -]?request/i;
504
572
  const TRANSIENT_STREAM_ERROR = /overload|rate[_ -]?limit|too many requests|temporar|unavailable|busy|try again|time[ds]? ?out|capacity/i;
505
573
  /**
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.
574
+ * A failure the provider reported inside the stream (`{"error": {...}}`, `{"error": "..."}`, or an `event: error`), or `null` when the
575
+ * 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
576
+ * 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),
577
+ * 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
578
+ * its words say it depends on the moment (a deterministic failure, `context too long`, would be the same every time).
508
579
  */
509
- function streamError(value, label, details, redact) {
580
+ function streamError(value, label, details, redact, started) {
510
581
  const source = value && typeof value === "object" ? value : null;
511
582
  const message = typeof value === "string" ? value.trim() : typeof source?.message === "string" ? source.message.trim() : "";
512
583
  if (!source && !message)
@@ -518,14 +589,22 @@ function streamError(value, label, details, redact) {
518
589
  const permanent = (status !== undefined && status >= 400 && status < 500 && status !== 408 && status !== 409 && status !== 429) || PERMANENT_STREAM_ERROR.test(words);
519
590
  const transient = !permanent && ((status !== undefined && TRANSIENT_STATUSES.has(status)) || TRANSIENT_STREAM_ERROR.test(`${message} ${words}`));
520
591
  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 } : {}) });
592
+ const said = redact(`${label}: the provider reported an error during the reply — ${detail}`);
593
+ if (started && !permanent)
594
+ return new AiStreamInterruptedError(said, "provider-error", status, details);
595
+ return new AiProviderError(said, status, !permanent, { ...details, ...(transient ? { transient: true } : {}) });
522
596
  }
523
- /** Characters of reasoning a reply carried. Only the count is kept, never the reasoning itself. */
597
+ /**
598
+ * 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`
599
+ * (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.
600
+ */
524
601
  function reasoningLength(source) {
525
602
  if (!source || typeof source !== "object")
526
603
  return 0;
527
604
  const { reasoning_content: content, reasoning } = source;
528
- return (typeof content === "string" ? content.length : 0) + (typeof reasoning === "string" ? reasoning.length : 0);
605
+ const first = typeof content === "string" ? content : "";
606
+ const second = typeof reasoning === "string" ? reasoning : "";
607
+ return first === second ? first.length : first.length + second.length;
529
608
  }
530
609
  /** The function calls of a message (`tool_calls`) whose arguments are text, in their order. */
531
610
  function callsOf(value) {
@@ -559,7 +638,44 @@ function chosenArguments(calls, wanted) {
559
638
  }
560
639
  return firstWithArguments ?? first ?? "";
561
640
  }
562
- async function callCandidate(config, attempt, built, request, options, deadlines, secrets, trace) {
641
+ /** 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. */
642
+ const TAIL_WINDOW_CHARACTERS = TRANSPORT_TAIL_CHARACTERS * 3;
643
+ /** 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. */
644
+ const REQUEST_ID_HEADERS = ["x-llmproxy-request-id", "x-request-id", "request-id", "x-ms-request-id", "apim-request-id"];
645
+ /** The most addresses a set of refusals of `stream_options` keeps. */
646
+ const MAX_REMEMBERED_REFUSALS = 200;
647
+ /** 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). */
648
+ function requestIdOf(headers) {
649
+ for (const name of REQUEST_ID_HEADERS) {
650
+ const value = headers?.get?.(name)?.trim();
651
+ if (value && /^[A-Za-z0-9._:-]{1,100}$/.test(value))
652
+ return value;
653
+ }
654
+ return undefined;
655
+ }
656
+ /** 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). */
657
+ const REASONING_FIELD = /("(?:reasoning_content|reasoning)"\s*:\s*")(?:[^"\\]|\\.)*("?)/g;
658
+ /**
659
+ * 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
660
+ * 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.
661
+ */
662
+ function streamTail(window, whole) {
663
+ let text = window;
664
+ if (!whole) {
665
+ const at = text.search(/\r\n|\r|\n/);
666
+ text = at < 0 ? "" : text.slice(at + (text.startsWith("\r\n", at) ? 2 : 1));
667
+ }
668
+ return text.replace(REASONING_FIELD, "$1…$2");
669
+ }
670
+ /** A refusal of `stream_options`: a 400 or a 422 whose message names the option (or `include_usage`). */
671
+ function refusesUsageOption(failure, label) {
672
+ return (failure.status === 400 || failure.status === 422) && /stream[_ -]?options|include[_ -]?usage/i.test(failure.message.replace(label, ""));
673
+ }
674
+ function withoutUsageOption(body) {
675
+ const { stream_options: _refused, ...rest } = body;
676
+ return rest;
677
+ }
678
+ async function callCandidate(config, attempt, built, request, options, deadlines, secrets, trace, refusals) {
563
679
  const { candidate } = attempt;
564
680
  const { integration, model } = candidate;
565
681
  const label = `${integration.provider} ${model}`;
@@ -579,14 +695,38 @@ async function callCandidate(config, attempt, built, request, options, deadlines
579
695
  let wholeArguments = "";
580
696
  /** The response ended properly: a stream that closed with `[DONE]`, or a complete JSON body. */
581
697
  let ended = true;
698
+ /** How the stream ended, once it has: what the diagnostics say unless a failure tells better. */
699
+ let streamEnd;
582
700
  let bytes = 0;
701
+ let chunks = 0;
583
702
  let events = 0;
703
+ let lastChunkAt;
704
+ /** The end of what arrived, as it came (see `TAIL_WINDOW_CHARACTERS`), and how many characters arrived in all. */
705
+ let tailWindow = "";
706
+ let tailCharacters = 0;
707
+ let status;
708
+ let requestId;
709
+ /** The request that is answered asks the provider for the tokens of the stream (`stream_options.include_usage`). */
710
+ let usageRequested = Boolean(built.body.stream_options);
584
711
  let lastProgressAt;
585
712
  let response;
586
713
  /** Where the call is, to say what went wrong when something does. */
587
714
  let stage = "send";
588
715
  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. */
716
+ /** The cumulative value of a structured reply for `onStructuredText`: the arguments of the call, else the text. Sent only when it grew. */
717
+ let structuredSent = 0;
718
+ const reportStructured = () => {
719
+ if (!request.onStructuredText)
720
+ return;
721
+ const value = callArguments() || text;
722
+ if (value.length <= structuredSent)
723
+ return;
724
+ structuredSent = value.length;
725
+ notify(request.onStructuredText, value);
726
+ };
727
+ /** The model has written something of the reply (its text, its reasoning or the call of its function): the provider is answering. */
728
+ const started = () => Boolean(text || reasoningCharacters || calls.size || wholeArguments);
729
+ /** What an attempt used: the provider's count, else an estimate once the model has started to answer. */
590
730
  const measure = () => {
591
731
  if (usage && usage.inputTokens + usage.outputTokens > 0)
592
732
  return { usage, usageKnown: true };
@@ -598,8 +738,30 @@ async function callCandidate(config, attempt, built, request, options, deadlines
598
738
  usageKnown: false,
599
739
  };
600
740
  };
601
- const details = (extra = {}) => {
741
+ /** 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. */
742
+ const transport = (end = streamEnd, withTail = true) => {
743
+ const tail = withTail ? redact(streamTail(tailWindow, tailCharacters <= TAIL_WINDOW_CHARACTERS)).slice(-TRANSPORT_TAIL_CHARACTERS) : "";
744
+ const shown = redact(finishReason).replace(/\s+/g, " ").trim().slice(0, 60);
745
+ return {
746
+ ...(status !== undefined ? { status } : {}),
747
+ streamed: trace.streamed,
748
+ bytes,
749
+ chunks,
750
+ events,
751
+ ...(lastChunkAt !== undefined ? { lastChunkAfterMs: Math.max(0, lastChunkAt - trace.startedAt), lastChunkAt: new Date(lastChunkAt).toISOString(), silentMs: Math.max(0, Date.now() - lastChunkAt) } : {}),
752
+ ...(tail ? { tail } : {}),
753
+ ...(shown ? { finishReason: shown } : {}),
754
+ usageReceived: Boolean(usage && usage.inputTokens + usage.outputTokens > 0),
755
+ usageRequested,
756
+ ...(end ? { end } : {}),
757
+ ...(requestId ? { requestId } : {}),
758
+ };
759
+ };
760
+ const details = (extra = {}, end) => {
602
761
  const measured = measure();
762
+ // The reply that had arrived: its text without a reasoning block, else the arguments of its function.
763
+ const written = splitReasoningBlock(text).reply;
764
+ const partial = written.trim() ? written : callArguments();
603
765
  return {
604
766
  usage: measured.usage,
605
767
  cost: estimateCost(measured.usage, candidate.pricing),
@@ -608,13 +770,15 @@ async function callCandidate(config, attempt, built, request, options, deadlines
608
770
  model,
609
771
  provider: integration.provider,
610
772
  integrationId: integration.id,
773
+ ...(status !== undefined || bytes > 0 ? { transport: transport(end) } : {}),
774
+ ...(partial ? { partialText: redact(partial.slice(0, MAX_PARTIAL_CHARACTERS)) } : {}),
611
775
  ...extra,
612
776
  };
613
777
  };
614
778
  /** A stream that no model's answer explains: stopped, with what it used and what to do. */
615
779
  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
780
  const timeoutError = (expired, answering) => new AiProviderError(redact(timeoutMessage(label, expired, deadlines, integration.name)), undefined, true, {
617
- ...(answering ? details() : {}),
781
+ ...(answering ? details({}, "timeout") : {}),
618
782
  transient: true,
619
783
  timedOut: true,
620
784
  timeout: { phase: expired.phase, ms: expired.ms, ...(expired.phase === "start" && deadlines.raisedFrom !== undefined ? { raisedFrom: deadlines.raisedFrom } : {}) },
@@ -651,18 +815,29 @@ async function callCandidate(config, attempt, built, request, options, deadlines
651
815
  call.arguments += fn.arguments;
652
816
  }
653
817
  };
654
- const take = (data) => {
655
- let chunk;
818
+ const take = (data, event = "") => {
819
+ let parsed;
656
820
  try {
657
- chunk = JSON.parse(data);
821
+ parsed = JSON.parse(data);
658
822
  }
659
823
  catch {
660
- return;
824
+ parsed = undefined;
825
+ }
826
+ let chunk;
827
+ if (event === "error") {
828
+ // An `event: error`: whatever its data is (an error object, a message, nothing), the provider is reporting a failure.
829
+ const inner = parsed && typeof parsed === "object" && "error" in parsed ? parsed.error : parsed;
830
+ chunk = { error: inner || data.trim() || "the provider sent an error event without details" };
831
+ }
832
+ else {
833
+ if (parsed === undefined)
834
+ return;
835
+ chunk = parsed;
661
836
  }
662
837
  if (!chunk || typeof chunk !== "object")
663
838
  return;
664
839
  if (chunk.error) {
665
- const failure = streamError(chunk.error, label, details(), redact);
840
+ const failure = streamError(chunk.error, label, details({}, "error"), redact, started());
666
841
  if (failure)
667
842
  throw failure;
668
843
  }
@@ -676,7 +851,7 @@ async function callCandidate(config, attempt, built, request, options, deadlines
676
851
  text += delta.content;
677
852
  // The text of a structured reply is no prose for the listener: its progress is `onProgress`.
678
853
  if (!structured)
679
- request.onText?.(text);
854
+ notify(request.onText, text);
680
855
  }
681
856
  addCalls(delta?.tool_calls);
682
857
  // Some providers end the stream with the whole message instead of (or after) the pieces.
@@ -690,28 +865,44 @@ async function callCandidate(config, attempt, built, request, options, deadlines
690
865
  const reason = choices.find((choice) => typeof choice?.finish_reason === "string" && choice.finish_reason)?.finish_reason;
691
866
  if (reason)
692
867
  finishReason = reason;
693
- if (chunk.usage)
694
- usage = normalizeUsage(chunk.usage);
868
+ if (structured)
869
+ reportStructured();
870
+ // 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.
871
+ if (chunk.usage) {
872
+ const next = normalizeUsage(chunk.usage);
873
+ if (next && (next.inputTokens + next.outputTokens > 0 || !usage))
874
+ usage = next;
875
+ }
695
876
  };
696
- const countBytes = (count, what) => {
877
+ const chunkArrived = (count, decoded, what) => {
697
878
  bytes += count;
879
+ chunks += 1;
880
+ lastChunkAt = Date.now();
881
+ tailCharacters += decoded.length;
882
+ tailWindow = decoded.length >= TAIL_WINDOW_CHARACTERS ? decoded.slice(-TAIL_WINDOW_CHARACTERS) : (tailWindow + decoded).slice(-TAIL_WINDOW_CHARACTERS);
698
883
  trace.firstByteMs ??= elapsed();
699
884
  if (bytes > MAX_STREAM_TRANSPORT_BYTES)
700
885
  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
886
  };
702
887
  const hooks = {
703
- onData: (data) => {
888
+ onData: (data, event) => {
704
889
  events += 1;
705
- take(data);
890
+ take(data, event);
706
891
  },
707
- onBytes: (count) => countBytes(count, "stream"),
892
+ onChunk: (count, decoded) => chunkArrived(count, decoded, "stream"),
708
893
  onPiece: reportProgress,
709
894
  };
710
- try {
895
+ // What is sent: an address that refused `stream_options` before is not asked it again.
896
+ let body = built.body;
897
+ if (usageRequested && refusals.has(built.url)) {
898
+ body = withoutUsageOption(body);
899
+ usageRequested = false;
900
+ }
901
+ const send = () => {
711
902
  const sent = Promise.resolve(fetchImpl(built.url, {
712
903
  method: "POST",
713
904
  headers: built.headers,
714
- body: JSON.stringify(built.body),
905
+ body: JSON.stringify(body),
715
906
  signal: clock.signal,
716
907
  }));
717
908
  // A reply that comes after the call was given up is dropped, and its body let go.
@@ -719,11 +910,29 @@ async function callCandidate(config, attempt, built, request, options, deadlines
719
910
  if (clock.interrupted())
720
911
  discardBody(late);
721
912
  }, () => undefined);
722
- response = await clock.guard(sent);
723
- stage = "other";
724
- if (!response.ok) {
913
+ return clock.guard(sent);
914
+ };
915
+ try {
916
+ for (;;) {
917
+ stage = "send";
918
+ response = await send();
919
+ stage = "other";
920
+ status = response.status;
921
+ requestId = requestIdOf(response.headers);
922
+ if (response.ok)
923
+ break;
725
924
  trace.firstByteMs ??= elapsed();
726
925
  const failure = await clock.guard(providerError(response, integration.provider, model, redact, built.thinking ? { integration: integration.name, parameter: built.reasoningParameter ?? "reasoning_effort" } : undefined));
926
+ failure.transport = transport();
927
+ // 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.
928
+ if (usageRequested && refusesUsageOption(failure, label)) {
929
+ if (refusals.size >= MAX_REMEMBERED_REFUSALS)
930
+ refusals.delete(refusals.values().next().value);
931
+ refusals.add(built.url);
932
+ usageRequested = false;
933
+ body = withoutUsageOption(body);
934
+ continue;
935
+ }
727
936
  // A provider that cannot stream says so with a 400: tell where to switch streaming off.
728
937
  if (built.stream && (failure.status === 400 || failure.status === 422) && /stream/i.test(failure.message.replace(label, ""))) {
729
938
  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 +948,14 @@ async function callCandidate(config, attempt, built, request, options, deadlines
739
948
  if (streamed) {
740
949
  stage = "stream";
741
950
  ended = await readEventStream(response, clock, hooks);
951
+ streamEnd = ended ? "done" : "closed";
742
952
  }
743
953
  else {
744
954
  stage = "json";
745
955
  trace.firstByteMs ??= elapsed();
746
- const payload = await readJsonBody(response, clock, (count) => countBytes(count, "reply"));
956
+ const payload = await readJsonBody(response, clock, (count, decoded) => chunkArrived(count, decoded, "reply"));
747
957
  if (payload?.error) {
748
- const failure = streamError(payload.error, label, details(), redact);
958
+ const failure = streamError(payload.error, label, details(), redact, false);
749
959
  if (failure)
750
960
  throw failure;
751
961
  }
@@ -759,7 +969,9 @@ async function callCandidate(config, attempt, built, request, options, deadlines
759
969
  usage = normalizeUsage(payload?.usage);
760
970
  // A plain reply that came whole still reaches the listener of the text, once.
761
971
  if (!structured && text)
762
- request.onText?.(text);
972
+ notify(request.onText, text);
973
+ if (structured)
974
+ reportStructured();
763
975
  }
764
976
  stage = "other";
765
977
  const outcome = classifyFinishReason(finishReason, ended);
@@ -770,12 +982,15 @@ async function callCandidate(config, attempt, built, request, options, deadlines
770
982
  trace.finishReason = shown;
771
983
  trace.replyCharacters = read.reply.trim().length + (isEmptyToolArguments(readArguments) ? 0 : readArguments.trim().length);
772
984
  trace.reasoningCharacters = reasoningCharacters + read.reasoningCharacters;
985
+ // The record of an attempt that worked carries numbers only: the end of the stream is for the one that failed.
986
+ trace.transport = transport(undefined, false);
987
+ // 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
988
  if (outcome === "incomplete")
774
- throw new AiProviderError(`${label}: the stream ended before the reply was complete.`, undefined, true, details({ transient: true }));
989
+ throw new AiStreamInterruptedError(`${label}: the stream ended before the reply was complete.`, "ended", undefined, details());
775
990
  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());
991
+ 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
992
  if (outcome === "failed")
778
- throw new AiProviderError(`${label}: the provider ended the reply with the finish reason "${shown}".`, undefined, true, details());
993
+ 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
994
  if (outcome === "filtered")
780
995
  throw new AiProviderError(`${label}: the provider filtered the reply content (${shown}).`, undefined, false, details());
781
996
  // Some local servers leave the reasoning in the content as a leading <think> block: it is not the reply.
@@ -839,10 +1054,10 @@ async function callCandidate(config, attempt, built, request, options, deadlines
839
1054
  if (stage === "send")
840
1055
  throw new AiProviderError(redact(`${label}: ${error instanceof Error ? error.message : String(error)}`), undefined, true, { transient: true });
841
1056
  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 }));
1057
+ 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
1058
  }
844
1059
  if (stage === "stream" || stage === "json")
845
- throw new AiProviderError(redact(`${label}: the reply could not be read.`), undefined, true, details({ transient: true }));
1060
+ throw new AiProviderError(redact(`${label}: the reply could not be read.`), undefined, true, details({ transient: true }, stage === "stream" ? "reset" : undefined));
846
1061
  throw error;
847
1062
  }
848
1063
  finally {