UNPKG

@eko-ai/eko

Version:

Empowering language to transform human words into action.

1,608 lines (1,584 loc) 1.55 MB
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var buffer = require('buffer'); const config$1 = { name: "Eko", mode: "normal", platform: "mac", maxReactNum: 500, maxOutputTokens: 16000, maxRetryNum: 3, agentParallel: false, workflowConfirm: false, compressThreshold: 80, compressTokensThreshold: 80000, largeTextLength: 8000, fileTextMaxLength: 20000, maxDialogueImgFileNum: 1, toolResultMultimodal: true, parallelToolCalls: true, markImageMode: "draw", expertModeTodoLoopNum: 10, memoryConfig: { maxMessageNum: 15, maxInputTokens: 64000, enableCompression: true, compressionThreshold: 10, compressionMaxLength: 6000, }, }; var LogLevel; (function (LogLevel) { LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG"; LogLevel[LogLevel["INFO"] = 1] = "INFO"; LogLevel[LogLevel["WARN"] = 2] = "WARN"; LogLevel[LogLevel["ERROR"] = 3] = "ERROR"; LogLevel[LogLevel["FATAL"] = 4] = "FATAL"; LogLevel[LogLevel["OFF"] = 5] = "OFF"; })(LogLevel || (LogLevel = {})); class ConsoleTransport { log(level, message) { const methods = { [LogLevel.DEBUG]: console.debug, [LogLevel.INFO]: console.info, [LogLevel.WARN]: console.warn, [LogLevel.ERROR]: console.error, [LogLevel.FATAL]: console.error, [LogLevel.OFF]: () => { } }; const method = methods[level] || console.log; method(message); } } class Logger { constructor(options = {}) { this.level = options.level ?? LogLevel.INFO; this.prefix = options.prefix ?? ''; this.dateFormat = options.dateFormat ?? true; this.transports = options.transport ?? [new ConsoleTransport()]; } setLevel(level) { this.level = level; return this; } setPrefix(prefix) { this.prefix = prefix; return this; } addTransport(transport) { this.transports.push(transport); return this; } formatMessage(level, message) { const levelNames = { [LogLevel.DEBUG]: 'DEBUG', [LogLevel.INFO]: 'INFO', [LogLevel.WARN]: 'WARN', [LogLevel.ERROR]: 'ERROR', [LogLevel.FATAL]: 'FATAL', [LogLevel.OFF]: 'OFF' }; let formattedMessage = ''; if (this.dateFormat) { formattedMessage += `[${new Date().toLocaleString()}] `; } formattedMessage += `[${levelNames[level] || 'UNKNOWN'}] `; if (this.prefix) { formattedMessage += `[${this.prefix}] `; } formattedMessage += message; return formattedMessage; } log(level, message, ...args) { if (level < this.level) { return; } let finalMessage; if (message instanceof Error) { finalMessage = `${message.message}\n${message.stack}`; } else { finalMessage = message; } if (args.length > 0) { finalMessage += ' ' + args.map(arg => { if (arg == null || arg == undefined) { return arg + ''; } else if (arg instanceof Error || (arg.stack && arg.message)) { return `${arg.message}\n${arg.stack}`; } else if (typeof arg === 'object') { return JSON.stringify(arg); } return String(arg); }).join(' '); } const formattedMessage = this.formatMessage(level, finalMessage); this.transports.forEach(transport => { transport.log(level, formattedMessage); }); } isEnableDebug() { return this.level <= LogLevel.DEBUG; } debug(message, ...args) { this.log(LogLevel.DEBUG, message, ...args); } isEnableInfo() { return this.level <= LogLevel.INFO; } info(message, ...args) { this.log(LogLevel.INFO, message, ...args); } warn(message, ...args) { this.log(LogLevel.WARN, message, ...args); } error(message, ...args) { this.log(LogLevel.ERROR, message, ...args); } fatal(message, ...args) { this.log(LogLevel.FATAL, message, ...args); } createChild(name, options = {}) { const childPrefix = this.prefix ? `${this.prefix}.${name}` : name; return new Logger({ level: options.level || this.level, prefix: childPrefix, dateFormat: options.dateFormat !== undefined ? options.dateFormat : this.dateFormat, transport: options.transport || this.transports }); } } const Log = new Logger(); function sleep(time) { return new Promise((resolve) => setTimeout(() => resolve(), time)); } function uuidv4() { return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) { const r = (Math.random() * 16) | 0; const v = c === "x" ? r : (r & 0x3) | 0x8; return v.toString(16); }); } function call_timeout(fun, timeout, error_callback) { return new Promise(async (resolve, reject) => { let timer = setTimeout(() => { reject(new Error("Timeout")); error_callback && error_callback("Timeout"); }, timeout); try { const result = await fun(); clearTimeout(timer); resolve(result); } catch (e) { clearTimeout(timer); reject(e); error_callback && error_callback(e + ""); } }); } function convertToolSchema(tool) { if ("function" in tool) { return { type: "function", name: tool.function.name, description: tool.function.description, inputSchema: tool.function.parameters, }; } else if ("input_schema" in tool) { return { type: "function", name: tool.name, description: tool.description, inputSchema: tool.input_schema, }; } else if ("inputSchema" in tool) { return { type: "function", name: tool.name, description: tool.description, inputSchema: tool.inputSchema, }; } else { return { type: "function", name: tool.name, description: tool.description, inputSchema: tool.parameters, }; } } function toImage(mediaData) { return toFile(mediaData); } function toFile(mediaData, type = "base64|url") { if (mediaData.startsWith("http://") || mediaData.startsWith("https://")) { return new URL(mediaData); } else if (mediaData.startsWith("//") && mediaData.indexOf(".") > 0 && mediaData.length < 1000) { return new URL("https:" + mediaData); } if (mediaData.startsWith("data:")) { mediaData = mediaData.substring(mediaData.indexOf(",") + 1); } if (type === "binary|url") { // @ts-ignore if (typeof Buffer != "undefined") { // @ts-ignore const buffer = Buffer.from(mediaData, "base64"); return new Uint8Array(buffer); } else { const binaryString = atob(mediaData); const fileData = new Uint8Array(binaryString.length); for (let i = 0; i < binaryString.length; i++) { fileData[i] = binaryString.charCodeAt(i); } return fileData; } } else { return mediaData; } } function getMimeType(data) { let mediaType = "image/png"; if (data.startsWith("data:")) { mediaType = data.split(";")[0].split(":")[1]; } else if (data.indexOf(".") > -1) { if (data.indexOf(".png") > -1) { mediaType = "image/png"; } else if (data.indexOf(".jpg") > -1 || data.indexOf(".jpeg") > -1) { mediaType = "image/jpeg"; } else if (data.indexOf(".pdf") > -1) { mediaType = "application/pdf"; } else if (data.indexOf(".docx") > -1) { mediaType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; } else if (data.indexOf(".xlsx") > -1) { mediaType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; } else if (data.indexOf(".pptx") > -1) { mediaType = "application/vnd.openxmlformats-officedocument.presentationml.presentation"; } else if (data.indexOf(".txt") > -1) { mediaType = "text/plain"; } else if (data.indexOf(".md") > -1) { mediaType = "text/markdown"; } else if (data.indexOf(".json") > -1) { mediaType = "application/json"; } else if (data.indexOf(".xml") > -1) { mediaType = "application/xml"; } else if (data.indexOf(".csv") > -1) { mediaType = "text/csv"; } } return mediaType; } async function compressImageData(imageBase64, imageType, compress, quality) { const base64Data = imageBase64; const binaryString = typeof atob !== "undefined" ? atob(base64Data) : // @ts-ignore Buffer.from(base64Data, "base64").toString("binary"); const bytes = new Uint8Array(binaryString.length); for (let i = 0; i < binaryString.length; i++) { bytes[i] = binaryString.charCodeAt(i); } if (!quality) { if (bytes.length >= 1024 * 1024 * 3) { quality = 0.6; } else if (bytes.length >= 1024 * 1024 * 1.5) { quality = 0.8; } else { quality = 1; } } const targetByScale = (bitmapWidth, bitmapHeight) => ({ width: compress.scale ? bitmapWidth * compress.scale : compress.resizeWidth, height: compress.scale ? bitmapHeight * compress.scale : compress.resizeHeight, }); const hasOffscreen = typeof OffscreenCanvas !== "undefined"; const hasCreateImageBitmap = typeof createImageBitmap !== "undefined"; const hasDOM = typeof document !== "undefined" && typeof Image !== "undefined"; const isNode = typeof window === "undefined" && // @ts-ignore typeof process !== "undefined" && // @ts-ignore !!process.versions && // @ts-ignore !!process.versions.node; const loadImageAny = async () => { if (hasCreateImageBitmap) { const blob = new Blob([bytes], { type: imageType }); const bitmap = await createImageBitmap(blob); return { img: bitmap, width: bitmap.width, height: bitmap.height }; } if (hasDOM) { const img = await new Promise((resolve, reject) => { const image = new Image(); image.onload = () => resolve(image); image.onerror = (e) => reject(e); image.src = `data:${imageType};base64,${imageBase64}`; }); return { img, width: img.width, height: img.height }; } if (isNode) { const canvasMod = await loadPackage("canvas"); const { loadImage } = canvasMod; const dataUrl = `data:${imageType};base64,${imageBase64}`; const img = await loadImage(dataUrl); return { img, width: img.width, height: img.height }; } throw new Error("No image environment available"); }; const createCanvasAny = async (width, height) => { if (hasOffscreen) { const canvas = new OffscreenCanvas(width, height); return { ctx: canvas.getContext("2d"), exportBase64: async (mime, q) => { const blob = await canvas.convertToBlob({ type: mime, quality: q }); return await new Promise((res, rej) => { const reader = new FileReader(); reader.onloadend = () => { const url = reader.result; res(url.substring(url.indexOf("base64,") + 7)); }; reader.onerror = () => rej(new Error("Failed to convert blob to base64")); reader.readAsDataURL(blob); }); }, }; } if (hasDOM) { const canvas = document.createElement("canvas"); canvas.width = width; canvas.height = height; return { ctx: canvas.getContext("2d"), exportBase64: async (mime, q) => { const dataUrl = canvas.toDataURL(mime, q); return dataUrl.substring(dataUrl.indexOf("base64,") + 7); }, }; } if (isNode) { const canvasMod = await loadPackage("canvas"); const { createCanvas } = canvasMod; const canvas = createCanvas(width, height); return { ctx: canvas.getContext("2d"), exportBase64: async (mime, q) => { const buffer = canvas.toBuffer(mime, { quality: q }); const _Buffer = // @ts-ignore typeof Buffer !== "undefined" ? Buffer.from(buffer) : buffer; return _Buffer.toString("base64"); }, }; } throw new Error("No canvas environment available"); }; const loaded = await loadImageAny(); const { width, height } = targetByScale(loaded.width, loaded.height); if (loaded.width == width && loaded.height == height && quality == 1) { return { imageBase64: imageBase64, imageType: imageType, }; } const { ctx, exportBase64 } = await createCanvasAny(width, height); if (!ctx) { return { imageBase64: imageBase64, imageType: imageType, }; } ctx.drawImage(loaded.img, 0, 0, width, height); const outBase64 = await exportBase64("image/jpeg", quality); return { imageBase64: outBase64, imageType: "image/jpeg", }; } function mergeTools(tools1, tools2) { let tools = []; let toolMap2 = tools2.reduce((map, tool) => { map[tool.name] = tool; return map; }, {}); let names = []; for (let i = 0; i < tools1.length; i++) { let tool1 = tools1[i]; let tool2 = toolMap2[tool1.name]; if (tool2) { tools.push(tool2); delete toolMap2[tool1.name]; } else { tools.push(tool1); } } for (let i = 0; i < tools2.length; i++) { let tool2 = tools2[i]; if (toolMap2[tool2.name] && names.indexOf(tool2.name) === -1) { tools.push(tool2); names.push(tool2.name); } } return tools; } function mergeAgents(agents1, agents2) { let agents = []; let agentMap2 = agents2.reduce((map, agent) => { map[agent.Name] = agent; return map; }, {}); for (let i = 0; i < agents1.length; i++) { let agent1 = agents1[i]; let agent2 = agentMap2[agent1.Name]; if (agent2) { agents.push(agent2); delete agentMap2[agent1.Name]; } else { agents.push(agent1); } } for (let i = 0; i < agents2.length; i++) { let agent2 = agents2[i]; if (agentMap2[agent2.Name]) { agents.push(agent2); } } return agents; } function sub(str, maxLength, appendPoint = true, showTruncated = true) { if (!str) { return ""; } if (str.length > maxLength) { const truncatedLength = str.length - maxLength; // return str.substring(0, maxLength) + (appendPoint ? showTruncated ? `...(truncated: +${truncatedLength} chars)` : "..." : ""); return (Array.from(str).slice(0, maxLength).join("") + (appendPoint ? showTruncated ? `...(truncated: +${truncatedLength} chars)` : "..." : "")); } return str; } function fixJson(code) { if (!code) { return {}; } try { return JSON.parse(code); } catch (e) { } try { return JSON.parse(code + '"}'); } catch (e) { } const stack = []; for (let i = 0; i < code.length; i++) { let s = code[i]; if (s === "{") { stack.push("}"); } else if (s === "}") { stack.pop(); } else if (s === "[") { stack.push("]"); } else if (s === "]") { stack.pop(); } else if (s === '"') { if (stack[stack.length - 1] === '"') { stack.pop(); } else { stack.push('"'); } } } const missingParts = []; while (stack.length > 0) { missingParts.push(stack.pop()); } let json = code + missingParts.join(""); try { return JSON.parse(json); } catch (e) { return {}; } } function fixXmlTag(code) { code = code.trim(); if (code.endsWith("<")) { code = code.substring(0, code.length - 1); } if (code.indexOf("&") > -1) { code = code.replace(/&(?![a-zA-Z0-9#]+;)/g, "&amp;"); } function fixDoubleChar(code) { const stack = []; for (let i = 0; i < code.length; i++) { let s = code[i]; if (s === "<") { stack.push(">"); } else if (s === ">") { stack.pop(); } else if (s === '"') { if (stack[stack.length - 1] === '"') { stack.pop(); } else { stack.push('"'); } } } const missingParts = []; while (stack.length > 0) { missingParts.push(stack.pop()); } return code + missingParts.join(""); } let eIdx = code.lastIndexOf(" "); let endStr = eIdx > -1 ? code.substring(eIdx + 1) : ""; if (code.endsWith("=")) { code += '""'; } else if (endStr == "name" || endStr == "id" || endStr == "depen" || endStr == "depends" || endStr == "dependsOn" || endStr == "input" || endStr == "output" || endStr == "items" || endStr == "event" || endStr == "loop") { let idx1 = code.lastIndexOf(">"); let idx2 = code.lastIndexOf("<"); if (idx1 < idx2 && code.lastIndexOf(" ") > idx2) { code += '=""'; } } code = fixDoubleChar(code); const stack = []; function isSelfClosing(tag) { return tag.endsWith("/>"); } for (let i = 0; i < code.length; i++) { let s = code[i]; if (s === "<") { const isEndTag = code[i + 1] === "/"; let endIndex = code.indexOf(">", i); let tagContent = code.slice(i, endIndex + 1); if (isSelfClosing(tagContent)) ; else if (isEndTag) { stack.pop(); } else { stack.push(tagContent); } if (endIndex == -1) { break; } i = endIndex; } } const missingParts = []; while (stack.length > 0) { const top = stack.pop(); if (top.startsWith("<")) { let arr = top.match(/<(\w+)/); if (arr) { const tagName = arr[1]; missingParts.push(`</${tagName}>`); } } else { missingParts.push(top); } } let completedCode = code + missingParts.join(""); return completedCode; } async function loadPackage(packageName) { // @ts-ignore if (typeof require !== "undefined") { try { return await import(packageName); } catch { // @ts-ignore return require(packageName); } } return await import(packageName); } // src/errors/ai-sdk-error.ts var marker$1 = "vercel.ai.error"; var symbol$1 = Symbol.for(marker$1); var _a$2; var _AISDKError$1 = class _AISDKError extends Error { /** * 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$2] = 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; } }; _a$2 = symbol$1; var AISDKError$1 = _AISDKError$1; // src/errors/api-call-error.ts var name$1 = "AI_APICallError"; var marker2$1 = `vercel.ai.error.${name$1}`; var symbol2$1 = Symbol.for(marker2$1); var _a2$1; var APICallError$1 = class APICallError extends AISDKError$1 { 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: name$1, message, cause }); this[_a2$1] = 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$1.hasMarker(error, marker2$1); } }; _a2$1 = symbol2$1; // src/errors/empty-response-body-error.ts var name2$1 = "AI_EmptyResponseBodyError"; var marker3$1 = `vercel.ai.error.${name2$1}`; var symbol3$1 = Symbol.for(marker3$1); var _a3$1; var EmptyResponseBodyError$1 = class EmptyResponseBodyError extends AISDKError$1 { // used in isInstance constructor({ message = "Empty response body" } = {}) { super({ name: name2$1, message }); this[_a3$1] = true; } static isInstance(error) { return AISDKError$1.hasMarker(error, marker3$1); } }; _a3$1 = symbol3$1; // src/errors/get-error-message.ts function getErrorMessage$1(error) { if (error == null) { return "unknown error"; } if (typeof error === "string") { return error; } if (error instanceof Error) { return error.message; } return JSON.stringify(error); } // src/errors/invalid-argument-error.ts var name3$1 = "AI_InvalidArgumentError"; var marker4$1 = `vercel.ai.error.${name3$1}`; var symbol4$1 = Symbol.for(marker4$1); var _a4$1; var InvalidArgumentError$1 = class InvalidArgumentError extends AISDKError$1 { constructor({ message, cause, argument }) { super({ name: name3$1, message, cause }); this[_a4$1] = true; this.argument = argument; } static isInstance(error) { return AISDKError$1.hasMarker(error, marker4$1); } }; _a4$1 = symbol4$1; // src/errors/invalid-prompt-error.ts var name4$1 = "AI_InvalidPromptError"; var marker5$1 = `vercel.ai.error.${name4$1}`; var symbol5$1 = Symbol.for(marker5$1); var _a5$1; var InvalidPromptError$1 = class InvalidPromptError extends AISDKError$1 { constructor({ prompt, message, cause }) { super({ name: name4$1, message: `Invalid prompt: ${message}`, cause }); this[_a5$1] = true; this.prompt = prompt; } static isInstance(error) { return AISDKError$1.hasMarker(error, marker5$1); } }; _a5$1 = symbol5$1; // src/errors/invalid-response-data-error.ts var name5$1 = "AI_InvalidResponseDataError"; var marker6$1 = `vercel.ai.error.${name5$1}`; var symbol6$1 = Symbol.for(marker6$1); var _a6$1; var InvalidResponseDataError$1 = class InvalidResponseDataError extends AISDKError$1 { constructor({ data, message = `Invalid response data: ${JSON.stringify(data)}.` }) { super({ name: name5$1, message }); this[_a6$1] = true; this.data = data; } static isInstance(error) { return AISDKError$1.hasMarker(error, marker6$1); } }; _a6$1 = symbol6$1; // src/errors/json-parse-error.ts var name6$1 = "AI_JSONParseError"; var marker7$1 = `vercel.ai.error.${name6$1}`; var symbol7$1 = Symbol.for(marker7$1); var _a7$1; var JSONParseError$1 = class JSONParseError extends AISDKError$1 { constructor({ text, cause }) { super({ name: name6$1, message: `JSON parsing failed: Text: ${text}. Error message: ${getErrorMessage$1(cause)}`, cause }); this[_a7$1] = true; this.text = text; } static isInstance(error) { return AISDKError$1.hasMarker(error, marker7$1); } }; _a7$1 = symbol7$1; // src/errors/load-api-key-error.ts var name7$1 = "AI_LoadAPIKeyError"; var marker8$1 = `vercel.ai.error.${name7$1}`; var symbol8$1 = Symbol.for(marker8$1); var _a8$1; var LoadAPIKeyError$1 = class LoadAPIKeyError extends AISDKError$1 { // used in isInstance constructor({ message }) { super({ name: name7$1, message }); this[_a8$1] = true; } static isInstance(error) { return AISDKError$1.hasMarker(error, marker8$1); } }; _a8$1 = symbol8$1; // src/errors/load-setting-error.ts var name8 = "AI_LoadSettingError"; var marker9 = `vercel.ai.error.${name8}`; var symbol9 = Symbol.for(marker9); var _a9; var LoadSettingError = class extends AISDKError$1 { // used in isInstance constructor({ message }) { super({ name: name8, message }); this[_a9] = true; } static isInstance(error) { return AISDKError$1.hasMarker(error, marker9); } }; _a9 = symbol9; // src/errors/no-such-model-error.ts var name10 = "AI_NoSuchModelError"; var marker11 = `vercel.ai.error.${name10}`; var symbol11 = Symbol.for(marker11); var _a11; var NoSuchModelError = class extends AISDKError$1 { 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$1.hasMarker(error, marker11); } }; _a11 = symbol11; // src/errors/too-many-embedding-values-for-call-error.ts var name11 = "AI_TooManyEmbeddingValuesForCallError"; var marker12 = `vercel.ai.error.${name11}`; var symbol12 = Symbol.for(marker12); var _a12; var TooManyEmbeddingValuesForCallError = class extends AISDKError$1 { 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$1.hasMarker(error, marker12); } }; _a12 = symbol12; // src/errors/type-validation-error.ts var name12$1 = "AI_TypeValidationError"; var marker13$1 = `vercel.ai.error.${name12$1}`; var symbol13$1 = Symbol.for(marker13$1); var _a13$1; var _TypeValidationError$1 = class _TypeValidationError extends AISDKError$1 { constructor({ value, cause }) { super({ name: name12$1, message: `Type validation failed: Value: ${JSON.stringify(value)}. Error message: ${getErrorMessage$1(cause)}`, cause }); this[_a13$1] = true; this.value = value; } static isInstance(error) { return AISDKError$1.hasMarker(error, marker13$1); } /** * 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 }); } }; _a13$1 = symbol13$1; var TypeValidationError$1 = _TypeValidationError$1; // src/errors/unsupported-functionality-error.ts var name13$1 = "AI_UnsupportedFunctionalityError"; var marker14$1 = `vercel.ai.error.${name13$1}`; var symbol14$1 = Symbol.for(marker14$1); var _a14$1; var UnsupportedFunctionalityError$1 = class UnsupportedFunctionalityError extends AISDKError$1 { constructor({ functionality, message = `'${functionality}' functionality not supported.` }) { super({ name: name13$1, message }); this[_a14$1] = true; this.functionality = functionality; } static isInstance(error) { return AISDKError$1.hasMarker(error, marker14$1); } }; _a14$1 = symbol14$1; let ParseError$1 = class ParseError 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$1(_arg) { } function createParser$1(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$1, onError = noop$1, onRetry = noop$1, onComment } = callbacks; let incompleteLine = "", isFirstChunk = true, id, data = "", eventType = ""; function feed(newChunk) { const chunk = isFirstChunk ? newChunk.replace(/^\xEF\xBB\xBF/, "") : newChunk, [complete, incomplete] = splitLines$1(`${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$1(`Invalid \`retry\` value: "${value}"`, { type: "invalid-retry", value, line }) ); break; default: onError( new ParseError$1( `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$1(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]; } let EventSourceParserStream$1 = class EventSourceParserStream extends TransformStream { constructor({ onError, onRetry, onComment } = {}) { let parser; super({ start(controller) { parser = createParser$1({ onEvent: (event) => { controller.enqueue(event); }, onError(error) { onError === "terminate" ? controller.error(error) : typeof onError == "function" && onError(error); }, onRetry, onComment }); }, transform(chunk) { parser.feed(chunk); } }); } }; /** A special constant with type `never` */ function $constructor(name, initializer, params) { function init(inst, def) { if (!inst._zod) { Object.defineProperty(inst, "_zod", { value: { def, constr: _, traits: new Set(), }, enumerable: false, }); } if (inst._zod.traits.has(name)) { return; } inst._zod.traits.add(name); initializer(inst, def); // support prototype modifications const proto = _.prototype; const keys = Object.keys(proto); for (let i = 0; i < keys.length; i++) { const k = keys[i]; if (!(k in inst)) { inst[k] = proto[k].bind(inst); } } } // doesn't work if Parent has a constructor with arguments const Parent = params?.Parent ?? Object; class Definition extends Parent { } Object.defineProperty(Definition, "name", { value: name }); function _(def) { var _a; const inst = params?.Parent ? new Definition() : this; init(inst, def); (_a = inst._zod).deferred ?? (_a.deferred = []); for (const fn of inst._zod.deferred) { fn(); } return inst; } Object.defineProperty(_, "init", { value: init }); Object.defineProperty(_, Symbol.hasInstance, { value: (inst) => { if (params?.Parent && inst instanceof params.Parent) return true; return inst?._zod?.traits?.has(name); }, }); Object.defineProperty(_, "name", { value: name }); return _; } class $ZodAsyncError extends Error { constructor() { super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); } } class $ZodEncodeError extends Error { constructor(name) { super(`Encountered unidirectional transform during encode: ${name}`); this.name = "ZodEncodeError"; } } const globalConfig = {}; function config(newConfig) { return globalConfig; } // functions function getEnumValues(entries) { const numericValues = Object.values(entries).filter((v) => typeof v === "number"); const values = Object.entries(entries) .filter(([k, _]) => numericValues.indexOf(+k) === -1) .map(([_, v]) => v); return values; } function jsonStringifyReplacer(_, value) { if (typeof value === "bigint") return value.toString(); return value; } function cached(getter) { return { get value() { { const value = getter(); Object.defineProperty(this, "value", { value }); return value; } }, }; } function nullish(input) { return input === null || input === undefined; } function cleanRegex(source) { const start = source.startsWith("^") ? 1 : 0; const end = source.endsWith("$") ? source.length - 1 : source.length; return source.slice(start, end); } function floatSafeRemainder(val, step) { const valDecCount = (val.toString().split(".")[1] || "").length; const stepString = step.toString(); let stepDecCount = (stepString.split(".")[1] || "").length; if (stepDecCount === 0 && /\d?e-\d?/.test(stepString)) { const match = stepString.match(/\d?e-(\d?)/); if (match?.[1]) { stepDecCount = Number.parseInt(match[1]); } } const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); return (valInt % stepInt) / 10 ** decCount; } const EVALUATING = Symbol("evaluating"); function defineLazy(object, key, getter) { let value = undefined; Object.defineProperty(object, key, { get() { if (value === EVALUATING) { // Circular reference detected, return undefined to break the cycle return undefined; } if (value === undefined) { value = EVALUATING; value = getter(); } return value; }, set(v) { Object.defineProperty(object, key, { value: v, // configurable: true, }); // object[key] = v; }, configurable: true, }); } function assignProp(target, prop, value) { Object.defineProperty(target, prop, { value, writable: true, enumerable: true, configurable: true, }); } function mergeDefs(...defs) { const mergedDescriptors = {}; for (const def of defs) { const descriptors = Object.getOwnPropertyDescriptors(def); Object.assign(mergedDescriptors, descriptors); } return Object.defineProperties({}, mergedDescriptors); } function esc(str) { return JSON.stringify(str); } function slugify(input) { return input .toLowerCase() .trim() .replace(/[^\w\s-]/g, "") .replace(/[\s_-]+/g, "-") .replace(/^-+|-+$/g, ""); } const captureStackTrace = ("captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { }); function isObject(data) { return typeof data === "object" && data !== null && !Array.isArray(data); } const allowsEval = cached(() => { // @ts-ignore if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { return false; } try { const F = Function; new F(""); return true; } catch (_) { return false; } }); function isPlainObject(o) { if (isObject(o) === false) return false; // modified constructor const ctor = o.constructor; if (ctor === undefined) return true; if (typeof ctor !== "function") return true; // modified prototype const prot = ctor.prototype; if (isObject(prot) === false) return false; // ctor doesn't have static `isPrototypeOf` if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { return false; } return true; } function shallowClone(o) { if (isPlainObject(o)) return { ...o }; if (Array.isArray(o)) return [...o]; return o; } const propertyKeyTypes = new Set(["string", "number", "symbol"]); function escapeRegex(str) { return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } // zod-specific utils function clone(inst, def, params) { const cl = new inst._zod.constr(def ?? inst._zod.def); if (!def || params?.parent) cl._zod.parent = inst; return cl; } function normalizeParams(_params) { const params = _params; if (!params) return {}; if (typeof params === "string") return { error: () => params }; if (params?.message !== undefined) { if (params?.error !== undefined) throw new Error("Cannot specify both `message` and `error` params"); params.error = params.message; } delete params.message; if (typeof params.error === "string") return { ...params, error: () => params.error }; return params; } function optionalKeys(shape) { return Object.keys(shape).filter((k) => { return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional"; }); } const NUMBER_FORMAT_RANGES = { safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], int32: [-2147483648, 2147483647], uint32: [0, 4294967295], float32: [-34028234663852886e22, 3.4028234663852886e38], float64: [-Number.MAX_VALUE, Number.MAX_VALUE], }; function pick(schema, mask) { const currDef = schema._zod.def; const def = mergeDefs(schema._zod.def, { get shape() { const newShape = {}; for (const key in mask) { if (!(key in currDef.shape)) { throw new Error(`Unrecognized key: "${key}"`); } if (!mask[key]) continue; newShape[key] = currDef.shape[key]; } assignProp(this, "shape", newShape); // self-caching return newShape; }, checks: [], }); return clone(schema, def); } function omit(schema, mask) { const currDef = schema._zod.def; const def = mergeDefs(schema._zod.def, { get shape() { const newShape = { ...schema._zod.def.shape }; for (const key in mask) { if (!(key in currDef.shape)) { throw new Error(`Unrecognized key: "${key}"`); } if (!mask[key]) continue; delete newShape[key]; } assignProp(this, "shape", newShape); // self-caching return newShape; }, checks: [], }); return clone(schema, def); } function extend(schema, shape) { if (!isPlainObject(shape)) { throw new Error("Invalid input to extend: expected a plain object"); } const checks = schema._zod.def.checks; const hasChecks = checks && checks.length > 0; if (hasChecks) { throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead."); } const def = mergeDefs(schema._zod.def, { get shape() { const _shape = { ...schema._zod.def.shape, ...shape }; assignProp(this, "shape", _shape); // self-caching return _shape; }, checks: [], }); return clone(schema, def); } function safeExtend(schema, shape) { if (!isPlainObject(shape)) { throw new Error("Invalid input to safeExtend: expected a plain object"); } const def = { ...schema._zod.def, get shape() { const _shape = { ...schema._zod.def.shape, ...shape }; assignProp(this, "shape", _shape); // self-caching return _shape; }, checks: schema._zod.def.checks, }; return clone(schema, def); } function merge(a, b) { const def = mergeDefs(a._zod.def, { get shape() { const _shape = { ...a._zod.def.shape, ...b._zod.def.shape }; assignProp(this, "shape", _shape); // self-caching return _shape; }, get catchall() { return b._zod.def.catchall; }, checks: [], // delete existing checks }); return clone(a, def); } function partial(Class, schema, mask) { const def = mergeDefs(schema._zod.def, { get shape() { const oldShape = schema._zod.def.shape; const shape = { ...oldShape }; if (mask) { for (const key in mask) { if (!(key in oldShape)) { throw new Error(`Unrecognized key: "${key}"`); } if (!mask[key]) continue; // if (oldShape[key]!._zod.optin === "optional") continue; shape[key] = Class ? new Class({ type: "optional", innerType: oldShape[key], }) : oldShape[key]; } } else { for (const key in oldShape) { // if (oldShape[key]!._zod.optin === "optional") continue; shape[key] = Class ? new Class({ type: "optional", innerType: oldShape[key], }) : oldShape[key]; } } assignProp(this, "shape", shape); // self-caching return shape; }, checks: [], }); return clone(schema, def); } function required(Class, schema, mask) { const def = mergeDefs(schema._zod.def, { get shape() { const oldShape = schema._zod.def.shape; const shape = { ...oldShape }; if (mask) { for (const key in mask) { if (!(key in shape)) { throw new Error(`Unrecognized key: "${key}"`); } if (!mask[key]) continue; // overwrite with non-optional shape[key] = new Class({ type: "nonoptional", innerType: oldShape[key], }); } } else { for (const key in oldShape) { // overwrite with non-optional shape[key] = new Class({ type: "nonoptional", innerType: oldShape[key], }); } } assignProp(this, "shape", shape); // self-caching return shape; }, checks: [], }); return clone(schema, def); } // invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom function aborted(x, startIndex = 0) { if (x.aborted === true) return true; for (let i = startIndex; i < x.issues.length; i++) { if (x.issues[i]?.continue !== true) { return true; } } return false; } function prefixIssues(path, issues) { return issues.map((iss) => { var _a; (_a = iss).path ?? (_a.path = []); iss.path.unshift(path); return iss; }); } function unwrapMessage(message) { return typeof message === "string" ? message : message?.message; } function finalizeIssue(iss, ctx, config) { const full = { ...iss, path: iss.path ?? [] }; // for backwards compatibility if (!iss.message) { const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? unwrapMessage(ctx?.error?.(iss)) ?? unwrapMessage(config.customError?.(iss)) ?? unwrapMessage(config.localeError?.(iss)) ?? "Invalid input"; full.message = message; } // delete (full as any).def; delete full.inst; delete full.continue; if (!ctx?.reportInput) { delete full.input; } return full; } function getLengthableOrigin(input) { if (Array.isArray(input)) return "array"; if (typeof input === "string") return "string"; return "unknown"; } function issue(...args) { const [iss, input, inst] = args; if (typeof iss === "string") { return { message: iss, code: "custom", input, inst, }; } return { ...iss }; } const initializer$1 = (inst, def) => { inst.name = "$ZodError"; Object.defineProperty(inst, "_zod", { value: inst._zod, enumerable: false, }); Object.defineProperty(inst, "issues", { value: def, enumerable: false, }); inst.message = JSON.stringify(def, jsonStringifyReplacer, 2); Object.defineProperty(inst, "toString", { value: () => inst.message, enumerable: false, }); }; const $ZodError = $constructor("$ZodError", initializer$1); const $ZodRealError = $constructor("$ZodError", initializer$1, { Parent: Error }); function flattenError(error, mapper = (issue) => issue.message) { const fieldErr