narrarium-engine 0.1.17 → 0.1.21

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 (97) hide show
  1. package/README.md +44 -20
  2. package/dist/ai/config.d.ts +91 -0
  3. package/dist/ai/config.d.ts.map +1 -1
  4. package/dist/ai/config.js +150 -0
  5. package/dist/ai/config.js.map +1 -1
  6. package/dist/ai/fetch-client.d.ts +27 -3
  7. package/dist/ai/fetch-client.d.ts.map +1 -1
  8. package/dist/ai/fetch-client.js +228 -126
  9. package/dist/ai/fetch-client.js.map +1 -1
  10. package/dist/ai/memory.d.ts +34 -0
  11. package/dist/ai/memory.d.ts.map +1 -0
  12. package/dist/ai/memory.js +27 -0
  13. package/dist/ai/memory.js.map +1 -0
  14. package/dist/ai/provider-error.d.ts +50 -0
  15. package/dist/ai/provider-error.d.ts.map +1 -0
  16. package/dist/ai/provider-error.js +197 -0
  17. package/dist/ai/provider-error.js.map +1 -0
  18. package/dist/ai/redact.js +1 -1
  19. package/dist/ai/redact.js.map +1 -1
  20. package/dist/ai/request.d.ts +98 -9
  21. package/dist/ai/request.d.ts.map +1 -1
  22. package/dist/ai/request.js +153 -23
  23. package/dist/ai/request.js.map +1 -1
  24. package/dist/ai/responses.d.ts +106 -0
  25. package/dist/ai/responses.d.ts.map +1 -0
  26. package/dist/ai/responses.js +226 -0
  27. package/dist/ai/responses.js.map +1 -0
  28. package/dist/ai/router.d.ts +16 -6
  29. package/dist/ai/router.d.ts.map +1 -1
  30. package/dist/ai/router.js +41 -12
  31. package/dist/ai/router.js.map +1 -1
  32. package/dist/ai/routing.d.ts.map +1 -1
  33. package/dist/ai/routing.js +11 -5
  34. package/dist/ai/routing.js.map +1 -1
  35. package/dist/ai/types.d.ts +40 -2
  36. package/dist/ai/types.d.ts.map +1 -1
  37. package/dist/ai/types.js +16 -0
  38. package/dist/ai/types.js.map +1 -1
  39. package/dist/autopilot/attempt.d.ts +11 -0
  40. package/dist/autopilot/attempt.d.ts.map +1 -0
  41. package/dist/autopilot/attempt.js +53 -0
  42. package/dist/autopilot/attempt.js.map +1 -0
  43. package/dist/autopilot/calls/recorder.d.ts.map +1 -1
  44. package/dist/autopilot/calls/recorder.js +5 -1
  45. package/dist/autopilot/calls/recorder.js.map +1 -1
  46. package/dist/autopilot/calls/run-calls.d.ts.map +1 -1
  47. package/dist/autopilot/calls/run-calls.js +5 -0
  48. package/dist/autopilot/calls/run-calls.js.map +1 -1
  49. package/dist/autopilot/calls/types.d.ts +10 -3
  50. package/dist/autopilot/calls/types.d.ts.map +1 -1
  51. package/dist/autopilot/calls/types.js +2 -2
  52. package/dist/autopilot/calls/types.js.map +1 -1
  53. package/dist/autopilot/errors.d.ts.map +1 -1
  54. package/dist/autopilot/errors.js +42 -0
  55. package/dist/autopilot/errors.js.map +1 -1
  56. package/dist/autopilot/estimate-texts.js +4 -4
  57. package/dist/autopilot/estimate-texts.js.map +1 -1
  58. package/dist/autopilot/frozen.d.ts.map +1 -1
  59. package/dist/autopilot/frozen.js +14 -9
  60. package/dist/autopilot/frozen.js.map +1 -1
  61. package/dist/autopilot/live.d.ts +11 -1
  62. package/dist/autopilot/live.d.ts.map +1 -1
  63. package/dist/autopilot/live.js +17 -2
  64. package/dist/autopilot/live.js.map +1 -1
  65. package/dist/autopilot/outline-check.js +4 -4
  66. package/dist/autopilot/outline-check.js.map +1 -1
  67. package/dist/autopilot/planner.js +4 -4
  68. package/dist/autopilot/planner.js.map +1 -1
  69. package/dist/autopilot/runner.d.ts +5 -0
  70. package/dist/autopilot/runner.d.ts.map +1 -1
  71. package/dist/autopilot/runner.js +40 -1
  72. package/dist/autopilot/runner.js.map +1 -1
  73. package/dist/autopilot/session.d.ts +8 -0
  74. package/dist/autopilot/session.d.ts.map +1 -1
  75. package/dist/autopilot/session.js +10 -2
  76. package/dist/autopilot/session.js.map +1 -1
  77. package/dist/autopilot/tasks.js +4 -4
  78. package/dist/autopilot/tasks.js.map +1 -1
  79. package/dist/autopilot/types.d.ts +81 -6
  80. package/dist/autopilot/types.d.ts.map +1 -1
  81. package/dist/autopilot/types.js.map +1 -1
  82. package/dist/book/outline.d.ts.map +1 -1
  83. package/dist/book/outline.js +7 -6
  84. package/dist/book/outline.js.map +1 -1
  85. package/dist/book/paths.d.ts +5 -0
  86. package/dist/book/paths.d.ts.map +1 -1
  87. package/dist/book/paths.js +5 -0
  88. package/dist/book/paths.js.map +1 -1
  89. package/dist/index.d.ts +3 -0
  90. package/dist/index.d.ts.map +1 -1
  91. package/dist/index.js +3 -0
  92. package/dist/index.js.map +1 -1
  93. package/dist/server/client.js +1 -1
  94. package/dist/server/client.js.map +1 -1
  95. package/dist/version.d.ts +1 -1
  96. package/dist/version.js +1 -1
  97. package/package.json +1 -1
@@ -4,7 +4,9 @@ import { discardBody, release } from "./body.js";
4
4
  import { likelyTextTokens } from "./budget.js";
