@mastra/code-sdk 1.21.0 → 1.22.0-alpha.1
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/dist/agents/custom-provider-check.d.ts +98 -0
- package/dist/agents/custom-provider-check.js +700 -0
- package/dist/agents/mastracode-gateway.d.ts +9 -0
- package/dist/agents/mastracode-gateway.js +18 -15
- package/dist/agents/model.d.ts +23 -21
- package/dist/agents/model.js +97 -18
- package/dist/auth/account-rotation-processor.d.ts +19 -53
- package/dist/auth/account-rotation-processor.js +28 -69
- package/dist/auth/index.js +2 -1
- package/dist/headless/run-mc.js +1 -1
- package/dist/index.d.ts +5 -0
- package/dist/index.js +10 -7
- package/dist/model-fallback.d.ts +75 -0
- package/dist/model-fallback.js +48 -0
- package/dist/onboarding/custom-provider-headers.d.ts +50 -0
- package/dist/onboarding/custom-provider-headers.js +112 -0
- package/dist/onboarding/custom-providers.js +11 -0
- package/dist/onboarding/settings.d.ts +13 -0
- package/dist/onboarding/settings.js +27 -0
- package/dist/processors/route-aware-stream-error-retry.d.ts +6 -0
- package/dist/processors/route-aware-stream-error-retry.js +15 -0
- package/dist/restricted.d.ts +115 -0
- package/dist/restricted.js +257 -0
- package/dist/schema.d.ts +5 -8
- package/dist/schema.js +2 -8
- package/package.json +6 -6
|
@@ -0,0 +1,700 @@
|
|
|
1
|
+
import { CONTROL_CHARACTER_PATTERN, customProviderAuthHeaderName, customProviderHeaderProblem, mergeHeadersIgnoringCase } from "../onboarding/custom-provider-headers.js";
|
|
2
|
+
import { APICallError, JSONParseError, RetryError, StreamProviderError, TypeValidationError, streamText } from "ai";
|
|
3
|
+
import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
|
|
4
|
+
import { STATUS_CODES } from "http";
|
|
5
|
+
// src/agents/custom-provider-check.ts
|
|
6
|
+
/**
|
|
7
|
+
* Requests to custom OpenAI-compatible endpoints: the headers they carry, the
|
|
8
|
+
* chat model a session uses, and the checks that call an endpoint before or
|
|
9
|
+
* after it is saved.
|
|
10
|
+
*
|
|
11
|
+
* `mastracode-gateway.ts` imports this module, so this module must never import
|
|
12
|
+
* the gateway.
|
|
13
|
+
*/
|
|
14
|
+
/**
|
|
15
|
+
* `fetch` that refuses redirects. Servers call custom endpoints too, and a
|
|
16
|
+
* redirect could aim that call at an address the saved URL never named.
|
|
17
|
+
*/
|
|
18
|
+
const fetchWithoutRedirects = (input, init) => fetch(input, {
|
|
19
|
+
...init,
|
|
20
|
+
redirect: "error"
|
|
21
|
+
});
|
|
22
|
+
/**
|
|
23
|
+
* The headers of a connection that is typed but may come straight from a
|
|
24
|
+
* request body. Anything that is not a list of objects counts as no headers,
|
|
25
|
+
* so a check returns a result instead of throwing on it.
|
|
26
|
+
*/
|
|
27
|
+
function headerList(connection) {
|
|
28
|
+
const headers = connection.headers;
|
|
29
|
+
if (!Array.isArray(headers)) return [];
|
|
30
|
+
return headers.filter((header) => typeof header === "object" && header !== null);
|
|
31
|
+
}
|
|
32
|
+
/** `value` when it is a string, for connection fields that may come from a request body. */
|
|
33
|
+
function stringOrUndefined(value) {
|
|
34
|
+
return typeof value === "string" ? value : void 0;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* The custom headers of a connection plus the header that carries its key.
|
|
38
|
+
* The auth header comes last so that nothing can replace it.
|
|
39
|
+
*/
|
|
40
|
+
function customProviderRequestHeaders(connection) {
|
|
41
|
+
const custom = Object.fromEntries(headerList(connection).filter((header) => typeof header.name === "string" && typeof header.value === "string").map((header) => [header.name, header.value]));
|
|
42
|
+
const apiKey = stringOrUndefined(connection.apiKey)?.trim();
|
|
43
|
+
if (!apiKey) return mergeHeadersIgnoringCase(custom);
|
|
44
|
+
const authValue = connection.authScheme === "x-api-key" ? apiKey : `Bearer ${apiKey}`;
|
|
45
|
+
return mergeHeadersIgnoringCase(custom, { [customProviderAuthHeaderName(connection.authScheme)]: authValue });
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* The chat model a session uses for a custom endpoint. `requestHeaders` are
|
|
49
|
+
* Mastra's own per-request headers (`x-thread-id`, `x-resource-id`). A custom
|
|
50
|
+
* header may replace them, and nothing replaces the auth header.
|
|
51
|
+
*/
|
|
52
|
+
function createCustomProviderChatModel(args) {
|
|
53
|
+
return buildChatModel(args, fetchWithoutRedirects);
|
|
54
|
+
}
|
|
55
|
+
/** {@link createCustomProviderChatModel} with the `fetch` to call through, so the model test can cap what it reads. */
|
|
56
|
+
function buildChatModel(args, fetchImpl) {
|
|
57
|
+
return createOpenAICompatible({
|
|
58
|
+
name: args.providerId,
|
|
59
|
+
baseURL: args.connection.url,
|
|
60
|
+
headers: mergeHeadersIgnoringCase(args.requestHeaders, customProviderRequestHeaders(args.connection)),
|
|
61
|
+
fetch: fetchImpl
|
|
62
|
+
}).chatModel(args.modelId);
|
|
63
|
+
}
|
|
64
|
+
const LIST_TIMEOUT_MS = 1e4;
|
|
65
|
+
/**
|
|
66
|
+
* The most response bytes a check reads, for the model list and for the test
|
|
67
|
+
* message alike. A real answer to either is far smaller, and the cap keeps an
|
|
68
|
+
* endpoint from holding memory or the connection until the timeout.
|
|
69
|
+
*/
|
|
70
|
+
const MAX_RESPONSE_BYTES = 2097152;
|
|
71
|
+
const MAX_DETAIL_LENGTH = 1e3;
|
|
72
|
+
/** Shorter values match too much ordinary text to be worth redacting. */
|
|
73
|
+
const MIN_REDACTED_LENGTH = 4;
|
|
74
|
+
/** The cause message undici gives a fetch made with `redirect: 'error'` that met a redirect. */
|
|
75
|
+
const REDIRECT_CAUSE_MESSAGE = "unexpected redirect";
|
|
76
|
+
/**
|
|
77
|
+
* The key and secret header values a check sends. A header without a
|
|
78
|
+
* `secret` flag counts as secret. Each value is listed as sent and in the
|
|
79
|
+
* form `oneLine` turns it into, so a value with a tab or a double space still
|
|
80
|
+
* matches after the text was collapsed.
|
|
81
|
+
*/
|
|
82
|
+
function secretsSent(connection) {
|
|
83
|
+
const values = [stringOrUndefined(connection.apiKey)?.trim(), ...headerList(connection).filter((header) => header.secret !== false).map((header) => header.value)].filter((value) => typeof value === "string" && value.length > 0);
|
|
84
|
+
const forms = [...new Set(values.flatMap((value) => [value, oneLine(value)]))].filter(Boolean);
|
|
85
|
+
return {
|
|
86
|
+
redacted: forms.filter((form) => form.length >= MIN_REDACTED_LENGTH).sort((a, b) => b.length - a.length),
|
|
87
|
+
tooShort: forms.filter((form) => form.length < MIN_REDACTED_LENGTH)
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
/** Replace every sent secret in `text`. Endpoints echo request headers in error pages often enough to matter. */
|
|
91
|
+
function redact(text, secrets) {
|
|
92
|
+
return secrets.redacted.reduce((redacted, secret) => redacted.split(secret).join("[redacted]"), text);
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Redact the failure text and cut `detail` to its limit. Redaction runs first
|
|
96
|
+
* so a cut never leaves part of a secret. The detail builders also redact the
|
|
97
|
+
* upstream text before their own cuts and collapses. A detail that still
|
|
98
|
+
* contains a secret too short to redact is dropped.
|
|
99
|
+
*/
|
|
100
|
+
function finishFailure(failure, secrets) {
|
|
101
|
+
const { detail: rawDetail, ...rest } = failure;
|
|
102
|
+
const redactedDetail = rawDetail === void 0 ? "" : redact(rawDetail, secrets);
|
|
103
|
+
const detail = secrets.tooShort.some((secret) => redactedDetail.includes(secret)) ? "" : redactedDetail.slice(0, MAX_DETAIL_LENGTH);
|
|
104
|
+
return {
|
|
105
|
+
...rest,
|
|
106
|
+
message: redact(failure.message, secrets),
|
|
107
|
+
...detail ? { detail } : {}
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
/** Every control character, for `replace`. */
|
|
111
|
+
const CONTROL_CHARACTERS = new RegExp(CONTROL_CHARACTER_PATTERN.source, "g");
|
|
112
|
+
/**
|
|
113
|
+
* Collapse a text into one line. Control characters become spaces: the TUI
|
|
114
|
+
* prints `detail`, and an endpoint must not be able to send escape sequences
|
|
115
|
+
* to the user's terminal. Callers decode HTML entities first, so `` is
|
|
116
|
+
* caught too.
|
|
117
|
+
*/
|
|
118
|
+
function oneLine(text) {
|
|
119
|
+
return text.replace(CONTROL_CHARACTERS, " ").replace(/\s+/g, " ").trim();
|
|
120
|
+
}
|
|
121
|
+
/** Narrow an unknown JSON value to an object. */
|
|
122
|
+
function isRecord(value) {
|
|
123
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
124
|
+
}
|
|
125
|
+
/** The error message of a JSON error body, in the shapes OpenAI-compatible servers use. */
|
|
126
|
+
function jsonErrorMessage(body) {
|
|
127
|
+
if (!isRecord(body)) return void 0;
|
|
128
|
+
if (isRecord(body.error) && typeof body.error.message === "string") return body.error.message;
|
|
129
|
+
if (typeof body.error === "string") return body.error;
|
|
130
|
+
if (typeof body.message === "string") return body.message;
|
|
131
|
+
}
|
|
132
|
+
const HTML_ENTITIES = {
|
|
133
|
+
amp: "&",
|
|
134
|
+
lt: "<",
|
|
135
|
+
gt: ">",
|
|
136
|
+
quot: "\"",
|
|
137
|
+
apos: "'",
|
|
138
|
+
nbsp: " "
|
|
139
|
+
};
|
|
140
|
+
/**
|
|
141
|
+
* How much of an upstream body the detail is read from. Error pages put their
|
|
142
|
+
* title and message near the top and the detail keeps 1,000 characters, so a
|
|
143
|
+
* longer read adds nothing. The parsing is synchronous, which the timeout
|
|
144
|
+
* cannot interrupt, so it must stay cheap on any body an endpoint sends.
|
|
145
|
+
*/
|
|
146
|
+
const DETAIL_SCAN_CHARS = 32768;
|
|
147
|
+
/** Elements whose content is not page text. */
|
|
148
|
+
const NON_TEXT_ELEMENTS = /* @__PURE__ */ new Set([
|
|
149
|
+
"head",
|
|
150
|
+
"script",
|
|
151
|
+
"style",
|
|
152
|
+
"title"
|
|
153
|
+
]);
|
|
154
|
+
/**
|
|
155
|
+
* Decode the entities error pages commonly carry. Others, and numeric ones
|
|
156
|
+
* outside Unicode, stay as written. The bounded lengths keep the scan linear.
|
|
157
|
+
*/
|
|
158
|
+
function decodeHtmlEntities(text) {
|
|
159
|
+
return text.replace(/&(#[0-9]{1,8}|#x[0-9a-f]{1,8}|[a-z]{1,10});/gi, (entity, name) => {
|
|
160
|
+
if (!name.startsWith("#")) return HTML_ENTITIES[name.toLowerCase()] ?? entity;
|
|
161
|
+
const codePoint = name[1] === "x" || name[1] === "X" ? Number.parseInt(name.slice(2), 16) : Number(name.slice(1));
|
|
162
|
+
return Number.isInteger(codePoint) && codePoint <= 1114111 ? String.fromCodePoint(codePoint) : entity;
|
|
163
|
+
});
|
|
164
|
+
}
|
|
165
|
+
/**
|
|
166
|
+
* The `<title>` of an HTML page, then its text with tags removed. With
|
|
167
|
+
* `summaryOnly`, the title alone.
|
|
168
|
+
*
|
|
169
|
+
* Every search is an `indexOf` that either moves the cursor past what it read
|
|
170
|
+
* or ends the scan, so the work stays linear on tags that never close. An
|
|
171
|
+
* unclosed comment, tag or non-text element ends the text there.
|
|
172
|
+
*/
|
|
173
|
+
function htmlDetail(html, summaryOnly, secrets) {
|
|
174
|
+
const readable = (text) => oneLine(redact(decodeHtmlEntities(text), secrets));
|
|
175
|
+
const lower = html.replace(/[A-Z]/g, (letter) => letter.toLowerCase());
|
|
176
|
+
let title = "";
|
|
177
|
+
const titleStart = lower.indexOf("<title");
|
|
178
|
+
const titleOpenEnd = titleStart < 0 ? -1 : lower.indexOf(">", titleStart);
|
|
179
|
+
const titleClose = titleOpenEnd < 0 ? -1 : lower.indexOf("</title", titleOpenEnd);
|
|
180
|
+
if (titleClose >= 0) title = readable(html.slice(titleOpenEnd + 1, titleClose));
|
|
181
|
+
if (summaryOnly) return title || void 0;
|
|
182
|
+
const parts = [];
|
|
183
|
+
const tagName = /[a-z][a-z0-9]*/y;
|
|
184
|
+
let cursor = 0;
|
|
185
|
+
while (cursor < html.length) {
|
|
186
|
+
const open = lower.indexOf("<", cursor);
|
|
187
|
+
if (open < 0) {
|
|
188
|
+
parts.push(html.slice(cursor));
|
|
189
|
+
break;
|
|
190
|
+
}
|
|
191
|
+
parts.push(html.slice(cursor, open), " ");
|
|
192
|
+
let resume = -1;
|
|
193
|
+
if (lower.startsWith("<!--", open)) {
|
|
194
|
+
const close = lower.indexOf("-->", open + 4);
|
|
195
|
+
resume = close < 0 ? -1 : close + 3;
|
|
196
|
+
} else {
|
|
197
|
+
tagName.lastIndex = open + 1;
|
|
198
|
+
const name = tagName.exec(lower)?.[0];
|
|
199
|
+
const close = name && NON_TEXT_ELEMENTS.has(name) ? lower.indexOf(`</${name}`, open + 1) : open;
|
|
200
|
+
const end = close < 0 ? -1 : lower.indexOf(">", close);
|
|
201
|
+
resume = end < 0 ? -1 : end + 1;
|
|
202
|
+
}
|
|
203
|
+
if (resume < 0) break;
|
|
204
|
+
cursor = resume;
|
|
205
|
+
}
|
|
206
|
+
const text = readable(parts.join(""));
|
|
207
|
+
return [title, text].filter(Boolean).join(": ") || void 0;
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Plain text from an upstream body for {@link CustomProviderCheckFailure.detail}.
|
|
211
|
+
* A body that cannot be read gives no detail, so a check still returns its failure.
|
|
212
|
+
*
|
|
213
|
+
* Secrets are redacted in the raw body, again in the decoded JSON message or
|
|
214
|
+
* HTML text, both before any cut or whitespace collapse could split one or
|
|
215
|
+
* change its spacing, and once more on the final text.
|
|
216
|
+
*/
|
|
217
|
+
function upstreamDetail(body, contentType, summaryOnly, secrets) {
|
|
218
|
+
try {
|
|
219
|
+
const trimmed = redact(body, secrets).trim();
|
|
220
|
+
if (!trimmed) return void 0;
|
|
221
|
+
let parsed;
|
|
222
|
+
try {
|
|
223
|
+
parsed = JSON.parse(trimmed);
|
|
224
|
+
} catch {
|
|
225
|
+
parsed = void 0;
|
|
226
|
+
}
|
|
227
|
+
const message = jsonErrorMessage(parsed);
|
|
228
|
+
if (message !== void 0) return dropCutSecretStart(oneLine(redact(message, secrets).slice(0, DETAIL_SCAN_CHARS)), secrets, message.length > DETAIL_SCAN_CHARS) || void 0;
|
|
229
|
+
const head = trimmed.slice(0, DETAIL_SCAN_CHARS);
|
|
230
|
+
const cut = trimmed.length > DETAIL_SCAN_CHARS;
|
|
231
|
+
if (contentType?.toLowerCase().includes("text/html") || /^<(!doctype html|html)\b/i.test(head)) return dropCutSecretStart(htmlDetail(cut ? withoutTrailingPartialEntity(head) : head, summaryOnly, secrets) ?? "", secrets, cut) || void 0;
|
|
232
|
+
return summaryOnly ? void 0 : dropCutSecretStart(oneLine(head), secrets, cut) || void 0;
|
|
233
|
+
} catch {
|
|
234
|
+
return;
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
/**
|
|
238
|
+
* The failure for a response with an error status. Both checks map statuses
|
|
239
|
+
* through this. The status text is the standard one for the code, never the
|
|
240
|
+
* reason phrase the endpoint sent, so `message` carries no upstream text.
|
|
241
|
+
*/
|
|
242
|
+
function httpFailure(args) {
|
|
243
|
+
const statusText = STATUS_CODES[args.status] ?? "";
|
|
244
|
+
return {
|
|
245
|
+
kind: "http",
|
|
246
|
+
message: `HTTP ${args.status}${statusText ? ` ${statusText}` : ""} from ${args.url}`,
|
|
247
|
+
status: args.status,
|
|
248
|
+
detail: upstreamDetail(args.body, args.contentType, args.summaryOnly, args.secrets)
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
/** Every message on an error's `cause` chain, outermost first. */
|
|
252
|
+
function causeMessages(error) {
|
|
253
|
+
const messages = [];
|
|
254
|
+
const seen = /* @__PURE__ */ new Set();
|
|
255
|
+
let current = error;
|
|
256
|
+
while (current instanceof Error && !seen.has(current)) {
|
|
257
|
+
seen.add(current);
|
|
258
|
+
messages.push(current.message);
|
|
259
|
+
current = current.cause;
|
|
260
|
+
}
|
|
261
|
+
return messages;
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* The failure for a request that got no response. `fetchWithoutRedirects`
|
|
265
|
+
* refuses a redirect before any status is read, so a redirect is only
|
|
266
|
+
* recognizable by its cause message.
|
|
267
|
+
*/
|
|
268
|
+
function connectionFailure(error, url, abort) {
|
|
269
|
+
if (abort.timedOut) return {
|
|
270
|
+
kind: "timeout",
|
|
271
|
+
message: `No answer from ${url} within ${abort.timeoutMs / 1e3} s`
|
|
272
|
+
};
|
|
273
|
+
if (abort.aborted) return {
|
|
274
|
+
kind: "timeout",
|
|
275
|
+
message: `The request to ${url} was cancelled`
|
|
276
|
+
};
|
|
277
|
+
const messages = causeMessages(error);
|
|
278
|
+
if (messages.includes(REDIRECT_CAUSE_MESSAGE)) return {
|
|
279
|
+
kind: "redirect",
|
|
280
|
+
message: `${url} answered with a redirect, and redirects are refused`
|
|
281
|
+
};
|
|
282
|
+
return {
|
|
283
|
+
kind: "network",
|
|
284
|
+
message: `Could not reach ${url}: ${messages.at(-1) ?? String(error)}`
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
/** Read at most `maxBytes` of a body, so an endpoint cannot make a check buffer without limit. */
|
|
288
|
+
async function readCappedBody(response, maxBytes) {
|
|
289
|
+
if (!response.body) return {
|
|
290
|
+
text: "",
|
|
291
|
+
truncated: false
|
|
292
|
+
};
|
|
293
|
+
const reader = response.body.getReader();
|
|
294
|
+
const decoder = new TextDecoder();
|
|
295
|
+
let text = "";
|
|
296
|
+
let received = 0;
|
|
297
|
+
while (true) {
|
|
298
|
+
const { done, value } = await reader.read();
|
|
299
|
+
if (done) return {
|
|
300
|
+
text: text + decoder.decode(),
|
|
301
|
+
truncated: false
|
|
302
|
+
};
|
|
303
|
+
const room = maxBytes - received;
|
|
304
|
+
if (value.byteLength > room) {
|
|
305
|
+
text += decoder.decode(value.subarray(0, room));
|
|
306
|
+
await reader.cancel();
|
|
307
|
+
return {
|
|
308
|
+
text,
|
|
309
|
+
truncated: true
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
received += value.byteLength;
|
|
313
|
+
text += decoder.decode(value, { stream: true });
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
/**
|
|
317
|
+
* The longest model id kept. Real ids are well under this; a longer one is
|
|
318
|
+
* noise or an attempt to flood the lists that show it.
|
|
319
|
+
*/
|
|
320
|
+
const MAX_MODEL_ID_LENGTH = 256;
|
|
321
|
+
/**
|
|
322
|
+
* Whether an id from a model list may be shown and saved. Ids are dropped,
|
|
323
|
+
* never cleaned, because a cleaned id is no longer the one the endpoint
|
|
324
|
+
* expects. The TUI prints ids, so one with a control character could inject a
|
|
325
|
+
* terminal escape sequence. An id that contains a secret the check sent is an
|
|
326
|
+
* echo of the request and would hand that secret to whoever reads the list.
|
|
327
|
+
*/
|
|
328
|
+
function isUsableModelId(id, sentSecrets) {
|
|
329
|
+
if (!id || id.length > MAX_MODEL_ID_LENGTH) return false;
|
|
330
|
+
if (CONTROL_CHARACTER_PATTERN.test(id)) return false;
|
|
331
|
+
return !sentSecrets.some((secret) => id.includes(secret));
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
334
|
+
* The model ids in a model list body, trimmed, deduplicated and sorted, or
|
|
335
|
+
* undefined when the body is not a model list. Ids that fail
|
|
336
|
+
* {@link isUsableModelId} are dropped, and a non-empty list that yields no id
|
|
337
|
+
* is not a model list either.
|
|
338
|
+
*/
|
|
339
|
+
function modelIdsFromList(body, secrets) {
|
|
340
|
+
const sent = secrets.redacted;
|
|
341
|
+
let entries;
|
|
342
|
+
let nameIsId = false;
|
|
343
|
+
if (Array.isArray(body)) entries = body;
|
|
344
|
+
else if (isRecord(body) && Array.isArray(body.data)) entries = body.data;
|
|
345
|
+
else if (isRecord(body) && Array.isArray(body.models)) {
|
|
346
|
+
entries = body.models;
|
|
347
|
+
nameIsId = true;
|
|
348
|
+
} else return void 0;
|
|
349
|
+
const ids = /* @__PURE__ */ new Set();
|
|
350
|
+
for (const entry of entries) {
|
|
351
|
+
let id;
|
|
352
|
+
if (typeof entry === "string") id = Array.isArray(body) ? entry : void 0;
|
|
353
|
+
else if (isRecord(entry)) id = typeof entry.id === "string" ? entry.id : nameIsId ? entry.name : void 0;
|
|
354
|
+
if (typeof id !== "string") continue;
|
|
355
|
+
const trimmed = id.trim();
|
|
356
|
+
if (isUsableModelId(trimmed, sent)) ids.add(trimmed);
|
|
357
|
+
}
|
|
358
|
+
if (entries.length > 0 && ids.size === 0) return void 0;
|
|
359
|
+
return [...ids].sort();
|
|
360
|
+
}
|
|
361
|
+
/** The largest delay Node timers accept. */
|
|
362
|
+
const MAX_TIMEOUT_MS = 2147483647;
|
|
363
|
+
/**
|
|
364
|
+
* The timeout a check runs with. `AbortSignal.timeout` throws on a negative,
|
|
365
|
+
* fractional or oversized value, and a check must return its failure, never
|
|
366
|
+
* throw, so anything unusable falls back to the default.
|
|
367
|
+
*/
|
|
368
|
+
function checkTimeoutMs(requested, fallback) {
|
|
369
|
+
if (typeof requested !== "number" || !Number.isFinite(requested) || requested <= 0) return fallback;
|
|
370
|
+
return Math.min(Math.ceil(requested), MAX_TIMEOUT_MS);
|
|
371
|
+
}
|
|
372
|
+
/**
|
|
373
|
+
* A timeout signal joined with the caller's signal. `abortState` tells the
|
|
374
|
+
* two apart after an abort. A caller signal that is not an `AbortSignal` is
|
|
375
|
+
* ignored, because `AbortSignal.any` would throw on it.
|
|
376
|
+
*/
|
|
377
|
+
function checkSignal(timeoutMs, callerSignal) {
|
|
378
|
+
const timeout = AbortSignal.timeout(timeoutMs);
|
|
379
|
+
const signal = callerSignal instanceof AbortSignal ? AbortSignal.any([timeout, callerSignal]) : timeout;
|
|
380
|
+
return {
|
|
381
|
+
signal,
|
|
382
|
+
abortState: () => ({
|
|
383
|
+
timedOut: timeout.aborted,
|
|
384
|
+
aborted: signal.aborted,
|
|
385
|
+
timeoutMs
|
|
386
|
+
})
|
|
387
|
+
};
|
|
388
|
+
}
|
|
389
|
+
/**
|
|
390
|
+
* Call `GET {url}/models` and return the model ids the endpoint lists, or why
|
|
391
|
+
* it could not. A failure is returned, never thrown.
|
|
392
|
+
*/
|
|
393
|
+
async function listCustomProviderModels(connection, options = {}) {
|
|
394
|
+
const started = performance.now();
|
|
395
|
+
const latencyMs = () => Math.round(performance.now() - started);
|
|
396
|
+
const secrets = secretsSent(connection);
|
|
397
|
+
const summaryOnly = options.summaryDetailOnly ?? false;
|
|
398
|
+
const timeoutMs = checkTimeoutMs(options.timeoutMs, LIST_TIMEOUT_MS);
|
|
399
|
+
const url = `${(stringOrUndefined(connection.url) ?? "").trim().replace(/\/+$/, "")}/models`;
|
|
400
|
+
const fail = (failure) => ({
|
|
401
|
+
ok: false,
|
|
402
|
+
failure: finishFailure(failure, secrets),
|
|
403
|
+
latencyMs: latencyMs()
|
|
404
|
+
});
|
|
405
|
+
const { signal, abortState } = checkSignal(timeoutMs, options.signal);
|
|
406
|
+
let response;
|
|
407
|
+
let body;
|
|
408
|
+
try {
|
|
409
|
+
response = await fetchWithoutRedirects(url, {
|
|
410
|
+
method: "GET",
|
|
411
|
+
headers: mergeHeadersIgnoringCase({ Accept: "application/json" }, customProviderRequestHeaders(connection)),
|
|
412
|
+
signal
|
|
413
|
+
});
|
|
414
|
+
} catch (error) {
|
|
415
|
+
return fail(connectionFailure(error, url, abortState()));
|
|
416
|
+
}
|
|
417
|
+
const contentType = response.headers.get("content-type") ?? void 0;
|
|
418
|
+
try {
|
|
419
|
+
body = await readCappedBody(response, MAX_RESPONSE_BYTES);
|
|
420
|
+
} catch (error) {
|
|
421
|
+
if (!response.ok) return fail(httpFailure({
|
|
422
|
+
status: response.status,
|
|
423
|
+
url,
|
|
424
|
+
body: "",
|
|
425
|
+
summaryOnly,
|
|
426
|
+
secrets
|
|
427
|
+
}));
|
|
428
|
+
return fail(connectionFailure(error, url, abortState()));
|
|
429
|
+
}
|
|
430
|
+
if (!response.ok) return fail(httpFailure({
|
|
431
|
+
status: response.status,
|
|
432
|
+
url,
|
|
433
|
+
body: body.text,
|
|
434
|
+
contentType,
|
|
435
|
+
summaryOnly,
|
|
436
|
+
secrets
|
|
437
|
+
}));
|
|
438
|
+
if (body.truncated) return fail({
|
|
439
|
+
kind: "invalid_response",
|
|
440
|
+
message: `The model list from ${url} is larger than ${MAX_RESPONSE_BYTES / 1024 / 1024} MB`
|
|
441
|
+
});
|
|
442
|
+
let parsed;
|
|
443
|
+
try {
|
|
444
|
+
parsed = JSON.parse(body.text);
|
|
445
|
+
} catch {
|
|
446
|
+
parsed = void 0;
|
|
447
|
+
}
|
|
448
|
+
const models = modelIdsFromList(parsed, secrets);
|
|
449
|
+
if (!models) return fail({
|
|
450
|
+
kind: "invalid_response",
|
|
451
|
+
message: `The response from ${url} is not a model list`,
|
|
452
|
+
status: response.status,
|
|
453
|
+
detail: upstreamDetail(body.text, contentType, summaryOnly, secrets)
|
|
454
|
+
});
|
|
455
|
+
return {
|
|
456
|
+
ok: true,
|
|
457
|
+
models,
|
|
458
|
+
latencyMs: latencyMs()
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
const MODEL_TEST_TIMEOUT_MS = 3e4;
|
|
462
|
+
const MODEL_TEST_PROMPT = "Reply with the single word \"yes\".";
|
|
463
|
+
/**
|
|
464
|
+
* The longest reply the model test keeps. The prompt asks for one word, so a
|
|
465
|
+
* few thousand characters already prove the model answers, and a model that
|
|
466
|
+
* keeps going would otherwise hold the check and its memory until the timeout.
|
|
467
|
+
* A reply cut here is still a working model.
|
|
468
|
+
*/
|
|
469
|
+
const MAX_REPLY_CHARS = 4e3;
|
|
470
|
+
/**
|
|
471
|
+
* `fetchWithoutRedirects` that counts the bytes of each response body and
|
|
472
|
+
* calls `onCap` once the count passes `maxBytes`. The body then ends with an
|
|
473
|
+
* error, and `onCap` aborts the request so the connection closes.
|
|
474
|
+
*/
|
|
475
|
+
function byteCappedFetch(maxBytes, onCap) {
|
|
476
|
+
return async (input, init) => {
|
|
477
|
+
const response = await fetchWithoutRedirects(input, init);
|
|
478
|
+
if (!response.body) return response;
|
|
479
|
+
let received = 0;
|
|
480
|
+
const counted = response.body.pipeThrough(new TransformStream({ transform(chunk, controller) {
|
|
481
|
+
received += chunk.byteLength;
|
|
482
|
+
if (received <= maxBytes) {
|
|
483
|
+
controller.enqueue(chunk);
|
|
484
|
+
return;
|
|
485
|
+
}
|
|
486
|
+
onCap();
|
|
487
|
+
controller.error(/* @__PURE__ */ new Error(`response passed ${maxBytes} bytes`));
|
|
488
|
+
} }));
|
|
489
|
+
return new Response(counted, {
|
|
490
|
+
status: response.status,
|
|
491
|
+
statusText: response.statusText,
|
|
492
|
+
headers: response.headers
|
|
493
|
+
});
|
|
494
|
+
};
|
|
495
|
+
}
|
|
496
|
+
/** A response header by name, ignoring case, from the plain object the AI SDK keeps on its errors. */
|
|
497
|
+
function headerValue(headers, name) {
|
|
498
|
+
return Object.entries(headers ?? {}).find(([key]) => key.toLowerCase() === name)?.[1];
|
|
499
|
+
}
|
|
500
|
+
/**
|
|
501
|
+
* The failure for an error from the test message. With `maxRetries: 0` the
|
|
502
|
+
* AI SDK should not wrap it in a `RetryError`, but the last attempt is read
|
|
503
|
+
* if one gets through.
|
|
504
|
+
*/
|
|
505
|
+
function modelTestFailure(args) {
|
|
506
|
+
const error = RetryError.isInstance(args.error) ? args.error.lastError : args.error;
|
|
507
|
+
if (APICallError.isInstance(error)) {
|
|
508
|
+
if (error.statusCode !== void 0 && (error.statusCode < 200 || error.statusCode >= 300) && error.statusCode !== void 0) return httpFailure({
|
|
509
|
+
status: error.statusCode,
|
|
510
|
+
url: error.url,
|
|
511
|
+
body: error.responseBody ?? "",
|
|
512
|
+
contentType: headerValue(error.responseHeaders, "content-type"),
|
|
513
|
+
summaryOnly: args.summaryOnly,
|
|
514
|
+
secrets: args.secrets
|
|
515
|
+
});
|
|
516
|
+
if (error.statusCode !== void 0 && !args.abort.aborted) {
|
|
517
|
+
const reason = causeMessages(error).at(-1) ?? "the connection closed";
|
|
518
|
+
return {
|
|
519
|
+
kind: "network",
|
|
520
|
+
message: `The answer from ${error.url} broke off: ${reason}`
|
|
521
|
+
};
|
|
522
|
+
}
|
|
523
|
+
return connectionFailure(error, error.url, args.abort);
|
|
524
|
+
}
|
|
525
|
+
if (args.abort.aborted) return connectionFailure(error, args.chatUrl, args.abort);
|
|
526
|
+
return {
|
|
527
|
+
kind: "invalid_response",
|
|
528
|
+
message: `The answer from ${args.chatUrl} is not an OpenAI-compatible stream`,
|
|
529
|
+
detail: streamErrorDetail(error, args.summaryOnly, args.secrets)
|
|
530
|
+
};
|
|
531
|
+
}
|
|
532
|
+
/**
|
|
533
|
+
* The detail for a stream that failed after a 200. The AI SDK puts raw
|
|
534
|
+
* upstream text in the messages of its parse errors, so that text only goes
|
|
535
|
+
* in `detail`, and only without `summaryOnly`. An error chunk is the
|
|
536
|
+
* endpoint's own error report, so its message is kept like a JSON error body.
|
|
537
|
+
*
|
|
538
|
+
* The AI SDK turns an error chunk with an `error.message` into a
|
|
539
|
+
* `StreamProviderError`. A chunk whose `error` is a plain string fails the
|
|
540
|
+
* chunk schema and arrives as a `TypeValidationError` holding the parsed
|
|
541
|
+
* chunk in `value`, which is read the same way an HTTP error body is.
|
|
542
|
+
* Secrets are redacted before the text is cut or collapsed.
|
|
543
|
+
*/
|
|
544
|
+
function streamErrorDetail(error, summaryOnly, secrets) {
|
|
545
|
+
const clean = (text) => oneLine(redact(text, secrets).slice(0, DETAIL_SCAN_CHARS)) || void 0;
|
|
546
|
+
let reported;
|
|
547
|
+
if (StreamProviderError.isInstance(error)) reported = error.message;
|
|
548
|
+
else if (TypeValidationError.isInstance(error)) reported = jsonErrorMessage(error.value);
|
|
549
|
+
else if (!(error instanceof Error)) reported = jsonErrorMessage({ error });
|
|
550
|
+
if (reported !== void 0) return clean(reported);
|
|
551
|
+
if (summaryOnly) return void 0;
|
|
552
|
+
let raw;
|
|
553
|
+
try {
|
|
554
|
+
if (JSONParseError.isInstance(error)) raw = error.text;
|
|
555
|
+
else if (TypeValidationError.isInstance(error)) raw = JSON.stringify(error.value) ?? "";
|
|
556
|
+
else if (error instanceof Error) raw = error.message;
|
|
557
|
+
else raw = typeof error === "string" ? error : JSON.stringify(error) ?? "";
|
|
558
|
+
} catch {
|
|
559
|
+
return;
|
|
560
|
+
}
|
|
561
|
+
return clean(raw);
|
|
562
|
+
}
|
|
563
|
+
/**
|
|
564
|
+
* Send one short message to a model on a custom endpoint and return its reply,
|
|
565
|
+
* or why it failed. A failure is returned, never thrown, and the request is
|
|
566
|
+
* made once: a check that retries hides the error the user needs to see.
|
|
567
|
+
*/
|
|
568
|
+
async function testCustomProviderModel(args, options = {}) {
|
|
569
|
+
const started = performance.now();
|
|
570
|
+
const latencyMs = () => Math.round(performance.now() - started);
|
|
571
|
+
const secrets = secretsSent(args.connection);
|
|
572
|
+
const timeoutMs = checkTimeoutMs(options.timeoutMs, MODEL_TEST_TIMEOUT_MS);
|
|
573
|
+
const chatUrl = `${(stringOrUndefined(args.connection.url) ?? "").trim().replace(/\/+$/, "")}/chat/completions`;
|
|
574
|
+
const { signal, abortState } = checkSignal(timeoutMs, options.signal);
|
|
575
|
+
let reply = "";
|
|
576
|
+
let finishReason;
|
|
577
|
+
let streamError;
|
|
578
|
+
let stopped = false;
|
|
579
|
+
let replyCut = false;
|
|
580
|
+
let bytesCapped = false;
|
|
581
|
+
const stopReading = new AbortController();
|
|
582
|
+
const cappedFetch = byteCappedFetch(MAX_RESPONSE_BYTES, () => {
|
|
583
|
+
bytesCapped = true;
|
|
584
|
+
stopReading.abort();
|
|
585
|
+
});
|
|
586
|
+
try {
|
|
587
|
+
const result = streamText({
|
|
588
|
+
model: buildChatModel(args, cappedFetch),
|
|
589
|
+
prompt: MODEL_TEST_PROMPT,
|
|
590
|
+
maxRetries: 0,
|
|
591
|
+
abortSignal: AbortSignal.any([signal, stopReading.signal]),
|
|
592
|
+
onError: () => {}
|
|
593
|
+
});
|
|
594
|
+
for await (const part of result.fullStream) if (part.type === "text-delta") {
|
|
595
|
+
reply += part.text;
|
|
596
|
+
if (reply.length >= MAX_REPLY_CHARS) {
|
|
597
|
+
replyCut = true;
|
|
598
|
+
stopReading.abort();
|
|
599
|
+
break;
|
|
600
|
+
}
|
|
601
|
+
} else if (part.type === "finish") finishReason = part.finishReason;
|
|
602
|
+
else if (part.type === "error") {
|
|
603
|
+
streamError = part.error;
|
|
604
|
+
stopped = true;
|
|
605
|
+
break;
|
|
606
|
+
} else if (part.type === "abort") {
|
|
607
|
+
stopped = true;
|
|
608
|
+
break;
|
|
609
|
+
}
|
|
610
|
+
} catch (error) {
|
|
611
|
+
streamError = error;
|
|
612
|
+
stopped = true;
|
|
613
|
+
}
|
|
614
|
+
if (bytesCapped && !replyCut && !reply) return {
|
|
615
|
+
ok: false,
|
|
616
|
+
failure: finishFailure({
|
|
617
|
+
kind: "invalid_response",
|
|
618
|
+
message: `The answer from ${chatUrl} passed ${MAX_RESPONSE_BYTES / 1024 / 1024} MB without any text`
|
|
619
|
+
}, secrets),
|
|
620
|
+
latencyMs: latencyMs()
|
|
621
|
+
};
|
|
622
|
+
const cut = replyCut || bytesCapped;
|
|
623
|
+
if (!cut && (stopped || signal.aborted && finishReason === void 0)) return {
|
|
624
|
+
ok: false,
|
|
625
|
+
failure: finishFailure(modelTestFailure({
|
|
626
|
+
error: streamError,
|
|
627
|
+
chatUrl,
|
|
628
|
+
abort: abortState(),
|
|
629
|
+
summaryOnly: options.summaryDetailOnly ?? false,
|
|
630
|
+
secrets
|
|
631
|
+
}), secrets),
|
|
632
|
+
latencyMs: latencyMs()
|
|
633
|
+
};
|
|
634
|
+
return {
|
|
635
|
+
ok: true,
|
|
636
|
+
reply: safeReply(reply, secrets, cut),
|
|
637
|
+
...finishReason ? { finishReason } : {},
|
|
638
|
+
latencyMs: latencyMs()
|
|
639
|
+
};
|
|
640
|
+
}
|
|
641
|
+
/** Control characters except tab and newline, which a multi-line reply may keep. */
|
|
642
|
+
const REPLY_CONTROL_CHARACTERS = /[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g;
|
|
643
|
+
/**
|
|
644
|
+
* The reply as it may be returned. An endpoint that echoes request headers
|
|
645
|
+
* into its completion would hand a saved secret to someone allowed to run the
|
|
646
|
+
* check but not to read the secret, so the reply is redacted like failure
|
|
647
|
+
* text. Redaction runs before the cut to the reply budget so the cut cannot
|
|
648
|
+
* split a secret.
|
|
649
|
+
*
|
|
650
|
+
* Unlike `detail`, a reply is not emptied for a secret too short to redact:
|
|
651
|
+
* a one to three character value inside a one-word reply reveals nothing,
|
|
652
|
+
* while an error excerpt can repeat it next to its header name.
|
|
653
|
+
*
|
|
654
|
+
* When the reply was cut, by the reply budget or the byte cap, a trailing
|
|
655
|
+
* part that begins a secret is dropped, since the rest of that secret never
|
|
656
|
+
* arrived to be matched. Control characters become spaces because the TUI
|
|
657
|
+
* prints the reply.
|
|
658
|
+
*/
|
|
659
|
+
function safeReply(reply, secrets, cut) {
|
|
660
|
+
return dropCutSecretStart(redact(reply, secrets).slice(0, MAX_REPLY_CHARS), secrets, cut).replace(REPLY_CONTROL_CHARACTERS, " ").trim();
|
|
661
|
+
}
|
|
662
|
+
/**
|
|
663
|
+
* `html` without an entity that the scan limit cut before its `;`, such as
|
|
664
|
+
* `tenant&#`. Left in place it is never decoded, so the decoded text would
|
|
665
|
+
* end in a piece of an encoded secret that no secret form begins with.
|
|
666
|
+
* Removing it lets {@link dropCutSecretStart} see the decoded start that
|
|
667
|
+
* remains. Only the last `&` is examined, so the work stays constant.
|
|
668
|
+
*/
|
|
669
|
+
function withoutTrailingPartialEntity(html) {
|
|
670
|
+
const ampersand = html.lastIndexOf("&");
|
|
671
|
+
if (ampersand < 0 || html.length - ampersand > 12) return html;
|
|
672
|
+
return /^&(#x?[0-9a-f]*|[a-z]*)$/i.test(html.slice(ampersand)) ? html.slice(0, ampersand) : html;
|
|
673
|
+
}
|
|
674
|
+
/**
|
|
675
|
+
* `text` without a trailing piece that begins a sent secret, when the text was
|
|
676
|
+
* cut. Only the start of such a secret arrived, so no redaction could match it.
|
|
677
|
+
* Both the sent and the collapsed form of each secret are checked.
|
|
678
|
+
*/
|
|
679
|
+
function dropCutSecretStart(text, secrets, cut) {
|
|
680
|
+
if (!cut) return text;
|
|
681
|
+
return text.slice(0, text.length - trailingSecretPrefixLength(text, secrets)).trim();
|
|
682
|
+
}
|
|
683
|
+
/**
|
|
684
|
+
* The length of the longest end of `text` that is the start of a sent secret.
|
|
685
|
+
* Candidate starts are scanned from the longest down, and each comparison
|
|
686
|
+
* stops at the first differing character, so ordinary text costs little.
|
|
687
|
+
*/
|
|
688
|
+
function trailingSecretPrefixLength(text, secrets) {
|
|
689
|
+
let longest = 0;
|
|
690
|
+
for (const secret of secrets.redacted) for (let start = Math.max(0, text.length - secret.length + 1); start < text.length - longest; start++) {
|
|
691
|
+
let matched = 0;
|
|
692
|
+
while (start + matched < text.length && text.charCodeAt(start + matched) === secret.charCodeAt(matched)) matched++;
|
|
693
|
+
if (start + matched === text.length) {
|
|
694
|
+
longest = matched;
|
|
695
|
+
break;
|
|
696
|
+
}
|
|
697
|
+
}
|
|
698
|
+
return longest;
|
|
699
|
+
}
|
|
700
|
+
export { createCustomProviderChatModel, customProviderHeaderProblem, customProviderRequestHeaders, fetchWithoutRedirects, listCustomProviderModels, testCustomProviderModel };
|