narrarium-engine 0.1.6 → 0.1.8

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 (82) hide show
  1. package/README.md +224 -16
  2. package/dist/ai/body.d.ts +20 -0
  3. package/dist/ai/body.d.ts.map +1 -0
  4. package/dist/ai/body.js +112 -0
  5. package/dist/ai/body.js.map +1 -0
  6. package/dist/ai/catalog-fetch.d.ts +51 -0
  7. package/dist/ai/catalog-fetch.d.ts.map +1 -0
  8. package/dist/ai/catalog-fetch.js +260 -0
  9. package/dist/ai/catalog-fetch.js.map +1 -0
  10. package/dist/ai/catalog-support.d.ts +13 -0
  11. package/dist/ai/catalog-support.d.ts.map +1 -0
  12. package/dist/ai/catalog-support.js +28 -0
  13. package/dist/ai/catalog-support.js.map +1 -0
  14. package/dist/ai/catalog.d.ts +148 -0
  15. package/dist/ai/catalog.d.ts.map +1 -0
  16. package/dist/ai/catalog.js +367 -0
  17. package/dist/ai/catalog.js.map +1 -0
  18. package/dist/ai/config.d.ts +105 -7
  19. package/dist/ai/config.d.ts.map +1 -1
  20. package/dist/ai/config.js +100 -9
  21. package/dist/ai/config.js.map +1 -1
  22. package/dist/ai/deadlines.d.ts +79 -0
  23. package/dist/ai/deadlines.d.ts.map +1 -0
  24. package/dist/ai/deadlines.js +151 -0
  25. package/dist/ai/deadlines.js.map +1 -0
  26. package/dist/ai/fetch-client.d.ts +61 -5
  27. package/dist/ai/fetch-client.d.ts.map +1 -1
  28. package/dist/ai/fetch-client.js +399 -130
  29. package/dist/ai/fetch-client.js.map +1 -1
  30. package/dist/ai/probe.d.ts +40 -0
  31. package/dist/ai/probe.d.ts.map +1 -0
  32. package/dist/ai/probe.js +110 -0
  33. package/dist/ai/probe.js.map +1 -0
  34. package/dist/ai/request.d.ts +58 -3
  35. package/dist/ai/request.d.ts.map +1 -1
  36. package/dist/ai/request.js +96 -5
  37. package/dist/ai/request.js.map +1 -1
  38. package/dist/ai/router.d.ts +12 -1
  39. package/dist/ai/router.d.ts.map +1 -1
  40. package/dist/ai/router.js +10 -2
  41. package/dist/ai/router.js.map +1 -1
  42. package/dist/ai/routing.d.ts +15 -4
  43. package/dist/ai/routing.d.ts.map +1 -1
  44. package/dist/ai/routing.js +25 -6
  45. package/dist/ai/routing.js.map +1 -1
  46. package/dist/ai/token-limit.d.ts +4 -4
  47. package/dist/ai/token-limit.d.ts.map +1 -1
  48. package/dist/ai/token-limit.js +5 -4
  49. package/dist/ai/token-limit.js.map +1 -1
  50. package/dist/ai/types.d.ts +44 -2
  51. package/dist/ai/types.d.ts.map +1 -1
  52. package/dist/ai/types.js +13 -0
  53. package/dist/ai/types.js.map +1 -1
  54. package/dist/autopilot/errors.d.ts +5 -3
  55. package/dist/autopilot/errors.d.ts.map +1 -1
  56. package/dist/autopilot/errors.js +44 -4
  57. package/dist/autopilot/errors.js.map +1 -1
  58. package/dist/autopilot/runner.d.ts.map +1 -1
  59. package/dist/autopilot/runner.js +21 -4
  60. package/dist/autopilot/runner.js.map +1 -1
  61. package/dist/autopilot/session.js +1 -1
  62. package/dist/autopilot/session.js.map +1 -1
  63. package/dist/autopilot/state.d.ts +4 -3
  64. package/dist/autopilot/state.d.ts.map +1 -1
  65. package/dist/autopilot/state.js +35 -9
  66. package/dist/autopilot/state.js.map +1 -1
  67. package/dist/autopilot/tasks.js +2 -2
  68. package/dist/autopilot/tasks.js.map +1 -1
  69. package/dist/autopilot/types.d.ts +35 -6
  70. package/dist/autopilot/types.d.ts.map +1 -1
  71. package/dist/autopilot/types.js +1 -1
  72. package/dist/autopilot/types.js.map +1 -1
  73. package/dist/index.d.ts +3 -0
  74. package/dist/index.d.ts.map +1 -1
  75. package/dist/index.js +3 -0
  76. package/dist/index.js.map +1 -1
  77. package/dist/server/protocol.d.ts +6 -1
  78. package/dist/server/protocol.d.ts.map +1 -1
  79. package/dist/server/protocol.js.map +1 -1
  80. package/dist/version.d.ts +1 -1
  81. package/dist/version.js +1 -1
  82. package/package.json +1 -1
@@ -1,13 +1,24 @@
1
- import { isAbortError, linkedSignal } from "../util/abort.js";
1
+ import { abortError, isAbortError } from "../util/abort.js";
2
2
  import { randomId } from "../util/hash.js";
3
+ import { discardBody, release } from "./body.js";
3
4
  import { likelyTextTokens } from "./budget.js";
5
+ import { resolveDeadlines, startClock, timeoutMessage } from "./deadlines.js";
4
6
  import { redactSecrets } from "./redact.js";
5
7
  import { effectiveAiBase, endpointOrigin } from "./request.js";
