@mastra/code-sdk 1.22.0-alpha.0 → 1.22.0-alpha.2
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/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/package.json +8 -8
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import type { OpenAICompatibleProvider } from '@ai-sdk/openai-compatible';
|
|
2
|
+
import type { CustomProviderAuthScheme, CustomProviderHeader } from '../onboarding/settings.js';
|
|
3
|
+
export { customProviderHeaderProblem } from '../onboarding/custom-provider-headers.js';
|
|
4
|
+
/** The language model `createCustomProviderChatModel` returns. */
|
|
5
|
+
export type CustomProviderChatModel = ReturnType<OpenAICompatibleProvider['chatModel']>;
|
|
6
|
+
/** Everything needed to call a custom endpoint, with saved secrets already resolved. */
|
|
7
|
+
export interface CustomProviderConnection {
|
|
8
|
+
/**
|
|
9
|
+
* Base URL, such as `https://host/v1`. Paths are appended to it as text, so
|
|
10
|
+
* a query string or fragment (`https://host/v1/?api-version=1`) ends up in
|
|
11
|
+
* the middle of every request path and is not supported.
|
|
12
|
+
*/
|
|
13
|
+
url: string;
|
|
14
|
+
apiKey?: string;
|
|
15
|
+
authScheme?: CustomProviderAuthScheme;
|
|
16
|
+
headers?: CustomProviderHeader[];
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* `fetch` that refuses redirects. Servers call custom endpoints too, and a
|
|
20
|
+
* redirect could aim that call at an address the saved URL never named.
|
|
21
|
+
*/
|
|
22
|
+
export declare const fetchWithoutRedirects: typeof fetch;
|
|
23
|
+
/**
|
|
24
|
+
* The custom headers of a connection plus the header that carries its key.
|
|
25
|
+
* The auth header comes last so that nothing can replace it.
|
|
26
|
+
*/
|
|
27
|
+
export declare function customProviderRequestHeaders(connection: CustomProviderConnection): Record<string, string>;
|
|
28
|
+
/**
|
|
29
|
+
* The chat model a session uses for a custom endpoint. `requestHeaders` are
|
|
30
|
+
* Mastra's own per-request headers (`x-thread-id`, `x-resource-id`). A custom
|
|
31
|
+
* header may replace them, and nothing replaces the auth header.
|
|
32
|
+
*/
|
|
33
|
+
export declare function createCustomProviderChatModel(args: {
|
|
34
|
+
providerId: string;
|
|
35
|
+
connection: CustomProviderConnection;
|
|
36
|
+
modelId: string;
|
|
37
|
+
requestHeaders?: Record<string, string>;
|
|
38
|
+
}): CustomProviderChatModel;
|
|
39
|
+
/** Why a check failed, in terms a user can act on. */
|
|
40
|
+
export interface CustomProviderCheckFailure {
|
|
41
|
+
kind: 'http' | 'network' | 'timeout' | 'redirect' | 'invalid_response';
|
|
42
|
+
/** One line, for example "HTTP 403 Forbidden from https://host/v1/models". */
|
|
43
|
+
message: string;
|
|
44
|
+
status?: number;
|
|
45
|
+
/** Upstream body excerpt as plain text, at most 1,000 characters. */
|
|
46
|
+
detail?: string;
|
|
47
|
+
}
|
|
48
|
+
/** The outcome of {@link listCustomProviderModels}. */
|
|
49
|
+
export type CustomProviderModelsResult = {
|
|
50
|
+
ok: true;
|
|
51
|
+
models: string[];
|
|
52
|
+
latencyMs: number;
|
|
53
|
+
} | {
|
|
54
|
+
ok: false;
|
|
55
|
+
failure: CustomProviderCheckFailure;
|
|
56
|
+
latencyMs: number;
|
|
57
|
+
};
|
|
58
|
+
/** The outcome of {@link testCustomProviderModel}. */
|
|
59
|
+
export type CustomProviderModelTestResult = {
|
|
60
|
+
ok: true;
|
|
61
|
+
reply: string;
|
|
62
|
+
finishReason?: string;
|
|
63
|
+
latencyMs: number;
|
|
64
|
+
} | {
|
|
65
|
+
ok: false;
|
|
66
|
+
failure: CustomProviderCheckFailure;
|
|
67
|
+
latencyMs: number;
|
|
68
|
+
};
|
|
69
|
+
/** Options shared by both checks. */
|
|
70
|
+
export interface CustomProviderCheckOptions {
|
|
71
|
+
/**
|
|
72
|
+
* Deadline for the whole check: 10 s for the model list, 30 s for the test
|
|
73
|
+
* message by default. A value that is not a positive finite number uses the
|
|
74
|
+
* default, a fraction is rounded up to the next millisecond, and a value
|
|
75
|
+
* above the platform timer maximum (2,147,483,647 ms) is capped at it, so a
|
|
76
|
+
* check always has a deadline and never rejects on this option.
|
|
77
|
+
*/
|
|
78
|
+
timeoutMs?: number;
|
|
79
|
+
signal?: AbortSignal;
|
|
80
|
+
/** Keep only the upstream error message or page title in `detail`, never raw body text. */
|
|
81
|
+
summaryDetailOnly?: boolean;
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Call `GET {url}/models` and return the model ids the endpoint lists, or why
|
|
85
|
+
* it could not. A failure is returned, never thrown.
|
|
86
|
+
*/
|
|
87
|
+
export declare function listCustomProviderModels(connection: CustomProviderConnection, options?: CustomProviderCheckOptions): Promise<CustomProviderModelsResult>;
|
|
88
|
+
/**
|
|
89
|
+
* Send one short message to a model on a custom endpoint and return its reply,
|
|
90
|
+
* or why it failed. A failure is returned, never thrown, and the request is
|
|
91
|
+
* made once: a check that retries hides the error the user needs to see.
|
|
92
|
+
*/
|
|
93
|
+
export declare function testCustomProviderModel(args: {
|
|
94
|
+
providerId: string;
|
|
95
|
+
connection: CustomProviderConnection;
|
|
96
|
+
modelId: string;
|
|
97
|
+
}, options?: CustomProviderCheckOptions): Promise<CustomProviderModelTestResult>;
|
|
98
|
+
//# sourceMappingURL=custom-provider-check.d.ts.map
|
|
@@ -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 };
|
|
@@ -3,6 +3,7 @@ import { MastraModelGateway } from '@mastra/core/llm';
|
|
|
3
3
|
import type { GatewayAuthRequest, GatewayAuthResult, GatewayLanguageModel, MastraModelGatewayInterface, ProviderConfig } from '@mastra/core/llm';
|
|
4
4
|
import { AuthStorage } from '../auth/storage.js';
|
|
5
5
|
import type { CredentialStore } from '../auth/types.js';
|
|
6
|
+
import type { CustomProviderAuthScheme, CustomProviderHeader } from '../onboarding/settings.js';
|
|
6
7
|
import type { AnthropicPromptCacheScope } from '../providers/anthropic-prompt-cache.js';
|
|
7
8
|
import type { CodexServiceTier } from '../providers/model-ids.js';
|
|
8
9
|
import type { ThinkingLevel } from '../providers/openai-codex.js';
|
|
@@ -12,6 +13,9 @@ export type MastraCodeCustomProvider = {
|
|
|
12
13
|
name: string;
|
|
13
14
|
url: string;
|
|
14
15
|
apiKey?: string;
|
|
16
|
+
/** Absent means `bearer`. */
|
|
17
|
+
authScheme?: CustomProviderAuthScheme;
|
|
18
|
+
headers?: CustomProviderHeader[];
|
|
15
19
|
models?: string[];
|
|
16
20
|
};
|
|
17
21
|
export type MastraCodeGatewayOptions = {
|
|
@@ -68,10 +72,15 @@ export declare class MastraCodeGateway extends MastraModelGateway {
|
|
|
68
72
|
static resolveProviderAuth(request: GatewayAuthRequest, mastraGatewayApiKey?: string, credentials?: CredentialStore): GatewayAuthResult | undefined;
|
|
69
73
|
static createModelCatalogProvider(gateway: MastraModelGatewayInterface): CustomModelCatalogProvider;
|
|
70
74
|
createModelCatalogProvider(): CustomModelCatalogProvider;
|
|
75
|
+
/** The catalog entries for custom providers that list at least one model. */
|
|
71
76
|
fetchProviders(): Promise<Record<string, ProviderConfig>>;
|
|
72
77
|
buildUrl(modelId: string): string | undefined | Promise<string | undefined>;
|
|
73
78
|
getApiKey(modelId: string): Promise<string>;
|
|
74
79
|
resolveAuth(request: GatewayAuthRequest): GatewayAuthResult | undefined;
|
|
80
|
+
/**
|
|
81
|
+
* The model a session calls. A custom provider wins over a built-in provider
|
|
82
|
+
* with the same id, and `args.headers` are Mastra's per-request headers.
|
|
83
|
+
*/
|
|
75
84
|
resolveLanguageModel(args: {
|
|
76
85
|
modelId: string;
|
|
77
86
|
providerId: string;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { AuthStorage } from "../auth/storage.js";
|
|
2
|
+
import { customProviderAuthHeaderName } from "../onboarding/custom-provider-headers.js";
|
|
2
3
|
import { getCustomProviderId, loadSettings } from "../onboarding/settings.js";
|
|
3
4
|
import { buildAnthropicOAuthFetch, claudeCodeMiddleware, createAnthropicThinkingMiddleware, createPromptCacheMiddleware, opencodeClaudeMaxProvider } from "../providers/claude-max.js";
|
|
4
5
|
import { githubCopilotProvider } from "../providers/github-copilot.js";
|
|
@@ -9,12 +10,12 @@ import { THINKING_LEVEL_TO_REASONING_EFFORT, buildOpenAICodexOAuthFetch, createC
|
|
|
9
10
|
import { ModelRouterLanguageModelWithThinking, providerThinkingOptions, withThinkingOptionsModel } from "../providers/provider-thinking.js";
|
|
10
11
|
import { xaiProvider } from "../providers/xai.js";
|
|
11
12
|
import { getAppDataDir } from "../utils/project.js";
|
|
13
|
+
import { createCustomProviderChatModel } from "./custom-provider-check.js";
|
|
12
14
|
import { resolveCustomProviders } from "./custom-provider-source.js";
|
|
13
15
|
import { GATEWAY_AUTH_HEADER, MastraGateway, MastraModelGateway, ModelRouterLanguageModel, PROVIDER_REGISTRY } from "@mastra/core/llm";
|
|
14
16
|
import { createOpenAI } from "@ai-sdk/openai";
|
|
15
17
|
import { wrapLanguageModel } from "ai";
|
|
16
18
|
import { createAnthropic } from "@ai-sdk/anthropic";
|
|
17
|
-
import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
|
|
18
19
|
// src/agents/mastracode-gateway.ts
|
|
19
20
|
const PROVIDERS = PROVIDER_REGISTRY;
|
|
20
21
|
const MASTRACODE_GATEWAY_ID = "mastracode";
|
|
@@ -174,11 +175,6 @@ function hasProviderEnvironmentKey(providerId) {
|
|
|
174
175
|
if (!envVars) return false;
|
|
175
176
|
return (Array.isArray(envVars) ? envVars : [envVars]).some((envVar) => Boolean(process.env[envVar]?.trim()));
|
|
176
177
|
}
|
|
177
|
-
/** Servers call custom endpoints too: a redirect could aim that call at an address the saved URL never named. */
|
|
178
|
-
const fetchWithoutRedirects = (input, init) => fetch(input, {
|
|
179
|
-
...init,
|
|
180
|
-
redirect: "error"
|
|
181
|
-
});
|
|
182
178
|
var MastraCodeGateway = class MastraCodeGateway extends MastraModelGateway {
|
|
183
179
|
id = MASTRACODE_GATEWAY_ID;
|
|
184
180
|
name = "MastraCode Gateway";
|
|
@@ -286,6 +282,7 @@ var MastraCodeGateway = class MastraCodeGateway extends MastraModelGateway {
|
|
|
286
282
|
if (this.#routeThroughMastraGateway) return void 0;
|
|
287
283
|
return this.#getCustomProviders().find((provider) => providerId === getCustomProviderId(provider.name));
|
|
288
284
|
}
|
|
285
|
+
/** The catalog entries for custom providers that list at least one model. */
|
|
289
286
|
async fetchProviders() {
|
|
290
287
|
this.#credentials.reload();
|
|
291
288
|
const providers = {};
|
|
@@ -296,7 +293,7 @@ var MastraCodeGateway = class MastraCodeGateway extends MastraModelGateway {
|
|
|
296
293
|
name: provider.name,
|
|
297
294
|
url: provider.url,
|
|
298
295
|
apiKeyEnvVar: "",
|
|
299
|
-
apiKeyHeader:
|
|
296
|
+
apiKeyHeader: customProviderAuthHeaderName(provider.authScheme),
|
|
300
297
|
gateway: this.id,
|
|
301
298
|
models
|
|
302
299
|
};
|
|
@@ -326,6 +323,10 @@ var MastraCodeGateway = class MastraCodeGateway extends MastraModelGateway {
|
|
|
326
323
|
} : { source: "gateway" };
|
|
327
324
|
return MastraCodeGateway.resolveProviderAuth(request, void 0, this.#credentials);
|
|
328
325
|
}
|
|
326
|
+
/**
|
|
327
|
+
* The model a session calls. A custom provider wins over a built-in provider
|
|
328
|
+
* with the same id, and `args.headers` are Mastra's per-request headers.
|
|
329
|
+
*/
|
|
329
330
|
resolveLanguageModel(args) {
|
|
330
331
|
const customProvider = this.#customProvider(args.providerId);
|
|
331
332
|
const selection = customProvider ? void 0 : parseCodexModelSelection(`${args.providerId}/${args.modelId}`);
|
|
@@ -335,18 +336,20 @@ var MastraCodeGateway = class MastraCodeGateway extends MastraModelGateway {
|
|
|
335
336
|
...selection.codexServiceTier ? { codexServiceTier: selection.codexServiceTier } : {}
|
|
336
337
|
};
|
|
337
338
|
if (customProvider) {
|
|
338
|
-
const
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
339
|
+
const model = createCustomProviderChatModel({
|
|
340
|
+
providerId: args.providerId,
|
|
341
|
+
connection: {
|
|
342
|
+
...customProvider,
|
|
343
|
+
apiKey: args.apiKey
|
|
344
|
+
},
|
|
345
|
+
modelId: args.modelId,
|
|
346
|
+
requestHeaders: args.headers
|
|
344
347
|
});
|
|
345
348
|
const reasoningEffort = this.#thinkingLevel ? THINKING_LEVEL_TO_REASONING_EFFORT[this.#thinkingLevel] : void 0;
|
|
346
349
|
const middleware = createReasoningEffortMiddleware(args.providerId, reasoningEffort);
|
|
347
|
-
if (!middleware) return
|
|
350
|
+
if (!middleware) return model;
|
|
348
351
|
return wrapLanguageModel({
|
|
349
|
-
model
|
|
352
|
+
model,
|
|
350
353
|
middleware: [middleware]
|
|
351
354
|
});
|
|
352
355
|
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Rules for the extra headers a custom OpenAI-compatible provider sends.
|
|
3
|
+
*
|
|
4
|
+
* This module imports nothing at runtime, so settings parsing, the TUI and the
|
|
5
|
+
* Factory routes can validate headers without loading the AI SDK.
|
|
6
|
+
*/
|
|
7
|
+
import type { CustomProviderAuthScheme } from './settings.js';
|
|
8
|
+
/** The most custom headers one provider may send. */
|
|
9
|
+
export declare const MAX_CUSTOM_PROVIDER_HEADERS = 20;
|
|
10
|
+
/** The longest custom header value accepted, in characters. */
|
|
11
|
+
export declare const MAX_CUSTOM_PROVIDER_HEADER_VALUE_LENGTH = 4096;
|
|
12
|
+
/**
|
|
13
|
+
* Header names a custom header may never use, in lower case. The HTTP client
|
|
14
|
+
* owns these, and a wrong value breaks or smuggles the request. The header the
|
|
15
|
+
* auth scheme writes is refused as well, see {@link customProviderAuthHeaderName}.
|
|
16
|
+
*/
|
|
17
|
+
export declare const REFUSED_CUSTOM_PROVIDER_HEADER_NAMES: readonly string[];
|
|
18
|
+
/**
|
|
19
|
+
* A C0 or C1 control character, including the ESC and CSI that start terminal
|
|
20
|
+
* escape sequences. Text from an endpoint or a request body is printed in the
|
|
21
|
+
* TUI, so every place that shows it uses this one definition. Not global, so
|
|
22
|
+
* `test` keeps no state; derive a global copy for `replace`.
|
|
23
|
+
*/
|
|
24
|
+
export declare const CONTROL_CHARACTER_PATTERN: RegExp;
|
|
25
|
+
/**
|
|
26
|
+
* The header the auth scheme writes the key into. A missing scheme means
|
|
27
|
+
* `bearer`, which is how providers saved before schemes existed authenticate.
|
|
28
|
+
*/
|
|
29
|
+
export declare function customProviderAuthHeaderName(authScheme: CustomProviderAuthScheme | undefined): string;
|
|
30
|
+
/** Whether a value read from settings or a request body is a known auth scheme. */
|
|
31
|
+
export declare function isCustomProviderAuthScheme(value: unknown): value is CustomProviderAuthScheme;
|
|
32
|
+
/**
|
|
33
|
+
* Why `headers` cannot be saved with `authScheme`, or undefined when they can.
|
|
34
|
+
*
|
|
35
|
+
* An entry without `value` is accepted, because an edit may keep a saved value
|
|
36
|
+
* by naming the header only. The caller decides whether a value is required.
|
|
37
|
+
* Entries are typed loosely because they often come straight from a request
|
|
38
|
+
* body, where a name or value may not be a string.
|
|
39
|
+
*/
|
|
40
|
+
export declare function customProviderHeaderProblem(headers: ReadonlyArray<{
|
|
41
|
+
name: unknown;
|
|
42
|
+
value?: unknown;
|
|
43
|
+
}>, authScheme: CustomProviderAuthScheme | undefined): string | undefined;
|
|
44
|
+
/**
|
|
45
|
+
* Merge header maps in order. Names are compared ignoring case and a later
|
|
46
|
+
* entry replaces an earlier one, keeping the later spelling. `fetch` would
|
|
47
|
+
* otherwise join `X-Foo` and `x-foo` into one comma-separated value.
|
|
48
|
+
*/
|
|
49
|
+
export declare function mergeHeadersIgnoringCase(...sources: Array<Record<string, string> | undefined>): Record<string, string>;
|
|
50
|
+
//# sourceMappingURL=custom-provider-headers.d.ts.map
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
// src/onboarding/custom-provider-headers.ts
|
|
2
|
+
/** The most custom headers one provider may send. */
|
|
3
|
+
const MAX_CUSTOM_PROVIDER_HEADERS = 20;
|
|
4
|
+
/** The longest custom header value accepted, in characters. */
|
|
5
|
+
const MAX_CUSTOM_PROVIDER_HEADER_VALUE_LENGTH = 4096;
|
|
6
|
+
/**
|
|
7
|
+
* Header names a custom header may never use, in lower case. The HTTP client
|
|
8
|
+
* owns these, and a wrong value breaks or smuggles the request. The header the
|
|
9
|
+
* auth scheme writes is refused as well, see {@link customProviderAuthHeaderName}.
|
|
10
|
+
*/
|
|
11
|
+
const REFUSED_CUSTOM_PROVIDER_HEADER_NAMES = [
|
|
12
|
+
"host",
|
|
13
|
+
"content-length",
|
|
14
|
+
"content-type",
|
|
15
|
+
"transfer-encoding",
|
|
16
|
+
"connection",
|
|
17
|
+
"keep-alive",
|
|
18
|
+
"upgrade",
|
|
19
|
+
"expect",
|
|
20
|
+
"te",
|
|
21
|
+
"trailer",
|
|
22
|
+
"proxy-connection"
|
|
23
|
+
];
|
|
24
|
+
/** The `token` grammar of RFC 9110, which every header name must match. */
|
|
25
|
+
const HEADER_NAME_PATTERN = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
26
|
+
/**
|
|
27
|
+
* Characters outside tab, printable ASCII and printable Latin-1. The HTTP
|
|
28
|
+
* client refuses ASCII control characters and anything above 0xFF at call
|
|
29
|
+
* time, so such a value would fail every request instead of failing when it
|
|
30
|
+
* is saved. The C1 controls (0x80 to 0x9F) are refused too: a plain value is
|
|
31
|
+
* shown in lists, and U+009B starts an escape sequence on terminals that act
|
|
32
|
+
* on 8-bit controls.
|
|
33
|
+
*/
|
|
34
|
+
const INVALID_HEADER_VALUE_CHARACTER = /[^\t\x20-\x7e\xa0-\xff]/;
|
|
35
|
+
/** The longest part of a refused header name repeated in the problem text. */
|
|
36
|
+
const MAX_QUOTED_NAME_LENGTH = 100;
|
|
37
|
+
/**
|
|
38
|
+
* A C0 or C1 control character, including the ESC and CSI that start terminal
|
|
39
|
+
* escape sequences. Text from an endpoint or a request body is printed in the
|
|
40
|
+
* TUI, so every place that shows it uses this one definition. Not global, so
|
|
41
|
+
* `test` keeps no state; derive a global copy for `replace`.
|
|
42
|
+
*/
|
|
43
|
+
const CONTROL_CHARACTER_PATTERN = /[\u0000-\u001f\u007f-\u009f]/;
|
|
44
|
+
/**
|
|
45
|
+
* A refused header name made safe to show. The name may come from a request
|
|
46
|
+
* body and end up in a terminal, so it is cut short and its control
|
|
47
|
+
* characters become spaces.
|
|
48
|
+
*/
|
|
49
|
+
function quotableName(name) {
|
|
50
|
+
const shown = name.slice(0, MAX_QUOTED_NAME_LENGTH).replace(new RegExp(CONTROL_CHARACTER_PATTERN.source, "g"), " ");
|
|
51
|
+
return name.length > MAX_QUOTED_NAME_LENGTH ? `${shown}...` : shown;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* The header the auth scheme writes the key into. A missing scheme means
|
|
55
|
+
* `bearer`, which is how providers saved before schemes existed authenticate.
|
|
56
|
+
*/
|
|
57
|
+
function customProviderAuthHeaderName(authScheme) {
|
|
58
|
+
return authScheme === "x-api-key" ? "x-api-key" : "Authorization";
|
|
59
|
+
}
|
|
60
|
+
/** Whether a value read from settings or a request body is a known auth scheme. */
|
|
61
|
+
function isCustomProviderAuthScheme(value) {
|
|
62
|
+
return value === "bearer" || value === "x-api-key";
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* Why `headers` cannot be saved with `authScheme`, or undefined when they can.
|
|
66
|
+
*
|
|
67
|
+
* An entry without `value` is accepted, because an edit may keep a saved value
|
|
68
|
+
* by naming the header only. The caller decides whether a value is required.
|
|
69
|
+
* Entries are typed loosely because they often come straight from a request
|
|
70
|
+
* body, where a name or value may not be a string.
|
|
71
|
+
*/
|
|
72
|
+
function customProviderHeaderProblem(headers, authScheme) {
|
|
73
|
+
if (!Array.isArray(headers)) return "Custom headers must be a list.";
|
|
74
|
+
if (headers.length > 20) return `A provider can send at most 20 custom headers.`;
|
|
75
|
+
const authHeader = customProviderAuthHeaderName(authScheme).toLowerCase();
|
|
76
|
+
const seen = /* @__PURE__ */ new Set();
|
|
77
|
+
for (const header of headers) {
|
|
78
|
+
if (typeof header !== "object" || header === null) return "Each custom header needs a name and a value.";
|
|
79
|
+
const { name, value } = header;
|
|
80
|
+
if (typeof name !== "string") return "Each custom header name must be text.";
|
|
81
|
+
if (!HEADER_NAME_PATTERN.test(name)) return `"${quotableName(name)}" is not a valid header name.`;
|
|
82
|
+
const lowerName = name.toLowerCase();
|
|
83
|
+
if (REFUSED_CUSTOM_PROVIDER_HEADER_NAMES.includes(lowerName)) return `The ${name} header is set by the HTTP client and cannot be sent as a custom header.`;
|
|
84
|
+
if (lowerName === authHeader) return `The ${name} header carries the API key for this auth scheme and cannot be sent as a custom header.`;
|
|
85
|
+
if (seen.has(lowerName)) return `The ${name} header is listed more than once.`;
|
|
86
|
+
seen.add(lowerName);
|
|
87
|
+
if (value === void 0) continue;
|
|
88
|
+
if (typeof value !== "string") return `The ${name} header value must be text.`;
|
|
89
|
+
if (value.trim().length === 0) return `The ${name} header has no value.`;
|
|
90
|
+
if (value.length > 4096) return `The ${name} header value is longer than ${MAX_CUSTOM_PROVIDER_HEADER_VALUE_LENGTH} characters.`;
|
|
91
|
+
if (/[\r\n]/.test(value)) return `The ${name} header value cannot contain a line break.`;
|
|
92
|
+
if (INVALID_HEADER_VALUE_CHARACTER.test(value)) return `The ${name} header value can only hold printable characters up to U+00FF.`;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Merge header maps in order. Names are compared ignoring case and a later
|
|
97
|
+
* entry replaces an earlier one, keeping the later spelling. `fetch` would
|
|
98
|
+
* otherwise join `X-Foo` and `x-foo` into one comma-separated value.
|
|
99
|
+
*/
|
|
100
|
+
function mergeHeadersIgnoringCase(...sources) {
|
|
101
|
+
const merged = /* @__PURE__ */ new Map();
|
|
102
|
+
for (const source of sources) {
|
|
103
|
+
if (!source) continue;
|
|
104
|
+
for (const [name, value] of Object.entries(source)) {
|
|
105
|
+
const key = name.toLowerCase();
|
|
106
|
+
merged.delete(key);
|
|
107
|
+
merged.set(key, [name, value]);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return Object.fromEntries(merged.values());
|
|
111
|
+
}
|
|
112
|
+
export { CONTROL_CHARACTER_PATTERN, MAX_CUSTOM_PROVIDER_HEADERS, MAX_CUSTOM_PROVIDER_HEADER_VALUE_LENGTH, REFUSED_CUSTOM_PROVIDER_HEADER_NAMES, customProviderAuthHeaderName, customProviderHeaderProblem, isCustomProviderAuthScheme, mergeHeadersIgnoringCase };
|
|
@@ -5,11 +5,22 @@ import { getCustomProviderId } from "./settings.js";
|
|
|
5
5
|
* providers. Shared by the TUI `/custom-providers` command and the web
|
|
6
6
|
* settings routes — no UI dependencies.
|
|
7
7
|
*/
|
|
8
|
+
/**
|
|
9
|
+
* Trim the fields a user typed, header names and values included, the way
|
|
10
|
+
* `parseCustomProviders` reads them back. Callers validate headers first.
|
|
11
|
+
*/
|
|
8
12
|
function normalizeProvider(input) {
|
|
13
|
+
const headers = input.headers?.map((header) => ({
|
|
14
|
+
...header,
|
|
15
|
+
name: header.name.trim(),
|
|
16
|
+
value: header.value.trim()
|
|
17
|
+
}));
|
|
9
18
|
return {
|
|
10
19
|
name: input.name.trim(),
|
|
11
20
|
url: input.url.trim(),
|
|
12
21
|
apiKey: input.apiKey?.trim() || void 0,
|
|
22
|
+
...input.authScheme ? { authScheme: input.authScheme } : {},
|
|
23
|
+
...headers?.length ? { headers } : {},
|
|
13
24
|
models: [...new Set(input.models.map((model) => model.trim()).filter(Boolean))]
|
|
14
25
|
};
|
|
15
26
|
}
|
|
@@ -16,11 +16,23 @@ export interface CustomPack {
|
|
|
16
16
|
models: Record<string, string>;
|
|
17
17
|
createdAt: string;
|
|
18
18
|
}
|
|
19
|
+
/** How a custom provider sends its API key: `Authorization: Bearer <key>` or `x-api-key: <key>`. */
|
|
20
|
+
export type CustomProviderAuthScheme = 'bearer' | 'x-api-key';
|
|
21
|
+
/** An extra header a custom provider sends on every call. */
|
|
22
|
+
export interface CustomProviderHeader {
|
|
23
|
+
name: string;
|
|
24
|
+
value: string;
|
|
25
|
+
/** Hidden in UIs and never returned by the Factory API. */
|
|
26
|
+
secret?: boolean;
|
|
27
|
+
}
|
|
19
28
|
/** A saved custom provider for OpenAI-compatible endpoints. */
|
|
20
29
|
export interface CustomProviderSetting {
|
|
21
30
|
name: string;
|
|
22
31
|
url: string;
|
|
23
32
|
apiKey?: string;
|
|
33
|
+
/** Absent means `bearer`. */
|
|
34
|
+
authScheme?: CustomProviderAuthScheme;
|
|
35
|
+
headers?: CustomProviderHeader[];
|
|
24
36
|
models: string[];
|
|
25
37
|
}
|
|
26
38
|
/** Storage backend type. */
|
|
@@ -389,6 +401,7 @@ export declare function toCustomProviderModelId(providerName: string, modelName:
|
|
|
389
401
|
* legitimate `mastracode/...` gateway-routed ids are left untouched.
|
|
390
402
|
*/
|
|
391
403
|
export declare function stripMastraCodeCustomProviderPrefix(modelId: string, customProviders: Array<Pick<CustomProviderSetting, 'name'>>): string;
|
|
404
|
+
/** Read and sanitize the `customProviders` list of settings.json. */
|
|
392
405
|
export declare function parseCustomProviders(rawProviders: unknown): CustomProviderSetting[];
|
|
393
406
|
/**
|
|
394
407
|
* Resolve the effective LSP config. LSP is opt-in: `false` and an absent
|
|
@@ -4,6 +4,7 @@ import { buildCodexStagehandFetch, createCodexMiddleware } from "../providers/op
|
|
|
4
4
|
import { THINKING_LEVEL_VALUES, isThinkingLevelSetting, resolveDefaultThinkingLevel as resolveDefaultThinkingLevel$1 } from "../thinking.js";
|
|
5
5
|
import { getAppDataDir } from "../utils/project.js";
|
|
6
6
|
import { DEFAULT_STT_PROVIDER, resolveSTTModel } from "../voice/stt-registry.js";
|
|
7
|
+
import { customProviderHeaderProblem, isCustomProviderAuthScheme } from "./custom-provider-headers.js";
|
|
7
8
|
import { pruneUnknownModePackFallbacks, pruneUnknownPackAccountPreferences } from "./packs.js";
|
|
8
9
|
import { dirname, join } from "path";
|
|
9
10
|
import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from "fs";
|
|
@@ -371,6 +372,28 @@ function stripMastraCodeCustomProviderPrefix(modelId, customProviders) {
|
|
|
371
372
|
if (!providerId || modelParts.length === 0 || modelParts.some((part) => part.length === 0)) return modelId;
|
|
372
373
|
return customProviders.some((provider) => getCustomProviderId(provider.name) === providerId) ? rest : modelId;
|
|
373
374
|
}
|
|
375
|
+
/**
|
|
376
|
+
* Read the custom headers of a saved provider. An entry that breaks the header
|
|
377
|
+
* rules is dropped on its own, so one bad hand-edited header does not discard
|
|
378
|
+
* the provider or its other headers.
|
|
379
|
+
*/
|
|
380
|
+
function parseCustomProviderHeaders(rawHeaders, authScheme) {
|
|
381
|
+
if (!Array.isArray(rawHeaders)) return [];
|
|
382
|
+
const headers = [];
|
|
383
|
+
for (const rawHeader of rawHeaders) {
|
|
384
|
+
if (!rawHeader || typeof rawHeader !== "object") continue;
|
|
385
|
+
const candidate = rawHeader;
|
|
386
|
+
if (typeof candidate.name !== "string" || typeof candidate.value !== "string") continue;
|
|
387
|
+
const header = {
|
|
388
|
+
name: candidate.name.trim(),
|
|
389
|
+
value: candidate.value.trim(),
|
|
390
|
+
...typeof candidate.secret === "boolean" ? { secret: candidate.secret } : {}
|
|
391
|
+
};
|
|
392
|
+
if (customProviderHeaderProblem([...headers, header], authScheme) === void 0) headers.push(header);
|
|
393
|
+
}
|
|
394
|
+
return headers;
|
|
395
|
+
}
|
|
396
|
+
/** Read and sanitize the `customProviders` list of settings.json. */
|
|
374
397
|
function parseCustomProviders(rawProviders) {
|
|
375
398
|
if (!Array.isArray(rawProviders)) return [];
|
|
376
399
|
const parsedProviders = [];
|
|
@@ -387,10 +410,14 @@ function parseCustomProviders(rawProviders) {
|
|
|
387
410
|
return model;
|
|
388
411
|
}))].filter((model) => model.length > 0) : [];
|
|
389
412
|
const apiKey = typeof candidate.apiKey === "string" && candidate.apiKey.trim().length > 0 ? candidate.apiKey.trim() : void 0;
|
|
413
|
+
const authScheme = isCustomProviderAuthScheme(candidate.authScheme) ? candidate.authScheme : void 0;
|
|
414
|
+
const headers = parseCustomProviderHeaders(candidate.headers, authScheme);
|
|
390
415
|
parsedProviders.push({
|
|
391
416
|
name,
|
|
392
417
|
url,
|
|
393
418
|
...apiKey ? { apiKey } : {},
|
|
419
|
+
...authScheme ? { authScheme } : {},
|
|
420
|
+
...headers.length > 0 ? { headers } : {},
|
|
394
421
|
models
|
|
395
422
|
});
|
|
396
423
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mastra/code-sdk",
|
|
3
|
-
"version": "1.22.0-alpha.
|
|
3
|
+
"version": "1.22.0-alpha.2",
|
|
4
4
|
"description": "Mastra Code SDK: the agent core behind Mastra Code (everything except the TUI) — build your own UIs and surfaces on top of it",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"publishConfig": {
|
|
@@ -65,19 +65,19 @@
|
|
|
65
65
|
"yaml": "^2.9.1",
|
|
66
66
|
"zod": "^4.6.7",
|
|
67
67
|
"@mastra/agent-browser": "0.7.0",
|
|
68
|
-
"@mastra/client-js": "1.62.1-alpha.
|
|
68
|
+
"@mastra/client-js": "1.62.1-alpha.2",
|
|
69
69
|
"@mastra/duckdb": "1.19.2",
|
|
70
|
-
"@mastra/github-signals": "0.5.4",
|
|
71
70
|
"@mastra/fastembed": "1.4.0",
|
|
71
|
+
"@mastra/github-signals": "0.5.4",
|
|
72
72
|
"@mastra/libsql": "1.33.0-alpha.0",
|
|
73
73
|
"@mastra/mcp": "2.11.0",
|
|
74
|
+
"@mastra/memory": "1.41.3",
|
|
74
75
|
"@mastra/observability": "1.24.4-alpha.0",
|
|
75
76
|
"@mastra/parallel": "0.1.6",
|
|
76
|
-
"@mastra/memory": "1.41.3",
|
|
77
77
|
"@mastra/pg": "1.39.0-alpha.0",
|
|
78
78
|
"@mastra/schema-compat": "1.4.1",
|
|
79
|
-
"@mastra/tavily": "1.1.4",
|
|
80
79
|
"@mastra/stagehand": "0.4.1",
|
|
80
|
+
"@mastra/tavily": "1.1.4",
|
|
81
81
|
"@mastra/voice-deepgram": "0.13.5",
|
|
82
82
|
"@mastra/voice-mistral": "0.1.4",
|
|
83
83
|
"@mastra/voice-openai": "0.13.5"
|
|
@@ -92,10 +92,10 @@
|
|
|
92
92
|
"tsx": "^4.23.15",
|
|
93
93
|
"typescript": "^6.0.3",
|
|
94
94
|
"vitest": "5.1.0",
|
|
95
|
-
"@
|
|
95
|
+
"@mastra/core": "1.87.0-alpha.2",
|
|
96
96
|
"@internal/types-builder": "0.0.127",
|
|
97
|
-
"@
|
|
98
|
-
"@internal/
|
|
97
|
+
"@internal/workspace-test-utils": "0.0.96",
|
|
98
|
+
"@internal/lint": "0.0.152"
|
|
99
99
|
},
|
|
100
100
|
"peerDependencies": {
|
|
101
101
|
"@mastra/core": ">=1.86.0-0 <2.0.0-0"
|