UNPKG

@mastra/core

Version:
733 lines (732 loc) • 24.8 kB
import { t as convertDataContentToBase64String } from "./data-content-BCNBHZXc.js"; import { convertBase64ToUint8Array, convertUint8ArrayToBase64 } from "@ai-sdk/provider-utils-v6"; // src/stream/aisdk/v5/compat/media.ts const imageMediaTypeSignatures = [ { mediaType: "image/gif", bytesPrefix: [ 71, 73, 70 ], base64Prefix: "R0lG" }, { mediaType: "image/png", bytesPrefix: [ 137, 80, 78, 71 ], base64Prefix: "iVBORw" }, { mediaType: "image/jpeg", bytesPrefix: [255, 216], base64Prefix: "/9j/" }, { mediaType: "image/webp", bytesPrefix: [ 82, 73, 70, 70 ], base64Prefix: "UklGRg" }, { mediaType: "image/bmp", bytesPrefix: [66, 77], base64Prefix: "Qk" }, { mediaType: "image/tiff", bytesPrefix: [ 73, 73, 42, 0 ], base64Prefix: "SUkqAA" }, { mediaType: "image/tiff", bytesPrefix: [ 77, 77, 0, 42 ], base64Prefix: "TU0AKg" }, { mediaType: "image/avif", bytesPrefix: [ 0, 0, 0, 32, 102, 116, 121, 112, 97, 118, 105, 102 ], base64Prefix: "AAAAIGZ0eXBhdmlm" }, { mediaType: "image/heic", bytesPrefix: [ 0, 0, 0, 32, 102, 116, 121, 112, 104, 101, 105, 99 ], base64Prefix: "AAAAIGZ0eXBoZWlj" } ]; const stripID3 = (data) => { const bytes = typeof data === "string" ? convertBase64ToUint8Array(data) : data; const id3Size = (bytes[6] & 127) << 21 | (bytes[7] & 127) << 14 | (bytes[8] & 127) << 7 | bytes[9] & 127; return bytes.slice(id3Size + 10); }; function stripID3TagsIfPresent(data) { return typeof data === "string" && data.startsWith("SUQz") || typeof data !== "string" && data.length > 10 && data[0] === 73 && data[1] === 68 && data[2] === 51 ? stripID3(data) : data; } function detectMediaType({ data, signatures }) { const processedData = stripID3TagsIfPresent(data); for (const signature of signatures) if (typeof processedData === "string" ? processedData.startsWith(signature.base64Prefix) : processedData.length >= signature.bytesPrefix.length && signature.bytesPrefix.every((byte, index) => processedData[index] === byte)) return signature.mediaType; } // src/agent/message-list/prompt/image-utils.ts /** * Parses a data URI string into its components. * Format: data:[<mediatype>][;base64],<data> * * @param dataUri - The data URI string to parse * @returns Parsed components including MIME type and base64 content */ function parseDataUri(dataUri) { if (!dataUri.startsWith("data:")) return { isDataUri: false, base64Content: dataUri }; const base64Index = dataUri.indexOf(","); if (base64Index === -1) return { isDataUri: true, base64Content: dataUri }; const header = dataUri.substring(5, base64Index); const base64Content = dataUri.substring(base64Index + 1); const semicolonIndex = header.indexOf(";"); return { isDataUri: true, mimeType: (semicolonIndex !== -1 ? header.substring(0, semicolonIndex) : header) || void 0, base64Content }; } /** * Creates a data URI from base64 content and MIME type. * * @param base64Content - The base64 encoded content * @param mimeType - The MIME type (defaults to 'application/octet-stream') * @returns A properly formatted data URI */ function createDataUri(base64Content, mimeType = "application/octet-stream") { if (base64Content.startsWith("data:")) return base64Content; return `data:${mimeType};base64,${base64Content}`; } /** * Converts various image data formats to a string representation. * - Strings are returned as-is (could be URLs or data URIs) * - URL objects are converted to strings * - Binary data (Uint8Array, ArrayBuffer, Buffer) is converted to base64 * * @param image - The image data in various formats * @param fallbackMimeType - MIME type to use when creating data URIs from binary data * @returns String representation of the image (URL, data URI, or base64) */ function imageContentToString(image, fallbackMimeType) { if (typeof image === "string") return image; if (image instanceof URL) return image.toString(); if (image instanceof Uint8Array || image instanceof ArrayBuffer || globalThis.Buffer && Buffer.isBuffer(image)) { const base64 = convertDataContentToBase64String(image); if (fallbackMimeType && !base64.startsWith("data:")) return `data:${fallbackMimeType};base64,${base64}`; return base64; } return String(image); } /** * Gets a stable cache key component for image content. * Used for generating hash keys for caching purposes. * * @param image - The image data in various formats * @returns A string or number suitable for cache key generation */ function getImageCacheKey(image) { if (image instanceof URL) return image.toString(); if (typeof image === "string") return image.length; if (image instanceof Uint8Array) return image.byteLength; if (image instanceof ArrayBuffer) return image.byteLength; return image; } /** * Checks if a string is a valid URL (including protocol-relative URLs). * * @param str - The string to check * @returns true if the string is a valid URL */ function isValidUrl(str) { try { new URL(str); return true; } catch { if (str.startsWith("//")) try { new URL(`https:${str}`); return true; } catch { return false; } return false; } } const BASE64_PATTERN = /^[A-Za-z0-9+/\-_=\s]*$/; /** * Checks whether a string plausibly holds raw base64 content. Relative paths such as * `/api/images/foo.png` fail, so they aren't wrapped as a data URL that can never decode. */ function isBase64Like(data) { return BASE64_PATTERN.test(data); } const STRICT_BASE64_PATTERN = /^[A-Za-z0-9+/]*={0,2}$/; const SIGNED_IMAGE_MEDIA_TYPES = /* @__PURE__ */ new Set([...imageMediaTypeSignatures.map((signature) => signature.mediaType), "image/jpg"]); const HEIF_BRANDS = /* @__PURE__ */ new Set([ "heic", "heix", "hevc", "hevx", "heim", "heis", "hevm", "hevs", "mif1", "msf1", "avif", "avis" ]); const ascii = (bytes, start, length = 4) => String.fromCharCode(...bytes.subarray(start, start + length)); /** * HEIC and AVIF files start with an ISO BMFF `ftyp` box whose size and brand list vary (iPhone * HEIC uses a 24-byte box), so the fixed signature table misses most real files. Check the box * structure instead: `ftyp` at byte 4, then a HEIF/AVIF major or compatible brand. */ function isHeifImage(bytes) { if (bytes.length < 16 || ascii(bytes, 4) !== "ftyp") return false; const boxSize = (bytes[0] << 24 | bytes[1] << 16 | bytes[2] << 8 | bytes[3]) >>> 0; if (boxSize < 16 || boxSize % 4 !== 0) return false; if (HEIF_BRANDS.has(ascii(bytes, 8))) return true; for (let offset = 16; offset + 4 <= Math.min(boxSize, bytes.length); offset += 4) if (HEIF_BRANDS.has(ascii(bytes, offset))) return true; return false; } const PATH_PATTERN = /^\/?[A-Za-z0-9_-]+(?:\/[A-Za-z0-9_-]+)+\/?$|^\/[A-Za-z0-9_-]+\/?$/; const MAX_PATH_LENGTH = 256; /** * Checks whether inline base64 content can be decoded. Images with a known signature and PDFs * (whose `%PDF` header must appear in the first 1 KB) must also look like one; mislabelled * images are fine, since any known image signature passes. Other types can't be validated * exhaustively (audio containers and text encodings vary too much), so they are only rejected * when the content is a path rather than encoded file data. */ function isValidInlineContent(base64, mediaType) { const payload = base64.replace(/\s/g, "").replace(/-/g, "+").replace(/_/g, "/"); if (!payload || !STRICT_BASE64_PATTERN.test(payload)) return false; const unpaddedLength = payload.replace(/=+$/, "").length; if (unpaddedLength % 4 === 1 || unpaddedLength !== payload.length && payload.length % 4 !== 0) return false; const head = (chars) => convertBase64ToUint8Array(payload.slice(0, chars)); if (mediaType && SIGNED_IMAGE_MEDIA_TYPES.has(mediaType)) { const bytes = head(64); return detectMediaType({ data: bytes, signatures: imageMediaTypeSignatures }) !== void 0 || isHeifImage(bytes); } if (mediaType === "application/pdf") return ascii(head(1368), 0, 1026).includes("%PDF"); const trimmed = base64.trim(); return trimmed.length > MAX_PATH_LENGTH || !PATH_PATTERN.test(trimmed); } /** Whether a data URL's header declares base64 content (`data:<type>;base64,...`). */ function isBase64DataUri(data) { const comma = data.indexOf(","); return comma !== -1 && /;base64$/i.test(data.slice(5, comma)); } /** * Converts a percent-encoded data URL (`data:image/svg+xml,%3Csvg...`) to its base64 form, which * is what the AI SDK prompt conversion expects. Decodes like `fetch()` does: the `#fragment` is * not content, and an invalid escape such as `%zz` stays as literal text. */ function toBase64DataUri(dataUri) { const comma = dataUri.indexOf(","); if (comma === -1) return void 0; const hash = dataUri.indexOf("#", comma); const payload = dataUri.slice(comma + 1, hash === -1 ? void 0 : hash); return `data:${dataUri.slice(5, comma)};base64,${convertUint8ArrayToBase64(decodePercentEncoded(payload))}`; } function decodePercentEncoded(payload) { const encoder = new TextEncoder(); const bytes = []; for (let i = 0; i < payload.length;) { const hex = payload.slice(i + 1, i + 3); if (payload[i] === "%" && /^[0-9a-f]{2}$/i.test(hex)) { bytes.push(Number.parseInt(hex, 16)); i += 3; } else { const char = String.fromCodePoint(payload.codePointAt(i)); bytes.push(...encoder.encode(char)); i += char.length; } } return new Uint8Array(bytes); } /** * Checks whether file/image part data can be sent to a model: an OpenAI file ID (`file-...`), * an absolute URL (any scheme), or inline content (raw base64 or a data URL) that decodes and, * for images and PDFs, looks like one. Anything else, such as a relative path or a path that * was wrapped as a base64 data URL, can't be downloaded or decoded. */ function isSendableFileData(data, mediaType) { if (data.startsWith("data:")) { const base64Uri = isBase64DataUri(data) ? data : toBase64DataUri(data); if (!base64Uri) return false; const comma = base64Uri.indexOf(","); return isValidInlineContent(base64Uri.slice(comma + 1), base64Uri.slice(5, comma).split(";")[0] || mediaType); } if (data.startsWith("file-") || isAbsoluteUrl(data)) return true; return isValidInlineContent(data, mediaType); } /** * Checks if a string parses as an absolute URL (any scheme, e.g. `https:`, `gs:`, `s3:`). * Unlike {@link isValidUrl}, protocol-relative and relative paths are not accepted. */ function isAbsoluteUrl(str) { try { new URL(str); return true; } catch { return false; } } /** * Categorizes a string as a URL, data URI, or raw data (base64/other). * Also extracts MIME type from data URIs when present. * * @param data - The string data to categorize * @param fallbackMimeType - Optional fallback MIME type * @returns Categorized data with type and extracted MIME type */ function categorizeFileData(data, fallbackMimeType) { const parsed = parseDataUri(data); const mimeType = parsed.isDataUri && parsed.mimeType ? parsed.mimeType : fallbackMimeType; if (parsed.isDataUri) return { type: "dataUri", mimeType, data }; if (data.startsWith("file-")) return { type: "providerFileId", mimeType, data }; if (isValidUrl(data)) return { type: "url", mimeType, data }; return { type: "raw", mimeType, data }; } /** * Resolve a stored file part's media type and payload across the AI SDK v4 and v5 shapes. * * Stored "v2" file parts are typed as the AI SDK v4 UI shape (`mimeType`/`data`), but * v5-shaped file parts (`mediaType`/`url`, renamed in the v5 Media Type Standardization) * reach the same read sites. Reading only the v4 fields leaves a v5 part with both values * `undefined`, which downstream becomes `contentType: undefined` (making `attachmentsToParts` * throw) or collapses distinct parts onto a single cache key. Read whichever shape is present. * * Returns the RAW resolved values (undefined-preserving); call sites that build a * `contentType` should apply their own `'application/octet-stream'` fallback. Mirrors #17366. */ function resolveFilePartMediaTypeAndData(part) { const filePart = part; return { mediaType: filePart.mimeType ?? filePart.mediaType, data: filePart.data ?? filePart.url }; } // src/agent/message-list/utils/tool-name.ts const TOOL_NAME_PATTERN = /^[a-zA-Z0-9_-]+$/; const FALLBACK_TOOL_NAME = "unknown_tool"; function sanitizeToolName(toolName) { if (typeof toolName !== "string") return FALLBACK_TOOL_NAME; return TOOL_NAME_PATTERN.test(toolName) ? toolName : FALLBACK_TOOL_NAME; } // src/agent/message-list/conversion/to-prompt.ts /** * Convert an AI SDK V4 CoreMessage to a V1 LanguageModel prompt message. * Used for creating LLM prompt messages without AI SDK streamText/generateText. */ function aiV4CoreMessageToV1PromptMessage(coreMessage) { if (coreMessage.role === `system`) return coreMessage; if (typeof coreMessage.content === `string` && (coreMessage.role === `assistant` || coreMessage.role === `user`)) return { ...coreMessage, content: [{ type: "text", text: coreMessage.content }] }; if (typeof coreMessage.content === `string`) throw new Error(`Saw text content for input CoreMessage, but the role is ${coreMessage.role}. This is only allowed for "system", "assistant", and "user" roles.`); const roleContent = { user: [], assistant: [], tool: [] }; const role = coreMessage.role; for (const part of coreMessage.content) { const incompatibleMessage = `Saw incompatible message content part type ${part.type} for message role ${role}`; switch (part.type) { case "text": if (role === `tool`) throw new Error(incompatibleMessage); roleContent[role].push(part); break; case "redacted-reasoning": case "reasoning": if (role !== `assistant`) throw new Error(incompatibleMessage); roleContent[role].push(part); break; case "tool-call": if (role === `tool` || role === `user`) throw new Error(incompatibleMessage); roleContent[role].push({ ...part, toolName: sanitizeToolName(part.toolName) }); break; case "tool-result": if (role === `assistant` || role === `user`) throw new Error(incompatibleMessage); roleContent[role].push({ ...part, toolName: sanitizeToolName(part.toolName) }); break; case "image": { if (role === `tool` || role === `assistant`) throw new Error(incompatibleMessage); let processedImage; if (part.image instanceof URL || part.image instanceof Uint8Array) processedImage = part.image; else if (Buffer.isBuffer(part.image) || part.image instanceof ArrayBuffer) processedImage = new Uint8Array(part.image); else { const categorized = categorizeFileData(part.image, part.mimeType); if (categorized.type === "raw") processedImage = new Uint8Array(Buffer.from(part.image, "base64")); else if (categorized.type === "providerFileId") { const { image: _image, type: _type, ...rest } = part; roleContent[role].push({ ...rest, type: "file", data: part.image, mimeType: categorized.mimeType || "application/octet-stream" }); break; } else processedImage = new URL(part.image); } roleContent[role].push({ ...part, image: processedImage }); break; } case "file": if (role === `tool`) throw new Error(incompatibleMessage); roleContent[role].push({ ...part, data: part.data instanceof URL ? part.data : typeof part.data === "string" ? part.data : convertDataContentToBase64String(part.data) }); } } if (role === `tool`) return { ...coreMessage, content: roleContent[role] }; if (role === `user`) return { ...coreMessage, content: roleContent[role] }; if (role === `assistant`) return { ...coreMessage, content: roleContent[role] }; throw new Error(`Encountered unknown role ${role} when converting V4 CoreMessage -> V4 LanguageModelV1Prompt, input message: ${JSON.stringify(coreMessage, null, 2)}`); } /** * Deep-copy plain objects with their keys sorted, so the serialized bytes of tool * payloads depend only on content. Storage such as Postgres `jsonb` reorders object * keys, and an unstable prompt busts provider prompt caches on resumed runs. * Arrays keep their order; non-plain values (Dates, Uint8Arrays, class instances) pass through. */ function sortKeysDeep(value) { if (Array.isArray(value)) return value.map(sortKeysDeep); if (value === null || typeof value !== "object") return value; const proto = Object.getPrototypeOf(value); if (proto !== Object.prototype && proto !== null) return value; const sorted = {}; for (const key of Object.keys(value).sort()) Object.defineProperty(sorted, key, { value: sortKeysDeep(value[key]), enumerable: true, writable: true, configurable: true }); return sorted; } /** * Convert an AI SDK V5 ModelMessage to a V2 LanguageModel prompt message. * Used for creating LLM prompt messages without AI SDK streamText/generateText. */ function aiV5ModelMessageToV2PromptMessage(modelMessage) { if (modelMessage.role === `system`) return modelMessage; if (typeof modelMessage.content === `string` && (modelMessage.role === `assistant` || modelMessage.role === `user`)) return { role: modelMessage.role, content: [{ type: "text", text: modelMessage.content }], providerOptions: modelMessage.providerOptions }; if (typeof modelMessage.content === `string`) throw new Error(`Saw text content for input ModelMessage, but the role is ${modelMessage.role}. This is only allowed for "system", "assistant", and "user" roles.`); const roleContent = { user: [], assistant: [], tool: [] }; const role = modelMessage.role; for (const part of modelMessage.content ?? []) { if (!part || typeof part !== "object") continue; const incompatibleMessage = `Saw incompatible message content part type ${part.type} for message role ${role}`; switch (part.type) { case "text": if (role === `tool`) throw new Error(incompatibleMessage); roleContent[role].push(part); break; case "reasoning": if (role === `tool` || role === `user`) throw new Error(incompatibleMessage); roleContent[role].push(part); break; case "tool-call": if (role !== `assistant`) throw new Error(incompatibleMessage); roleContent[role].push({ ...part, toolName: sanitizeToolName(part.toolName), input: sortKeysDeep(part.input ?? {}) }); break; case "tool-result": { if (role === `user`) throw new Error(incompatibleMessage); const output = part.output ?? { type: "json", value: null }; roleContent[role].push({ ...part, toolName: sanitizeToolName(part.toolName), output: output.type === "json" || output.type === "error-json" ? { ...output, value: sortKeysDeep(output.value) } : output }); break; } case "file": if (role === `tool`) throw new Error(incompatibleMessage); roleContent[role].push({ ...part, data: part.data instanceof ArrayBuffer ? new Uint8Array(part.data) : part.data }); break; case "image": if (role === `tool`) throw new Error(incompatibleMessage); roleContent[role].push({ ...part, mediaType: part.mediaType || "image/unknown", type: "file", data: part.image instanceof ArrayBuffer ? new Uint8Array(part.image) : part.image }); } } if (role === `tool`) return { ...modelMessage, content: roleContent[role] }; if (role === `user`) return { ...modelMessage, content: roleContent[role] }; if (role === `assistant`) return { ...modelMessage, content: roleContent[role] }; throw new Error(`Encountered unknown role ${role} when converting V5 ModelMessage -> V5 LanguageModelV2Message, input message: ${JSON.stringify(modelMessage, null, 2)}`); } /** * Convert multimodal tool-result parts (`media`, `image-url`, `file-url`) in a * V2 (AI SDK v5 / spec `v2`) prompt using a caller-provided target shape. * * Mastra's `toModelOutput` and the vendored AI SDK v5 use `{ type: 'media' }` * as the authored Base64 tool-result content type, while remote URLs are kept * as `image-url`/`file-url` parts. Newer AI SDK provider specs use different * content-part shapes, so callers provide the target conversion for their * provider spec. Returning the same item from the callback is a pass-through. */ function convertToolResultContent(prompt, convertPart) { return prompt.map((message) => { if (message.role !== `tool`) return message; let messageModified = false; const content = message.content.map((part) => { if (part.type !== `tool-result`) return part; const output = part.output; if (!output || output.type !== `content` || !Array.isArray(output.value)) return part; let outputModified = false; const value = output.value.map((item) => { if (item == null || typeof item !== `object`) return item; const contentPart = item; const isMediaPart = contentPart.type === `media` && typeof contentPart.data === `string`; const isUrlPart = (contentPart.type === `image-url` || contentPart.type === `file-url`) && typeof contentPart.url === `string`; if (!isMediaPart && !isUrlPart) return item; const mediaType = typeof contentPart.mediaType === `string` ? contentPart.mediaType : ``; const converted = convertPart(contentPart, contentPart.type, mediaType); if (converted !== item) outputModified = true; return converted; }); if (!outputModified) return part; messageModified = true; return { ...part, output: { ...output, value } }; }); return messageModified ? { ...message, content } : message; }); } /** * Remote URLs cannot appear in Base64 `media.data`, but messages persisted by * older versions stored them there (issue #22618) — `://` is not valid Base64, * so this detection is unambiguous. Scheme matching is case-insensitive per * RFC 3986: legacy values were stored verbatim, so `HTTPS://…` must heal too. */ function isRemoteUrl(data) { return /^https?:\/\//i.test(data); } /** * Convert v5-authored media tool results to the `image-data`/`file-data` shape * expected only by AI SDK v6 (`v3`) providers. V5 providers accept `media`, and * V7 providers expect `file` parts with tagged data instead. `image-url` and * `file-url` parts are natively valid V3 tool-result content and pass through * unchanged; legacy `media` parts carrying a remote URL are healed into them. * * See: https://github.com/mastra-ai/mastra/issues/17876 and * https://github.com/mastra-ai/mastra/issues/22618 */ function aiV5PromptToAIV6Prompt(prompt) { return convertToolResultContent(prompt, (contentPart, partType, mediaType) => { if (partType !== `media`) return contentPart; const isImage = mediaType.startsWith(`image/`); const data = contentPart.data; if (isRemoteUrl(data) ? parseUrl(data) : void 0) { const rest = { ...contentPart }; delete rest.data; return { ...rest, type: isImage ? `image-url` : `file-url`, url: data }; } return { ...contentPart, type: isImage ? `image-data` : `file-data`, mediaType }; }); } function parseUrl(url) { if (url instanceof URL) return url; if (typeof url !== "string") return void 0; try { return new URL(url); } catch { return; } } function aiV5PromptToAIV7Prompt(prompt) { return convertToolResultContent(prompt, (contentPart, partType, mediaType) => { if (partType === `image-url` || partType === `file-url`) { const url = parseUrl(contentPart.url); if (!url) return { type: `text`, text: String(contentPart.url) }; const rest = { ...contentPart }; delete rest.url; return { ...rest, type: `file`, data: { type: `url`, url }, mediaType: mediaType || (partType === `image-url` ? `image/jpeg` : `application/octet-stream`) }; } const data = contentPart.data; const remoteUrl = isRemoteUrl(data) ? parseUrl(data) : void 0; if (remoteUrl) { const rest = { ...contentPart }; delete rest.data; return { ...rest, type: `file`, data: { type: `url`, url: remoteUrl }, mediaType: mediaType || `application/octet-stream` }; } return { ...contentPart, type: `file`, data: { type: `data`, data }, mediaType }; }); } export { detectMediaType as _, sanitizeToolName as a, getImageCacheKey as c, isBase64DataUri as d, isBase64Like as f, toBase64DataUri as g, resolveFilePartMediaTypeAndData as h, aiV5PromptToAIV7Prompt as i, imageContentToString as l, parseDataUri as m, aiV5ModelMessageToV2PromptMessage as n, categorizeFileData as o, isSendableFileData as p, aiV5PromptToAIV6Prompt as r, createDataUri as s, aiV4CoreMessageToV1PromptMessage as t, isAbsoluteUrl as u, imageMediaTypeSignatures as v }; //# sourceMappingURL=to-prompt-BsDtVXrf.js.map