6
8
  import { candidateBoundary, planAttempts } from "./routing.js";
7
9
  import { splitReasoningBlock, structuredFromReply } from "./structured.js";
8
10
  import { AiFallbackBlockedError, AiProviderError, AiReplyRejectedError } from "./types.js";
9
- /** How long one candidate may take before it is given up, for every host (an integration's own timeout wins). */
10
- export const DEFAULT_REQUEST_TIMEOUT_MS = 600_000;
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
+ export { DEFAULT_REQUEST_TIMEOUT_MS, MIN_REQUEST_TIMEOUT_MS, TOTAL_REQUEST_CAP_MS } from "./deadlines.js";
13
+ /**
14
+ * Raw bytes of a stream include the JSON envelope of every piece (a few hundred bytes for a few characters), so a long reasoning phase is
15
+ * far larger than its text. A stream over this many bytes is a model that loops, and is stopped.
16
+ */
17
+ export const MAX_STREAM_TRANSPORT_BYTES = 256_000_000;
18
+ /** The characters of reasoning a stream may carry before it is taken for a loop and stopped. */
19
+ export const MAX_STREAM_REASONING_CHARACTERS = 16_000_000;
20
+ /** A host's progress listener is called at most this often. */
21
+ const PROGRESS_INTERVAL_MS = 250;
11
22
  const MAX_RETRY_AFTER_MS = 300_000;
