narrarium-engine 0.1.5 → 0.1.7
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.
- package/README.md +90 -12
- package/dist/ai/config.d.ts +22 -0
- package/dist/ai/config.d.ts.map +1 -1
- package/dist/ai/config.js +19 -0
- package/dist/ai/config.js.map +1 -1
- package/dist/ai/deadlines.d.ts +79 -0
- package/dist/ai/deadlines.d.ts.map +1 -0
- package/dist/ai/deadlines.js +151 -0
- package/dist/ai/deadlines.js.map +1 -0
- package/dist/ai/fetch-client.d.ts +41 -5
- package/dist/ai/fetch-client.d.ts.map +1 -1
- package/dist/ai/fetch-client.js +374 -126
- package/dist/ai/fetch-client.js.map +1 -1
- package/dist/ai/request.d.ts +8 -1
- package/dist/ai/request.d.ts.map +1 -1
- package/dist/ai/request.js +18 -1
- package/dist/ai/request.js.map +1 -1
- package/dist/ai/types.d.ts +47 -1
- package/dist/ai/types.d.ts.map +1 -1
- package/dist/ai/types.js +2 -0
- package/dist/ai/types.js.map +1 -1
- package/dist/autopilot/errors.d.ts +32 -0
- package/dist/autopilot/errors.d.ts.map +1 -0
- package/dist/autopilot/errors.js +190 -0
- package/dist/autopilot/errors.js.map +1 -0
- package/dist/autopilot/runner.d.ts +12 -3
- package/dist/autopilot/runner.d.ts.map +1 -1
- package/dist/autopilot/runner.js +60 -26
- package/dist/autopilot/runner.js.map +1 -1
- package/dist/autopilot/session.d.ts +1 -1
- package/dist/autopilot/session.d.ts.map +1 -1
- package/dist/autopilot/session.js +16 -7
- package/dist/autopilot/session.js.map +1 -1
- package/dist/autopilot/state.d.ts +35 -2
- package/dist/autopilot/state.d.ts.map +1 -1
- package/dist/autopilot/state.js +117 -4
- package/dist/autopilot/state.js.map +1 -1
- package/dist/autopilot/tasks.d.ts.map +1 -1
- package/dist/autopilot/tasks.js +11 -2
- package/dist/autopilot/tasks.js.map +1 -1
- package/dist/autopilot/types.d.ts +112 -8
- package/dist/autopilot/types.d.ts.map +1 -1
- package/dist/autopilot/types.js +1 -0
- package/dist/autopilot/types.js.map +1 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -0
- package/dist/index.js.map +1 -1
- package/dist/server/client.d.ts +9 -0
- package/dist/server/client.d.ts.map +1 -1
- package/dist/server/client.js +15 -0
- package/dist/server/client.js.map +1 -1
- package/dist/server/protocol.d.ts +19 -0
- package/dist/server/protocol.d.ts.map +1 -1
- package/dist/server/protocol.js +11 -0
- package/dist/server/protocol.js.map +1 -1
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +1 -1
package/dist/ai/fetch-client.js
CHANGED
|
@@ -1,13 +1,23 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { abortError, isAbortError } from "../util/abort.js";
|
|
2
2
|
import { randomId } from "../util/hash.js";
|
|
3
3
|
import { likelyTextTokens } from "./budget.js";
|
|
4
|
+
import { resolveDeadlines, startClock, timeoutMessage } from "./deadlines.js";
|
|
4
5
|
import { redactSecrets } from "./redact.js";
|
|
5
|
-
import { effectiveAiBase } from "./request.js";
|
|
6
|
+
import { effectiveAiBase, endpointOrigin } from "./request.js";
|
|
6
7
|
import { candidateBoundary, planAttempts } from "./routing.js";
|
|
7
8
|
import { splitReasoningBlock, structuredFromReply } from "./structured.js";
|
|
8
9
|
import { AiFallbackBlockedError, AiProviderError, AiReplyRejectedError } from "./types.js";
|
|
9
|
-
|
|
10
|
-
export
|
|
10
|
+
// 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.
|
|
11
|
+
export { DEFAULT_REQUEST_TIMEOUT_MS, MIN_REQUEST_TIMEOUT_MS, TOTAL_REQUEST_CAP_MS } from "./deadlines.js";
|
|
12
|
+
/**
|
|
13
|
+
* 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
|
|
14
|
+
* far larger than its text. A stream over this many bytes is a model that loops, and is stopped.
|
|
15
|
+
*/
|
|
16
|
+
export const MAX_STREAM_TRANSPORT_BYTES = 256_000_000;
|
|
17
|
+
/** The characters of reasoning a stream may carry before it is taken for a loop and stopped. */
|
|
18
|
+
export const MAX_STREAM_REASONING_CHARACTERS = 16_000_000;
|
|
19
|
+
/** A host's progress listener is called at most this often. */
|
|
20
|
+
const PROGRESS_INTERVAL_MS = 250;
|
|
11
21
|
const MAX_RETRY_AFTER_MS = 300_000;
|
|
12
22
|
function notify(hook, value) {
|
|
13
23
|
try {
|
|
@@ -68,9 +78,8 @@ export function createFetchAi(config, options = {}) {
|
|
|
68
78
|
continue;
|
|
69
79
|
}
|
|
70
80
|
}
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
timeoutMs = Math.max(1, Math.min(timeoutMs, Math.ceil(maxTotal - (Date.now() - startedAt))));
|
|
81
|
+
// The first candidate runs for its own deadlines whatever the total; a later one runs for the routing time that is left.
|
|
82
|
+
const deadlines = resolveDeadlines(integration, options, tried > 0 && maxTotal !== undefined ? maxTotal - (Date.now() - startedAt) : undefined);
|
|
74
83
|
const identity = { attemptId: randomId("attempt"), label: request.label, capability: request.capability, provider: integration.provider, model: candidate.model, integrationId: integration.id, index: attempt.index };
|
|
75
84
|
const sent = attempt.built?.body.messages ?? [{ role: "system", content: request.system }, { role: "user", content: request.user }];
|
|
76
85
|
notify(options.onAttempt, {
|
|
@@ -81,15 +90,18 @@ export function createFetchAi(config, options = {}) {
|
|
|
81
90
|
stream: attempt.built?.stream ?? false,
|
|
82
91
|
tools: attempt.built?.useTools ?? false,
|
|
83
92
|
endpoint: effectiveAiBase(integration, options.githubModelsBaseUrl),
|
|
84
|
-
timeoutMs,
|
|
93
|
+
timeoutMs: deadlines.startMs,
|
|
94
|
+
timeouts: { startMs: deadlines.startMs, idleMs: deadlines.idleMs, capMs: deadlines.capMs, ...(deadlines.raisedFrom !== undefined ? { raised: { from: deadlines.raisedFrom } } : {}) },
|
|
95
|
+
streamMode: integration.streamMode === "off" ? "off" : "auto",
|
|
85
96
|
});
|
|
86
97
|
const attemptStarted = Date.now();
|
|
98
|
+
const trace = { startedAt: attemptStarted, streamed: false, toolSeen: false };
|
|
87
99
|
lastSent = candidate;
|
|
88
100
|
tried += 1;
|
|
89
101
|
try {
|
|
90
102
|
if (!attempt.built)
|
|
91
103
|
throw attempt.buildError;
|
|
92
|
-
const response = await callCandidate(config, attempt, attempt.built, request, options,
|
|
104
|
+
const response = await callCandidate(config, attempt, attempt.built, request, options, deadlines, secrets, trace);
|
|
93
105
|
notify(options.onAttemptEnd, {
|
|
94
106
|
...identity,
|
|
95
107
|
outcome: "ok",
|
|
@@ -99,15 +111,20 @@ export function createFetchAi(config, options = {}) {
|
|
|
99
111
|
costKnown: response.costKnown ?? false,
|
|
100
112
|
currency: response.currency,
|
|
101
113
|
text: response.text,
|
|
114
|
+
...replyTrace(trace, Boolean(request.json)),
|
|
102
115
|
durationMs: Date.now() - attemptStarted,
|
|
103
116
|
});
|
|
104
117
|
return withSpent(response, spent);
|
|
105
118
|
}
|
|
106
119
|
catch (error) {
|
|
107
120
|
const cancelled = Boolean(request.signal?.aborted) && isAbortError(error);
|
|
108
|
-
notify(options.onAttemptEnd, failedAttempt(identity, error, cancelled,
|
|
121
|
+
notify(options.onAttemptEnd, failedAttempt(identity, error, cancelled, deadlines.startMs, Date.now() - attemptStarted, secrets, replyTrace(trace, Boolean(request.json))));
|
|
109
122
|
if (cancelled)
|
|
110
123
|
throw error;
|
|
124
|
+
if (error instanceof AiProviderError && !error.target) {
|
|
125
|
+
const origin = endpointOrigin(effectiveAiBase(integration, options.githubModelsBaseUrl));
|
|
126
|
+
error.target = { provider: integration.provider, model: candidate.model, integrationId: integration.id, ...(origin ? { endpoint: origin } : {}) };
|
|
127
|
+
}
|
|
111
128
|
addSpent(spent, error);
|
|
112
129
|
lastError = error;
|
|
113
130
|
request.onText?.("");
|
|
@@ -179,7 +196,14 @@ function withSpent(response, spent) {
|
|
|
179
196
|
...(spent.costKnown === false ? { costKnown: false } : {}),
|
|
180
197
|
};
|
|
181
198
|
}
|
|
182
|
-
function
|
|
199
|
+
function replyTrace(trace, structured) {
|
|
200
|
+
return {
|
|
201
|
+
streamed: trace.streamed,
|
|
202
|
+
...(trace.firstByteMs !== undefined ? { firstByteMs: trace.firstByteMs } : {}),
|
|
203
|
+
...(structured && trace.firstByteMs !== undefined ? { toolCalled: trace.toolSeen } : {}),
|
|
204
|
+
};
|
|
205
|
+
}
|
|
206
|
+
function failedAttempt(identity, error, cancelled, timeoutMs, durationMs, secrets, reply) {
|
|
183
207
|
const provider = error instanceof AiProviderError ? error : undefined;
|
|
184
208
|
const timedOut = provider?.timedOut === true;
|
|
185
209
|
return {
|
|
@@ -194,7 +218,9 @@ function failedAttempt(identity, error, cancelled, timeoutMs, durationMs, secret
|
|
|
194
218
|
failureKind: cancelled ? "cancelled" : timedOut ? "timeout" : "provider",
|
|
195
219
|
...(provider?.status !== undefined ? { status: provider.status } : {}),
|
|
196
220
|
...(provider?.retryAfterMs !== undefined ? { retryAfterMs: provider.retryAfterMs } : {}),
|
|
197
|
-
...(timedOut ? { timeoutMs } : {}),
|
|
221
|
+
...(timedOut ? { timeoutMs: provider?.timeout?.ms ?? timeoutMs } : {}),
|
|
222
|
+
...(timedOut && provider?.timeout ? { timeoutPhase: provider.timeout.phase } : {}),
|
|
223
|
+
...reply,
|
|
198
224
|
durationMs,
|
|
199
225
|
};
|
|
200
226
|
}
|
|
@@ -256,18 +282,48 @@ async function providerError(response, provider, model, redact) {
|
|
|
256
282
|
const retryAfterMs = status === 429 || status === 503 ? parseRetryAfter(response.headers?.get?.("retry-after")) : undefined;
|
|
257
283
|
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 } : {}) });
|
|
258
284
|
}
|
|
285
|
+
/** 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). */
|
|
286
|
+
class StreamReadError extends Error {
|
|
287
|
+
reason;
|
|
288
|
+
constructor(reason) {
|
|
289
|
+
super("The stream could not be read.");
|
|
290
|
+
this.reason = reason;
|
|
291
|
+
this.name = "StreamReadError";
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
/** Stops reading without waiting for the other side: whatever it does with the cancel, the call must not hang on it. */
|
|
295
|
+
function release(reader) {
|
|
296
|
+
try {
|
|
297
|
+
void reader.cancel().catch(() => undefined);
|
|
298
|
+
}
|
|
299
|
+
catch {
|
|
300
|
+
// A reader that cannot be cancelled is of no use any more.
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
/** Lets a body go that nobody is going to read (a reply that arrived too late, or that the call gave up). */
|
|
304
|
+
function discardBody(response) {
|
|
305
|
+
try {
|
|
306
|
+
void response.body?.cancel().catch(() => undefined);
|
|
307
|
+
}
|
|
308
|
+
catch {
|
|
309
|
+
// A body that is locked or already read has nothing left to discard.
|
|
310
|
+
}
|
|
311
|
+
}
|
|
259
312
|
/**
|
|
260
313
|
* Reads server-sent events; resolves `true` when the provider closed the stream with `[DONE]`. An event is its `data:`
|
|
261
314
|
* lines joined with a newline, ended by a blank line; a value that is complete as it stands (one JSON object, or
|
|
262
315
|
* `[DONE]`) is delivered at once, so servers that leave out the blank lines still stream.
|
|
316
|
+
* Every piece that arrives starts the idle deadline again, a comment (`: keep-alive`) too, and no read can hold the call past
|
|
317
|
+
* a deadline or the author's cancel. However it ends, but by the end of the stream, the reader is released.
|
|
263
318
|
*/
|
|
264
|
-
async function readEventStream(response,
|
|
319
|
+
async function readEventStream(response, clock, hooks) {
|
|
265
320
|
if (!response.body)
|
|
266
321
|
throw new AiProviderError("The provider returned an empty stream.", undefined, true, { transient: true });
|
|
267
322
|
const reader = response.body.getReader();
|
|
268
323
|
const decoder = new TextDecoder();
|
|
269
324
|
let buffer = "";
|
|
270
325
|
let pending = [];
|
|
326
|
+
let exhausted = false;
|
|
271
327
|
const complete = (value) => {
|
|
272
328
|
const text = value.trim();
|
|
273
329
|
if (text === "[DONE]")
|
|
@@ -297,12 +353,12 @@ async function readEventStream(response, onData) {
|
|
|
297
353
|
if (single === "[DONE]")
|
|
298
354
|
return true;
|
|
299
355
|
if (single)
|
|
300
|
-
onData(single);
|
|
356
|
+
hooks.onData(single);
|
|
301
357
|
}
|
|
302
358
|
return false;
|
|
303
359
|
}
|
|
304
360
|
if (joined)
|
|
305
|
-
onData(joined);
|
|
361
|
+
hooks.onData(joined);
|
|
306
362
|
return false;
|
|
307
363
|
};
|
|
308
364
|
const takeLine = (line) => {
|
|
@@ -316,30 +372,76 @@ async function readEventStream(response, onData) {
|
|
|
316
372
|
};
|
|
317
373
|
try {
|
|
318
374
|
for (;;) {
|
|
319
|
-
|
|
320
|
-
|
|
375
|
+
let piece;
|
|
376
|
+
try {
|
|
377
|
+
piece = await clock.guard(reader.read());
|
|
378
|
+
}
|
|
379
|
+
catch (error) {
|
|
380
|
+
// A deadline or the author's cancel is told by the call; anything else here is the connection.
|
|
381
|
+
throw clock.interrupted() ? error : new StreamReadError(error);
|
|
382
|
+
}
|
|
383
|
+
if (piece.done) {
|
|
384
|
+
exhausted = true;
|
|
321
385
|
break;
|
|
322
|
-
|
|
386
|
+
}
|
|
387
|
+
clock.activity();
|
|
388
|
+
hooks.onBytes(piece.value.byteLength);
|
|
389
|
+
buffer += decoder.decode(piece.value, { stream: true });
|
|
323
390
|
let newline = buffer.indexOf("\n");
|
|
324
391
|
while (newline >= 0) {
|
|
325
392
|
const line = buffer.slice(0, newline);
|
|
326
393
|
buffer = buffer.slice(newline + 1);
|
|
327
|
-
if (takeLine(line))
|
|
328
|
-
await reader.cancel().catch(() => undefined);
|
|
394
|
+
if (takeLine(line))
|
|
329
395
|
return true;
|
|
330
|
-
}
|
|
331
396
|
newline = buffer.indexOf("\n");
|
|
332
397
|
}
|
|
398
|
+
hooks.onPiece();
|
|
333
399
|
}
|
|
334
400
|
buffer += decoder.decode();
|
|
335
401
|
if (buffer.trim() && takeLine(buffer))
|
|
336
402
|
return true;
|
|
337
403
|
return flush();
|
|
338
404
|
}
|
|
339
|
-
|
|
340
|
-
// The reply
|
|
341
|
-
|
|
342
|
-
|
|
405
|
+
finally {
|
|
406
|
+
// 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.
|
|
407
|
+
if (!exhausted)
|
|
408
|
+
release(reader);
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
/**
|
|
412
|
+
* 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
|
|
413
|
+
* be held past a deadline or the author's cancel, and releases the body however it ends (`response.json()` would keep it locked).
|
|
414
|
+
*/
|
|
415
|
+
async function readJsonBody(response, clock, onBytes) {
|
|
416
|
+
if (!response.body)
|
|
417
|
+
return clock.guard(response.json());
|
|
418
|
+
const reader = response.body.getReader();
|
|
419
|
+
const decoder = new TextDecoder();
|
|
420
|
+
let body = "";
|
|
421
|
+
let exhausted = false;
|
|
422
|
+
try {
|
|
423
|
+
for (;;) {
|
|
424
|
+
let piece;
|
|
425
|
+
try {
|
|
426
|
+
piece = await clock.guard(reader.read());
|
|
427
|
+
}
|
|
428
|
+
catch (error) {
|
|
429
|
+
throw clock.interrupted() ? error : new StreamReadError(error);
|
|
430
|
+
}
|
|
431
|
+
if (piece.done) {
|
|
432
|
+
exhausted = true;
|
|
433
|
+
break;
|
|
434
|
+
}
|
|
435
|
+
clock.activity();
|
|
436
|
+
onBytes(piece.value.byteLength);
|
|
437
|
+
body += decoder.decode(piece.value, { stream: true });
|
|
438
|
+
}
|
|
439
|
+
body += decoder.decode();
|
|
440
|
+
return JSON.parse(body);
|
|
441
|
+
}
|
|
442
|
+
finally {
|
|
443
|
+
if (!exhausted)
|
|
444
|
+
release(reader);
|
|
343
445
|
}
|
|
344
446
|
}
|
|
345
447
|
const COMPLETE_REASONS = new Set(["stop", "tool_calls", "function_call", "end_turn", "stop_sequence", "tool_use", "eos"]);
|
|
@@ -392,117 +494,241 @@ function reasoningLength(source) {
|
|
|
392
494
|
const { reasoning_content: content, reasoning } = source;
|
|
393
495
|
return (typeof content === "string" ? content.length : 0) + (typeof reasoning === "string" ? reasoning.length : 0);
|
|
394
496
|
}
|
|
395
|
-
|
|
497
|
+
/** The function calls of a message (`tool_calls`) whose arguments are text, in their order. */
|
|
498
|
+
function callsOf(value) {
|
|
499
|
+
if (!Array.isArray(value))
|
|
500
|
+
return [];
|
|
501
|
+
const calls = [];
|
|
502
|
+
for (const entry of value) {
|
|
503
|
+
const fn = entry && typeof entry === "object" ? entry.function : undefined;
|
|
504
|
+
if (!fn || typeof fn !== "object")
|
|
505
|
+
continue;
|
|
506
|
+
const { name, arguments: args } = fn;
|
|
507
|
+
if (typeof args === "string")
|
|
508
|
+
calls.push({ name: typeof name === "string" ? name : "", arguments: args });
|
|
509
|
+
}
|
|
510
|
+
return calls;
|
|
511
|
+
}
|
|
512
|
+
/**
|
|
513
|
+
* 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
|
|
514
|
+
* that carries any, else the first. The other calls are ignored, never joined to it.
|
|
515
|
+
*/
|
|
516
|
+
function chosenArguments(calls, wanted) {
|
|
517
|
+
let first;
|
|
518
|
+
let firstWithArguments;
|
|
519
|
+
for (const call of calls) {
|
|
520
|
+
first ??= call.arguments;
|
|
521
|
+
if (!call.arguments.trim())
|
|
522
|
+
continue;
|
|
523
|
+
if (wanted && call.name === wanted)
|
|
524
|
+
return call.arguments;
|
|
525
|
+
firstWithArguments ??= call.arguments;
|
|
526
|
+
}
|
|
527
|
+
return firstWithArguments ?? first ?? "";
|
|
528
|
+
}
|
|
529
|
+
async function callCandidate(config, attempt, built, request, options, deadlines, secrets, trace) {
|
|
396
530
|
const { candidate } = attempt;
|
|
397
531
|
const { integration, model } = candidate;
|
|
398
532
|
const label = `${integration.provider} ${model}`;
|
|
399
533
|
const redact = (text) => redactSecrets(text, secrets);
|
|
400
534
|
const fetchImpl = options.fetch ?? fetch;
|
|
401
|
-
const
|
|
402
|
-
|
|
403
|
-
|
|
535
|
+
const clock = startClock(request.signal, deadlines);
|
|
536
|
+
const structured = Boolean(request.json);
|
|
537
|
+
const wanted = request.json?.name;
|
|
538
|
+
const elapsed = () => Date.now() - trace.startedAt;
|
|
539
|
+
let text = "";
|
|
540
|
+
let usage;
|
|
541
|
+
let finishReason = "";
|
|
542
|
+
let reasoningCharacters = 0;
|
|
543
|
+
/** The function calls of a streamed reply by their index, in the order they came. */
|
|
544
|
+
const calls = new Map();
|
|
545
|
+
/** The arguments of a call that came whole: in the message of a JSON reply, or in the last piece of a stream. */
|
|
546
|
+
let wholeArguments = "";
|
|
547
|
+
/** The response ended properly: a stream that closed with `[DONE]`, or a complete JSON body. */
|
|
548
|
+
let ended = true;
|
|
549
|
+
let bytes = 0;
|
|
550
|
+
let events = 0;
|
|
551
|
+
let lastProgressAt;
|
|
552
|
+
let response;
|
|
553
|
+
/** Where the call is, to say what went wrong when something does. */
|
|
554
|
+
let stage = "send";
|
|
555
|
+
const callArguments = () => wholeArguments || chosenArguments(calls.values(), wanted);
|
|
556
|
+
/** What the attempt used: the provider's count, else an estimate once the model has started to answer. */
|
|
557
|
+
const measure = () => {
|
|
558
|
+
if (usage && usage.inputTokens + usage.outputTokens > 0)
|
|
559
|
+
return { usage, usageKnown: true };
|
|
560
|
+
const args = callArguments();
|
|
561
|
+
if (!text && !args && !reasoningCharacters)
|
|
562
|
+
return {};
|
|
563
|
+
return {
|
|
564
|
+
usage: { inputTokens: attempt.inputTokens, outputTokens: likelyTextTokens(text) + likelyTextTokens(args) + Math.ceil(reasoningCharacters / 4), cachedInputTokens: 0 },
|
|
565
|
+
usageKnown: false,
|
|
566
|
+
};
|
|
567
|
+
};
|
|
568
|
+
const details = (extra = {}) => {
|
|
569
|
+
const measured = measure();
|
|
570
|
+
return {
|
|
571
|
+
usage: measured.usage,
|
|
572
|
+
cost: estimateCost(measured.usage, candidate.pricing),
|
|
573
|
+
...(measured.usageKnown === undefined ? {} : { usageKnown: measured.usageKnown, costKnown: measured.usageKnown && Boolean(candidate.pricing) }),
|
|
574
|
+
currency: config.costCurrency,
|
|
575
|
+
model,
|
|
576
|
+
provider: integration.provider,
|
|
577
|
+
integrationId: integration.id,
|
|
578
|
+
...extra,
|
|
579
|
+
};
|
|
580
|
+
};
|
|
581
|
+
/** A stream that no model's answer explains: stopped, with what it used and what to do. */
|
|
582
|
+
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());
|
|
583
|
+
const timeoutError = (expired, answering) => new AiProviderError(redact(timeoutMessage(label, expired, deadlines, integration.name)), undefined, true, {
|
|
584
|
+
...(answering ? details() : {}),
|
|
585
|
+
transient: true,
|
|
586
|
+
timedOut: true,
|
|
587
|
+
timeout: { phase: expired.phase, ms: expired.ms, ...(expired.phase === "start" && deadlines.raisedFrom !== undefined ? { raisedFrom: deadlines.raisedFrom } : {}) },
|
|
588
|
+
});
|
|
589
|
+
const reportProgress = () => {
|
|
590
|
+
if (!request.onProgress)
|
|
591
|
+
return;
|
|
592
|
+
const now = Date.now();
|
|
593
|
+
if (lastProgressAt !== undefined && now - lastProgressAt < PROGRESS_INTERVAL_MS)
|
|
594
|
+
return;
|
|
595
|
+
lastProgressAt = now;
|
|
596
|
+
notify(request.onProgress, { bytes, events, characters: text.length + callArguments().length });
|
|
597
|
+
};
|
|
598
|
+
const addCalls = (value) => {
|
|
599
|
+
if (!Array.isArray(value))
|
|
600
|
+
return;
|
|
601
|
+
for (const entry of value) {
|
|
602
|
+
if (!entry || typeof entry !== "object")
|
|
603
|
+
continue;
|
|
604
|
+
const { index, function: fn } = entry;
|
|
605
|
+
if (!fn || typeof fn !== "object")
|
|
606
|
+
continue;
|
|
607
|
+
trace.toolSeen = true;
|
|
608
|
+
// A piece without an index belongs to the only call there is.
|
|
609
|
+
const key = typeof index === "number" && Number.isInteger(index) && index >= 0 ? index : 0;
|
|
610
|
+
let call = calls.get(key);
|
|
611
|
+
if (!call) {
|
|
612
|
+
call = { name: "", arguments: "" };
|
|
613
|
+
calls.set(key, call);
|
|
614
|
+
}
|
|
615
|
+
if (typeof fn.name === "string" && fn.name)
|
|
616
|
+
call.name = fn.name;
|
|
617
|
+
if (typeof fn.arguments === "string")
|
|
618
|
+
call.arguments += fn.arguments;
|
|
619
|
+
}
|
|
620
|
+
};
|
|
621
|
+
const take = (data) => {
|
|
622
|
+
let chunk;
|
|
404
623
|
try {
|
|
405
|
-
|
|
406
|
-
method: "POST",
|
|
407
|
-
headers: built.headers,
|
|
408
|
-
body: JSON.stringify(built.body),
|
|
409
|
-
signal: timer.signal,
|
|
410
|
-
});
|
|
624
|
+
chunk = JSON.parse(data);
|
|
411
625
|
}
|
|
412
|
-
catch
|
|
413
|
-
|
|
414
|
-
throw error;
|
|
415
|
-
const timedOut = timer.timedOut();
|
|
416
|
-
throw new AiProviderError(redact(`${label}: ${timedOut ? "request timed out" : error instanceof Error ? error.message : String(error)}`), undefined, true, { transient: true, ...(timedOut ? { timedOut: true } : {}) });
|
|
626
|
+
catch {
|
|
627
|
+
return;
|
|
417
628
|
}
|
|
418
|
-
if (!
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
629
|
+
if (!chunk || typeof chunk !== "object")
|
|
630
|
+
return;
|
|
631
|
+
if (chunk.error) {
|
|
632
|
+
const failure = streamError(chunk.error, label, details(), redact);
|
|
633
|
+
if (failure)
|
|
634
|
+
throw failure;
|
|
635
|
+
}
|
|
636
|
+
const choices = Array.isArray(chunk.choices) ? chunk.choices : [];
|
|
637
|
+
const first = choices[0];
|
|
638
|
+
const delta = first?.delta;
|
|
639
|
+
reasoningCharacters += reasoningLength(delta);
|
|
640
|
+
if (reasoningCharacters > MAX_STREAM_REASONING_CHARACTERS)
|
|
641
|
+
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)`);
|
|
642
|
+
if (delta?.content) {
|
|
643
|
+
text += delta.content;
|
|
644
|
+
// The text of a structured reply is no prose for the listener: its progress is `onProgress`.
|
|
645
|
+
if (!structured)
|
|
646
|
+
request.onText?.(text);
|
|
647
|
+
}
|
|
648
|
+
addCalls(delta?.tool_calls);
|
|
649
|
+
// Some providers end the stream with the whole message instead of (or after) the pieces.
|
|
650
|
+
const whole = callsOf(first?.message?.tool_calls);
|
|
651
|
+
if (whole.length) {
|
|
652
|
+
trace.toolSeen = true;
|
|
653
|
+
const args = chosenArguments(whole, wanted);
|
|
654
|
+
if (args.trim())
|
|
655
|
+
wholeArguments = args;
|
|
656
|
+
}
|
|
657
|
+
const reason = choices.find((choice) => typeof choice?.finish_reason === "string" && choice.finish_reason)?.finish_reason;
|
|
658
|
+
if (reason)
|
|
659
|
+
finishReason = reason;
|
|
660
|
+
if (chunk.usage)
|
|
661
|
+
usage = normalizeUsage(chunk.usage);
|
|
662
|
+
};
|
|
663
|
+
const countBytes = (count, what) => {
|
|
664
|
+
bytes += count;
|
|
665
|
+
trace.firstByteMs ??= elapsed();
|
|
666
|
+
if (bytes > MAX_STREAM_TRANSPORT_BYTES)
|
|
667
|
+
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)`);
|
|
668
|
+
};
|
|
669
|
+
const hooks = {
|
|
670
|
+
onData: (data) => {
|
|
671
|
+
events += 1;
|
|
672
|
+
take(data);
|
|
673
|
+
},
|
|
674
|
+
onBytes: (count) => countBytes(count, "stream"),
|
|
675
|
+
onPiece: reportProgress,
|
|
676
|
+
};
|
|
677
|
+
try {
|
|
678
|
+
const sent = Promise.resolve(fetchImpl(built.url, {
|
|
679
|
+
method: "POST",
|
|
680
|
+
headers: built.headers,
|
|
681
|
+
body: JSON.stringify(built.body),
|
|
682
|
+
signal: clock.signal,
|
|
683
|
+
}));
|
|
684
|
+
// A reply that comes after the call was given up is dropped, and its body let go.
|
|
685
|
+
sent.then((late) => {
|
|
686
|
+
if (clock.interrupted())
|
|
687
|
+
discardBody(late);
|
|
688
|
+
}, () => undefined);
|
|
689
|
+
response = await clock.guard(sent);
|
|
690
|
+
stage = "other";
|
|
691
|
+
if (!response.ok) {
|
|
692
|
+
trace.firstByteMs ??= elapsed();
|
|
693
|
+
const failure = await clock.guard(providerError(response, integration.provider, model, redact));
|
|
694
|
+
// A provider that cannot stream says so with a 400: tell where to switch streaming off.
|
|
695
|
+
if (built.stream && (failure.status === 400 || failure.status === 422) && /stream/i.test(failure.message.replace(label, ""))) {
|
|
696
|
+
failure.message = redact(`${failure.message}${/[.!?]$/.test(failure.message) ? "" : "."} If this provider cannot stream its replies, set "Streaming" of the integration "${integration.name}" to "off".`);
|
|
697
|
+
}
|
|
698
|
+
throw failure;
|
|
699
|
+
}
|
|
700
|
+
// A streamed request: the start deadline is over, the silence between two pieces is what is watched now.
|
|
701
|
+
if (built.stream)
|
|
702
|
+
clock.streaming();
|
|
451
703
|
// A JSON body to a streaming request means the server ignored `stream`: its reply is read as a whole.
|
|
452
704
|
const streamed = built.stream && !/\bjson\b/i.test(response.headers?.get?.("content-type") ?? "");
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
try {
|
|
458
|
-
chunk = JSON.parse(data);
|
|
459
|
-
}
|
|
460
|
-
catch {
|
|
461
|
-
return;
|
|
462
|
-
}
|
|
463
|
-
if (!chunk || typeof chunk !== "object")
|
|
464
|
-
return;
|
|
465
|
-
if (chunk.error) {
|
|
466
|
-
const failure = streamError(chunk.error, label, details(), redact);
|
|
467
|
-
if (failure)
|
|
468
|
-
throw failure;
|
|
469
|
-
}
|
|
470
|
-
const delta = chunk.choices?.[0]?.delta;
|
|
471
|
-
reasoningCharacters += reasoningLength(delta);
|
|
472
|
-
if (delta?.content) {
|
|
473
|
-
text += delta.content;
|
|
474
|
-
request.onText?.(text);
|
|
475
|
-
}
|
|
476
|
-
const reason = chunk.choices?.find((choice) => typeof choice?.finish_reason === "string" && choice.finish_reason)?.finish_reason;
|
|
477
|
-
if (reason)
|
|
478
|
-
finishReason = reason;
|
|
479
|
-
if (chunk.usage)
|
|
480
|
-
usage = normalizeUsage(chunk.usage);
|
|
481
|
-
});
|
|
482
|
-
}
|
|
483
|
-
else {
|
|
484
|
-
const payload = await response.json();
|
|
485
|
-
if (payload?.error) {
|
|
486
|
-
const failure = streamError(payload.error, label, details(), redact);
|
|
487
|
-
if (failure)
|
|
488
|
-
throw failure;
|
|
489
|
-
}
|
|
490
|
-
const choice = payload?.choices?.[0];
|
|
491
|
-
text = typeof choice?.message?.content === "string" ? choice.message.content : "";
|
|
492
|
-
toolArguments = choice?.message?.tool_calls?.find((call) => typeof call.function?.arguments === "string")?.function?.arguments ?? "";
|
|
493
|
-
finishReason = typeof choice?.finish_reason === "string" ? choice.finish_reason : "";
|
|
494
|
-
reasoningCharacters = reasoningLength(choice?.message);
|
|
495
|
-
usage = normalizeUsage(payload?.usage);
|
|
496
|
-
if (built.stream && text)
|
|
497
|
-
request.onText?.(text);
|
|
498
|
-
}
|
|
705
|
+
trace.streamed = streamed;
|
|
706
|
+
if (streamed) {
|
|
707
|
+
stage = "stream";
|
|
708
|
+
ended = await readEventStream(response, clock, hooks);
|
|
499
709
|
}
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
const
|
|
504
|
-
|
|
710
|
+
else {
|
|
711
|
+
stage = "json";
|
|
712
|
+
trace.firstByteMs ??= elapsed();
|
|
713
|
+
const payload = await readJsonBody(response, clock, (count) => countBytes(count, "reply"));
|
|
714
|
+
if (payload?.error) {
|
|
715
|
+
const failure = streamError(payload.error, label, details(), redact);
|
|
716
|
+
if (failure)
|
|
717
|
+
throw failure;
|
|
718
|
+
}
|
|
719
|
+
const choice = payload?.choices?.[0];
|
|
720
|
+
text = typeof choice?.message?.content === "string" ? choice.message.content : "";
|
|
721
|
+
wholeArguments = choice?.message?.tool_calls?.find((call) => typeof call.function?.arguments === "string")?.function?.arguments ?? "";
|
|
722
|
+
if (Array.isArray(choice?.message?.tool_calls) && choice.message.tool_calls.length)
|
|
723
|
+
trace.toolSeen = true;
|
|
724
|
+
finishReason = typeof choice?.finish_reason === "string" ? choice.finish_reason : "";
|
|
725
|
+
reasoningCharacters = reasoningLength(choice?.message);
|
|
726
|
+
usage = normalizeUsage(payload?.usage);
|
|
727
|
+
// A plain reply that came whole still reaches the listener of the text, once.
|
|
728
|
+
if (!structured && text)
|
|
729
|
+
request.onText?.(text);
|
|
505
730
|
}
|
|
731
|
+
stage = "other";
|
|
506
732
|
const outcome = classifyFinishReason(finishReason, ended);
|
|
507
733
|
const shown = redact(finishReason).replace(/\s+/g, " ").trim().slice(0, 60);
|
|
508
734
|
if (outcome === "incomplete")
|
|
@@ -517,6 +743,7 @@ async function callCandidate(config, attempt, built, request, options, timeoutMs
|
|
|
517
743
|
const inline = splitReasoningBlock(text);
|
|
518
744
|
text = inline.reply;
|
|
519
745
|
reasoningCharacters += inline.reasoningCharacters;
|
|
746
|
+
const toolArguments = callArguments();
|
|
520
747
|
const answered = Boolean(text.trim() || toolArguments.trim());
|
|
521
748
|
if (outcome === "truncated") {
|
|
522
749
|
const reasoned = !answered && reasoningCharacters > 0;
|
|
@@ -524,6 +751,8 @@ async function callCandidate(config, attempt, built, request, options, timeoutMs
|
|
|
524
751
|
}
|
|
525
752
|
if (!answered)
|
|
526
753
|
throw new AiProviderError(`${label}: ${reasoningCharacters > 0 ? "the model finished after reasoning without a reply" : "the provider returned an empty reply"}.`, undefined, true, details());
|
|
754
|
+
// Measured before the arguments of a function become the text of the reply: they are counted once.
|
|
755
|
+
const measured = measure();
|
|
527
756
|
let json;
|
|
528
757
|
if (request.json) {
|
|
529
758
|
try {
|
|
@@ -535,7 +764,6 @@ async function callCandidate(config, attempt, built, request, options, timeoutMs
|
|
|
535
764
|
if (!text)
|
|
536
765
|
text = toolArguments;
|
|
537
766
|
}
|
|
538
|
-
const measured = measure();
|
|
539
767
|
return {
|
|
540
768
|
text,
|
|
541
769
|
json,
|
|
@@ -549,8 +777,28 @@ async function callCandidate(config, attempt, built, request, options, timeoutMs
|
|
|
549
777
|
currency: config.costCurrency,
|
|
550
778
|
};
|
|
551
779
|
}
|
|
780
|
+
catch (error) {
|
|
781
|
+
if (response && clock.interrupted())
|
|
782
|
+
discardBody(response);
|
|
783
|
+
// The author's cancel wins over everything, and is never a timeout.
|
|
784
|
+
if (request.signal?.aborted)
|
|
785
|
+
throw request.signal.reason instanceof Error ? request.signal.reason : abortError();
|
|
786
|
+
const expired = clock.expired();
|
|
787
|
+
if (expired)
|
|
788
|
+
throw timeoutError(expired, stage === "stream" || stage === "json");
|
|
789
|
+
if (error instanceof AiProviderError)
|
|
790
|
+
throw error;
|
|
791
|
+
if (stage === "send")
|
|
792
|
+
throw new AiProviderError(redact(`${label}: ${error instanceof Error ? error.message : String(error)}`), undefined, true, { transient: true });
|
|
793
|
+
if (stage === "stream" && error instanceof StreamReadError) {
|
|
794
|
+
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 }));
|
|
795
|
+
}
|
|
796
|
+
if (stage === "stream" || stage === "json")
|
|
797
|
+
throw new AiProviderError(redact(`${label}: the reply could not be read.`), undefined, true, details({ transient: true }));
|
|
798
|
+
throw error;
|
|
799
|
+
}
|
|
552
800
|
finally {
|
|
553
|
-
|
|
801
|
+
clock.dispose();
|
|
554
802
|
}
|
|
555
803
|
}
|
|
556
804
|
//# sourceMappingURL=fetch-client.js.map
|