5
5
  import { resolveDeadlines, startClock, timeoutMessage } from "./deadlines.js";
6
6
  import { redactSecrets } from "./redact.js";
7
- import { effectiveAiBase, endpointOrigin } from "./request.js";
7
+ import { describeErrorBody, errorBodyOfObject, parseErrorBody, refusesThinkingWithTools, suggestsResponsesApi } from "./provider-error.js";
8
+ import { ResponsesStreamReader, responseAsChat } from "./responses.js";
9
+ import { attemptThinking, buildChatRequest, candidateDestination, candidateEndpoint, canSendNone } from "./request.js";
8
10
  import { candidateBoundary, leftOutStep, planAttempts, sortedRoute } from "./routing.js";
9
11
  import { isEmptyToolArguments, splitReasoningBlock, structuredFromReply } from "./structured.js";
10
12
  import { AiFallbackBlockedError, AiProviderError, AiReplyRejectedError, AiStreamInterruptedError, MAX_PARTIAL_CHARACTERS, TRANSPORT_TAIL_CHARACTERS } from "./types.js";
@@ -25,7 +27,7 @@ const MAX_RETRY_AFTER_MS = 300_000;
25
27
  * a word of what is sent). An attempt that could not be built reports what the request would have sent.
26
28
  */
27
29
  function reportedMessages(built, request) {
28
- const wire = built?.body.messages;
30
+ const wire = built?.messages;
29
31
  if (wire) {
30
32
  return wire.map((message) => ({
31
33
  role: message.role,
@@ -63,6 +65,9 @@ export function createFetchAi(config, options = {}) {
63
65
  async complete(request) {
64
66
  let startedAt = Date.now();
65
67
  const secrets = config.aiIntegrations.map((integration) => integration.apiKey);
68
+ // What the client's host remembers of its models applies to every call it makes, unless the call brings its own memory.
69
+ if (options.memory && !request.memory)
70
+ request = { ...request, memory: options.memory };
66
71
  const plan = planAttempts(config, request, options.githubModelsBaseUrl);
67
72
  const skipped = plan.skipped.map((entry) => ({ model: entry.candidate.model, reason: entry.reason }));
68
73
  const decisions = new Map();
@@ -75,100 +80,156 @@ export function createFetchAi(config, options = {}) {
75
80
  let outOfTime = false;
76
81
  /** What became of every candidate of the route, as far as this call has gone: what the plan left out, and each attempt as it ends. */
77
82
  const steps = [...plan.leftOut];
78
- for (const [at, attempt] of plan.attempts.entries()) {
83
+ /** The candidates asked so far: a candidate that is asked again (without a thinking level) is still one. */
84
+ let askedCandidates = 0;
85
+ for (const [at, planned] of plan.attempts.entries()) {
79
86
  request.signal?.throwIfAborted();
80
- const { candidate } = attempt;
81
- const integration = candidate.integration;
87
+ let attempt = planned;
88
+ const integration = planned.candidate.integration;
82
89
  const maxTotal = plan.limits.maxTotalDurationMs;
83
90
  // The first candidate runs for its own timeout whatever the total; the others start only while time remains.
84
- if (tried > 0 && maxTotal !== undefined && maxTotal - (Date.now() - startedAt) <= 0) {
91
+ if (askedCandidates > 0 && maxTotal !== undefined && maxTotal - (Date.now() - startedAt) <= 0) {
85
92
  outOfTime = true;
86
93
  for (const rest of plan.attempts.slice(at))
87
94
  steps.push(leftOutStep(rest.candidate, rest.index, "out-of-time", secrets, options.githubModelsBaseUrl));
88
95
  break;
89
96
  }
90
- if (config.fallbackDisclosure?.requireAcknowledgement && candidateBoundary(candidate) !== candidateBoundary(lastSent)) {
91
- const pair = `${candidateBoundary(lastSent)}>${candidateBoundary(candidate)}`;
97
+ if (config.fallbackDisclosure?.requireAcknowledgement && candidateBoundary(planned.candidate) !== candidateBoundary(lastSent)) {
98
+ const pair = `${candidateBoundary(lastSent)}>${candidateBoundary(planned.candidate)}`;
92
99
  let accepted = decisions.get(pair);
93
100
  if (accepted === undefined) {
94
101
  const asking = Date.now();
95
- accepted = options.acknowledgeFallback ? (await options.acknowledgeFallback(fallbackTarget(lastSent), fallbackTarget(candidate), { capability: request.capability, label: request.label })) === true : false;
102
+ accepted = options.acknowledgeFallback ? (await options.acknowledgeFallback(fallbackTarget(lastSent), fallbackTarget(planned.candidate), { capability: request.capability, label: request.label })) === true : false;
96
103
  // The time a person takes to decide is not the call's time.
97
104
  startedAt += Date.now() - asking;
98
105
  decisions.set(pair, accepted);
99
106
  }
100
107
  if (!accepted) {
101
- blocked.push({ candidate, from: lastSent, asked: Boolean(options.acknowledgeFallback) });
102
- steps.push(leftOutStep(candidate, attempt.index, "not-acknowledged", secrets, options.githubModelsBaseUrl));
108
+ blocked.push({ candidate: planned.candidate, from: lastSent, asked: Boolean(options.acknowledgeFallback) });
109
+ steps.push(leftOutStep(planned.candidate, planned.index, "not-acknowledged", secrets, options.githubModelsBaseUrl));
103
110
  continue;
104
111
  }
105
112
  }
106
- // The first candidate runs for its own deadlines whatever the total; a later one runs for the routing time that is left.
107
- const deadlines = resolveDeadlines(integration, options, tried > 0 && maxTotal !== undefined ? maxTotal - (Date.now() - startedAt) : undefined);
108
- const identity = { attemptId: randomId("attempt"), label: request.label, capability: request.capability, provider: integration.provider, model: candidate.model, integrationId: integration.id, index: attempt.index };
109
- const attemptReport = {
110
- ...identity,
111
- // Copies: a listener can never change what is sent.
112
- messages: reportedMessages(attempt.built, request),
113
- ...(attempt.built?.outputLimit ? { maxOutputTokens: attempt.built.outputLimit } : {}),
114
- stream: attempt.built?.stream ?? false,
115
- tools: attempt.built?.useTools ?? false,
116
- endpoint: effectiveAiBase(integration, options.githubModelsBaseUrl),
117
- timeoutMs: deadlines.startMs,
118
- timeouts: { startMs: deadlines.startMs, idleMs: deadlines.idleMs, capMs: deadlines.capMs, ...(deadlines.raisedFrom !== undefined ? { raised: { from: deadlines.raisedFrom } } : {}) },
119
- streamMode: integration.streamMode === "off" ? "off" : "auto",
120
- toolsOnly: config.toolsOnly !== false,
121
- ...(attempt.built?.thinking ? { thinking: attempt.built.thinking } : {}),
122
- ...(attempt.built?.reasoningParameter ? { reasoningParameter: attempt.built.reasoningParameter } : {}),
123
- ...(skipped.length ? { skipped: skipped.map((entry) => ({ ...entry })) } : {}),
124
- ...(steps.some((step) => step.outcome === "left-out") ? { leftOut: sortedRoute(steps.filter((step) => step.outcome === "left-out")).map((step) => ({ ...step })) } : {}),
125
- ...(attempt.built?.notes?.length ? { notes: [...attempt.built.notes] } : {}),
126
- };
127
- notify(options.onAttempt, attemptReport);
128
- notify(request.onAttempt, attemptReport);
129
- const attemptStarted = Date.now();
130
- const trace = { startedAt: attemptStarted, streamed: false, toolSeen: false };
131
- lastSent = candidate;
132
- tried += 1;
133
- try {
134
- if (!attempt.built)
135
- throw attempt.buildError;
136
- const response = await callCandidate(config, attempt, attempt.built, request, options, deadlines, secrets, trace, refusals);
137
- const endReport = {
113
+ // The first candidate runs for its own deadlines whatever the total; a later one runs for the routing time that is left (and the same candidate asked again runs for what its first request had).
114
+ const routingLeft = askedCandidates > 0 && maxTotal !== undefined ? () => maxTotal - (Date.now() - startedAt) : undefined;
115
+ /** The ways this candidate was asked without thinking, in order, because the provider refuses a level when the request carries function tools (see `nextWithoutThinking`). */
116
+ const withoutThinking = [];
117
+ /** What its requests carried of the thinking, so far: the level (`level`), none of it (`omit`) or `none`: a way is never asked twice. */
118
+ const sent = new Set();
119
+ /** What the provider said the first time it refused: what a model that then answers is learned from. */
120
+ let refusedWith;
121
+ for (;;) {
122
+ const { candidate } = attempt;
123
+ const deadlines = resolveDeadlines(integration, options, routingLeft?.());
124
+ const destination = candidateDestination(candidate, options.githubModelsBaseUrl);
125
+ const identity = { attemptId: randomId("attempt"), label: request.label, capability: request.capability, provider: integration.provider, model: candidate.model, integrationId: integration.id, index: attempt.index };
126
+ const attemptReport = {
138
127
  ...identity,
139
- outcome: "ok",
140
- usage: response.usage,
141
- usageKnown: response.usageKnown ?? false,
142
- cost: response.cost,
143
- costKnown: response.costKnown ?? false,
144
- currency: response.currency,
145
- text: response.text,
146
- ...replyTrace(trace, Boolean(request.json)),
147
- ...(trace.transport ? { transport: trace.transport } : {}),
148
- durationMs: Date.now() - attemptStarted,
128
+ integrationName: redactSecrets(integration.name, secrets),
129
+ candidates: plan.attempts.length + plan.leftOut.length,
130
+ attempt: tried + 1,
131
+ attempts: plan.attempts.length,
132
+ // Copies: a listener can never change what is sent.
133
+ messages: reportedMessages(attempt.built, request),
134
+ ...(attempt.built?.outputLimit ? { maxOutputTokens: attempt.built.outputLimit } : {}),
135
+ ...(attempt.built?.apiVersion ? { apiVersion: attempt.built.apiVersion } : {}),
136
+ ...(destination.protocol ? { protocol: destination.protocol } : {}),
137
+ stream: attempt.built?.stream ?? false,
138
+ tools: attempt.built?.useTools ?? false,
139
+ endpoint: candidateEndpoint(candidate, options.githubModelsBaseUrl),
140
+ timeoutMs: deadlines.startMs,
141
+ timeouts: { startMs: deadlines.startMs, idleMs: deadlines.idleMs, capMs: deadlines.capMs, ...(deadlines.raisedFrom !== undefined ? { raised: { from: deadlines.raisedFrom } } : {}) },
142
+ streamMode: integration.streamMode === "off" ? "off" : "auto",
143
+ toolsOnly: config.toolsOnly !== false,
144
+ ...(attempt.built?.thinking ? { thinking: attempt.built.thinking } : {}),
145
+ thinkingMode: attemptThinking(candidate, attempt.built?.useTools ?? false),
146
+ ...(attempt.built?.thinkingWhy ? { thinkingWhy: attempt.built.thinkingWhy } : {}),
147
+ ...(attempt.built?.reasoningParameter ? { reasoningParameter: attempt.built.reasoningParameter } : {}),
148
+ ...(skipped.length ? { skipped: skipped.map((entry) => ({ ...entry })) } : {}),
149
+ ...(steps.some((step) => step.outcome === "left-out") ? { leftOut: sortedRoute(steps.filter((step) => step.outcome === "left-out")).map((step) => ({ ...step })) } : {}),
150
+ ...(attempt.built?.notes?.length ? { notes: [...attempt.built.notes] } : {}),
149
151
  };
150
- notify(options.onAttemptEnd, endReport);
151
- notify(request.onAttemptEnd, endReport);
152
- return withSpent(response, spent);
153
- }
154
- catch (error) {
155
- // A host that is ending (a page that is reloaded) cancelled the request as much as the author did: its failure is not the provider's, and the prompt goes to no other candidate.
156
- const interrupted = options.interrupted?.() === true;
157
- const cancelled = (Boolean(request.signal?.aborted) && isAbortError(error)) || interrupted;
158
- const failedReport = failedAttempt(identity, error, cancelled, deadlines.startMs, Date.now() - attemptStarted, secrets, replyTrace(trace, Boolean(request.json)));
159
- notify(options.onAttemptEnd, failedReport);
160
- notify(request.onAttemptEnd, failedReport);
161
- if (cancelled)
162
- throw error;
163
- const origin = endpointOrigin(effectiveAiBase(integration, options.githubModelsBaseUrl));
164
- if (error instanceof AiProviderError && !error.target) {
165
- error.target = { provider: integration.provider, model: candidate.model, integrationId: integration.id, ...(origin ? { endpoint: origin } : {}) };
152
+ notify(options.onAttempt, attemptReport);
153
+ notify(request.onAttempt, attemptReport);
154
+ const attemptStarted = Date.now();
155
+ const trace = { startedAt: attemptStarted, streamed: false, toolSeen: false };
156
+ lastSent = candidate;
157
+ tried += 1;
158
+ if (withoutThinking.length === 0)
159
+ askedCandidates += 1;
160
+ sent.add(attempt.built?.thinking === "none" ? "none" : attempt.built?.thinking ? "level" : "omit");
161
+ try {
162
+ if (!attempt.built)
163
+ throw attempt.buildError;
164
+ const response = await callCandidate(config, attempt, attempt.built, request, options, deadlines, secrets, trace, refusals);
165
+ const endReport = {
166
+ ...identity,
167
+ outcome: "ok",
168
+ usage: response.usage,
169
+ usageKnown: response.usageKnown ?? false,
170
+ cost: response.cost,
171
+ costKnown: response.costKnown ?? false,
172
+ currency: response.currency,
173
+ text: response.text,
174
+ ...replyTrace(trace, Boolean(request.json)),
175
+ ...(trace.transport ? { transport: trace.transport } : {}),
176
+ durationMs: Date.now() - attemptStarted,
177
+ };
178
+ notify(options.onAttemptEnd, endReport);
179
+ notify(request.onAttemptEnd, endReport);
180
+ // The model answered when it was asked without thinking: that is what is learned of it, once. A model that no way answered is learned nothing of.
181
+ if (refusedWith && withoutThinking.length) {
182
+ const learning = { kind: "no-thinking-with-tools", integrationId: integration.id, integrationName: redactSecrets(integration.name, secrets), model: candidate.model, off: withoutThinking[withoutThinking.length - 1], body: refusedWith };
183
+ try {
184
+ request.memory?.learn(learning);
185
+ }
186
+ catch {
187
+ // A host's memory must never break a call.
188
+ }
189
+ notify(request.onLearned, learning);
190
+ notify(options.onLearned, learning);
191
+ }
192
+ return withSpent(response, spent);
193
+ }
194
+ catch (error) {
195
+ // A host that is ending (a page that is reloaded) cancelled the request as much as the author did: its failure is not the provider's, and the prompt goes to no other candidate.
196
+ const interrupted = options.interrupted?.() === true;
197
+ const cancelled = (Boolean(request.signal?.aborted) && isAbortError(error)) || interrupted;
198
+ const failedReport = failedAttempt(identity, error, cancelled, deadlines.startMs, Date.now() - attemptStarted, secrets, replyTrace(trace, Boolean(request.json)));
199
+ notify(options.onAttemptEnd, failedReport);
200
+ notify(request.onAttemptEnd, failedReport);
201
+ if (cancelled)
202
+ throw error;
203
+ if (error instanceof AiProviderError && !error.target) {
204
+ error.target = { provider: integration.provider, model: candidate.model, integrationId: integration.id, ...(destination.endpoint ? { endpoint: destination.endpoint } : {}), ...(attempt.built?.apiVersion ? { apiVersion: attempt.built.apiVersion } : {}), ...(destination.protocol ? { protocol: destination.protocol } : {}), ...(destination.path ? { path: redactSecrets(destination.path, secrets) } : {}) };
205
+ }
206
+ steps.push(triedStep(attempt, failedReport, error, destination, secrets));
207
+ addSpent(spent, error);
208
+ lastError = error;
209
+ notify(request.onText, "");
210
+ notify(request.onStructuredText, "");
211
+ // A provider that refuses a thinking level because the request carries function tools is asked again without it, and if that is refused too, with `none` (the GPT-6 models take no request with
212
+ // tools that leaves the level out): each way once. The model is remembered by the way that answers, so that every later request with tools is asked that way (a request without tools keeps its
213
+ // level). Every request stays in the trail as the failed attempt it was, with the provider's words.
214
+ const next = nextWithoutThinking(candidate, attempt.built, error, sent);
215
+ if (next) {
216
+ const asked = { ...candidate, noThinkingWithTools: next === "none" ? "none" : true };
217
+ try {
218
+ attempt = { ...attempt, candidate: asked, built: buildChatRequest(asked, request, { githubModelsBaseUrl: options.githubModelsBaseUrl }) };
219
+ }
220
+ catch {
221
+ break;
222
+ }
223
+ withoutThinking.push(next);
224
+ if (!refusedWith)
225
+ refusedWith = error.body;
226
+ continue;
227
+ }
228
+ // Asked every way, and refused every time: the provider's last words are the error, with what was tried, and where the provider says function tools are taken.
229
+ if (withoutThinking.length && error instanceof AiProviderError)
230
+ error.message = redactSecrets(`${error.message}${/[.!?]$/.test(error.message) ? "" : "."} ${refusedEveryWay(withoutThinking, refusedWith, integration.provider)}`, secrets);
231
+ break;
166
232
  }
167
- steps.push(triedStep(attempt, failedReport, error, origin, secrets));
168
- addSpent(spent, error);
169
- lastError = error;
170
- notify(request.onText, "");
171
- notify(request.onStructuredText, "");
172
233
  }
173
234
  }
174
235
  const notes = [];
@@ -226,7 +287,28 @@ const UNUSABLE_WORDS = {
226
287
  /** The most characters of what a provider said that a step of a route keeps. */
227
288
  const MAX_STEP_MESSAGE_CHARACTERS = 240;
228
289
  /** The step that says how an attempt ended, from the report of its end (whose words are already cleaned of credentials). */
229
- function triedStep(attempt, end, error, endpoint, secrets) {
290
+ /**
291
+ * How a candidate is asked next, when its provider refused the request because it carries function tools together with a thinking level («Function tools with reasoning_effort are not supported…»), or
292
+ * `undefined` when there is no way left: without a level first (a model of the GPT-5.6 family still reasons then), then with `none` (the GPT-6 models refuse a request with tools that leaves the level out,
293
+ * and take `none`), each way once (`sent` says which were put on the wire, the first request included), and `none` only for a model that takes its level in `reasoning_effort`. A refusal of the value of the
294
+ * level («does not support 'none' with this model») is not this: that model takes function tools on the Responses API only.
295
+ */
296
+ function nextWithoutThinking(candidate, built, error, sent) {
297
+ // The Responses API takes function tools with a thinking level: a refusal there is no refusal of this kind, and asking again without the level would be the same request.
298
+ if (!(error instanceof AiProviderError) || !built?.useTools || built.protocol === "responses" || !refusesThinkingWithTools(error.body))
299
+ return undefined;
300
+ return ["omit", "none"].find((way) => !sent.has(way) && (way !== "none" || canSendNone(candidate)));
301
+ }
302
+ /**
303
+ * What an error says after a model was asked every way without thinking and refused function tools each time: what was tried, and, when the provider says it, where the tools are taken, and what to set so that
304
+ * they are (the model's API protocol, for a provider that has the Responses API).
305
+ */
306
+ function refusedEveryWay(tried, first, provider) {
307
+ const how = tried.includes("none") ? "without a thinking level and with \"none\"" : "without a thinking level";
308
+ const responses = suggestsResponsesApi(first);
309
+ return `Narrarium asked again ${how}, and the model still refuses function tools on this endpoint${responses ? ": the provider says to use /v1/responses for them" : ""}.${responses && provider !== "github_models" ? ' Set the "API protocol" of the model to "Responses API" in AI Integrations to use them.' : ""}`;
310
+ }
311
+ function triedStep(attempt, end, error, destination, secrets) {
230
312
  const integration = attempt.candidate.integration;
231
313
  const timeout = error instanceof AiProviderError ? error.timeout : undefined;
232
314
  const message = (end.error ?? "").replace(/\s+/g, " ").trim();
@@ -237,8 +319,12 @@ function triedStep(attempt, end, error, endpoint, secrets) {
237
319
  provider: integration.provider,
238
320
  model: redactSecrets(attempt.candidate.model, secrets),
239
321
  outcome: end.outcome === "cancelled" ? "cancelled" : end.failureKind === "timeout" ? "timeout" : "failed",
240
- ...(endpoint ? { endpoint } : {}),
322
+ ...(destination.endpoint ? { endpoint: destination.endpoint } : {}),
323
+ ...(destination.path ? { path: redactSecrets(destination.path, secrets) } : {}),
324
+ ...(attempt.built?.apiVersion ? { apiVersion: attempt.built.apiVersion } : {}),
325
+ ...(destination.protocol ? { protocol: destination.protocol } : {}),
241
326
  ...(end.status !== undefined ? { status: end.status } : {}),
327
+ ...(end.errorBody ? { body: end.errorBody } : {}),
242
328
  durationMs: end.durationMs,
243
329
  ...(message ? { message: message.length > MAX_STEP_MESSAGE_CHARACTERS ? `${message.slice(0, MAX_STEP_MESSAGE_CHARACTERS - 1)}…` : message } : {}),
244
330
  ...(end.failureKind === "timeout" && end.timeoutPhase ? { timeoutPhase: end.timeoutPhase } : {}),
@@ -304,6 +390,7 @@ function failedAttempt(identity, error, cancelled, timeoutMs, durationMs, secret
304
390
  failureKind: cancelled ? "cancelled" : timedOut ? "timeout" : "provider",
305
391
  ...(provider?.status !== undefined ? { status: provider.status } : {}),
306
392
  ...(provider?.retryAfterMs !== undefined ? { retryAfterMs: provider.retryAfterMs } : {}),
393
+ ...(provider?.body ? { errorBody: provider.body } : {}),
307
394
  ...(timedOut ? { timeoutMs: provider?.timeout?.ms ?? timeoutMs } : {}),
308
395
  ...(timedOut && provider?.timeout ? { timeoutPhase: provider.timeout.phase } : {}),
309
396
  ...reply,
@@ -360,52 +447,43 @@ function parseRetryAfter(value) {
360
447
  const TRANSIENT_STATUSES = new Set([408, 429, 502, 503, 504, 520, 521, 522, 523, 524]);
361
448
  /**
362
449
  * 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
363
- * object (some providers say only `"param": "reasoning_effort"`): the OpenAI field, or the chat-template argument (`chat_template_kwargs`, `reasoning_strength`).
450
+ * object (some providers say only `"param": "reasoning_effort"`): the OpenAI field (`reasoning.effort` in the Responses API), or the chat-template argument (`chat_template_kwargs`, `reasoning_strength`).
364
451
  * 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
365
452
  * the same setting.
366
453
  */
367
- const THINKING_PARAMETER = /reasoning[\s_-]?effort|reasoning[\s_-]?strength|chat[\s_-]?template[\s_-]?kwargs/i;
368
- /** 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. */
454
+ const THINKING_PARAMETER = /reasoning[\s._-]?effort|reasoning[\s_-]?strength|chat[\s_-]?template[\s_-]?kwargs/i;
455
+ /** 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. The Responses API has one field for the level, so there is no other to offer. */
369
456
  function thinkingRemedy(model, sent) {
370
457
  const other = sent.parameter === "reasoning_effort"
371
458
  ? `"chat_template_kwargs.reasoning_strength" (the level as an argument of the chat template, as Muse Glimmer takes it)`
372
459
  : `"reasoning_effort" (the OpenAI field)`;
373
- 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.`;
460
+ const choices = sent.parameter === "reasoning.effort" ? `"none" (no level is sent)` : `${other} or to "none" (no level is sent)`;
461
+ return `Set "Thinking parameter" of the model "${model}" in AI Integrations to ${choices}, or set thinking to "Automatic" for this task in the AI Router, or for the integration "${sent.integration}" in AI Integrations.`;
374
462
  }
375
- /** 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. */
463
+ /**
464
+ * The error of a response that is not OK: what the provider answered, read as its words (`AiErrorBody`: the status, the message, the type, the parameter and the code of its error, or its text when it is no
465
+ * known shape, or only the status when it said nothing), whole, and never cut but with an ellipsis. `sent` says where the level went when the request carried a thinking level: a refusal of that parameter is
466
+ * then said in the author's words too.
467
+ */
376
468
  async function providerError(response, provider, model, redact, sent) {
377
- let detail = "";
378
- /** The parameter the provider says it refuses, when its error object names one. */
379
- let param = "";
469
+ let text = "";
380
470
  try {
381
- const text = await response.text();
382
- const raw = redact(text.length > 50_000 ? text.slice(0, 50_000) : text).slice(0, 2000);
383
- try {
384
- const parsed = JSON.parse(raw);
385
- const message = typeof parsed.error === "string" ? parsed.error : parsed.error?.message ?? parsed.message;
386
- const refused = typeof parsed.error === "object" && parsed.error ? parsed.error.param : parsed.param;
387
- if (typeof refused === "string")
388
- param = refused;
389
- detail = typeof message === "string" ? message : raw;
390
- }
391
- catch {
392
- // 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.
393
- const page = /^\s*<(?:!doctype\s+html|html)\b/i.test(raw) ? /<title[^>]*>([^<]{1,200})<\/title>/i.exec(raw)?.[1]?.replace(/\s+/g, " ").trim() : undefined;
394
- 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;
395
- }
471
+ text = await response.text();
396
472
  }
397
473
  catch {
398
- detail = response.statusText;
474
+ text = response.statusText ?? "";
399
475
  }
400
476
  const status = response.status;
477
+ const body = parseErrorBody(status, text, redact);
478
+ const said = describeErrorBody(body);
401
479
  const retryable = status === 408 || status === 409 || status === 429 || status >= 500;
402
480
  const retryAfterMs = status === 429 || status === 503 ? parseRetryAfter(response.headers?.get?.("retry-after")) : undefined;
403
- const said = `HTTP ${status}${detail ? ` — ${detail.replace(/\s+/g, " ").slice(0, 400)}` : ""}`;
404
- // 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.
405
- if (sent !== undefined && (status === 400 || status === 422) && THINKING_PARAMETER.test(`${detail} ${param}`)) {
406
- return new AiProviderError(redact(`${provider} ${model}: the model does not accept a thinking level (${said}). Nothing was applied. ${thinkingRemedy(model, sent)}`), status, false);
481
+ // 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. (A level refused only because the request carries function tools is not
482
+ // this: that request is asked again without it, and the provider's own words are all there is to say.)
483
+ if (sent !== undefined && (status === 400 || status === 422) && THINKING_PARAMETER.test(`${body.message ?? body.raw ?? ""} ${body.param ?? ""}`) && !refusesThinkingWithTools(body)) {
484
+ return new AiProviderError(redact(`${provider} ${model}: the model does not accept a thinking level (${said}). Nothing was applied. ${thinkingRemedy(model, sent)}`), status, false, { body });
407
485
  }
408
- return new AiProviderError(redact(`${provider} ${model}: ${said}`), status, retryable, { ...(TRANSIENT_STATUSES.has(status) ? { transient: true } : {}), ...(retryAfterMs !== undefined ? { retryAfterMs } : {}) });
486
+ return new AiProviderError(redact(`${provider} ${model}: ${said}`), status, retryable, { body, ...(TRANSIENT_STATUSES.has(status) ? { transient: true } : {}), ...(retryAfterMs !== undefined ? { retryAfterMs } : {}) });
409
487
  }
410
488
  /** 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). */
411
489
  class StreamReadError extends Error {
@@ -598,8 +676,8 @@ async function readJsonBody(response, clock, onChunk) {
598
676
  }
599
677
  const COMPLETE_REASONS = new Set(["stop", "tool_calls", "function_call", "end_turn", "stop_sequence", "tool_use", "eos"]);
600
678
  const TRUNCATED_REASONS = new Set(["length", "max_tokens", "max_output_tokens", "model_length", "context_length_exceeded"]);
601
- const FILTERED_REASONS = new Set(["content_filter", "safety", "blocked", "recitation", "prohibited_content"]);
602
- const FAILED_REASONS = new Set(["error", "failed", "abort", "aborted", "cancelled", "canceled"]);
679
+ const FILTERED_REASONS = new Set(["content_filter", "safety", "blocked", "recitation", "prohibited_content", "refusal"]);
680
+ const FAILED_REASONS = new Set(["error", "failed", "abort", "aborted", "cancelled", "canceled", "incomplete"]);
603
681
  /**
604
682
  * What a provider's `finish_reason` says about a reply. A known reason decides by itself. A reason this client does
605
683
  * not know is trusted only when the response also ended properly (`ended`: the `[DONE]` marker of a stream); with no
@@ -619,8 +697,8 @@ export function classifyFinishReason(reason, ended) {
619
697
  return "failed";
620
698
  return ended ? "complete" : "unexpected";
621
699
  }
622
- const PERMANENT_STREAM_ERROR = /authenticat|unauthori[sz]ed|forbidden|permission|invalid[_ -]?(?:request|api[_ -]?key|argument|parameter)|bad[_ -]?request/i;
623
- const TRANSIENT_STREAM_ERROR = /overload|rate[_ -]?limit|too many requests|temporar|unavailable|busy|try again|time[ds]? ?out|capacity/i;
700
+ const PERMANENT_STREAM_ERROR = /authenticat|unauthori[sz]ed|forbidden|permission|invalid[_ -]?(?:request|api[_ -]?key|argument|parameter)|bad[_ -]?request|user[_ -]?error/i;
701
+ const TRANSIENT_STREAM_ERROR = /overload|rate[_ -]?limit|too[_ ]many[_ ]requests|temporar|unavailable|busy|try again|time[ds]? ?out|capacity/i;
624
702
  /**
625
703
  * A failure the provider reported inside the stream (`{"error": {...}}`, `{"error": "..."}`, or an `event: error`), or `null` when the
626
704
  * 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
@@ -639,11 +717,12 @@ function streamError(value, label, details, redact, started) {
639
717
  const words = [source?.type, source?.code, source?.status].filter((entry) => typeof entry === "string").join(" ");
640
718
  const permanent = (status !== undefined && status >= 400 && status < 500 && status !== 408 && status !== 409 && status !== 429) || PERMANENT_STREAM_ERROR.test(words);
641
719
  const transient = !permanent && ((status !== undefined && TRANSIENT_STATUSES.has(status)) || TRANSIENT_STREAM_ERROR.test(`${message} ${words}`));
642
- const detail = redact(message || (source && Object.keys(source).length ? JSON.stringify(source) : "no details")).replace(/\s+/g, " ").slice(0, 400);
720
+ const body = errorBodyOfObject(value, status ?? 200, redact);
721
+ const detail = body ? describeErrorBody(body).replace(/^HTTP \d+(?:, no body| — )?/, "") || "no details" : "no details";
643
722
  const said = redact(`${label}: the provider reported an error during the reply — ${detail}`);
644
723
  if (started && !permanent)
645
- return new AiStreamInterruptedError(said, "provider-error", status, details);
646
- return new AiProviderError(said, status, !permanent, { ...details, ...(transient ? { transient: true } : {}) });
724
+ return new AiStreamInterruptedError(said, "provider-error", status, { ...details, ...(body ? { body } : {}) });
725
+ return new AiProviderError(said, status, !permanent, { ...details, ...(body ? { body } : {}), ...(transient ? { transient: true } : {}) });
647
726
  }
648
727
  /**
649
728
  * 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`
@@ -691,6 +770,8 @@ function chosenArguments(calls, wanted) {
691
770
  }
692
771
  /** 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. */
693
772
  const TAIL_WINDOW_CHARACTERS = TRANSPORT_TAIL_CHARACTERS * 3;
773
+ /** The most characters of what a model refused with that an error shows. */
774
+ const MAX_REFUSAL_CHARACTERS = 300;
694
775
  /** 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. */
695
776
  const REQUEST_ID_HEADERS = ["x-llmproxy-request-id", "x-request-id", "request-id", "x-ms-request-id", "apim-request-id"];
696
777
  /** The most addresses a set of refusals of `stream_options` keeps. */
@@ -762,6 +843,12 @@ async function callCandidate(config, attempt, built, request, options, deadlines
762
843
  let usage;
763
844
  let finishReason = "";
764
845
  let reasoningCharacters = 0;
846
+ /** The tokens the provider says the model spent reasoning, for a reasoning that is not shown (the Responses API): the characters of it that were seen are none. */
847
+ let reasoningTokens = 0;
848
+ /** What the model said when it refused to answer (the Responses API). */
849
+ let refusal = "";
850
+ /** The reply is read as the Responses API tells it: one reader per attempt, whose events become the chunks that Chat Completions has. */
851
+ const responsesReader = built.protocol === "responses" ? new ResponsesStreamReader() : undefined;
765
852
  /** The function calls of a streamed reply by their index, in the order they came. */
766
853
  const calls = new Map();
767
854
  /** The arguments of a call that came whole: in the message of a JSON reply, or in the last piece of a stream. */
@@ -779,8 +866,8 @@ async function callCandidate(config, attempt, built, request, options, deadlines
779
866
  let tailCharacters = 0;
780
867
  let status;
781
868
  let requestId;
782
- /** The request that is answered asks the provider for the tokens of the stream (`stream_options.include_usage`). */
783
- let usageRequested = Boolean(built.body.stream_options);
869
+ /** The request that is answered asks the provider for the tokens of the stream (`stream_options.include_usage`; the Responses API always ends its stream with them). */
870
+ let usageRequested = Boolean(responsesReader) || Boolean(built.body.stream_options);
784
871
  let lastProgressAt;
785
872
  let response;
786
873
  /** Where the call is, to say what went wrong when something does. */
@@ -905,7 +992,11 @@ async function callCandidate(config, attempt, built, request, options, deadlines
905
992
  else {
906
993
  if (parsed === undefined)
907
994
  return;
908
- chunk = parsed;
995
+ // The Responses API tells its events by name, and a few of them are the reply: they become the chunks that the rest of this reads.
996
+ const read = responsesReader ? responsesReader.read(parsed, event) : parsed;
997
+ if (!read)
998
+ return;
999
+ chunk = read;
909
1000
  }
910
1001
  if (!chunk || typeof chunk !== "object")
911
1002
  return;
@@ -917,7 +1008,11 @@ async function callCandidate(config, attempt, built, request, options, deadlines
917
1008
  const choices = Array.isArray(chunk.choices) ? chunk.choices : [];
918
1009
  const first = choices[0];
919
1010
  const delta = first?.delta;
920
- reasoningCharacters += reasoningLength(delta);
1011
+ reasoningCharacters += reasoningLength(delta) + (chunk.reasoningCharacters ?? 0);
1012
+ if (typeof chunk.reasoningTokens === "number")
1013
+ reasoningTokens = chunk.reasoningTokens;
1014
+ if (chunk.refusal)
1015
+ refusal = chunk.refusal;
921
1016
  if (reasoningCharacters > MAX_STREAM_REASONING_CHARACTERS)
922
1017
  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)`);
923
1018
  if (delta?.content) {
@@ -967,7 +1062,7 @@ async function callCandidate(config, attempt, built, request, options, deadlines
967
1062
  };
968
1063
  // What is sent: an address that refused `stream_options` before is not asked it again.
969
1064
  let body = built.body;
970
- if (usageRequested && refusals.has(built.url)) {
1065
+ if (usageRequested && !responsesReader && refusals.has(built.url)) {
971
1066
  body = withoutUsageOption(body);
972
1067
  usageRequested = false;
973
1068
  }
@@ -1001,10 +1096,10 @@ async function callCandidate(config, attempt, built, request, options, deadlines
1001
1096
  if (response.ok)
1002
1097
  break;
1003
1098
  trace.firstByteMs ??= elapsed();
1004
- const failure = await clock.guard(providerError(response, integration.provider, model, redact, built.thinking ? { integration: integration.name, parameter: built.reasoningParameter ?? "reasoning_effort" } : undefined));
1099
+ const failure = await clock.guard(providerError(response, integration.provider, model, redact, built.thinking && built.thinkingWhy !== "tools" ? { integration: integration.name, parameter: built.protocol === "responses" ? "reasoning.effort" : built.reasoningParameter ?? "reasoning_effort" } : undefined));
1005
1100
  failure.transport = transport();
1006
1101
  // 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.
1007
- if (usageRequested && refusesUsageOption(failure, label)) {
1102
+ if (usageRequested && !responsesReader && refusesUsageOption(failure, label)) {
1008
1103
  if (refusals.size >= MAX_REMEMBERED_REFUSALS)
1009
1104
  refusals.delete(refusals.values().next().value);
1010
1105
  refusals.add(built.url);
@@ -1036,13 +1131,15 @@ async function callCandidate(config, attempt, built, request, options, deadlines
1036
1131
  trace.streamed = streamed;
1037
1132
  if (streamed) {
1038
1133
  stage = "stream";
1039
- ended = await readEventStream(response, clock, hooks);
1134
+ // A stream of Chat Completions ends with `[DONE]`; the Responses API has no such marker: its last event (`response.completed`, `response.incomplete` or `response.failed`) is the end.
1135
+ ended = (await readEventStream(response, clock, hooks)) || Boolean(responsesReader?.finished);
1040
1136
  streamEnd = ended ? "done" : "closed";
1041
1137
  }
1042
1138
  else {
1043
1139
  stage = "json";
1044
1140
  trace.firstByteMs ??= elapsed();
1045
- const payload = await readJsonBody(response, clock, (count, decoded) => chunkArrived(count, decoded, "reply"));
1141
+ const raw = await readJsonBody(response, clock, (count, decoded) => chunkArrived(count, decoded, "reply"));
1142
+ const payload = (responsesReader ? responseAsChat(raw) : raw);
1046
1143
  if (payload?.error) {
1047
1144
  const failure = streamError(payload.error, label, details(), redact, false);
1048
1145
  if (failure)
@@ -1054,7 +1151,9 @@ async function callCandidate(config, attempt, built, request, options, deadlines
1054
1151
  if (Array.isArray(choice?.message?.tool_calls) && choice.message.tool_calls.length)
1055
1152
  trace.toolSeen = true;
1056
1153
  finishReason = typeof choice?.finish_reason === "string" ? choice.finish_reason : "";
1057
- reasoningCharacters = reasoningLength(choice?.message);
1154
+ reasoningCharacters = reasoningLength(choice?.message) + (payload?.reasoningCharacters ?? 0);
1155
+ reasoningTokens = payload?.reasoningTokens ?? 0;
1156
+ refusal = payload?.refusal ?? "";
1058
1157
  usage = normalizeUsage(payload?.usage);
1059
1158
  // A plain reply that came whole still reaches the listener of the text, once.
1060
1159
  if (!structured && text)
@@ -1080,8 +1179,11 @@ async function callCandidate(config, attempt, built, request, options, deadlines
1080
1179
  throw new AiStreamInterruptedError(`${label}: unexpected finish reason "${shown}" and the stream did not end with [DONE]: the reply may be incomplete.`, "ended", undefined, details());
1081
1180
  if (outcome === "failed")
1082
1181
  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"));
1083
- if (outcome === "filtered")
1084
- throw new AiProviderError(`${label}: the provider filtered the reply content (${shown}).`, undefined, false, details());
1182
+ if (outcome === "filtered") {
1183
+ // A model that refuses says so in words of its own (the Responses API gives them apart from the text); they are shown as they are, cut short.
1184
+ const said = redact(refusal).replace(/\s+/g, " ").trim();
1185
+ throw new AiProviderError(shown === "refusal" ? `${label}: the model refused to answer${said ? `: "${said.length > MAX_REFUSAL_CHARACTERS ? `${said.slice(0, MAX_REFUSAL_CHARACTERS)}…` : said}"` : ""}.` : `${label}: the provider filtered the reply content (${shown}).`, undefined, false, details());
1186
+ }
1085
1187
  // Some local servers leave the reasoning in the content as a leading <think> block: it is not the reply.
1086
1188
  const inline = splitReasoningBlock(text);
1087
1189
  text = inline.reply;
@@ -1089,14 +1191,14 @@ async function callCandidate(config, attempt, built, request, options, deadlines
1089
1191
  const toolArguments = callArguments();
1090
1192
  const answered = Boolean(text.trim() || toolArguments.trim());
1091
1193
  if (outcome === "truncated") {
1092
- const seen = !answered && reasoningCharacters > 0;
1194
+ const seen = !answered && (reasoningCharacters > 0 || reasoningTokens > 0);
1093
1195
  // 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.
1094
1196
  const declared = !answered && !seen && candidate.supportsReasoning === true;
1095
1197
  const reasoned = seen || declared;
1096
1198
  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 } : {}) } : {}) }));
1097
1199
  }
1098
1200
  if (!answered)
1099
- throw new AiProviderError(`${label}: ${reasoningCharacters > 0 ? "the model finished after reasoning without a reply" : "the provider returned an empty reply"}.`, undefined, true, details());
1201
+ throw new AiProviderError(`${label}: ${reasoningCharacters > 0 || reasoningTokens > 0 ? "the model finished after reasoning without a reply" : "the provider returned an empty reply"}.`, undefined, true, details());
1100
1202
  // Measured before the arguments of a function become the text of the reply: they are counted once.
1101
1203
  const measured = measure();
1102
1204
  let json;