12
23
  function notify(hook, value) {
13
24
  try {
@@ -35,6 +46,7 @@ export function createFetchAi(config, options = {}) {
35
46
  let startedAt = Date.now();
36
47
  const secrets = config.aiIntegrations.map((integration) => integration.apiKey);
37
48
  const plan = planAttempts(config, request, options.githubModelsBaseUrl);
49
+ const skipped = plan.skipped.map((entry) => ({ model: entry.candidate.model, reason: entry.reason }));
38
50
  const decisions = new Map();
39
51
  const blocked = [];
40
52
  const spent = {};
@@ -68,9 +80,8 @@ export function createFetchAi(config, options = {}) {
68
80
  continue;
69
81
  }
70
82
  }
71
- let timeoutMs = integration.requestTimeoutMs ?? options.defaultTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
72
- if (tried > 0 && maxTotal !== undefined)
73
- timeoutMs = Math.max(1, Math.min(timeoutMs, Math.ceil(maxTotal - (Date.now() - startedAt))));
83
+ // The first candidate runs for its own deadlines whatever the total; a later one runs for the routing time that is left.
84
+ const deadlines = resolveDeadlines(integration, options, tried > 0 && maxTotal !== undefined ? maxTotal - (Date.now() - startedAt) : undefined);
74
85
  const identity = { attemptId: randomId("attempt"), label: request.label, capability: request.capability, provider: integration.provider, model: candidate.model, integrationId: integration.id, index: attempt.index };
75
86
  const sent = attempt.built?.body.messages ?? [{ role: "system", content: request.system }, { role: "user", content: request.user }];
76
87
  notify(options.onAttempt, {
@@ -81,15 +92,23 @@ export function createFetchAi(config, options = {}) {
81
92
  stream: attempt.built?.stream ?? false,
82
93
  tools: attempt.built?.useTools ?? false,
83
94
  endpoint: effectiveAiBase(integration, options.githubModelsBaseUrl),
84
- timeoutMs,
95
+ timeoutMs: deadlines.startMs,
96
+ timeouts: { startMs: deadlines.startMs, idleMs: deadlines.idleMs, capMs: deadlines.capMs, ...(deadlines.raisedFrom !== undefined ? { raised: { from: deadlines.raisedFrom } } : {}) },
97
+ streamMode: integration.streamMode === "off" ? "off" : "auto",
98
+ toolsOnly: config.toolsOnly !== false,
99
+ ...(attempt.built?.thinking ? { thinking: attempt.built.thinking } : {}),
100
+ ...(attempt.built?.reasoningParameter ? { reasoningParameter: attempt.built.reasoningParameter } : {}),
101
+ ...(skipped.length ? { skipped: skipped.map((entry) => ({ ...entry })) } : {}),
102
+ ...(attempt.built?.notes?.length ? { notes: [...attempt.built.notes] } : {}),
85
103
  });
86
104
  const attemptStarted = Date.now();
105
+ const trace = { startedAt: attemptStarted, streamed: false, toolSeen: false };
87
106
  lastSent = candidate;
88
107
  tried += 1;
89
108
  try {
90
109
  if (!attempt.built)
91
110
  throw attempt.buildError;
92
- const response = await callCandidate(config, attempt, attempt.built, request, options, timeoutMs, secrets);
111
+ const response = await callCandidate(config, attempt, attempt.built, request, options, deadlines, secrets, trace);
93
112
  notify(options.onAttemptEnd, {
94
113
  ...identity,
95
114
  outcome: "ok",
@@ -99,13 +118,14 @@ export function createFetchAi(config, options = {}) {
99
118
  costKnown: response.costKnown ?? false,
100
119
  currency: response.currency,
101
120
  text: response.text,
121
+ ...replyTrace(trace, Boolean(request.json)),
102
122
  durationMs: Date.now() - attemptStarted,
103
123
  });
104
124
  return withSpent(response, spent);
105
125
  }
106
126
  catch (error) {
107
127
  const cancelled = Boolean(request.signal?.aborted) && isAbortError(error);
108
- notify(options.onAttemptEnd, failedAttempt(identity, error, cancelled, timeoutMs, Date.now() - attemptStarted, secrets));
128
+ notify(options.onAttemptEnd, failedAttempt(identity, error, cancelled, deadlines.startMs, Date.now() - attemptStarted, secrets, replyTrace(trace, Boolean(request.json))));
109
129
  if (cancelled)
110
130
  throw error;
111
131
  if (error instanceof AiProviderError && !error.target) {
@@ -120,6 +140,8 @@ export function createFetchAi(config, options = {}) {
120
140
  const notes = [];
121
141
  if (plan.excludedByBoundary > 0)
122
142
  notes.push(`Fallbacks in other accounts were not tried because "Never send fallback content outside the primary account" (fallbackDisclosure.sameBoundaryOnly) is on.`);
143
+ for (const entry of plan.skipped)
144
+ notes.push(redactSecrets(`Skipped "${entry.candidate.model}" in "${entry.candidate.integration.name}": it is marked as without tool calls and "Tools only" is on.`, secrets));
123
145
  if (blocked.length) {
124
146
  const names = [...new Set(blocked.map((entry) => `"${entry.candidate.integration.name}"`))].join(", ");
125
147
  const from = `"${blocked[0].from.integration.name}"`;
@@ -183,7 +205,14 @@ function withSpent(response, spent) {
183
205
  ...(spent.costKnown === false ? { costKnown: false } : {}),
184
206
  };
185
207
  }
186
- function failedAttempt(identity, error, cancelled, timeoutMs, durationMs, secrets) {
208
+ function replyTrace(trace, structured) {
209
+ return {
210
+ streamed: trace.streamed,
211
+ ...(trace.firstByteMs !== undefined ? { firstByteMs: trace.firstByteMs } : {}),
212
+ ...(structured && trace.firstByteMs !== undefined ? { toolCalled: trace.toolSeen } : {}),
213
+ };
214
+ }
215
+ function failedAttempt(identity, error, cancelled, timeoutMs, durationMs, secrets, reply) {
187
216
  const provider = error instanceof AiProviderError ? error : undefined;
188
217
  const timedOut = provider?.timedOut === true;
189
218
  return {
@@ -198,7 +227,9 @@ function failedAttempt(identity, error, cancelled, timeoutMs, durationMs, secret
198
227
  failureKind: cancelled ? "cancelled" : timedOut ? "timeout" : "provider",
199
228
  ...(provider?.status !== undefined ? { status: provider.status } : {}),
200
229
  ...(provider?.retryAfterMs !== undefined ? { retryAfterMs: provider.retryAfterMs } : {}),
201
- ...(timedOut ? { timeoutMs } : {}),
230
+ ...(timedOut ? { timeoutMs: provider?.timeout?.ms ?? timeoutMs } : {}),
231
+ ...(timedOut && provider?.timeout ? { timeoutPhase: provider.timeout.phase } : {}),
232
+ ...reply,
202
233
  durationMs,
203
234
  };
204
235
  }
@@ -238,14 +269,34 @@ function parseRetryAfter(value) {
238
269
  return Number.isNaN(date) ? undefined : Math.min(MAX_RETRY_AFTER_MS, Math.max(0, date - Date.now()));
239
270
  }
240
271
  const TRANSIENT_STATUSES = new Set([408, 429, 502, 503, 504]);
241
- async function providerError(response, provider, model, redact) {
272
+ /**
273
+ * 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
274
+ * object (some providers say only `"param": "reasoning_effort"`): the OpenAI field, or the chat-template argument (`chat_template_kwargs`, `reasoning_strength`).
275
+ * Either name is a refusal of the level, whichever of the two was sent: a gateway may answer with the name of the one it translated it into, and the remedy is
276
+ * the same setting.
277
+ */
278
+ const THINKING_PARAMETER = /reasoning[\s_-]?effort|reasoning[\s_-]?strength|chat[\s_-]?template[\s_-]?kwargs/i;
279
+ /** What to change when a model refuses its level: the "Thinking parameter" of the model (to the other of the two, or to none), or the thinking of the task or of the integration. */
280
+ function thinkingRemedy(model, sent) {
281
+ const other = sent.parameter === "reasoning_effort"
282
+ ? `"chat_template_kwargs.reasoning_strength" (the level as an argument of the chat template, as Muse Glimmer takes it)`
283
+ : `"reasoning_effort" (the OpenAI field)`;
284
+ return `Set "Thinking parameter" of the model "${model}" in AI Integrations to ${other} or to "none" (no level is sent), or set thinking to "Automatic" for this task in the AI Router, or for the integration "${sent.integration}" in AI Integrations.`;
285
+ }
286
+ /** The error of a response that is not OK. `sent` says where the level went when the request carried a thinking level: a refusal of that parameter is then said in the author's words. */
287
+ async function providerError(response, provider, model, redact, sent) {
242
288
  let detail = "";
289
+ /** The parameter the provider says it refuses, when its error object names one. */
290
+ let param = "";
243
291
  try {
244
292
  const text = await response.text();
245
293
  const raw = redact(text.length > 50_000 ? text.slice(0, 50_000) : text).slice(0, 2000);
246
294
  try {
247
295
  const parsed = JSON.parse(raw);
248
296
  const message = typeof parsed.error === "string" ? parsed.error : parsed.error?.message ?? parsed.message;
297
+ const refused = typeof parsed.error === "object" && parsed.error ? parsed.error.param : parsed.param;
298
+ if (typeof refused === "string")
299
+ param = refused;
249
300
  detail = typeof message === "string" ? message : raw;
250
301
  }
251
302
  catch {
@@ -258,20 +309,37 @@ async function providerError(response, provider, model, redact) {
258
309
  const status = response.status;
259
310
  const retryable = status === 408 || status === 409 || status === 429 || status >= 500;
260
311
  const retryAfterMs = status === 429 || status === 503 ? parseRetryAfter(response.headers?.get?.("retry-after")) : undefined;
261
- return new AiProviderError(redact(`${provider} ${model}: HTTP ${status}${detail ? ` — ${detail.replace(/\s+/g, " ").slice(0, 400)}` : ""}`), status, retryable, { ...(TRANSIENT_STATUSES.has(status) ? { transient: true } : {}), ...(retryAfterMs !== undefined ? { retryAfterMs } : {}) });
312
+ const said = `HTTP ${status}${detail ? ` — ${detail.replace(/\s+/g, " ").slice(0, 400)}` : ""}`;
313
+ // A level was sent and the provider refuses the parameter: the same request would be refused again, so it is no use to repeat it.
314
+ if (sent !== undefined && (status === 400 || status === 422) && THINKING_PARAMETER.test(`${detail} ${param}`)) {
315
+ return new AiProviderError(redact(`${provider} ${model}: the model does not accept a thinking level (${said}). Nothing was applied. ${thinkingRemedy(model, sent)}`), status, false);
316
+ }
317
+ return new AiProviderError(redact(`${provider} ${model}: ${said}`), status, retryable, { ...(TRANSIENT_STATUSES.has(status) ? { transient: true } : {}), ...(retryAfterMs !== undefined ? { retryAfterMs } : {}) });
318
+ }
319
+ /** The connection failed while a stream was being read (as opposed to a deadline, the author's cancel, or what the engine itself found wrong). */
320
+ class StreamReadError extends Error {
321
+ reason;
322
+ constructor(reason) {
323
+ super("The stream could not be read.");
324
+ this.reason = reason;
325
+ this.name = "StreamReadError";
326
+ }
262
327
  }
263
328
  /**
264
329
  * Reads server-sent events; resolves `true` when the provider closed the stream with `[DONE]`. An event is its `data:`
265
330
  * lines joined with a newline, ended by a blank line; a value that is complete as it stands (one JSON object, or
266
331
  * `[DONE]`) is delivered at once, so servers that leave out the blank lines still stream.
332
+ * Every piece that arrives starts the idle deadline again, a comment (`: keep-alive`) too, and no read can hold the call past
333
+ * a deadline or the author's cancel. However it ends, but by the end of the stream, the reader is released.
267
334
  */
268
- async function readEventStream(response, onData) {
335
+ async function readEventStream(response, clock, hooks) {
269
336
  if (!response.body)
270
337
  throw new AiProviderError("The provider returned an empty stream.", undefined, true, { transient: true });
271
338
  const reader = response.body.getReader();
272
339
  const decoder = new TextDecoder();
273
340
  let buffer = "";
274
341
  let pending = [];
342
+ let exhausted = false;
275
343
  const complete = (value) => {
276
344
  const text = value.trim();
277
345
  if (text === "[DONE]")
@@ -301,12 +369,12 @@ async function readEventStream(response, onData) {
301
369
  if (single === "[DONE]")
302
370
  return true;
303
371
  if (single)
304
- onData(single);
372
+ hooks.onData(single);
305
373
  }
306
374
  return false;
307
375
  }
308
376
  if (joined)
309
- onData(joined);
377
+ hooks.onData(joined);
310
378
  return false;
311
379
  };
312
380
  const takeLine = (line) => {
@@ -320,30 +388,76 @@ async function readEventStream(response, onData) {
320
388
  };
321
389
  try {
322
390
  for (;;) {
323
- const { value, done } = await reader.read();
324
- if (done)
391
+ let piece;
392
+ try {
393
+ piece = await clock.guard(reader.read());
394
+ }
395
+ catch (error) {
396
+ // A deadline or the author's cancel is told by the call; anything else here is the connection.
397
+ throw clock.interrupted() ? error : new StreamReadError(error);
398
+ }
399
+ if (piece.done) {
400
+ exhausted = true;
325
401
  break;
326
- buffer += decoder.decode(value, { stream: true });
402
+ }
403
+ clock.activity();
404
+ hooks.onBytes(piece.value.byteLength);
405
+ buffer += decoder.decode(piece.value, { stream: true });
327
406
  let newline = buffer.indexOf("\n");
328
407
  while (newline >= 0) {
329
408
  const line = buffer.slice(0, newline);
330
409
  buffer = buffer.slice(newline + 1);
331
- if (takeLine(line)) {
332
- await reader.cancel().catch(() => undefined);
410
+ if (takeLine(line))
333
411
  return true;
334
- }
335
412
  newline = buffer.indexOf("\n");
336
413
  }
414
+ hooks.onPiece();
337
415
  }
338
416
  buffer += decoder.decode();
339
417
  if (buffer.trim() && takeLine(buffer))
340
418
  return true;
341
419
  return flush();
342
420
  }
343
- catch (error) {
344
- // The reply was given up (an error chunk, a failing listener): release the connection instead of leaving it open.
345
- await reader.cancel().catch(() => undefined);
346
- throw error;
421
+ finally {
422
+ // The provider closed the stream, or the reply is given up (the end marker, an error chunk, a deadline, the author): let the connection go.
423
+ if (!exhausted)
424
+ release(reader);
425
+ }
426
+ }
427
+ /**
428
+ * 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
429
+ * be held past a deadline or the author's cancel, and releases the body however it ends (`response.json()` would keep it locked).
430
+ */
431
+ async function readJsonBody(response, clock, onBytes) {
432
+ if (!response.body)
433
+ return clock.guard(response.json());
434
+ const reader = response.body.getReader();
435
+ const decoder = new TextDecoder();
436
+ let body = "";
437
+ let exhausted = false;
438
+ try {
439
+ for (;;) {
440
+ let piece;
441
+ try {
442
+ piece = await clock.guard(reader.read());
443
+ }
444
+ catch (error) {
445
+ throw clock.interrupted() ? error : new StreamReadError(error);
446
+ }
447
+ if (piece.done) {
448
+ exhausted = true;
449
+ break;
450
+ }
451
+ clock.activity();
452
+ onBytes(piece.value.byteLength);
453
+ body += decoder.decode(piece.value, { stream: true });
454
+ }
455
+ body += decoder.decode();
456
+ return JSON.parse(body);
457
+ }
458
+ finally {
459
+ if (!exhausted)
460
+ release(reader);
347
461
  }
348
462
  }
349
463
  const COMPLETE_REASONS = new Set(["stop", "tool_calls", "function_call", "end_turn", "stop_sequence", "tool_use", "eos"]);
@@ -396,117 +510,241 @@ function reasoningLength(source) {
396
510
  const { reasoning_content: content, reasoning } = source;
397
511
  return (typeof content === "string" ? content.length : 0) + (typeof reasoning === "string" ? reasoning.length : 0);
398
512
  }
399
- async function callCandidate(config, attempt, built, request, options, timeoutMs, secrets) {
513
+ /** The function calls of a message (`tool_calls`) whose arguments are text, in their order. */
514
+ function callsOf(value) {
515
+ if (!Array.isArray(value))
516
+ return [];
517
+ const calls = [];
518
+ for (const entry of value) {
519
+ const fn = entry && typeof entry === "object" ? entry.function : undefined;
520
+ if (!fn || typeof fn !== "object")
521
+ continue;
522
+ const { name, arguments: args } = fn;
523
+ if (typeof args === "string")
524
+ calls.push({ name: typeof name === "string" ? name : "", arguments: args });
525
+ }
526
+ return calls;
527
+ }
528
+ /**
529
+ * The arguments of the call that is the reply: the first call to the function that was asked for that carries arguments, else the first
530
+ * that carries any, else the first. The other calls are ignored, never joined to it.
531
+ */
532
+ function chosenArguments(calls, wanted) {
533
+ let first;
534
+ let firstWithArguments;
535
+ for (const call of calls) {
536
+ first ??= call.arguments;
537
+ if (!call.arguments.trim())
538
+ continue;
539
+ if (wanted && call.name === wanted)
540
+ return call.arguments;
541
+ firstWithArguments ??= call.arguments;
542
+ }
543
+ return firstWithArguments ?? first ?? "";
544
+ }
545
+ async function callCandidate(config, attempt, built, request, options, deadlines, secrets, trace) {
400
546
  const { candidate } = attempt;
401
547
  const { integration, model } = candidate;
402
548
  const label = `${integration.provider} ${model}`;
403
549
  const redact = (text) => redactSecrets(text, secrets);
404
550
  const fetchImpl = options.fetch ?? fetch;
405
- const timer = linkedSignal(request.signal, timeoutMs);
406
- try {
407
- let response;
551
+ const clock = startClock(request.signal, deadlines);
552
+ const structured = Boolean(request.json);
553
+ const wanted = request.json?.name;
554
+ const elapsed = () => Date.now() - trace.startedAt;
555
+ let text = "";
556
+ let usage;
557
+ let finishReason = "";
558
+ let reasoningCharacters = 0;
559
+ /** The function calls of a streamed reply by their index, in the order they came. */
560
+ const calls = new Map();
561
+ /** The arguments of a call that came whole: in the message of a JSON reply, or in the last piece of a stream. */
562
+ let wholeArguments = "";
563
+ /** The response ended properly: a stream that closed with `[DONE]`, or a complete JSON body. */
564
+ let ended = true;
565
+ let bytes = 0;
566
+ let events = 0;
567
+ let lastProgressAt;
568
+ let response;
569
+ /** Where the call is, to say what went wrong when something does. */
570
+ let stage = "send";
571
+ const callArguments = () => wholeArguments || chosenArguments(calls.values(), wanted);
572
+ /** What the attempt used: the provider's count, else an estimate once the model has started to answer. */
573
+ const measure = () => {
574
+ if (usage && usage.inputTokens + usage.outputTokens > 0)
575
+ return { usage, usageKnown: true };
576
+ const args = callArguments();
577
+ if (!text && !args && !reasoningCharacters)
578
+ return {};
579
+ return {
580
+ usage: { inputTokens: attempt.inputTokens, outputTokens: likelyTextTokens(text) + likelyTextTokens(args) + Math.ceil(reasoningCharacters / 4), cachedInputTokens: 0 },
581
+ usageKnown: false,
582
+ };
583
+ };
584
+ const details = (extra = {}) => {
585
+ const measured = measure();
586
+ return {
587
+ usage: measured.usage,
588
+ cost: estimateCost(measured.usage, candidate.pricing),
589
+ ...(measured.usageKnown === undefined ? {} : { usageKnown: measured.usageKnown, costKnown: measured.usageKnown && Boolean(candidate.pricing) }),
590
+ currency: config.costCurrency,
591
+ model,
592
+ provider: integration.provider,
593
+ integrationId: integration.id,
594
+ ...extra,
595
+ };
596
+ };
597
+ /** A stream that no model's answer explains: stopped, with what it used and what to do. */
598
+ 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());
599
+ const timeoutError = (expired, answering) => new AiProviderError(redact(timeoutMessage(label, expired, deadlines, integration.name)), undefined, true, {
600
+ ...(answering ? details() : {}),
601
+ transient: true,
602
+ timedOut: true,
603
+ timeout: { phase: expired.phase, ms: expired.ms, ...(expired.phase === "start" && deadlines.raisedFrom !== undefined ? { raisedFrom: deadlines.raisedFrom } : {}) },
604
+ });
605
+ const reportProgress = () => {
606
+ if (!request.onProgress)
607
+ return;
608
+ const now = Date.now();
609
+ if (lastProgressAt !== undefined && now - lastProgressAt < PROGRESS_INTERVAL_MS)
610
+ return;
611
+ lastProgressAt = now;
612
+ notify(request.onProgress, { bytes, events, characters: text.length + callArguments().length });
613
+ };
614
+ const addCalls = (value) => {
615
+ if (!Array.isArray(value))
616
+ return;
617
+ for (const entry of value) {
618
+ if (!entry || typeof entry !== "object")
619
+ continue;
620
+ const { index, function: fn } = entry;
621
+ if (!fn || typeof fn !== "object")
622
+ continue;
623
+ trace.toolSeen = true;
624
+ // A piece without an index belongs to the only call there is.
625
+ const key = typeof index === "number" && Number.isInteger(index) && index >= 0 ? index : 0;
626
+ let call = calls.get(key);
627
+ if (!call) {
628
+ call = { name: "", arguments: "" };
629
+ calls.set(key, call);
630
+ }
631
+ if (typeof fn.name === "string" && fn.name)
632
+ call.name = fn.name;
633
+ if (typeof fn.arguments === "string")
634
+ call.arguments += fn.arguments;
635
+ }
636
+ };
637
+ const take = (data) => {
638
+ let chunk;
408
639
  try {
409
- response = await fetchImpl(built.url, {
410
- method: "POST",
411
- headers: built.headers,
412
- body: JSON.stringify(built.body),
413
- signal: timer.signal,
414
- });
640
+ chunk = JSON.parse(data);
415
641
  }
416
- catch (error) {
417
- if (request.signal?.aborted)
418
- throw error;
419
- const timedOut = timer.timedOut();
420
- throw new AiProviderError(redact(`${label}: ${timedOut ? "request timed out" : error instanceof Error ? error.message : String(error)}`), undefined, true, { transient: true, ...(timedOut ? { timedOut: true } : {}) });
642
+ catch {
643
+ return;
421
644
  }
422
- if (!response.ok)
423
- throw await providerError(response, integration.provider, model, redact);
424
- let text = "";
425
- let toolArguments = "";
426
- let usage;
427
- let finishReason = "";
428
- let reasoningCharacters = 0;
429
- /** The response ended properly: a stream that closed with `[DONE]`, or a complete JSON body. */
430
- let ended = true;
431
- /** What the attempt used: the provider's count, else an estimate once the model has started to answer. */
432
- const measure = () => {
433
- if (usage && usage.inputTokens + usage.outputTokens > 0)
434
- return { usage, usageKnown: true };
435
- if (!text && !toolArguments && !reasoningCharacters)
436
- return {};
437
- return {
438
- usage: { inputTokens: attempt.inputTokens, outputTokens: likelyTextTokens(text) + likelyTextTokens(toolArguments) + Math.ceil(reasoningCharacters / 4), cachedInputTokens: 0 },
439
- usageKnown: false,
440
- };
441
- };
442
- const details = (extra = {}) => {
443
- const measured = measure();
444
- return {
445
- usage: measured.usage,
446
- cost: estimateCost(measured.usage, candidate.pricing),
447
- ...(measured.usageKnown === undefined ? {} : { usageKnown: measured.usageKnown, costKnown: measured.usageKnown && Boolean(candidate.pricing) }),
448
- currency: config.costCurrency,
449
- model,
450
- provider: integration.provider,
451
- integrationId: integration.id,
452
- ...extra,
453
- };
454
- };
645
+ if (!chunk || typeof chunk !== "object")
646
+ return;
647
+ if (chunk.error) {
648
+ const failure = streamError(chunk.error, label, details(), redact);
649
+ if (failure)
650
+ throw failure;
651
+ }
652
+ const choices = Array.isArray(chunk.choices) ? chunk.choices : [];
653
+ const first = choices[0];
654
+ const delta = first?.delta;
655
+ reasoningCharacters += reasoningLength(delta);
656
+ if (reasoningCharacters > MAX_STREAM_REASONING_CHARACTERS)
657
+ throw runaway(`the model's reasoning passed the safety limit of ${MAX_STREAM_REASONING_CHARACTERS / 1_000_000} million characters (a reasoning loop is likely)`);
658
+ if (delta?.content) {
659
+ text += delta.content;
660
+ // The text of a structured reply is no prose for the listener: its progress is `onProgress`.
661
+ if (!structured)
662
+ request.onText?.(text);
663
+ }
664
+ addCalls(delta?.tool_calls);
665
+ // Some providers end the stream with the whole message instead of (or after) the pieces.
666
+ const whole = callsOf(first?.message?.tool_calls);
667
+ if (whole.length) {
668
+ trace.toolSeen = true;
669
+ const args = chosenArguments(whole, wanted);
670
+ if (args.trim())
671
+ wholeArguments = args;
672
+ }
673
+ const reason = choices.find((choice) => typeof choice?.finish_reason === "string" && choice.finish_reason)?.finish_reason;
674
+ if (reason)
675
+ finishReason = reason;
676
+ if (chunk.usage)
677
+ usage = normalizeUsage(chunk.usage);
678
+ };
679
+ const countBytes = (count, what) => {
680
+ bytes += count;
681
+ trace.firstByteMs ??= elapsed();
682
+ if (bytes > MAX_STREAM_TRANSPORT_BYTES)
683
+ 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)`);
684
+ };
685
+ const hooks = {
686
+ onData: (data) => {
687
+ events += 1;
688
+ take(data);
689
+ },
690
+ onBytes: (count) => countBytes(count, "stream"),
691
+ onPiece: reportProgress,
692
+ };
693
+ try {
694
+ const sent = Promise.resolve(fetchImpl(built.url, {
695
+ method: "POST",
696
+ headers: built.headers,
697
+ body: JSON.stringify(built.body),
698
+ signal: clock.signal,
699
+ }));
700
+ // A reply that comes after the call was given up is dropped, and its body let go.
701
+ sent.then((late) => {
702
+ if (clock.interrupted())
703
+ discardBody(late);
704
+ }, () => undefined);
705
+ response = await clock.guard(sent);
706
+ stage = "other";
707
+ if (!response.ok) {
708
+ trace.firstByteMs ??= elapsed();
709
+ const failure = await clock.guard(providerError(response, integration.provider, model, redact, built.thinking ? { integration: integration.name, parameter: built.reasoningParameter ?? "reasoning_effort" } : undefined));
710
+ // A provider that cannot stream says so with a 400: tell where to switch streaming off.
711
+ if (built.stream && (failure.status === 400 || failure.status === 422) && /stream/i.test(failure.message.replace(label, ""))) {
712
+ failure.message = redact(`${failure.message}${/[.!?]$/.test(failure.message) ? "" : "."} If this provider cannot stream its replies, set "Streaming" of the integration "${integration.name}" to "off".`);
713
+ }
714
+ throw failure;
715
+ }
716
+ // A streamed request: the start deadline is over, the silence between two pieces is what is watched now.
717
+ if (built.stream)
718
+ clock.streaming();
455
719
  // A JSON body to a streaming request means the server ignored `stream`: its reply is read as a whole.
456
720
  const streamed = built.stream && !/\bjson\b/i.test(response.headers?.get?.("content-type") ?? "");
457
- try {
458
- if (streamed) {
459
- ended = await readEventStream(response, (data) => {
460
- let chunk;
461
- try {
462
- chunk = JSON.parse(data);
463
- }
464
- catch {
465
- return;
466
- }
467
- if (!chunk || typeof chunk !== "object")
468
- return;
469
- if (chunk.error) {
470
- const failure = streamError(chunk.error, label, details(), redact);
471
- if (failure)
472
- throw failure;
473
- }
474
- const delta = chunk.choices?.[0]?.delta;
475
- reasoningCharacters += reasoningLength(delta);
476
- if (delta?.content) {
477
- text += delta.content;
478
- request.onText?.(text);
479
- }
480
- const reason = chunk.choices?.find((choice) => typeof choice?.finish_reason === "string" && choice.finish_reason)?.finish_reason;
481
- if (reason)
482
- finishReason = reason;
483
- if (chunk.usage)
484
- usage = normalizeUsage(chunk.usage);
485
- });
486
- }
487
- else {
488
- const payload = await response.json();
489
- if (payload?.error) {
490
- const failure = streamError(payload.error, label, details(), redact);
491
- if (failure)
492
- throw failure;
493
- }
494
- const choice = payload?.choices?.[0];
495
- text = typeof choice?.message?.content === "string" ? choice.message.content : "";
496
- toolArguments = choice?.message?.tool_calls?.find((call) => typeof call.function?.arguments === "string")?.function?.arguments ?? "";
497
- finishReason = typeof choice?.finish_reason === "string" ? choice.finish_reason : "";
498
- reasoningCharacters = reasoningLength(choice?.message);
499
- usage = normalizeUsage(payload?.usage);
500
- if (built.stream && text)
501
- request.onText?.(text);
502
- }
721
+ trace.streamed = streamed;
722
+ if (streamed) {
723
+ stage = "stream";
724
+ ended = await readEventStream(response, clock, hooks);
503
725
  }
504
- catch (error) {
505
- if (request.signal?.aborted || error instanceof AiProviderError)
506
- throw error;
507
- const timedOut = timer.timedOut();
508
- throw new AiProviderError(redact(`${label}: ${timedOut ? "request timed out" : "the reply could not be read"}.`), undefined, true, details({ transient: true, ...(timedOut ? { timedOut: true } : {}) }));
726
+ else {
727
+ stage = "json";
728
+ trace.firstByteMs ??= elapsed();
729
+ const payload = await readJsonBody(response, clock, (count) => countBytes(count, "reply"));
730
+ if (payload?.error) {
731
+ const failure = streamError(payload.error, label, details(), redact);
732
+ if (failure)
733
+ throw failure;
734
+ }
735
+ const choice = payload?.choices?.[0];
736
+ text = typeof choice?.message?.content === "string" ? choice.message.content : "";
737
+ wholeArguments = choice?.message?.tool_calls?.find((call) => typeof call.function?.arguments === "string")?.function?.arguments ?? "";
738
+ if (Array.isArray(choice?.message?.tool_calls) && choice.message.tool_calls.length)
739
+ trace.toolSeen = true;
740
+ finishReason = typeof choice?.finish_reason === "string" ? choice.finish_reason : "";
741
+ reasoningCharacters = reasoningLength(choice?.message);
742
+ usage = normalizeUsage(payload?.usage);
743
+ // A plain reply that came whole still reaches the listener of the text, once.
744
+ if (!structured && text)
745
+ request.onText?.(text);
509
746
  }
747
+ stage = "other";
510
748
  const outcome = classifyFinishReason(finishReason, ended);
511
749
  const shown = redact(finishReason).replace(/\s+/g, " ").trim().slice(0, 60);
512
750
  if (outcome === "incomplete")
@@ -521,17 +759,29 @@ async function callCandidate(config, attempt, built, request, options, timeoutMs
521
759
  const inline = splitReasoningBlock(text);
522
760
  text = inline.reply;
523
761
  reasoningCharacters += inline.reasoningCharacters;
762
+ const toolArguments = callArguments();
524
763
  const answered = Boolean(text.trim() || toolArguments.trim());
525
764
  if (outcome === "truncated") {
526
- const reasoned = !answered && reasoningCharacters > 0;
527
- throw new AiProviderError(`${label}: ${reasoned ? "the model used its output limit while reasoning, before writing the reply" : "the reply was cut by the output token limit"}. Nothing was applied.`, undefined, false, details({ truncated: true, ...(reasoned ? { reasoningOnly: true, ...(candidate.maxOutputTokens && (built.outputLimit ?? 0) >= candidate.maxOutputTokens ? { limitReached: true } : {}) } : {}) }));
765
+ const seen = !answered && reasoningCharacters > 0;
766
+ // A model that is declared as reasoning and wrote nothing spent its limit on a reasoning that it does not show: the reply is cut the same way.
767
+ const declared = !answered && !seen && candidate.supportsReasoning === true;
768
+ const reasoned = seen || declared;
769
+ throw new AiProviderError(`${label}: ${seen ? "the model used its output limit while reasoning, before writing the reply" : declared ? "the model, which is declared as reasoning, used its output limit before writing the reply (its reasoning counts in the limit)" : "the reply was cut by the output token limit"}. Nothing was applied.`, undefined, false, details({ truncated: true, ...(reasoned ? { reasoningOnly: true, ...(candidate.maxOutputTokens && (built.outputLimit ?? 0) >= candidate.maxOutputTokens ? { limitReached: true } : {}) } : {}) }));
528
770
  }
529
771
  if (!answered)
530
772
  throw new AiProviderError(`${label}: ${reasoningCharacters > 0 ? "the model finished after reasoning without a reply" : "the provider returned an empty reply"}.`, undefined, true, details());
773
+ // Measured before the arguments of a function become the text of the reply: they are counted once.
774
+ const measured = measure();
531
775
  let json;
532
776
  if (request.json) {
777
+ // With "Tools only" (on unless the configuration turned it off) the answer is the call of the function: the text of the reply is never
778
+ // read, neither as the answer nor as a fallback to empty or wrong arguments. A reply with no call at all is refused and the next candidate is tried.
779
+ const toolsOnly = config.toolsOnly !== false;
780
+ if (toolsOnly && !toolArguments.trim()) {
781
+ throw new AiReplyRejectedError(redact(`${label}: the model answered in text instead of calling the function "${request.json.name}": "Tools only" is on, so the text of a reply is never read as the answer. If this model cannot call functions, turn off "Tools only" in the AI Router.`), details());
782
+ }
533
783
  try {
534
- json = structuredFromReply({ toolArguments, content: text, schema: request.json });
784
+ json = structuredFromReply({ toolArguments, content: toolsOnly ? "" : text, schema: request.json });
535
785
  }
536
786
  catch (error) {
537
787
  throw new AiReplyRejectedError(redact(`${label}: ${error instanceof Error ? error.message : "invalid structured reply"}`), details());
@@ -539,7 +789,6 @@ async function callCandidate(config, attempt, built, request, options, timeoutMs
539
789
  if (!text)
540
790
  text = toolArguments;
541
791
  }
542
- const measured = measure();
543
792
  return {
544
793
  text,
545
794
  json,
@@ -553,8 +802,28 @@ async function callCandidate(config, attempt, built, request, options, timeoutMs
553
802
  currency: config.costCurrency,
554
803
  };
555
804
  }
805
+ catch (error) {
806
+ if (response && clock.interrupted())
807
+ discardBody(response);
808
+ // The author's cancel wins over everything, and is never a timeout.
809
+ if (request.signal?.aborted)
810
+ throw request.signal.reason instanceof Error ? request.signal.reason : abortError();
811
+ const expired = clock.expired();
812
+ if (expired)
813
+ throw timeoutError(expired, stage === "stream" || stage === "json");
814
+ if (error instanceof AiProviderError)
815
+ throw error;
816
+ if (stage === "send")
817
+ throw new AiProviderError(redact(`${label}: ${error instanceof Error ? error.message : String(error)}`), undefined, true, { transient: true });
818
+ if (stage === "stream" && error instanceof StreamReadError) {
819
+ 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 }));
820
+ }
821
+ if (stage === "stream" || stage === "json")
822
+ throw new AiProviderError(redact(`${label}: the reply could not be read.`), undefined, true, details({ transient: true }));
823
+ throw error;
824
+ }
556
825
  finally {
557
- timer.dispose();
826
+ clock.dispose();
558
827
  }
559
828
  }
560
829
  //# sourceMappingURL=fetch-client.js.map