UNPKG

@mastra/core

Version:

Mastra is a framework for building AI-powered applications and agents with a modern TypeScript stack.

1,745 lines (1,739 loc) • 841 kB
import { __export, __reExport } from './chunk-TM6AOUSD.js'; import * as z4 from 'zod/v4'; import { z } from 'zod/v4'; import { ZodFirstPartyTypeKind } from 'zod/v3'; import * as spec_star from '@standard-schema/spec'; // ../../node_modules/.pnpm/@ai-sdk+provider@2.0.3/node_modules/@ai-sdk/provider/dist/index.mjs var marker = "vercel.ai.error"; var symbol = Symbol.for(marker); var _a; var _b; var AISDKError = class _AISDKError extends (_b = Error, _a = symbol, _b) { /** * 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: name142, message, cause }) { super(message); this[_a] = true; this.name = name142; 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); } static hasMarker(error, marker152) { const markerSymbol = Symbol.for(marker152); return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true; } }; var name = "AI_APICallError"; var marker2 = `vercel.ai.error.${name}`; 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 || // request timeout statusCode === 409 || // conflict statusCode === 429 || // too many requests statusCode >= 500), // server error data }) { super({ name, 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) { // used in isInstance 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) { // used in isInstance 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) { // used in isInstance constructor({ message }) { super({ name: name8, message }); this[_a9] = true; } static isInstance(error) { return AISDKError.hasMarker(error, marker9); } }; var name10 = "AI_NoSuchModelError"; var marker11 = `vercel.ai.error.${name10}`; var symbol11 = Symbol.for(marker11); var _a11; var _b11; var NoSuchModelError = 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); } }; // ../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.25_zod@4.3.6/node_modules/@ai-sdk/provider-utils/dist/index.mjs var dist_exports = {}; __export(dist_exports, { DEFAULT_MAX_DOWNLOAD_SIZE: () => DEFAULT_MAX_DOWNLOAD_SIZE, DelayedPromise: () => DelayedPromise, DownloadError: () => DownloadError, EventSourceParserStream: () => EventSourceParserStream, VERSION: () => VERSION, asSchema: () => asSchema, asValidator: () => asValidator, combineHeaders: () => combineHeaders, convertAsyncIteratorToReadableStream: () => convertAsyncIteratorToReadableStream, convertBase64ToUint8Array: () => convertBase64ToUint8Array, convertToBase64: () => convertToBase64, convertUint8ArrayToBase64: () => convertUint8ArrayToBase64, createBinaryResponseHandler: () => createBinaryResponseHandler, createEventSourceResponseHandler: () => createEventSourceResponseHandler, createIdGenerator: () => createIdGenerator, createJsonErrorResponseHandler: () => createJsonErrorResponseHandler, createJsonResponseHandler: () => createJsonResponseHandler, createJsonStreamResponseHandler: () => createJsonStreamResponseHandler, createProviderDefinedToolFactory: () => createProviderDefinedToolFactory, createProviderDefinedToolFactoryWithOutputSchema: () => createProviderDefinedToolFactoryWithOutputSchema, createStatusCodeErrorResponseHandler: () => createStatusCodeErrorResponseHandler, delay: () => delay, dynamicTool: () => dynamicTool, executeTool: () => executeTool, extractResponseHeaders: () => extractResponseHeaders, generateId: () => generateId, getErrorMessage: () => getErrorMessage2, getFromApi: () => getFromApi, getRuntimeEnvironmentUserAgent: () => getRuntimeEnvironmentUserAgent, injectJsonInstructionIntoMessages: () => injectJsonInstructionIntoMessages, isAbortError: () => isAbortError, isParsableJson: () => isParsableJson, isUrlSupported: () => isUrlSupported, isValidator: () => isValidator, jsonSchema: () => jsonSchema, lazySchema: () => lazySchema, lazyValidator: () => lazyValidator, loadApiKey: () => loadApiKey, loadOptionalSetting: () => loadOptionalSetting, loadSetting: () => loadSetting, mediaTypeToExtension: () => mediaTypeToExtension, normalizeHeaders: () => normalizeHeaders, parseJSON: () => parseJSON, parseJsonEventStream: () => parseJsonEventStream, parseProviderOptions: () => parseProviderOptions, postFormDataToApi: () => postFormDataToApi, postJsonToApi: () => postJsonToApi, postToApi: () => postToApi, readResponseWithSizeLimit: () => readResponseWithSizeLimit, removeUndefinedEntries: () => removeUndefinedEntries, resolve: () => resolve, safeParseJSON: () => safeParseJSON, safeValidateTypes: () => safeValidateTypes, standardSchemaValidator: () => standardSchemaValidator, tool: () => tool, validateDownloadUrl: () => validateDownloadUrl, validateTypes: () => validateTypes, validator: () => validator, withUserAgentSuffix: () => withUserAgentSuffix, withoutTrailingSlash: () => withoutTrailingSlash, zodSchema: () => zodSchema }); // ../../node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/dist/index.js var ParseError = class extends Error { constructor(message, options) { super(message), this.name = "ParseError", this.type = options.type, this.field = options.field, this.value = options.value, this.line = options.line; } }; function noop(_arg) { } function createParser(callbacks) { if (typeof callbacks == "function") throw new TypeError( "`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?" ); const { onEvent = noop, onError = noop, onRetry = noop, onComment } = callbacks; let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = ""; function feed(newChunk) { const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines(`${incompleteLine}${chunk}`); for (const line of complete) parseLine(line); incompleteLine = incomplete, isFirstChunk = false; } function parseLine(line) { if (line === "") { dispatchEvent(); return; } if (line.startsWith(":")) { onComment && onComment(line.slice(line.startsWith(": ") ? 2 : 1)); return; } const fieldSeparatorIndex = line.indexOf(":"); if (fieldSeparatorIndex !== -1) { const field = line.slice(0, fieldSeparatorIndex), offset = line[fieldSeparatorIndex + 1] === " " ? 2 : 1, value = line.slice(fieldSeparatorIndex + offset); processField(field, value, line); return; } processField(line, "", line); } function processField(field, value, line) { switch (field) { case "event": eventType = value; break; case "data": data = `${data}${value} `; break; case "id": id = value.includes("\0") ? void 0 : value; break; case "retry": /^\d+$/.test(value) ? onRetry(parseInt(value, 10)) : onError( new ParseError(`Invalid \`retry\` value: "${value}"`, { type: "invalid-retry", value, line }) ); break; default: onError( new ParseError( `Unknown field "${field.length > 20 ? `${field.slice(0, 20)}\u2026` : field}"`, { type: "unknown-field", field, value, line } ) ); break; } } function dispatchEvent() { data.length > 0 && onEvent({ id, event: eventType || void 0, // If the data buffer's last character is a U+000A LINE FEED (LF) character, // then remove the last character from the data buffer. data: data.endsWith(` `) ? data.slice(0, -1) : data }), id = void 0, data = "", eventType = ""; } function reset(options = {}) { incompleteLine && options.consume && parseLine(incompleteLine), isFirstChunk = true, id = void 0, data = "", eventType = "", incompleteLine = ""; } return { feed, reset }; } function splitLines(chunk) { const lines = []; let incompleteLine = "", searchIndex = 0; for (; searchIndex < chunk.length; ) { const crIndex = chunk.indexOf("\r", searchIndex), lfIndex = chunk.indexOf(` `, searchIndex); let lineEnd = -1; if (crIndex !== -1 && lfIndex !== -1 ? lineEnd = Math.min(crIndex, lfIndex) : crIndex !== -1 ? crIndex === chunk.length - 1 ? lineEnd = -1 : lineEnd = crIndex : lfIndex !== -1 && (lineEnd = lfIndex), lineEnd === -1) { incompleteLine = chunk.slice(searchIndex); break; } else { const line = chunk.slice(searchIndex, lineEnd); lines.push(line), searchIndex = lineEnd + 1, chunk[searchIndex - 1] === "\r" && chunk[searchIndex] === ` ` && searchIndex++; } } return [lines, incompleteLine]; } // ../../node_modules/.pnpm/eventsource-parser@3.0.6/node_modules/eventsource-parser/dist/stream.js var EventSourceParserStream = class extends TransformStream { constructor({ onError, onRetry, onComment } = {}) { let parser; super({ start(controller) { parser = createParser({ onEvent: (event) => { controller.enqueue(event); }, onError(error) { onError === "terminate" ? controller.error(error) : typeof onError == "function" && onError(error); }, onRetry, onComment }); }, transform(chunk) { parser.feed(chunk); } }); } }; // ../../node_modules/.pnpm/@ai-sdk+provider-utils@3.0.25_zod@4.3.6/node_modules/@ai-sdk/provider-utils/dist/index.mjs __reExport(dist_exports, spec_star); function combineHeaders(...headers) { return headers.reduce( (combinedHeaders, currentHeaders) => ({ ...combinedHeaders, ...currentHeaders != null ? currentHeaders : {} }), {} ); } function convertAsyncIteratorToReadableStream(iterator) { let cancelled = false; return new ReadableStream({ /** * Called when the consumer wants to pull more data from the stream. * * @param {ReadableStreamDefaultController<T>} controller - The controller to enqueue data into the stream. * @returns {Promise<void>} */ async pull(controller) { if (cancelled) return; try { const { value, done } = await iterator.next(); if (done) { controller.close(); } else { controller.enqueue(value); } } catch (error) { controller.error(error); } }, /** * Called when the consumer cancels the stream. */ async cancel(reason) { cancelled = true; if (iterator.return) { try { await iterator.return(reason); } catch (e) { } } } }); } async function delay(delayInMs, options) { if (delayInMs == null) { return Promise.resolve(); } const signal = options == null ? void 0 : options.abortSignal; return new Promise((resolve22, reject) => { if (signal == null ? void 0 : signal.aborted) { reject(createAbortError()); return; } const timeoutId = setTimeout(() => { cleanup(); resolve22(); }, delayInMs); const cleanup = () => { clearTimeout(timeoutId); signal == null ? void 0 : signal.removeEventListener("abort", onAbort); }; const onAbort = () => { cleanup(); reject(createAbortError()); }; signal == null ? void 0 : signal.addEventListener("abort", onAbort); }); } function createAbortError() { return new DOMException("Delay was aborted", "AbortError"); } var DelayedPromise = class { constructor() { this.status = { type: "pending" }; this._resolve = void 0; this._reject = void 0; } get promise() { if (this._promise) { return this._promise; } this._promise = new Promise((resolve22, reject) => { if (this.status.type === "resolved") { resolve22(this.status.value); } else if (this.status.type === "rejected") { reject(this.status.error); } this._resolve = resolve22; this._reject = reject; }); return this._promise; } resolve(value) { var _a23; this.status = { type: "resolved", value }; if (this._promise) { (_a23 = this._resolve) == null ? void 0 : _a23.call(this, value); } } reject(error) { var _a23; this.status = { type: "rejected", error }; if (this._promise) { (_a23 = this._reject) == null ? void 0 : _a23.call(this, error); } } isResolved() { return this.status.type === "resolved"; } isRejected() { return this.status.type === "rejected"; } isPending() { return this.status.type === "pending"; } }; function extractResponseHeaders(response) { return Object.fromEntries([...response.headers]); } var name14 = "AI_DownloadError"; var marker15 = `vercel.ai.error.${name14}`; var symbol15 = Symbol.for(marker15); var _a15; var _b15; var DownloadError = class extends (_b15 = AISDKError, _a15 = symbol15, _b15) { constructor({ url, statusCode, statusText, cause, message = cause == null ? `Failed to download ${url}: ${statusCode} ${statusText}` : `Failed to download ${url}: ${cause}` }) { super({ name: name14, message, cause }); this[_a15] = true; this.url = url; this.statusCode = statusCode; this.statusText = statusText; } static isInstance(error) { return AISDKError.hasMarker(error, marker15); } }; 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) { 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 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 getErrorMessage2(error) { if (error == null) { return "unknown error"; } if (typeof error === "string") { return error; } if (error instanceof Error) { return error.message; } return JSON.stringify(error); } function isAbortError(error) { return (error instanceof Error || error instanceof DOMException) && (error.name === "AbortError" || error.name === "ResponseAborted" || // Next.js 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 // retry when network error }); } } return error; } function getRuntimeEnvironmentUserAgent(globalThisAny = globalThis) { var _a23, _b23, _c; if (globalThisAny.window) { return `runtime/browser`; } if ((_a23 = globalThisAny.navigator) == null ? void 0 : _a23.userAgent) { return `runtime/${globalThisAny.navigator.userAgent.toLowerCase()}`; } if ((_c = (_b23 = globalThisAny.process) == null ? void 0 : _b23.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(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(headers)); const currentUserAgentHeader = normalizedHeaders.get("user-agent") || ""; normalizedHeaders.set( "user-agent", [currentUserAgentHeader, ...userAgentSuffixParts].filter(Boolean).join(" ") ); return Object.fromEntries(normalizedHeaders.entries()); } var VERSION = "3.0.25" ; var getOriginalFetch = () => globalThis.fetch; var getFromApi = async ({ url, headers = {}, successfulResponseHandler, failedResponseHandler, abortSignal, fetch: fetch2 = getOriginalFetch() }) => { try { const response = await fetch2(url, { method: "GET", headers: withUserAgentSuffix( headers, `ai-sdk/provider-utils/${VERSION}`, getRuntimeEnvironmentUserAgent() ), signal: abortSignal }); const responseHeaders = extractResponseHeaders(response); if (!response.ok) { let errorInformation; try { errorInformation = await failedResponseHandler({ response, url, requestBodyValues: {} }); } 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: {} }); } throw errorInformation.value; } try { return await successfulResponseHandler({ response, url, requestBodyValues: {} }); } 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: {} }); } } catch (error) { throw handleFetchError({ error, url, requestBodyValues: {} }); } }; var DEFAULT_SCHEMA_PREFIX = "JSON schema:"; var DEFAULT_SCHEMA_SUFFIX = "You MUST answer with a JSON object that matches the JSON schema above."; var DEFAULT_GENERIC_SUFFIX = "You MUST answer with JSON."; function injectJsonInstruction({ prompt, schema, schemaPrefix = schema != null ? DEFAULT_SCHEMA_PREFIX : void 0, schemaSuffix = schema != null ? DEFAULT_SCHEMA_SUFFIX : DEFAULT_GENERIC_SUFFIX }) { return [ prompt != null && prompt.length > 0 ? prompt : void 0, prompt != null && prompt.length > 0 ? "" : void 0, // add a newline if prompt is not null schemaPrefix, schema != null ? JSON.stringify(schema) : void 0, schemaSuffix ].filter((line) => line != null).join("\n"); } function injectJsonInstructionIntoMessages({ messages, schema, schemaPrefix, schemaSuffix }) { var _a23, _b23; const systemMessage = ((_a23 = messages[0]) == null ? void 0 : _a23.role) === "system" ? { ...messages[0] } : { role: "system", content: "" }; systemMessage.content = injectJsonInstruction({ prompt: systemMessage.content, schema, schemaPrefix, schemaSuffix }); return [ systemMessage, ...((_b23 = messages[0]) == null ? void 0 : _b23.role) === "system" ? messages.slice(1) : messages ]; } function isUrlSupported({ mediaType, url, supportedUrls }) { url = url.toLowerCase(); mediaType = mediaType.toLowerCase(); return Object.entries(supportedUrls).map(([key, value]) => { const mediaType2 = key.toLowerCase(); return mediaType2 === "*" || mediaType2 === "*/*" ? { mediaTypePrefix: "", regexes: value } : { mediaTypePrefix: mediaType2.replace(/\*/, ""), regexes: value }; }).filter(({ mediaTypePrefix }) => mediaType.startsWith(mediaTypePrefix)).flatMap(({ regexes }) => regexes).some((pattern) => pattern.test(url)); } 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 loadOptionalSetting({ settingValue, environmentVariableName }) { if (typeof settingValue === "string") { return settingValue; } if (settingValue != null || typeof process === "undefined") { return void 0; } settingValue = process.env[environmentVariableName]; if (settingValue == null || typeof settingValue !== "string") { return void 0; } return settingValue; } 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 _a23; const [_type, subtype = ""] = mediaType.toLowerCase().split("/"); return (_a23 = { mpeg: "mp3", "x-wav": "wav", opus: "ogg", mp4: "m4a", "x-m4a": "m4a" }[subtype]) != null ? _a23 : 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 : typeof value === "function" ? value() : standardSchemaValidator(value); } function standardSchemaValidator(standardSchema2) { return validator(async (value) => { const result = await standardSchema2["~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 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 void 0; } 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: fetch2 }) => postToApi({ url, headers: { "Content-Type": "application/json", ...headers }, body: { content: JSON.stringify(body), values: body }, failedResponseHandler, successfulResponseHandler, abortSignal, fetch: fetch2 }); var postFormDataToApi = async ({ url, headers, formData, failedResponseHandler, successfulResponseHandler, abortSignal, fetch: fetch2 }) => postToApi({ url, headers, body: { content: formData, values: Object.fromEntries(formData.entries()) }, failedResponseHandler, successfulResponseHandler, abortSignal, fetch: fetch2 }); var postToApi = async ({ url, headers = {}, body, successfulResponseHandler, failedResponseHandler, abortSignal, fetch: fetch2 = getOriginalFetch2() }) => { try { const response = await fetch2(url, { method: "POST", headers: withUserAgentSuffix( headers, `ai-sdk/provider-utils/${VERSION}`, 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(tool22) { return tool22; } function dynamicTool(tool22) { return { ...tool22, type: "dynamic" }; } function createProviderDefinedToolFactory({ id, name: name23, inputSchema }) { return ({ execute, outputSchema, toModelOutput, onInputStart, onInputDelta, onInputAvailable, ...args }) => tool({ type: "provider-defined", id, name: name23, args, inputSchema, outputSchema, execute, toModelOutput, onInputStart, onInputDelta, onInputAvailable }); } function createProviderDefinedToolFactoryWithOutputSchema({ id, name: name23, inputSchema, outputSchema }) { return ({ execute, toModelOutput, onInputStart, onInputDelta, onInputAvailable, ...args }) => tool({ type: "provider-defined", id, name: name23, args, inputSchema, outputSchema, execute, toModelOutput, onInputStart, onInputDelta, onInputAvailable }); } function removeUndefinedEntries(record) { return Object.fromEntries( Object.entries(record).filter(([_key, value]) => value != null) ); } async function resolve(value) { if (typeof value === "function") { value = value(); } return Promise.resolve(value); } var createJsonErrorResponseHandler = ({ errorSchema, errorToMessage, isRetryable }) => async ({ response, url, requestBodyValues }) => { const responseBody = await response.text(); 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 = (chunkSchema2) => async ({ response }) => { const responseHeaders = extractResponseHeaders(response); if (response.body == null) { throw new EmptyResponseBodyError({}); } return { responseHeaders, value: parseJsonEventStream({ stream: response.body, schema: chunkSchema2 }) }; }; var createJsonStreamResponseHandler = (chunkSchema2) => async ({ response }) => { const responseHeaders = extractResponseHeaders(response); if (response.body == null) { throw new EmptyResponseBodyError({}); } let buffer = ""; return { responseHeaders, value: response.body.pipeThrough(new TextDecoderStream()).pipeThrough( new TransformStream({ async transform(chunkText, controller) { if (chunkText.endsWith("\n")) { controller.enqueue( await safeParseJSON({ text: buffer + chunkText, schema: chunkSchema2 }) ); buffer = ""; } else { buffer += chunkText; } } }) ) }; }; var createJsonResponseHandler = (responseSchema2) => async ({ response, url, requestBodyValues }) => { const responseBody = await response.text(); const parsedResult = await safeParseJSON({ text: responseBody, schema: responseSchema2 }); 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 createStatusCodeErrorResponseHandler = () => async ({ response, url, requestBodyValues }) => { const responseHeaders = extractResponseHeaders(response); const responseBody = await response.text(); return { responseHeaders, value: new APICallError({ message: response.statusText, url, requestBodyValues, statusCode: response.status, responseHeaders, responseBody }) }; }; var schemaSymbol = /* @__PURE__ */ Symbol.for("vercel.ai.schema"); function lazySchema(createSchema) { let schema; return () => { if (schema == null) { schema = createSchema(); } return schema; }; } function jsonSchema(jsonSchema22, { validate } = {}) { return { [schemaSymbol]: true, _type: void 0, // should never be used directly [validatorSymbol]: true, get jsonSchema() { if (typeof jsonSchema22 === "function") { jsonSchema22 = jsonSchema22(); } return jsonSchema22; }, validate }; } function addAdditionalPropertiesToJsonSchema(jsonSchema22) { if (jsonSchema22.type === "object") { jsonSchema22.additionalProperties = false; const properties = jsonSchema22.properties; if (properties != null) { for (const property in properties) { properties[property] = addAdditionalPropertiesToJsonSchema( properties[property] ); } } } if (jsonSchema22.type === "array" && jsonSchema22.items != null) { if (Array.isArray(jsonSchema22.items)) { jsonSchema22.items = jsonSchema22.items.map( (item) => addAdditionalPropertiesToJsonSchema(item) ); } else { jsonSchema22.items = addAdditionalPropertiesToJsonSchema( jsonSchema22.items ); } } return jsonSchema22; } 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 _a23, _b23, _c; const res = { type: "array" }; if (((_a23 = def.type) == null ? void 0 : _a23._def) && ((_c = (_b23 = def.type) == null ? void 0 : _b23._def) == null ? void 0 : _c.typeName) !== 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;