UNPKG

@mastra/core

Version:
1,546 lines (1,545 loc) • 293 kB
const require_rolldown_runtime = require("./rolldown-runtime-uwYp4b74.cjs"); const require_inmemory = require("./inmemory-CVHnncRp.cjs"); const require_error = require("./error-B-e62x-A.cjs"); const require_request_context = require("./request-context-ByoZMp-j.cjs"); const require_content = require("./content-fINNgB3A.cjs"); const require_dist = require("./dist-C4NOluIY.cjs"); const require_model = require("./model-CxJfDXLP.cjs"); const require_gateway_helpers = require("./gateway-helpers-CdK-tcyA.cjs"); const require_models_dev = require("./models-dev-B-wg68cr.cjs"); const require_provider_registry = require("./provider-registry-Bv8eMxuW.cjs"); const require_netlify = require("./netlify-DDJM4IYB.cjs"); let crypto = require("crypto"); let zod_v4 = require("zod/v4"); zod_v4 = require_rolldown_runtime.__toESM(zod_v4, 1); let zod_v3 = require("zod/v3"); let ws = require("ws"); ws = require_rolldown_runtime.__toESM(ws, 1); //#region src/stream/types.ts let ChunkFrom = /* @__PURE__ */ function(ChunkFrom) { ChunkFrom["AGENT"] = "AGENT"; ChunkFrom["USER"] = "USER"; ChunkFrom["SYSTEM"] = "SYSTEM"; ChunkFrom["WORKFLOW"] = "WORKFLOW"; ChunkFrom["NETWORK"] = "NETWORK"; return ChunkFrom; }({}); const MASTRA_MODEL_STREAM_TRANSPORT = Symbol.for("@mastra/core.modelStreamTransport"); function attachModelStreamTransport(target, transport) { if (!transport) return; Object.defineProperty(target, MASTRA_MODEL_STREAM_TRANSPORT, { configurable: true, value: transport }); } function readModelStreamTransport(target) { return target?.[MASTRA_MODEL_STREAM_TRANSPORT]; } //#endregion //#region src/llm/model/aisdk/v6/model.ts /** * Remaps tool types from V2 format ('provider-defined') to V3 format ('provider'). * Tools may arrive in V2 format when prepared upstream (e.g., by ToolBuilder or * prepareToolsAndToolChoice) without knowing the final model version. This ensures * provider tools (like openai.tools.webSearch()) work correctly with V3 models. */ function remapToolsToV3(options) { if (!options.tools?.length) return options; const remappedTools = options.tools.map((tool) => { if (tool.type === "provider-defined") return { ...tool, type: "provider" }; return tool; }); return { ...options, tools: remappedTools }; } /** * Wrapper class for AI SDK V6 (LanguageModelV3) that converts doGenerate to return * a stream format for consistency with Mastra's streaming architecture. */ var AISDKV6LanguageModel = class { /** * The language model must specify which language model interface version it implements. */ specificationVersion = "v3"; /** * Name of the provider for logging purposes. */ provider; /** * Provider-specific model ID for logging purposes. */ modelId; /** * Supported URL patterns by media type for the provider. * * The keys are media type patterns or full media types (e.g. `*\/*` for everything, `audio/*`, `video/*`, or `application/pdf`). * and the values are arrays of regular expressions that match the URL paths. * The matching should be against lower-case URLs. * Matched URLs are supported natively by the model and are not downloaded. * @returns A map of supported URL patterns by media type (as a promise or a plain object). */ supportedUrls; #model; constructor(config) { this.#model = config; this.provider = this.#model.provider; this.modelId = this.#model.modelId; this.supportedUrls = this.#model.supportedUrls; } async doGenerate(options) { const result = await this.#model.doGenerate(remapToolsToV3(options)); return { ...result, request: result.request, response: result.response, stream: require_model.createStreamFromGenerateResult(result) }; } async doStream(options) { return await this.#model.doStream(remapToolsToV3(options)); } /** * Custom serialization for tracing/observability spans. * `#model` is already a true JS private field and not enumerable, so * the wrapped provider SDK client can't leak. This method makes the * safe shape explicit and avoids walking `supportedUrls` (a * PromiseLike / regex map that isn't useful in spans). */ serializeForSpan() { return { specificationVersion: this.specificationVersion, modelId: this.modelId, provider: this.provider }; } }; //#endregion //#region src/llm/model/aisdk/v7/model.ts /** * Remaps tool types from V2 format ('provider-defined') to V4 format ('provider'). * Tools may arrive in V2 format when prepared upstream (e.g., by ToolBuilder or * prepareToolsAndToolChoice) without knowing the final model version. This ensures * provider tools (like openai.tools.webSearch()) work correctly with V4 models. * * V4 shares the V3 convention ('provider'), so the same remap applies. */ function remapToolsToV4(options) { if (!options.tools?.length) return options; const remappedTools = options.tools.map((tool) => { if (tool.type === "provider-defined") return { ...tool, type: "provider" }; return tool; }); return { ...options, tools: remappedTools }; } function isTaggedV4FileData(data) { if (typeof data !== "object" || data === null || !("type" in data)) return false; const type = data.type; return type === "data" || type === "url" || type === "reference" || type === "text"; } /** * The Agent loop calls V4 providers directly, bypassing AI SDK v7's prompt * conversion. Agent prompts may therefore still contain V2/V3 flat file data. * Convert that legacy shape while preserving already-normalized V4 data. */ function normalizeFileDataForV4(data) { if (isTaggedV4FileData(data)) return { data }; const { data: convertedData, mediaType } = require_content.convertToDataContent(data); return { data: convertedData instanceof URL ? { type: "url", url: convertedData } : { type: "data", data: convertedData }, mediaType }; } function remapFilePartsToV4(options) { let promptModified = false; const prompt = options.prompt.map((message) => { if (message.role !== "user" && message.role !== "assistant") return message; let contentModified = false; const content = message.content.map((part) => { if (part.type !== "file") return part; const { data, mediaType } = normalizeFileDataForV4(part.data); if (data === part.data && mediaType == null) return part; contentModified = true; return { ...part, data, mediaType: mediaType ?? part.mediaType }; }); if (!contentModified) return message; promptModified = true; return { ...message, content }; }); return promptModified ? { ...options, prompt } : options; } function remapCallOptionsToV4(options) { return remapToolsToV4(remapFilePartsToV4(options)); } /** * V4 responses tag generated file data ({type: 'data' | 'url'}), but Mastra's * shared response pipeline (chunk transforms, file buffering, message * persistence) expects the flat V2/V3 shape (base64 string | Uint8Array). * Untag before handing results to the shared pipeline so file chunks and * persisted message history keep the flat contract. This applies to both * 'file' and 'reasoning-file' parts, which carry the same tagged data shape. * * Response file data is typed as the 'data' | 'url' variants only, so this * guard is exhaustive for well-formed responses. Other tagged variants * ('reference' | 'text') have no flat equivalent and pass through untouched. */ function isUntaggableV4ResponseFileData(data) { if (typeof data !== "object" || data === null || !("type" in data)) return false; return data.type === "data" || data.type === "url"; } function untagV4ResponseFileData(data) { return data.type === "url" ? data.url.toString() : data.data; } function isFilePartType(type) { return type === "file" || type === "reasoning-file"; } function untagResponseFileContent(content) { let contentModified = false; const untagged = content.map((part) => { if (!isFilePartType(part.type) || !("data" in part) || !isUntaggableV4ResponseFileData(part.data)) return part; contentModified = true; return { ...part, data: untagV4ResponseFileData(part.data) }; }); return contentModified ? untagged : content; } function untagFileStreamParts(stream) { return stream.pipeThrough(new TransformStream({ transform(part, controller) { if (isFilePartType(part.type) && "data" in part && isUntaggableV4ResponseFileData(part.data)) controller.enqueue({ ...part, data: untagV4ResponseFileData(part.data) }); else controller.enqueue(part); } })); } /** * Wrapper class for AI SDK V7 (LanguageModelV4) that converts doGenerate to return * a stream format for consistency with Mastra's streaming architecture. */ var AISDKV7LanguageModel = class { /** * The language model must specify which language model interface version it implements. */ specificationVersion = "v4"; /** * Name of the provider for logging purposes. */ provider; /** * Provider-specific model ID for logging purposes. */ modelId; /** * Supported URL patterns by media type for the provider. * * The keys are media type patterns or full media types (e.g. `*\/*` for everything, `audio/*`, `video/*`, or `application/pdf`). * and the values are arrays of regular expressions that match the URL paths. * The matching should be against lower-case URLs. * Matched URLs are supported natively by the model and are not downloaded. * @returns A map of supported URL patterns by media type (as a promise or a plain object). */ supportedUrls; #model; constructor(config) { this.#model = config; this.provider = this.#model.provider; this.modelId = this.#model.modelId; this.supportedUrls = this.#model.supportedUrls; } async doGenerate(options) { const result = await this.#model.doGenerate(remapCallOptionsToV4(options)); const content = untagResponseFileContent(result.content); const untaggedResult = content === result.content ? result : { ...result, content }; return { ...untaggedResult, request: result.request, response: result.response, stream: require_model.createStreamFromGenerateResult(untaggedResult) }; } async doStream(options) { const result = await this.#model.doStream(remapCallOptionsToV4(options)); return { ...result, stream: untagFileStreamParts(result.stream) }; } /** * Custom serialization for tracing/observability spans. * `#model` is already a true JS private field and not enumerable, so * the wrapped provider SDK client can't leak. This method makes the * safe shape explicit and avoids walking `supportedUrls` (a * PromiseLike / regex map that isn't useful in spans). */ serializeForSpan() { return { specificationVersion: this.specificationVersion, modelId: this.modelId, provider: this.provider }; } }; //#endregion //#region src/llm/model/gateways/defaults.ts function getStaticProvidersByGateway(name) { return Object.fromEntries(Object.entries(require_provider_registry.PROVIDER_REGISTRY).filter(([_provider, config]) => config.gateway === name)); } const defaultGateways = [ new require_netlify.NetlifyGateway(), new require_provider_registry.MastraGateway(), new require_models_dev.ModelsDevGateway(getStaticProvidersByGateway(`models.dev`)) ]; //#endregion //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/provider/2.0.3/baf9ca0bc6c1e850f5a9c142d47d3731e6921106a5f2b12483df7e7922a48657/node_modules/@ai-sdk/provider/dist/index.mjs var marker$1 = "vercel.ai.error"; var symbol$1 = Symbol.for(marker$1); var _a$1; var _b$1; var AISDKError = class _AISDKError extends (_b$1 = Error, _a$1 = symbol$1, _b$1) { /** * Creates an AI SDK Error. * * @param {Object} params - The parameters for creating the error. * @param {string} params.name - The name of the error. * @param {string} params.message - The error message. * @param {unknown} [params.cause] - The underlying cause of the error. */ constructor({ name: name14, message, cause }) { super(message); this[_a$1] = true; this.name = name14; this.cause = cause; } /** * Checks if the given error is an AI SDK Error. * @param {unknown} error - The error to check. * @returns {boolean} True if the error is an AI SDK Error, false otherwise. */ static isInstance(error) { return _AISDKError.hasMarker(error, marker$1); } static hasMarker(error, marker15) { const markerSymbol = Symbol.for(marker15); return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true; } }; var name$1 = "AI_APICallError"; var marker2 = `vercel.ai.error.${name$1}`; var symbol2 = Symbol.for(marker2); var _a2; var _b2; var APICallError = class extends (_b2 = AISDKError, _a2 = symbol2, _b2) { constructor({ message, url, requestBodyValues, statusCode, responseHeaders, responseBody, cause, isRetryable = statusCode != null && (statusCode === 408 || statusCode === 409 || statusCode === 429 || statusCode >= 500), data }) { super({ name: name$1, message, cause }); this[_a2] = true; this.url = url; this.requestBodyValues = requestBodyValues; this.statusCode = statusCode; this.responseHeaders = responseHeaders; this.responseBody = responseBody; this.isRetryable = isRetryable; this.data = data; } static isInstance(error) { return AISDKError.hasMarker(error, marker2); } }; var name2 = "AI_EmptyResponseBodyError"; var marker3 = `vercel.ai.error.${name2}`; var symbol3 = Symbol.for(marker3); var _a3; var _b3; var EmptyResponseBodyError = class extends (_b3 = AISDKError, _a3 = symbol3, _b3) { constructor({ message = "Empty response body" } = {}) { super({ name: name2, message }); this[_a3] = true; } static isInstance(error) { return AISDKError.hasMarker(error, marker3); } }; function getErrorMessage(error) { if (error == null) return "unknown error"; if (typeof error === "string") return error; if (error instanceof Error) return error.message; return JSON.stringify(error); } var name3 = "AI_InvalidArgumentError"; var marker4 = `vercel.ai.error.${name3}`; var symbol4 = Symbol.for(marker4); var _a4; var _b4; var InvalidArgumentError = class extends (_b4 = AISDKError, _a4 = symbol4, _b4) { constructor({ message, cause, argument }) { super({ name: name3, message, cause }); this[_a4] = true; this.argument = argument; } static isInstance(error) { return AISDKError.hasMarker(error, marker4); } }; var name4 = "AI_InvalidPromptError"; var marker5 = `vercel.ai.error.${name4}`; var symbol5 = Symbol.for(marker5); var _a5; var _b5; var InvalidPromptError = class extends (_b5 = AISDKError, _a5 = symbol5, _b5) { constructor({ prompt, message, cause }) { super({ name: name4, message: `Invalid prompt: ${message}`, cause }); this[_a5] = true; this.prompt = prompt; } static isInstance(error) { return AISDKError.hasMarker(error, marker5); } }; var name5 = "AI_InvalidResponseDataError"; var marker6 = `vercel.ai.error.${name5}`; var symbol6 = Symbol.for(marker6); var _a6; var _b6; var InvalidResponseDataError = class extends (_b6 = AISDKError, _a6 = symbol6, _b6) { constructor({ data, message = `Invalid response data: ${JSON.stringify(data)}.` }) { super({ name: name5, message }); this[_a6] = true; this.data = data; } static isInstance(error) { return AISDKError.hasMarker(error, marker6); } }; var name6 = "AI_JSONParseError"; var marker7 = `vercel.ai.error.${name6}`; var symbol7 = Symbol.for(marker7); var _a7; var _b7; var JSONParseError = class extends (_b7 = AISDKError, _a7 = symbol7, _b7) { constructor({ text, cause }) { super({ name: name6, message: `JSON parsing failed: Text: ${text}. Error message: ${getErrorMessage(cause)}`, cause }); this[_a7] = true; this.text = text; } static isInstance(error) { return AISDKError.hasMarker(error, marker7); } }; var name7 = "AI_LoadAPIKeyError"; var marker8 = `vercel.ai.error.${name7}`; var symbol8 = Symbol.for(marker8); var _a8; var _b8; var LoadAPIKeyError = class extends (_b8 = AISDKError, _a8 = symbol8, _b8) { constructor({ message }) { super({ name: name7, message }); this[_a8] = true; } static isInstance(error) { return AISDKError.hasMarker(error, marker8); } }; var name8 = "AI_LoadSettingError"; var marker9 = `vercel.ai.error.${name8}`; var symbol9 = Symbol.for(marker9); var _a9; var _b9; var LoadSettingError = class extends (_b9 = AISDKError, _a9 = symbol9, _b9) { constructor({ message }) { super({ name: name8, message }); this[_a9] = true; } static isInstance(error) { return AISDKError.hasMarker(error, marker9); } }; var name9 = "AI_NoContentGeneratedError"; var marker10 = `vercel.ai.error.${name9}`; var symbol10 = Symbol.for(marker10); var _a10; var _b10; (class extends (_b10 = AISDKError, _a10 = symbol10, _b10) { constructor({ message = "No content generated." } = {}) { super({ name: name9, message }); this[_a10] = true; } static isInstance(error) { return AISDKError.hasMarker(error, marker10); } }); var name10 = "AI_NoSuchModelError"; var marker11 = `vercel.ai.error.${name10}`; var symbol11 = Symbol.for(marker11); var _a11; var _b11; (class extends (_b11 = AISDKError, _a11 = symbol11, _b11) { constructor({ errorName = name10, modelId, modelType, message = `No such ${modelType}: ${modelId}` }) { super({ name: errorName, message }); this[_a11] = true; this.modelId = modelId; this.modelType = modelType; } static isInstance(error) { return AISDKError.hasMarker(error, marker11); } }); var name11 = "AI_TooManyEmbeddingValuesForCallError"; var marker12 = `vercel.ai.error.${name11}`; var symbol12 = Symbol.for(marker12); var _a12; var _b12; var TooManyEmbeddingValuesForCallError = class extends (_b12 = AISDKError, _a12 = symbol12, _b12) { constructor(options) { super({ name: name11, message: `Too many values for a single embedding call. The ${options.provider} model "${options.modelId}" can only embed up to ${options.maxEmbeddingsPerCall} values per call, but ${options.values.length} values were provided.` }); this[_a12] = true; this.provider = options.provider; this.modelId = options.modelId; this.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall; this.values = options.values; } static isInstance(error) { return AISDKError.hasMarker(error, marker12); } }; var name12 = "AI_TypeValidationError"; var marker13 = `vercel.ai.error.${name12}`; var symbol13 = Symbol.for(marker13); var _a13; var _b13; var TypeValidationError = class _TypeValidationError extends (_b13 = AISDKError, _a13 = symbol13, _b13) { constructor({ value, cause }) { super({ name: name12, message: `Type validation failed: Value: ${JSON.stringify(value)}. Error message: ${getErrorMessage(cause)}`, cause }); this[_a13] = true; this.value = value; } static isInstance(error) { return AISDKError.hasMarker(error, marker13); } /** * Wraps an error into a TypeValidationError. * If the cause is already a TypeValidationError with the same value, it returns the cause. * Otherwise, it creates a new TypeValidationError. * * @param {Object} params - The parameters for wrapping the error. * @param {unknown} params.value - The value that failed validation. * @param {unknown} params.cause - The original error or cause of the validation failure. * @returns {TypeValidationError} A TypeValidationError instance. */ static wrap({ value, cause }) { return _TypeValidationError.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError({ value, cause }); } }; var name13 = "AI_UnsupportedFunctionalityError"; var marker14 = `vercel.ai.error.${name13}`; var symbol14 = Symbol.for(marker14); var _a14; var _b14; var UnsupportedFunctionalityError = class extends (_b14 = AISDKError, _a14 = symbol14, _b14) { constructor({ functionality, message = `'${functionality}' functionality not supported.` }) { super({ name: name13, message }); this[_a14] = true; this.functionality = functionality; } static isInstance(error) { return AISDKError.hasMarker(error, marker14); } }; //#endregion //#region ../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@ai-sdk/provider-utils/3.0.31/ec2b02e652373362f632ec2c411694343ca859aa4cde84046d95e39a09d5a1ac/node_modules/@ai-sdk/provider-utils/dist/index.mjs function combineHeaders(...headers) { return headers.reduce((combinedHeaders, currentHeaders) => ({ ...combinedHeaders, ...currentHeaders != null ? currentHeaders : {} }), {}); } function extractResponseHeaders(response) { return Object.fromEntries([...response.headers]); } var name = "AI_DownloadError"; var marker = `vercel.ai.error.${name}`; var symbol = Symbol.for(marker); var _a; var _b; var DownloadError = class extends (_b = AISDKError, _a = symbol, _b) { constructor({ url, statusCode, statusText, cause, message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}` }) { super({ name, message, cause }); this[_a] = true; this.url = url; this.statusCode = statusCode; this.statusText = statusText; } static isInstance(error) { return AISDKError.hasMarker(error, marker); } }; async function cancelResponseBody(response) { var _a2; try { await ((_a2 = response.body) == null ? void 0 : _a2.cancel()); } catch (e) {} } var initialGlobalFetch = globalThis.fetch; isNodeDefaultFetch(initialGlobalFetch); function isNodeDefaultFetch(fetch) { const source = Function.prototype.toString.call(fetch); return source.includes("internal/deps/undici") || source.includes("lazy loading of undici"); } var DEFAULT_MAX_DOWNLOAD_SIZE = 2 * 1024 * 1024 * 1024; async function readResponseWithSizeLimit({ response, url, maxBytes = DEFAULT_MAX_DOWNLOAD_SIZE }) { const contentLength = response.headers.get("content-length"); if (contentLength != null) { const length = parseInt(contentLength, 10); if (!isNaN(length) && length > maxBytes) { await cancelResponseBody(response); throw new DownloadError({ url, message: `Download of ${url} exceeded maximum size of ${maxBytes} bytes (Content-Length: ${length}).` }); } } const body = response.body; if (body == null) return /* @__PURE__ */ new Uint8Array(0); const reader = body.getReader(); const chunks = []; let totalBytes = 0; try { while (true) { const { done, value } = await reader.read(); if (done) break; totalBytes += value.length; if (totalBytes > maxBytes) throw new DownloadError({ url, message: `Download of ${url} exceeded maximum size of ${maxBytes} bytes.` }); chunks.push(value); } } finally { try { await reader.cancel(); } finally { reader.releaseLock(); } } const result = new Uint8Array(totalBytes); let offset = 0; for (const chunk of chunks) { result.set(chunk, offset); offset += chunk.length; } return result; } var createIdGenerator = ({ prefix, size = 16, alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", separator = "-" } = {}) => { const generator = () => { const alphabetLength = alphabet.length; const chars = new Array(size); for (let i = 0; i < size; i++) chars[i] = alphabet[Math.random() * alphabetLength | 0]; return chars.join(""); }; if (prefix == null) return generator; if (alphabet.includes(separator)) throw new InvalidArgumentError({ argument: "separator", message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".` }); return () => `${prefix}${separator}${generator()}`; }; var generateId = createIdGenerator(); function isAbortError(error) { return (error instanceof Error || error instanceof DOMException) && (error.name === "AbortError" || error.name === "ResponseAborted" || error.name === "TimeoutError"); } var FETCH_FAILED_ERROR_MESSAGES = ["fetch failed", "failed to fetch"]; function handleFetchError({ error, url, requestBodyValues }) { if (isAbortError(error)) return error; if (error instanceof TypeError && FETCH_FAILED_ERROR_MESSAGES.includes(error.message.toLowerCase())) { const cause = error.cause; if (cause != null) return new APICallError({ message: `Cannot connect to API: ${cause.message}`, cause, url, requestBodyValues, isRetryable: true }); } return error; } function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) { var _a2, _b2, _c; if (globalThisAny.window) return `runtime/browser`; if ((_a2 = globalThisAny.navigator) == null ? void 0 : _a2.userAgent) return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`; if ((_c = (_b2 = globalThisAny.process) == null ? void 0 : _b2.versions) == null ? void 0 : _c.node) return `runtime/node.js/${globalThisAny.process.version.substring(0)}`; if (globalThisAny.EdgeRuntime) return `runtime/vercel-edge`; return "runtime/unknown"; } function normalizeHeaders$1(headers) { if (headers == null) return {}; const normalized = {}; if (headers instanceof Headers) headers.forEach((value, key) => { normalized[key.toLowerCase()] = value; }); else { if (!Array.isArray(headers)) headers = Object.entries(headers); for (const [key, value] of headers) if (value != null) normalized[key.toLowerCase()] = value; } return normalized; } function withUserAgentSuffix(headers, ...userAgentSuffixParts) { const normalizedHeaders = new Headers(normalizeHeaders$1(headers)); const currentUserAgentHeader = normalizedHeaders.get("user-agent") || ""; normalizedHeaders.set("user-agent", [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" ")); return Object.fromEntries(normalizedHeaders.entries()); } var VERSION$1 = "3.0.31"; function loadApiKey({ apiKey, environmentVariableName, apiKeyParameterName = "apiKey", description }) { if (typeof apiKey === "string") return apiKey; if (apiKey != null) throw new LoadAPIKeyError({ message: `${description} API key must be a string.` }); if (typeof process === "undefined") throw new LoadAPIKeyError({ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.` }); apiKey = process.env[environmentVariableName]; if (apiKey == null) throw new LoadAPIKeyError({ message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.` }); if (typeof apiKey !== "string") throw new LoadAPIKeyError({ message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.` }); return apiKey; } function loadSetting({ settingValue, environmentVariableName, settingName, description }) { if (typeof settingValue === "string") return settingValue; if (settingValue != null) throw new LoadSettingError({ message: `${description} setting must be a string.` }); if (typeof process === "undefined") throw new LoadSettingError({ message: `${description} setting is missing. Pass it using the '${settingName}' parameter. Environment variables is not supported in this environment.` }); settingValue = process.env[environmentVariableName]; if (settingValue == null) throw new LoadSettingError({ message: `${description} setting is missing. Pass it using the '${settingName}' parameter or the ${environmentVariableName} environment variable.` }); if (typeof settingValue !== "string") throw new LoadSettingError({ message: `${description} setting must be a string. The value of the ${environmentVariableName} environment variable is not a string.` }); return settingValue; } function mediaTypeToExtension(mediaType) { var _a2; const [_type, subtype = ""] = mediaType.toLowerCase().split("/"); return (_a2 = { mpeg: "mp3", "x-wav": "wav", opus: "ogg", mp4: "m4a", "x-m4a": "m4a" }[subtype]) != null ? _a2 : subtype; } var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/; var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/; function _parse(text) { const obj = JSON.parse(text); if (obj === null || typeof obj !== "object") return obj; if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) return obj; return filter(obj); } function filter(obj) { let next = [obj]; while (next.length) { const nodes = next; next = []; for (const node of nodes) { if (Object.prototype.hasOwnProperty.call(node, "__proto__")) throw new SyntaxError("Object contains forbidden prototype property"); if (Object.prototype.hasOwnProperty.call(node, "constructor") && node.constructor !== null && typeof node.constructor === "object" && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) throw new SyntaxError("Object contains forbidden prototype property"); for (const key in node) { const value = node[key]; if (value && typeof value === "object") next.push(value); } } } return obj; } function secureJsonParse(text) { const { stackTraceLimit } = Error; try { Error.stackTraceLimit = 0; } catch (e) { return _parse(text); } try { return _parse(text); } finally { Error.stackTraceLimit = stackTraceLimit; } } var validatorSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.validator"); function validator(validate) { return { [validatorSymbol]: true, validate }; } function isValidator(value) { return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value; } function lazyValidator(createValidator) { let validator2; return () => { if (validator2 == null) validator2 = createValidator(); return validator2; }; } function asValidator(value) { return isValidator(value) ? value : "~standard" in value ? standardSchemaValidator(value) : value(); } function standardSchemaValidator(standardSchema) { return validator(async (value) => { const result = await standardSchema["~standard"].validate(value); return result.issues == null ? { success: true, value: result.value } : { success: false, error: new TypeValidationError({ value, cause: result.issues }) }; }); } async function validateTypes({ value, schema }) { const result = await safeValidateTypes({ value, schema }); if (!result.success) throw TypeValidationError.wrap({ value, cause: result.error }); return result.value; } async function safeValidateTypes({ value, schema }) { const validator2 = asValidator(schema); try { if (validator2.validate == null) return { success: true, value, rawValue: value }; const result = await validator2.validate(value); if (result.success) return { success: true, value: result.value, rawValue: value }; return { success: false, error: TypeValidationError.wrap({ value, cause: result.error }), rawValue: value }; } catch (error) { return { success: false, error: TypeValidationError.wrap({ value, cause: error }), rawValue: value }; } } async function parseJSON({ text, schema }) { try { const value = secureJsonParse(text); if (schema == null) return value; return validateTypes({ value, schema }); } catch (error) { if (JSONParseError.isInstance(error) || TypeValidationError.isInstance(error)) throw error; throw new JSONParseError({ text, cause: error }); } } async function safeParseJSON({ text, schema }) { try { const value = secureJsonParse(text); if (schema == null) return { success: true, value, rawValue: value }; return await safeValidateTypes({ value, schema }); } catch (error) { return { success: false, error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error }), rawValue: void 0 }; } } function isParsableJson(input) { try { secureJsonParse(input); return true; } catch (e) { return false; } } function parseJsonEventStream({ stream, schema }) { return stream.pipeThrough(new TextDecoderStream()).pipeThrough(new require_dist.EventSourceParserStream()).pipeThrough(new TransformStream({ async transform({ data }, controller) { if (data === "[DONE]") return; controller.enqueue(await safeParseJSON({ text: data, schema })); } })); } async function parseProviderOptions({ provider, providerOptions, schema }) { if ((providerOptions == null ? void 0 : providerOptions[provider]) == null) return; const parsedProviderOptions = await safeValidateTypes({ value: providerOptions[provider], schema }); if (!parsedProviderOptions.success) throw new InvalidArgumentError({ argument: "providerOptions", message: `invalid ${provider} provider options`, cause: parsedProviderOptions.error }); return parsedProviderOptions.value; } var getOriginalFetch2 = () => globalThis.fetch; var postJsonToApi = async ({ url, headers, body, failedResponseHandler, successfulResponseHandler, abortSignal, fetch }) => postToApi({ url, headers: { "Content-Type": "application/json", ...headers }, body: { content: JSON.stringify(body), values: body }, failedResponseHandler, successfulResponseHandler, abortSignal, fetch }); var postFormDataToApi = async ({ url, headers, formData, failedResponseHandler, successfulResponseHandler, abortSignal, fetch }) => postToApi({ url, headers, body: { content: formData, values: Object.fromEntries(formData.entries()) }, failedResponseHandler, successfulResponseHandler, abortSignal, fetch }); var postToApi = async ({ url, headers = {}, body, successfulResponseHandler, failedResponseHandler, abortSignal, fetch = getOriginalFetch2() }) => { try { const response = await fetch(url, { method: "POST", headers: withUserAgentSuffix(headers, `ai-sdk/provider-utils/${VERSION$1}`, getRuntimeEnvironmentUserAgent()), body: body.content, signal: abortSignal }); const responseHeaders = extractResponseHeaders(response); if (!response.ok) { let errorInformation; try { errorInformation = await failedResponseHandler({ response, url, requestBodyValues: body.values }); } catch (error) { if (isAbortError(error) || APICallError.isInstance(error)) throw error; throw new APICallError({ message: "Failed to process error response", cause: error, statusCode: response.status, url, responseHeaders, requestBodyValues: body.values }); } throw errorInformation.value; } try { return await successfulResponseHandler({ response, url, requestBodyValues: body.values }); } catch (error) { if (error instanceof Error) { if (isAbortError(error) || APICallError.isInstance(error)) throw error; } throw new APICallError({ message: "Failed to process successful response", cause: error, statusCode: response.status, url, responseHeaders, requestBodyValues: body.values }); } } catch (error) { throw handleFetchError({ error, url, requestBodyValues: body.values }); } }; function tool(tool2) { return tool2; } function createProviderDefinedToolFactoryWithOutputSchema({ id, name: name2, inputSchema, outputSchema }) { return ({ execute, toModelOutput, onInputStart, onInputDelta, onInputAvailable, ...args }) => tool({ type: "provider-defined", id, name: name2, args, inputSchema, outputSchema, execute, toModelOutput, onInputStart, onInputDelta, onInputAvailable }); } var textDecoder = new TextDecoder(); async function readResponseBodyAsText({ response, url }) { return textDecoder.decode(await readResponseWithSizeLimit({ response, url })); } var createJsonErrorResponseHandler = ({ errorSchema, errorToMessage, isRetryable }) => async ({ response, url, requestBodyValues }) => { const responseBody = await readResponseBodyAsText({ response, url }); const responseHeaders = extractResponseHeaders(response); if (responseBody.trim() === "") return { responseHeaders, value: new APICallError({ message: response.statusText, url, requestBodyValues, statusCode: response.status, responseHeaders, responseBody, isRetryable: isRetryable == null ? void 0 : isRetryable(response) }) }; try { const parsedError = await parseJSON({ text: responseBody, schema: errorSchema }); return { responseHeaders, value: new APICallError({ message: errorToMessage(parsedError), url, requestBodyValues, statusCode: response.status, responseHeaders, responseBody, data: parsedError, isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError) }) }; } catch (parseError) { return { responseHeaders, value: new APICallError({ message: response.statusText, url, requestBodyValues, statusCode: response.status, responseHeaders, responseBody, isRetryable: isRetryable == null ? void 0 : isRetryable(response) }) }; } }; var createEventSourceResponseHandler = (chunkSchema) => async ({ response }) => { const responseHeaders = extractResponseHeaders(response); if (response.body == null) throw new EmptyResponseBodyError({}); return { responseHeaders, value: parseJsonEventStream({ stream: response.body, schema: chunkSchema }) }; }; var createJsonResponseHandler = (responseSchema) => async ({ response, url, requestBodyValues }) => { const responseBody = await readResponseBodyAsText({ response, url }); const parsedResult = await safeParseJSON({ text: responseBody, schema: responseSchema }); const responseHeaders = extractResponseHeaders(response); if (!parsedResult.success) throw new APICallError({ message: "Invalid JSON response", cause: parsedResult.error, statusCode: response.status, responseHeaders, responseBody, url, requestBodyValues }); return { responseHeaders, value: parsedResult.value, rawValue: parsedResult.rawValue }; }; var createBinaryResponseHandler = () => async ({ response, url, requestBodyValues }) => { const responseHeaders = extractResponseHeaders(response); if (!response.body) throw new APICallError({ message: "Response body is empty", url, requestBodyValues, statusCode: response.status, responseHeaders, responseBody: void 0 }); try { const buffer = await response.arrayBuffer(); return { responseHeaders, value: new Uint8Array(buffer) }; } catch (error) { throw new APICallError({ message: "Failed to read response as array buffer", url, requestBodyValues, statusCode: response.status, responseHeaders, responseBody: void 0, cause: error }); } }; var schemaSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.schema"); function lazySchema(createSchema) { let schema; return () => { if (schema == null) schema = createSchema(); return schema; }; } function jsonSchema(jsonSchema2, { validate } = {}) { return { [schemaSymbol]: true, _type: void 0, [validatorSymbol]: true, get jsonSchema() { if (typeof jsonSchema2 === "function") jsonSchema2 = jsonSchema2(); return jsonSchema2; }, validate }; } function addAdditionalPropertiesToJsonSchema(jsonSchema2) { if (jsonSchema2.type === "object") { jsonSchema2.additionalProperties = false; const properties = jsonSchema2.properties; if (properties != null) for (const property in properties) properties[property] = addAdditionalPropertiesToJsonSchema(properties[property]); } if (jsonSchema2.type === "array" && jsonSchema2.items != null) if (Array.isArray(jsonSchema2.items)) jsonSchema2.items = jsonSchema2.items.map((item) => addAdditionalPropertiesToJsonSchema(item)); else jsonSchema2.items = addAdditionalPropertiesToJsonSchema(jsonSchema2.items); return jsonSchema2; } var ignoreOverride = /* @__PURE__ */ Symbol("Let zodToJsonSchema decide on which parser to use"); var defaultOptions = { name: void 0, $refStrategy: "root", basePath: ["#"], effectStrategy: "input", pipeStrategy: "all", dateStrategy: "format:date-time", mapStrategy: "entries", removeAdditionalStrategy: "passthrough", allowedAdditionalProperties: true, rejectedAdditionalProperties: false, definitionPath: "definitions", strictUnions: false, definitions: {}, errorMessages: false, patternStrategy: "escape", applyRegexFlags: false, emailStrategy: "format:email", base64Strategy: "contentEncoding:base64", nameStrategy: "ref" }; var getDefaultOptions = (options) => typeof options === "string" ? { ...defaultOptions, name: options } : { ...defaultOptions, ...options }; function parseAnyDef() { return {}; } function parseArrayDef(def, refs) { var _a2, _b2, _c; const res = { type: "array" }; if (((_a2 = def.type) == null ? void 0 : _a2._def) && ((_c = (_b2 = def.type) == null ? void 0 : _b2._def) == null ? void 0 : _c.typeName) !== zod_v3.ZodFirstPartyTypeKind.ZodAny) res.items = parseDef(def.type._def, { ...refs, currentPath: [...refs.currentPath, "items"] }); if (def.minLength) res.minItems = def.minLength.value; if (def.maxLength) res.maxItems = def.maxLength.value; if (def.exactLength) { res.minItems = def.exactLength.value; res.maxItems = def.exactLength.value; } return res; } function parseBigintDef(def) { const res = { type: "integer", format: "int64" }; if (!def.checks) return res; for (const check of def.checks) switch (check.kind) { case "min": if (check.inclusive) res.minimum = check.value; else res.exclusiveMinimum = check.value; break; case "max": if (check.inclusive) res.maximum = check.value; else res.exclusiveMaximum = check.value; break; case "multipleOf": res.multipleOf = check.value; break; } return res; } function parseBooleanDef() { return { type: "boolean" }; } function parseBrandedDef(_def, refs) { return parseDef(_def.type._def, refs); } var parseCatchDef = (def, refs) => { return parseDef(def.innerType._def, refs); }; function parseDateDef(def, refs, overrideDateStrategy) { const strategy = overrideDateStrategy != null ? overrideDateStrategy : refs.dateStrategy; if (Array.isArray(strategy)) return { anyOf: strategy.map((item, i) => parseDateDef(def, refs, item)) }; switch (strategy) { case "string": case "format:date-time": return { type: "string", format: "date-time" }; case "format:date": return { type: "string", format: "date" }; case "integer": return integerDateParser(def); } } var integerDateParser = (def) => { const res = { type: "integer", format: "unix-time" }; for (const check of def.checks) switch (check.kind) { case "min": res.minimum = check.value; break; case "max": res.maximum = check.value; break; } return res; }; function parseDefaultDef(_def, refs) { return { ...parseDef(_def.innerType._def, refs), default: _def.defaultValue() }; } function parseEffectsDef(_def, refs) { return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef(); } function parseEnumDef(def) { return { type: "string", enum: Array.from(def.values) }; } var isJsonSchema7AllOfType = (type) => { if ("type" in type && type.type === "string") return false; return "allOf" in type; }; function parseIntersectionDef(def, refs) { const allOf = [parseDef(def.left._def, { ...refs, currentPath: [ ...refs.currentPath, "allOf", "0" ] }), parseDef(def.right._def, { ...refs, currentPath: [ ...refs.currentPath, "allOf", "1" ] })].filter((x) => !!x); const mergedAllOf = []; allOf.forEach((schema) => { if (isJsonSchema7AllOfType(schema)) mergedAllOf.push(...schema.allOf); else { let nestedSchema = schema; if ("additionalProperties" in schema && schema.additionalProperties === false) { const { additionalProperties, ...rest } = schema; nestedSchema = rest; } mergedAllOf.push(nestedSchema); } }); return mergedAllOf.length ? { allOf: mergedAllOf } : void 0; } function parseLiteralDef(def) { const parsedType = typeof def.value; if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") return { type: Array.isArray(def.value) ? "array" : "object" }; return { type: parsedType === "bigint" ? "integer" : parsedType, const: def.value }; } var emojiRegex = void 0; var zodPatterns = { /** * `c` was changed to `[cC]` to replicate /i flag */ cuid: /^[cC][^\s-]{8,}$/, cuid2: /^[0-9a-z]+$/, ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/, /** * `a-z` was added to replicate /i flag */ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/, /** * Constructed a valid Unicode RegExp * * Lazily instantiate since this type of regex isn't supported * in all envs (e.g. React Native). * * See: * https://github.com/colinhacks/zod/issues/2433 * Fix in Zod: * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b */ emoji: () => { if (emojiRegex === void 0) emojiRegex = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u"); return emojiRegex; }, /** * Unused */ uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/, /** * Unused */ ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/, ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/, /** * Unused */ ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/, base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/, nanoid: /^[a-zA-Z0-9_-]{21}$/, jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/ }; function parseStringDef(def, refs) { const res = { type: "string" }; if (def.checks) for (const check of def.checks) switch (check.kind) { case "min": res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value; break; case "max": res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value; break; case "email": switch (refs.emailStrategy) { case "format:email": addFormat(res, "email", check.message, refs); break; case "format:idn-email": addFormat(res, "idn-email", check.message, refs); break; case "pattern:zod": addPattern(res, zodPatterns.email, check.message, refs); break; } break; case "url": addFormat(res, "uri", check.message, refs); break; case "uuid": addFormat(res, "uuid", check.message, refs); break; case "regex": addPattern(res, check.regex, check.message, refs); break; case "cuid": addPattern(res, zodPatterns.cuid, check.message, refs); break; case "cuid2": addPattern(res, zodPatterns.cuid2, check.message, refs); break; case "startsWith": addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs); break; case "endsWith": addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs); break; case "datetime": addFormat(res, "date-time", check.message, refs); break; case "date": addFormat(res, "date", check.message, refs); break; case "time": addFormat(res, "time", check.message, refs); break; case "duration": addFormat(res, "duration", check.message, refs); break; case "length": res.minLength = typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value; res.maxLength = typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value; break; case "includes": addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs); break; case "ip": if (check.version !== "v6") addFormat(res, "ipv4", check.message, refs); if (check.version !== "v4") addFormat(res, "ipv6", check.message, refs); break; case "base64url": addPattern(res, zodPatterns.base64url, check.message, refs); break; case "jwt": addPattern(res, zodPatterns.jwt, check.message, refs); break; case "cidr": if (check.version !== "v6") addPattern(res, zodPatterns.ipv4Cidr, check.message, refs); if (check.version !== "v4") addPattern(res, zodPatterns.ipv6Cidr, check.message, refs); break; case "emoji": addPattern(res, zodPatterns.emoji(), check.message, refs); break; case "ulid": addPattern(res, zodPatterns.ulid, check.message, refs); break; case "base64": switch (refs.base64Strategy) { case "format:binary": addFormat(res, "binary", check.message, refs); break; case "contentEncoding:base64": res.contentEncoding = "base64"; break; case "pattern:zod": addPattern(res, zodPatterns.base64, check.message, refs);