narrarium-engine 0.1.3 → 0.1.4
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 +130 -10
- package/dist/ai/budget.d.ts +26 -0
- package/dist/ai/budget.d.ts.map +1 -0
- package/dist/ai/budget.js +35 -0
- package/dist/ai/budget.js.map +1 -0
- package/dist/ai/config.d.ts +26 -0
- package/dist/ai/config.d.ts.map +1 -1
- package/dist/ai/config.js +33 -2
- package/dist/ai/config.js.map +1 -1
- package/dist/ai/fetch-client.d.ts +80 -9
- package/dist/ai/fetch-client.d.ts.map +1 -1
- package/dist/ai/fetch-client.js +287 -114
- package/dist/ai/fetch-client.js.map +1 -1
- package/dist/ai/redact.d.ts +7 -0
- package/dist/ai/redact.d.ts.map +1 -0
- package/dist/ai/redact.js +34 -0
- package/dist/ai/redact.js.map +1 -0
- package/dist/ai/request.d.ts +34 -0
- package/dist/ai/request.d.ts.map +1 -0
- package/dist/ai/request.js +86 -0
- package/dist/ai/request.js.map +1 -0
- package/dist/ai/router.js +1 -1
- package/dist/ai/router.js.map +1 -1
- package/dist/ai/routing.d.ts +47 -0
- package/dist/ai/routing.d.ts.map +1 -0
- package/dist/ai/routing.js +83 -0
- package/dist/ai/routing.js.map +1 -0
- package/dist/ai/structured.d.ts +13 -4
- package/dist/ai/structured.d.ts.map +1 -1
- package/dist/ai/structured.js +58 -8
- package/dist/ai/structured.js.map +1 -1
- package/dist/ai/token-limit.d.ts +21 -2
- package/dist/ai/token-limit.d.ts.map +1 -1
- package/dist/ai/token-limit.js +48 -4
- package/dist/ai/token-limit.js.map +1 -1
- package/dist/ai/types.d.ts +40 -0
- package/dist/ai/types.d.ts.map +1 -1
- package/dist/ai/types.js +32 -0
- package/dist/ai/types.js.map +1 -1
- package/dist/autopilot/planner.d.ts +22 -1
- package/dist/autopilot/planner.d.ts.map +1 -1
- package/dist/autopilot/planner.js +166 -14
- package/dist/autopilot/planner.js.map +1 -1
- package/dist/autopilot/profile-check.d.ts +24 -0
- package/dist/autopilot/profile-check.d.ts.map +1 -0
- package/dist/autopilot/profile-check.js +38 -0
- package/dist/autopilot/profile-check.js.map +1 -0
- package/dist/autopilot/prompts.d.ts +1 -0
- package/dist/autopilot/prompts.d.ts.map +1 -1
- package/dist/autopilot/prompts.js +9 -0
- package/dist/autopilot/prompts.js.map +1 -1
- package/dist/autopilot/runner.d.ts +75 -8
- package/dist/autopilot/runner.d.ts.map +1 -1
- package/dist/autopilot/runner.js +425 -84
- package/dist/autopilot/runner.js.map +1 -1
- package/dist/autopilot/session.d.ts +44 -2
- package/dist/autopilot/session.d.ts.map +1 -1
- package/dist/autopilot/session.js +115 -18
- package/dist/autopilot/session.js.map +1 -1
- package/dist/autopilot/state.d.ts +11 -0
- package/dist/autopilot/state.d.ts.map +1 -1
- package/dist/autopilot/state.js +31 -0
- package/dist/autopilot/state.js.map +1 -1
- package/dist/autopilot/tasks.d.ts +2 -0
- package/dist/autopilot/tasks.d.ts.map +1 -1
- package/dist/autopilot/tasks.js +233 -59
- package/dist/autopilot/tasks.js.map +1 -1
- package/dist/autopilot/types.d.ts +20 -2
- package/dist/autopilot/types.d.ts.map +1 -1
- package/dist/book/context.d.ts +20 -3
- package/dist/book/context.d.ts.map +1 -1
- package/dist/book/context.js +120 -20
- package/dist/book/context.js.map +1 -1
- package/dist/book/store.d.ts +5 -0
- package/dist/book/store.d.ts.map +1 -1
- package/dist/book/store.js.map +1 -1
- package/dist/director/opinion.d.ts +10 -0
- package/dist/director/opinion.d.ts.map +1 -1
- package/dist/director/opinion.js +43 -13
- package/dist/director/opinion.js.map +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -1
- package/dist/markdown/frontmatter.d.ts +22 -1
- package/dist/markdown/frontmatter.d.ts.map +1 -1
- package/dist/markdown/frontmatter.js +67 -11
- package/dist/markdown/frontmatter.js.map +1 -1
- package/dist/profiles/director.d.ts +15 -0
- package/dist/profiles/director.d.ts.map +1 -1
- package/dist/profiles/director.js +98 -37
- package/dist/profiles/director.js.map +1 -1
- package/dist/profiles/ghostwriter.d.ts +7 -0
- package/dist/profiles/ghostwriter.d.ts.map +1 -1
- package/dist/profiles/ghostwriter.js +54 -16
- package/dist/profiles/ghostwriter.js.map +1 -1
- package/dist/profiles/read.d.ts +33 -0
- package/dist/profiles/read.d.ts.map +1 -0
- package/dist/profiles/read.js +96 -0
- package/dist/profiles/read.js.map +1 -0
- package/dist/profiles/readers.d.ts +8 -0
- package/dist/profiles/readers.d.ts.map +1 -1
- package/dist/profiles/readers.js +82 -12
- package/dist/profiles/readers.js.map +1 -1
- package/dist/prompt/trust.d.ts +11 -0
- package/dist/prompt/trust.d.ts.map +1 -1
- package/dist/prompt/trust.js +26 -0
- package/dist/prompt/trust.js.map +1 -1
- package/dist/readers/evaluation.d.ts.map +1 -1
- package/dist/readers/evaluation.js +3 -2
- package/dist/readers/evaluation.js.map +1 -1
- package/dist/server/client.d.ts +38 -4
- package/dist/server/client.d.ts.map +1 -1
- package/dist/server/client.js +43 -9
- package/dist/server/client.js.map +1 -1
- package/dist/server/protocol.d.ts +25 -0
- package/dist/server/protocol.d.ts.map +1 -1
- package/dist/server/protocol.js +23 -2
- package/dist/server/protocol.js.map +1 -1
- package/dist/sync/files.d.ts +21 -1
- package/dist/sync/files.d.ts.map +1 -1
- package/dist/sync/files.js +84 -15
- package/dist/sync/files.js.map +1 -1
- package/dist/testing/index.d.ts.map +1 -1
- package/dist/testing/index.js +2 -0
- package/dist/testing/index.js.map +1 -1
- package/dist/util/text.d.ts +28 -0
- package/dist/util/text.d.ts.map +1 -1
- package/dist/util/text.js +80 -1
- package/dist/util/text.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,46 +1,146 @@
|
|
|
1
1
|
import { isAbortError, linkedSignal } from "../util/abort.js";
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
2
|
+
import { randomId } from "../util/hash.js";
|
|
3
|
+
import { likelyTextTokens } from "./budget.js";
|
|
4
|
+
import { redactSecrets } from "./redact.js";
|
|
5
|
+
import { effectiveAiBase } from "./request.js";
|
|
6
|
+
import { candidateBoundary, planAttempts } from "./routing.js";
|
|
7
|
+
import { splitReasoningBlock, structuredFromReply } from "./structured.js";
|
|
8
|
+
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
|
+
const MAX_RETRY_AFTER_MS = 300_000;
|
|
12
|
+
function notify(hook, value) {
|
|
13
|
+
try {
|
|
14
|
+
hook?.(value);
|
|
15
|
+
}
|
|
16
|
+
catch {
|
|
17
|
+
// A host's listener must never break a call.
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
function fallbackTarget(candidate) {
|
|
21
|
+
return { integrationId: candidate.integration.id, integrationName: candidate.integration.name, provider: candidate.integration.provider, model: candidate.model, boundary: candidateBoundary(candidate) };
|
|
22
|
+
}
|
|
10
23
|
/**
|
|
11
24
|
* OpenAI-compatible chat client built on `fetch`, usable from Node and browsers.
|
|
12
25
|
* Supports OpenAI and compatible endpoints, Azure OpenAI and GitHub Models, streaming text,
|
|
13
26
|
* forced function calls for structured output, and ordered fallbacks between candidates.
|
|
27
|
+
* It is the one client of every host, so the same book and configuration produce the same requests and the same
|
|
28
|
+
* outcomes: requests come from `buildChatRequest`, the routing limits and the privacy policy of the configuration are
|
|
29
|
+
* applied here, and a prompt is never cut to fit a window.
|
|
14
30
|
* What failed attempts cost is added to the final response (or error), so budgets never under-count.
|
|
15
31
|
*/
|
|
16
32
|
export function createFetchAi(config, options = {}) {
|
|
17
33
|
return {
|
|
18
34
|
async complete(request) {
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
35
|
+
let startedAt = Date.now();
|
|
36
|
+
const secrets = config.aiIntegrations.map((integration) => integration.apiKey);
|
|
37
|
+
const plan = planAttempts(config, request, options.githubModelsBaseUrl);
|
|
38
|
+
const decisions = new Map();
|
|
39
|
+
const blocked = [];
|
|
23
40
|
const spent = {};
|
|
24
|
-
|
|
41
|
+
let lastError = null;
|
|
42
|
+
/** The candidate content went to last: the primary until something is sent. */
|
|
43
|
+
let lastSent = plan.primary;
|
|
44
|
+
let tried = 0;
|
|
45
|
+
let outOfTime = false;
|
|
46
|
+
for (const attempt of plan.attempts) {
|
|
25
47
|
request.signal?.throwIfAborted();
|
|
26
|
-
|
|
48
|
+
const { candidate } = attempt;
|
|
49
|
+
const integration = candidate.integration;
|
|
50
|
+
const maxTotal = plan.limits.maxTotalDurationMs;
|
|
51
|
+
// The first candidate runs for its own timeout whatever the total; the others start only while time remains.
|
|
52
|
+
if (tried > 0 && maxTotal !== undefined && maxTotal - (Date.now() - startedAt) <= 0) {
|
|
53
|
+
outOfTime = true;
|
|
54
|
+
break;
|
|
55
|
+
}
|
|
56
|
+
if (config.fallbackDisclosure?.requireAcknowledgement && candidateBoundary(candidate) !== candidateBoundary(lastSent)) {
|
|
57
|
+
const pair = `${candidateBoundary(lastSent)}>${candidateBoundary(candidate)}`;
|
|
58
|
+
let accepted = decisions.get(pair);
|
|
59
|
+
if (accepted === undefined) {
|
|
60
|
+
const asking = Date.now();
|
|
61
|
+
accepted = options.acknowledgeFallback ? (await options.acknowledgeFallback(fallbackTarget(lastSent), fallbackTarget(candidate), { capability: request.capability, label: request.label })) === true : false;
|
|
62
|
+
// The time a person takes to decide is not the call's time.
|
|
63
|
+
startedAt += Date.now() - asking;
|
|
64
|
+
decisions.set(pair, accepted);
|
|
65
|
+
}
|
|
66
|
+
if (!accepted) {
|
|
67
|
+
blocked.push({ candidate, from: lastSent, asked: Boolean(options.acknowledgeFallback) });
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
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))));
|
|
74
|
+
const identity = { attemptId: randomId("attempt"), label: request.label, capability: request.capability, provider: integration.provider, model: candidate.model, integrationId: integration.id, index: attempt.index };
|
|
75
|
+
const sent = attempt.built?.body.messages ?? [{ role: "system", content: request.system }, { role: "user", content: request.user }];
|
|
76
|
+
notify(options.onAttempt, {
|
|
77
|
+
...identity,
|
|
78
|
+
// Copies: a listener can never change what is sent.
|
|
79
|
+
messages: sent.map((message) => ({ role: message.role, content: message.content })),
|
|
80
|
+
...(attempt.built?.outputLimit ? { maxOutputTokens: attempt.built.outputLimit } : {}),
|
|
81
|
+
stream: attempt.built?.stream ?? false,
|
|
82
|
+
tools: attempt.built?.useTools ?? false,
|
|
83
|
+
endpoint: effectiveAiBase(integration, options.githubModelsBaseUrl),
|
|
84
|
+
timeoutMs,
|
|
85
|
+
});
|
|
86
|
+
const attemptStarted = Date.now();
|
|
87
|
+
lastSent = candidate;
|
|
88
|
+
tried += 1;
|
|
27
89
|
try {
|
|
28
|
-
|
|
90
|
+
if (!attempt.built)
|
|
91
|
+
throw attempt.buildError;
|
|
92
|
+
const response = await callCandidate(config, attempt, attempt.built, request, options, timeoutMs, secrets);
|
|
93
|
+
notify(options.onAttemptEnd, {
|
|
94
|
+
...identity,
|
|
95
|
+
outcome: "ok",
|
|
96
|
+
usage: response.usage,
|
|
97
|
+
usageKnown: response.usageKnown ?? false,
|
|
98
|
+
cost: response.cost,
|
|
99
|
+
costKnown: response.costKnown ?? false,
|
|
100
|
+
currency: response.currency,
|
|
101
|
+
text: response.text,
|
|
102
|
+
durationMs: Date.now() - attemptStarted,
|
|
103
|
+
});
|
|
104
|
+
return withSpent(response, spent);
|
|
29
105
|
}
|
|
30
106
|
catch (error) {
|
|
31
|
-
|
|
107
|
+
const cancelled = Boolean(request.signal?.aborted) && isAbortError(error);
|
|
108
|
+
notify(options.onAttemptEnd, failedAttempt(identity, error, cancelled, timeoutMs, Date.now() - attemptStarted, secrets));
|
|
109
|
+
if (cancelled)
|
|
32
110
|
throw error;
|
|
33
111
|
addSpent(spent, error);
|
|
34
112
|
lastError = error;
|
|
35
113
|
request.onText?.("");
|
|
36
114
|
}
|
|
37
115
|
}
|
|
116
|
+
const notes = [];
|
|
117
|
+
if (plan.excludedByBoundary > 0)
|
|
118
|
+
notes.push(`Fallbacks in other accounts were not tried because "Never send fallback content outside the primary account" (fallbackDisclosure.sameBoundaryOnly) is on.`);
|
|
119
|
+
if (blocked.length) {
|
|
120
|
+
const names = [...new Set(blocked.map((entry) => `"${entry.candidate.integration.name}"`))].join(", ");
|
|
121
|
+
const from = `"${blocked[0].from.integration.name}"`;
|
|
122
|
+
notes.push(blocked[0].asked
|
|
123
|
+
? `The fallback ${names} was not used: sending content from ${from} to another account was not acknowledged (fallbackDisclosure.requireAcknowledgement).`
|
|
124
|
+
: `The fallback ${names} was not used: it is in another account than ${from}, "Ask before sending content to another account" (fallbackDisclosure.requireAcknowledgement) is on and this host cannot ask. To change it, open the AI settings and turn it off, or add a fallback in the same account as the primary.`);
|
|
125
|
+
}
|
|
126
|
+
if (outOfTime)
|
|
127
|
+
notes.push(`Fallbacks were not tried: the total routing time (maxTotalDurationMs, ${Math.round((plan.limits.maxTotalDurationMs ?? 0) / 1000)} s) was used up.`);
|
|
38
128
|
if (lastError instanceof AiProviderError) {
|
|
39
129
|
lastError.usage = spent.usage ?? lastError.usage;
|
|
40
130
|
lastError.cost = spent.cost ?? lastError.cost;
|
|
131
|
+
if (spent.usageKnown === false)
|
|
132
|
+
lastError.usageKnown = false;
|
|
133
|
+
if (spent.costKnown === false)
|
|
134
|
+
lastError.costKnown = false;
|
|
135
|
+
if (spent.retryAfterMs !== undefined)
|
|
136
|
+
lastError.retryAfterMs = Math.max(lastError.retryAfterMs ?? 0, spent.retryAfterMs);
|
|
137
|
+
if (notes.length)
|
|
138
|
+
lastError.message = `${lastError.message}${/[.!?]$/.test(lastError.message) ? "" : "."} ${notes.join(" ")}`;
|
|
41
139
|
throw lastError;
|
|
42
140
|
}
|
|
43
|
-
|
|
141
|
+
if (lastError instanceof Error)
|
|
142
|
+
throw lastError;
|
|
143
|
+
throw notes.length ? new AiFallbackBlockedError(notes.join(" ")) : new AiProviderError("All AI candidates failed.");
|
|
44
144
|
},
|
|
45
145
|
};
|
|
46
146
|
}
|
|
@@ -61,38 +161,42 @@ function addSpent(spent, error) {
|
|
|
61
161
|
spent.usage = sumUsage(spent.usage, error.usage);
|
|
62
162
|
if (error.cost !== undefined)
|
|
63
163
|
spent.cost = (spent.cost ?? 0) + error.cost;
|
|
164
|
+
if (error.usageKnown === false)
|
|
165
|
+
spent.usageKnown = false;
|
|
166
|
+
if (error.costKnown === false)
|
|
167
|
+
spent.costKnown = false;
|
|
168
|
+
if (error.retryAfterMs !== undefined)
|
|
169
|
+
spent.retryAfterMs = Math.max(spent.retryAfterMs ?? 0, error.retryAfterMs);
|
|
64
170
|
}
|
|
65
171
|
function withSpent(response, spent) {
|
|
66
|
-
if (!spent.usage && spent.cost === undefined)
|
|
172
|
+
if (!spent.usage && spent.cost === undefined && spent.usageKnown === undefined && spent.costKnown === undefined)
|
|
67
173
|
return response;
|
|
68
174
|
return {
|
|
69
175
|
...response,
|
|
70
176
|
usage: sumUsage(response.usage, spent.usage),
|
|
71
177
|
cost: spent.cost === undefined ? response.cost : (response.cost ?? 0) + spent.cost,
|
|
178
|
+
...(spent.usageKnown === false ? { usageKnown: false } : {}),
|
|
179
|
+
...(spent.costKnown === false ? { costKnown: false } : {}),
|
|
72
180
|
};
|
|
73
181
|
}
|
|
74
|
-
function
|
|
75
|
-
const
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
}
|
|
92
|
-
throw new AiProviderError(`Provider ${integration.provider} cannot run chat tasks outside Microsoft 365.`);
|
|
93
|
-
}
|
|
94
|
-
function jsonInstruction(schema) {
|
|
95
|
-
return `Reply with ONLY one JSON object, without code fences or commentary, matching this JSON schema (${schema.name}: ${schema.description}):\n${JSON.stringify(schema.parameters)}`;
|
|
182
|
+
function failedAttempt(identity, error, cancelled, timeoutMs, durationMs, secrets) {
|
|
183
|
+
const provider = error instanceof AiProviderError ? error : undefined;
|
|
184
|
+
const timedOut = provider?.timedOut === true;
|
|
185
|
+
return {
|
|
186
|
+
...identity,
|
|
187
|
+
outcome: cancelled ? "cancelled" : "failed",
|
|
188
|
+
usage: provider?.usage,
|
|
189
|
+
usageKnown: provider?.usageKnown ?? false,
|
|
190
|
+
cost: provider?.cost,
|
|
191
|
+
costKnown: provider?.costKnown ?? false,
|
|
192
|
+
currency: provider?.currency,
|
|
193
|
+
error: redactSecrets(error instanceof Error ? error.message : String(error), secrets),
|
|
194
|
+
failureKind: cancelled ? "cancelled" : timedOut ? "timeout" : "provider",
|
|
195
|
+
...(provider?.status !== undefined ? { status: provider.status } : {}),
|
|
196
|
+
...(provider?.retryAfterMs !== undefined ? { retryAfterMs: provider.retryAfterMs } : {}),
|
|
197
|
+
...(timedOut ? { timeoutMs } : {}),
|
|
198
|
+
durationMs,
|
|
199
|
+
};
|
|
96
200
|
}
|
|
97
201
|
function normalizeUsage(value) {
|
|
98
202
|
if (!value || typeof value !== "object")
|
|
@@ -104,19 +208,37 @@ function normalizeUsage(value) {
|
|
|
104
208
|
cachedInputTokens: usage.prompt_tokens_details?.cached_tokens ?? 0,
|
|
105
209
|
};
|
|
106
210
|
}
|
|
107
|
-
/**
|
|
211
|
+
/**
|
|
212
|
+
* Same formula as the web app's cost tracker: prices are per million tokens. Tokens served from the cache cost like
|
|
213
|
+
* normal input unless the model has its own cached price.
|
|
214
|
+
*/
|
|
108
215
|
export function estimateCost(usage, pricing) {
|
|
109
216
|
if (!usage || !pricing)
|
|
110
217
|
return undefined;
|
|
111
218
|
const billedInput = Math.max(0, usage.inputTokens - usage.cachedInputTokens);
|
|
219
|
+
const cachedRate = pricing.cachedPerMTok ?? pricing.inputPerMTok ?? 0;
|
|
112
220
|
return (billedInput / 1_000_000) * (pricing.inputPerMTok ?? 0)
|
|
113
|
-
+ (usage.cachedInputTokens / 1_000_000) *
|
|
221
|
+
+ (usage.cachedInputTokens / 1_000_000) * cachedRate
|
|
114
222
|
+ (usage.outputTokens / 1_000_000) * (pricing.outputPerMTok ?? 0);
|
|
115
223
|
}
|
|
116
|
-
|
|
224
|
+
/** `Retry-After` as milliseconds: whole or fractional seconds, or an HTTP date; never more than five minutes. */
|
|
225
|
+
function parseRetryAfter(value) {
|
|
226
|
+
const text = (value ?? "").trim();
|
|
227
|
+
if (!text)
|
|
228
|
+
return undefined;
|
|
229
|
+
if (/^\d+(?:\.\d+)?$/.test(text))
|
|
230
|
+
return Math.min(MAX_RETRY_AFTER_MS, Math.round(Number(text) * 1000));
|
|
231
|
+
if (!/[A-Za-z]{3}/.test(text) || !/\d/.test(text))
|
|
232
|
+
return undefined;
|
|
233
|
+
const date = Date.parse(text);
|
|
234
|
+
return Number.isNaN(date) ? undefined : Math.min(MAX_RETRY_AFTER_MS, Math.max(0, date - Date.now()));
|
|
235
|
+
}
|
|
236
|
+
const TRANSIENT_STATUSES = new Set([408, 429, 502, 503, 504]);
|
|
237
|
+
async function providerError(response, provider, model, redact) {
|
|
117
238
|
let detail = "";
|
|
118
239
|
try {
|
|
119
|
-
const
|
|
240
|
+
const text = await response.text();
|
|
241
|
+
const raw = redact(text.length > 50_000 ? text.slice(0, 50_000) : text).slice(0, 2000);
|
|
120
242
|
try {
|
|
121
243
|
const parsed = JSON.parse(raw);
|
|
122
244
|
const message = typeof parsed.error === "string" ? parsed.error : parsed.error?.message ?? parsed.message;
|
|
@@ -129,27 +251,69 @@ async function providerError(response, provider, model) {
|
|
|
129
251
|
catch {
|
|
130
252
|
detail = response.statusText;
|
|
131
253
|
}
|
|
132
|
-
const
|
|
133
|
-
|
|
254
|
+
const status = response.status;
|
|
255
|
+
const retryable = status === 408 || status === 409 || status === 429 || status >= 500;
|
|
256
|
+
const retryAfterMs = status === 429 || status === 503 ? parseRetryAfter(response.headers?.get?.("retry-after")) : undefined;
|
|
257
|
+
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 } : {}) });
|
|
134
258
|
}
|
|
135
|
-
/**
|
|
259
|
+
/**
|
|
260
|
+
* Reads server-sent events; resolves `true` when the provider closed the stream with `[DONE]`. An event is its `data:`
|
|
261
|
+
* lines joined with a newline, ended by a blank line; a value that is complete as it stands (one JSON object, or
|
|
262
|
+
* `[DONE]`) is delivered at once, so servers that leave out the blank lines still stream.
|
|
263
|
+
*/
|
|
136
264
|
async function readEventStream(response, onData) {
|
|
137
265
|
if (!response.body)
|
|
138
|
-
throw new AiProviderError("The provider returned an empty stream.", undefined, true);
|
|
266
|
+
throw new AiProviderError("The provider returned an empty stream.", undefined, true, { transient: true });
|
|
139
267
|
const reader = response.body.getReader();
|
|
140
268
|
const decoder = new TextDecoder();
|
|
141
269
|
let buffer = "";
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
270
|
+
let pending = [];
|
|
271
|
+
const complete = (value) => {
|
|
272
|
+
const text = value.trim();
|
|
273
|
+
if (text === "[DONE]")
|
|
274
|
+
return true;
|
|
275
|
+
if (!text.startsWith("{") && !text.startsWith("["))
|
|
145
276
|
return false;
|
|
146
|
-
|
|
147
|
-
|
|
277
|
+
try {
|
|
278
|
+
JSON.parse(text);
|
|
148
279
|
return true;
|
|
149
|
-
|
|
150
|
-
|
|
280
|
+
}
|
|
281
|
+
catch {
|
|
282
|
+
return false;
|
|
283
|
+
}
|
|
284
|
+
};
|
|
285
|
+
const flush = () => {
|
|
286
|
+
const lines = pending;
|
|
287
|
+
pending = [];
|
|
288
|
+
if (!lines.length)
|
|
289
|
+
return false;
|
|
290
|
+
const joined = lines.join("\n").trim();
|
|
291
|
+
if (joined === "[DONE]")
|
|
292
|
+
return true;
|
|
293
|
+
if (lines.length > 1 && !complete(joined)) {
|
|
294
|
+
// Lines that do not make one value are separate events that came without a blank line between them.
|
|
295
|
+
for (const line of lines) {
|
|
296
|
+
const single = line.trim();
|
|
297
|
+
if (single === "[DONE]")
|
|
298
|
+
return true;
|
|
299
|
+
if (single)
|
|
300
|
+
onData(single);
|
|
301
|
+
}
|
|
302
|
+
return false;
|
|
303
|
+
}
|
|
304
|
+
if (joined)
|
|
305
|
+
onData(joined);
|
|
151
306
|
return false;
|
|
152
307
|
};
|
|
308
|
+
const takeLine = (line) => {
|
|
309
|
+
const clean = line.replace(/\r$/, "");
|
|
310
|
+
if (!clean)
|
|
311
|
+
return flush();
|
|
312
|
+
if (!clean.startsWith("data:"))
|
|
313
|
+
return false;
|
|
314
|
+
pending.push(clean.slice(5).trimStart());
|
|
315
|
+
return complete(pending.join("\n")) ? flush() : false;
|
|
316
|
+
};
|
|
153
317
|
try {
|
|
154
318
|
for (;;) {
|
|
155
319
|
const { value, done } = await reader.read();
|
|
@@ -160,7 +324,7 @@ async function readEventStream(response, onData) {
|
|
|
160
324
|
while (newline >= 0) {
|
|
161
325
|
const line = buffer.slice(0, newline);
|
|
162
326
|
buffer = buffer.slice(newline + 1);
|
|
163
|
-
if (
|
|
327
|
+
if (takeLine(line)) {
|
|
164
328
|
await reader.cancel().catch(() => undefined);
|
|
165
329
|
return true;
|
|
166
330
|
}
|
|
@@ -168,7 +332,9 @@ async function readEventStream(response, onData) {
|
|
|
168
332
|
}
|
|
169
333
|
}
|
|
170
334
|
buffer += decoder.decode();
|
|
171
|
-
|
|
335
|
+
if (buffer.trim() && takeLine(buffer))
|
|
336
|
+
return true;
|
|
337
|
+
return flush();
|
|
172
338
|
}
|
|
173
339
|
catch (error) {
|
|
174
340
|
// The reply was given up (an error chunk, a failing listener): release the connection instead of leaving it open.
|
|
@@ -200,11 +366,12 @@ export function classifyFinishReason(reason, ended) {
|
|
|
200
366
|
return ended ? "complete" : "unexpected";
|
|
201
367
|
}
|
|
202
368
|
const PERMANENT_STREAM_ERROR = /authenticat|unauthori[sz]ed|forbidden|permission|invalid[_ -]?(?:request|api[_ -]?key|argument|parameter)|bad[_ -]?request/i;
|
|
369
|
+
const TRANSIENT_STREAM_ERROR = /overload|rate[_ -]?limit|too many requests|temporar|unavailable|busy|try again|time[ds]? ?out|capacity/i;
|
|
203
370
|
/**
|
|
204
371
|
* A failure the provider reported inside the stream (`{"error": {...}}` or `{"error": "..."}`), or `null` when the
|
|
205
372
|
* chunk carries none. It is retried unless its status or code says authentication or an invalid request.
|
|
206
373
|
*/
|
|
207
|
-
function streamError(value, label, details) {
|
|
374
|
+
function streamError(value, label, details, redact) {
|
|
208
375
|
const source = value && typeof value === "object" ? value : null;
|
|
209
376
|
const message = typeof value === "string" ? value.trim() : typeof source?.message === "string" ? source.message.trim() : "";
|
|
210
377
|
if (!source && !message)
|
|
@@ -214,8 +381,9 @@ function streamError(value, label, details) {
|
|
|
214
381
|
.find((entry) => Number.isInteger(entry) && entry >= 100 && entry < 600);
|
|
215
382
|
const words = [source?.type, source?.code, source?.status].filter((entry) => typeof entry === "string").join(" ");
|
|
216
383
|
const permanent = (status !== undefined && status >= 400 && status < 500 && status !== 408 && status !== 409 && status !== 429) || PERMANENT_STREAM_ERROR.test(words);
|
|
217
|
-
const
|
|
218
|
-
|
|
384
|
+
const transient = !permanent && ((status !== undefined && TRANSIENT_STATUSES.has(status)) || TRANSIENT_STREAM_ERROR.test(`${message} ${words}`));
|
|
385
|
+
const detail = redact(message || (source && Object.keys(source).length ? JSON.stringify(source) : "no details")).replace(/\s+/g, " ").slice(0, 400);
|
|
386
|
+
return new AiProviderError(redact(`${label}: the provider reported an error during the reply — ${detail}`), status, !permanent, { ...details, ...(transient ? { transient: true } : {}) });
|
|
219
387
|
}
|
|
220
388
|
/** Characters of reasoning a reply carried. Only the count is kept, never the reasoning itself. */
|
|
221
389
|
function reasoningLength(source) {
|
|
@@ -224,55 +392,31 @@ function reasoningLength(source) {
|
|
|
224
392
|
const { reasoning_content: content, reasoning } = source;
|
|
225
393
|
return (typeof content === "string" ? content.length : 0) + (typeof reasoning === "string" ? reasoning.length : 0);
|
|
226
394
|
}
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
const requested = request.json && request.maxOutputTokens ? Math.max(request.maxOutputTokens, STRUCTURED_OUTPUT_FLOOR) : request.maxOutputTokens;
|
|
230
|
-
return requested && candidate.maxOutputTokens ? Math.min(requested, candidate.maxOutputTokens) : requested ?? candidate.maxOutputTokens;
|
|
231
|
-
}
|
|
232
|
-
async function callCandidate(config, candidate, request, options) {
|
|
395
|
+
async function callCandidate(config, attempt, built, request, options, timeoutMs, secrets) {
|
|
396
|
+
const { candidate } = attempt;
|
|
233
397
|
const { integration, model } = candidate;
|
|
234
398
|
const label = `${integration.provider} ${model}`;
|
|
235
|
-
const
|
|
236
|
-
const useTools = Boolean(request.json) && candidate.supportsToolCalls !== false;
|
|
237
|
-
const stream = Boolean(request.onText) && !request.json;
|
|
238
|
-
const system = request.json && !useTools ? `${request.system}\n\n${jsonInstruction(request.json)}` : request.system;
|
|
239
|
-
const body = {
|
|
240
|
-
model,
|
|
241
|
-
messages: [
|
|
242
|
-
{ role: "system", content: system },
|
|
243
|
-
{ role: "user", content: request.user },
|
|
244
|
-
],
|
|
245
|
-
...completionTokenLimit(integration.provider, model, requestOutputLimit(request, candidate), candidate.underlyingModel),
|
|
246
|
-
};
|
|
247
|
-
if (request.temperature !== undefined && !isReasoningModel(integration.provider, model, candidate.underlyingModel))
|
|
248
|
-
body.temperature = request.temperature;
|
|
249
|
-
if (useTools && request.json) {
|
|
250
|
-
body.tools = [{ type: "function", function: request.json }];
|
|
251
|
-
body.tool_choice = forcedToolChoice(integration.provider, integration.apiVersion, request.json.name);
|
|
252
|
-
}
|
|
253
|
-
if (stream) {
|
|
254
|
-
body.stream = true;
|
|
255
|
-
body.stream_options = { include_usage: true };
|
|
256
|
-
}
|
|
399
|
+
const redact = (text) => redactSecrets(text, secrets);
|
|
257
400
|
const fetchImpl = options.fetch ?? fetch;
|
|
258
|
-
const timer = linkedSignal(request.signal,
|
|
401
|
+
const timer = linkedSignal(request.signal, timeoutMs);
|
|
259
402
|
try {
|
|
260
403
|
let response;
|
|
261
404
|
try {
|
|
262
|
-
response = await fetchImpl(
|
|
405
|
+
response = await fetchImpl(built.url, {
|
|
263
406
|
method: "POST",
|
|
264
|
-
headers:
|
|
265
|
-
body: JSON.stringify(body),
|
|
407
|
+
headers: built.headers,
|
|
408
|
+
body: JSON.stringify(built.body),
|
|
266
409
|
signal: timer.signal,
|
|
267
410
|
});
|
|
268
411
|
}
|
|
269
412
|
catch (error) {
|
|
270
413
|
if (request.signal?.aborted)
|
|
271
414
|
throw error;
|
|
272
|
-
|
|
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 } : {}) });
|
|
273
417
|
}
|
|
274
418
|
if (!response.ok)
|
|
275
|
-
throw await providerError(response, integration.provider, model);
|
|
419
|
+
throw await providerError(response, integration.provider, model, redact);
|
|
276
420
|
let text = "";
|
|
277
421
|
let toolArguments = "";
|
|
278
422
|
let usage;
|
|
@@ -280,17 +424,34 @@ async function callCandidate(config, candidate, request, options) {
|
|
|
280
424
|
let reasoningCharacters = 0;
|
|
281
425
|
/** The response ended properly: a stream that closed with `[DONE]`, or a complete JSON body. */
|
|
282
426
|
let ended = true;
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
427
|
+
/** What the attempt used: the provider's count, else an estimate once the model has started to answer. */
|
|
428
|
+
const measure = () => {
|
|
429
|
+
if (usage && usage.inputTokens + usage.outputTokens > 0)
|
|
430
|
+
return { usage, usageKnown: true };
|
|
431
|
+
if (!text && !toolArguments && !reasoningCharacters)
|
|
432
|
+
return {};
|
|
433
|
+
return {
|
|
434
|
+
usage: { inputTokens: attempt.inputTokens, outputTokens: likelyTextTokens(text) + likelyTextTokens(toolArguments) + Math.ceil(reasoningCharacters / 4), cachedInputTokens: 0 },
|
|
435
|
+
usageKnown: false,
|
|
436
|
+
};
|
|
437
|
+
};
|
|
438
|
+
const details = (extra = {}) => {
|
|
439
|
+
const measured = measure();
|
|
440
|
+
return {
|
|
441
|
+
usage: measured.usage,
|
|
442
|
+
cost: estimateCost(measured.usage, candidate.pricing),
|
|
443
|
+
...(measured.usageKnown === undefined ? {} : { usageKnown: measured.usageKnown, costKnown: measured.usageKnown && Boolean(candidate.pricing) }),
|
|
444
|
+
currency: config.costCurrency,
|
|
445
|
+
model,
|
|
446
|
+
provider: integration.provider,
|
|
447
|
+
integrationId: integration.id,
|
|
448
|
+
...extra,
|
|
449
|
+
};
|
|
450
|
+
};
|
|
451
|
+
// A JSON body to a streaming request means the server ignored `stream`: its reply is read as a whole.
|
|
452
|
+
const streamed = built.stream && !/\bjson\b/i.test(response.headers?.get?.("content-type") ?? "");
|
|
292
453
|
try {
|
|
293
|
-
if (
|
|
454
|
+
if (streamed) {
|
|
294
455
|
ended = await readEventStream(response, (data) => {
|
|
295
456
|
let chunk;
|
|
296
457
|
try {
|
|
@@ -302,7 +463,7 @@ async function callCandidate(config, candidate, request, options) {
|
|
|
302
463
|
if (!chunk || typeof chunk !== "object")
|
|
303
464
|
return;
|
|
304
465
|
if (chunk.error) {
|
|
305
|
-
const failure = streamError(chunk.error, label, details());
|
|
466
|
+
const failure = streamError(chunk.error, label, details(), redact);
|
|
306
467
|
if (failure)
|
|
307
468
|
throw failure;
|
|
308
469
|
}
|
|
@@ -321,23 +482,31 @@ async function callCandidate(config, candidate, request, options) {
|
|
|
321
482
|
}
|
|
322
483
|
else {
|
|
323
484
|
const payload = await response.json();
|
|
324
|
-
|
|
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];
|
|
325
491
|
text = typeof choice?.message?.content === "string" ? choice.message.content : "";
|
|
326
492
|
toolArguments = choice?.message?.tool_calls?.find((call) => typeof call.function?.arguments === "string")?.function?.arguments ?? "";
|
|
327
493
|
finishReason = typeof choice?.finish_reason === "string" ? choice.finish_reason : "";
|
|
328
494
|
reasoningCharacters = reasoningLength(choice?.message);
|
|
329
|
-
usage = normalizeUsage(payload
|
|
495
|
+
usage = normalizeUsage(payload?.usage);
|
|
496
|
+
if (built.stream && text)
|
|
497
|
+
request.onText?.(text);
|
|
330
498
|
}
|
|
331
499
|
}
|
|
332
500
|
catch (error) {
|
|
333
501
|
if (request.signal?.aborted || error instanceof AiProviderError)
|
|
334
502
|
throw error;
|
|
335
|
-
|
|
503
|
+
const timedOut = timer.timedOut();
|
|
504
|
+
throw new AiProviderError(redact(`${label}: ${timedOut ? "request timed out" : "the reply could not be read"}.`), undefined, true, details({ transient: true, ...(timedOut ? { timedOut: true } : {}) }));
|
|
336
505
|
}
|
|
337
506
|
const outcome = classifyFinishReason(finishReason, ended);
|
|
338
|
-
const shown = finishReason.replace(/\s+/g, " ").trim().slice(0, 60);
|
|
507
|
+
const shown = redact(finishReason).replace(/\s+/g, " ").trim().slice(0, 60);
|
|
339
508
|
if (outcome === "incomplete")
|
|
340
|
-
throw new AiProviderError(`${label}: the stream ended before the reply was complete.`, undefined, true, details());
|
|
509
|
+
throw new AiProviderError(`${label}: the stream ended before the reply was complete.`, undefined, true, details({ transient: true }));
|
|
341
510
|
if (outcome === "unexpected")
|
|
342
511
|
throw new AiProviderError(`${label}: unexpected finish reason "${shown}" and the stream did not end with [DONE]: the reply may be incomplete.`, undefined, true, details());
|
|
343
512
|
if (outcome === "failed")
|
|
@@ -350,7 +519,8 @@ async function callCandidate(config, candidate, request, options) {
|
|
|
350
519
|
reasoningCharacters += inline.reasoningCharacters;
|
|
351
520
|
const answered = Boolean(text.trim() || toolArguments.trim());
|
|
352
521
|
if (outcome === "truncated") {
|
|
353
|
-
|
|
522
|
+
const reasoned = !answered && reasoningCharacters > 0;
|
|
523
|
+
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 } : {}) } : {}) }));
|
|
354
524
|
}
|
|
355
525
|
if (!answered)
|
|
356
526
|
throw new AiProviderError(`${label}: ${reasoningCharacters > 0 ? "the model finished after reasoning without a reply" : "the provider returned an empty reply"}.`, undefined, true, details());
|
|
@@ -360,19 +530,22 @@ async function callCandidate(config, candidate, request, options) {
|
|
|
360
530
|
json = structuredFromReply({ toolArguments, content: text, schema: request.json });
|
|
361
531
|
}
|
|
362
532
|
catch (error) {
|
|
363
|
-
throw new AiReplyRejectedError(`${label}: ${error instanceof Error ? error.message : "invalid structured reply"}
|
|
533
|
+
throw new AiReplyRejectedError(redact(`${label}: ${error instanceof Error ? error.message : "invalid structured reply"}`), details());
|
|
364
534
|
}
|
|
365
535
|
if (!text)
|
|
366
536
|
text = toolArguments;
|
|
367
537
|
}
|
|
538
|
+
const measured = measure();
|
|
368
539
|
return {
|
|
369
540
|
text,
|
|
370
541
|
json,
|
|
371
|
-
usage,
|
|
542
|
+
usage: measured.usage,
|
|
543
|
+
usageKnown: measured.usageKnown ?? false,
|
|
372
544
|
model,
|
|
373
545
|
provider: integration.provider,
|
|
374
546
|
integrationId: integration.id,
|
|
375
|
-
cost: estimateCost(usage, candidate.pricing),
|
|
547
|
+
cost: estimateCost(measured.usage, candidate.pricing),
|
|
548
|
+
costKnown: measured.usageKnown === true && Boolean(candidate.pricing),
|
|
376
549
|
currency: config.costCurrency,
|
|
377
550
|
};
|
|
378
551
|
}
|