import { JSONParseError, NoObjectGeneratedError, TypeValidationError } from '@internal/ai-sdk-v5'; import { ErrorCategory, ErrorDomain, MastraError } from '../error'; import type { MastraLegacyLanguageModel, MastraLanguageModel } from '../llm/model/shared.types'; import type { StorageThreadType } from '../memory'; import type { StandardSchemaWithJSON, InferStandardSchemaOutput } from '../schema'; import type { FullOutput } from '../stream/base/output'; import type { Agent } from './agent'; import type { AgentExecutionOptions, AgentExecutionOptionsBase } from './agent.types'; import type { MessageListInput } from './message-list'; import type { StructuredOutputOptions } from './types'; export const supportedLanguageModelSpecifications = ['v2', 'v3', 'v4']; export const isSupportedLanguageModel = ( model: MastraLanguageModel | MastraLegacyLanguageModel, ): model is MastraLanguageModel => { return supportedLanguageModelSpecifications.includes(model.specificationVersion); }; function isStructuredOutputFormatError(error: unknown): boolean { return ( JSONParseError.isInstance(error) || NoObjectGeneratedError.isInstance(error) || TypeValidationError.isInstance(error) || (error instanceof MastraError && (error.id === 'STRUCTURED_OUTPUT_OBJECT_UNDEFINED' || error.id === 'STRUCTURED_OUTPUT_SCHEMA_VALIDATION_FAILED' || error.id === 'STRUCTURED_OUTPUT_TRUNCATED')) ); } export async function tryGenerateWithJsonFallback< SCHEMA extends StandardSchemaWithJSON, OUTPUT extends InferStandardSchemaOutput, >(agent: Agent, prompt: MessageListInput, options: AgentExecutionOptions): Promise>; export async function tryGenerateWithJsonFallback( agent: Agent, prompt: MessageListInput, options: AgentExecutionOptions, ): Promise>; export async function tryGenerateWithJsonFallback( agent: Agent, prompt: MessageListInput, options: AgentExecutionOptions, ): Promise> { if (!options.structuredOutput?.schema) { throw new MastraError({ id: 'STRUCTURED_OUTPUT_OPTIONS_REQUIRED', domain: ErrorDomain.AGENT, category: ErrorCategory.USER, text: 'structuredOutput is required to use tryGenerateWithJsonFallback', }); } try { const result = await agent.generate(prompt, options); // Some models resolve without throwing but produce no parseable structured // object (empty/malformed JSON). Treat that the same as a thrown error so the // caller still gets the json-prompt-injection retry instead of a downstream // crash when it reads `result.object`. Mirrors tryStreamWithJsonFallback. if (result.object === undefined) { throw new MastraError({ id: 'STRUCTURED_OUTPUT_OBJECT_UNDEFINED', domain: ErrorDomain.AGENT, category: ErrorCategory.USER, text: 'structuredOutput object is undefined', }); } return result; } catch (error) { if (!isStructuredOutputFormatError(error)) throw error; agent.__getLogger().warn('Error in tryGenerateWithJsonFallback. Attempting fallback.', error); const result = await agent.generate(prompt, { ...options, structuredOutput: { ...options.structuredOutput, jsonPromptInjection: options.structuredOutput.jsonPromptInjection === 'inline' || options.structuredOutput.jsonPromptInjection === 'system' ? options.structuredOutput.jsonPromptInjection : true, }, }); if (result.object === undefined) { throw new MastraError({ id: 'STRUCTURED_OUTPUT_OBJECT_UNDEFINED', domain: ErrorDomain.AGENT, category: ErrorCategory.USER, text: 'structuredOutput object is undefined', }); } return result; } } export async function tryStreamWithJsonFallback( agent: Agent, prompt: MessageListInput, options: AgentExecutionOptionsBase & { structuredOutput: StructuredOutputOptions; /** Override injection placement only for the structured-output retry. */ fallbackJsonPromptInjection?: 'system' | 'inline'; onStream?: (stream: Awaited>) => void | Promise; /** Called immediately before each primary or fallback stream invocation. */ onStreamAttempt?: () => void | Promise; /** Called after each stream invocation is consumed, including a failed structured-output attempt. */ onStreamFinish?: (stream: Awaited>) => void | Promise; }, ) { if (!options.structuredOutput?.schema) { throw new MastraError({ id: 'STRUCTURED_OUTPUT_OPTIONS_REQUIRED', domain: ErrorDomain.AGENT, category: ErrorCategory.USER, text: 'structuredOutput is required to use tryStreamWithJsonFallback', }); } const { onStream, onStreamAttempt, onStreamFinish, fallbackJsonPromptInjection, ...streamOptions } = options; try { await onStreamAttempt?.(); const result = await agent.stream(prompt, streamOptions); void onStream?.(result as unknown as Awaited>); try { const object = await result.object; if (object === undefined) { throw new MastraError({ id: 'STRUCTURED_OUTPUT_OBJECT_UNDEFINED', domain: ErrorDomain.AGENT, category: ErrorCategory.USER, text: 'structuredOutput object is undefined', }); } return result; } finally { await onStreamFinish?.(result as unknown as Awaited>); } } catch (error) { if (!isStructuredOutputFormatError(error)) throw error; agent.__getLogger().warn('Error in tryStreamWithJsonFallback. Attempting fallback.', error); await onStreamAttempt?.(); const result = await agent.stream(prompt, { ...streamOptions, structuredOutput: { ...streamOptions.structuredOutput, jsonPromptInjection: fallbackJsonPromptInjection ?? (streamOptions.structuredOutput.jsonPromptInjection === 'inline' || streamOptions.structuredOutput.jsonPromptInjection === 'system' ? streamOptions.structuredOutput.jsonPromptInjection : true), }, }); void onStream?.(result as unknown as Awaited>); try { const object = await result.object; if (object === undefined) { throw new MastraError({ id: 'STRUCTURED_OUTPUT_OBJECT_UNDEFINED', domain: ErrorDomain.AGENT, category: ErrorCategory.USER, text: 'structuredOutput object is undefined', }); } return result; } finally { await onStreamFinish?.(result as unknown as Awaited>); } } } /** * Sentinel strings some models emit for the optional `suspendedToolRunId` auto-resume * field when they mean "no value". These are serialization artifacts, not run ids — * treating them as real ids defeats every falsy-based guard downstream (#23739). */ const SUSPENDED_TOOL_RUN_ID_SENTINELS = new Set(['null', 'undefined', 'none', 'nil']); /** * Normalizes a model-supplied `suspendedToolRunId` at the LLM trust boundary. * Returns `undefined` for non-strings, empty/whitespace-only strings, and known * serialization sentinels (`"null"`, `"undefined"`, `"none"`, `"nil"`, case-insensitive) * so callers can treat them exactly as if the model had omitted the field. * Any other string is returned unchanged (it may be a framework-persisted or * hook-supplied run id, which are not required to be UUIDs). */ export function resolveSuspendedToolRunId(value: unknown): string | undefined { if (typeof value !== 'string') return undefined; const trimmed = value.trim(); if (!trimmed) return undefined; if (SUSPENDED_TOOL_RUN_ID_SENTINELS.has(trimmed.toLowerCase())) return undefined; return value; } export function resolveThreadIdFromArgs(args: { memory?: { thread?: string | { id: string } }; threadId?: string; overrideId?: string; }): (Partial & { id: string }) | undefined { let resolved: (Partial & { id: string }) | undefined; if (args?.memory?.thread) { if (typeof args.memory.thread === 'string') { resolved = { id: args.memory.thread }; } else if (typeof args.memory.thread === 'object' && args.memory.thread.id) { resolved = args.memory.thread as Partial & { id: string }; } } if (!resolved && args?.threadId) { resolved = { id: args.threadId }; } if (args.overrideId) { return { ...(resolved || {}), id: args.overrideId }; } return resolved; }