UNPKG

@mastra/core

Version:
1 lines • 881 kB
{"version":3,"file":"stream-hnlwNJ12.cjs","names":["MastraBase","readModelStreamTransport","isUrlString","exhaustiveCheck","consumeStream","isPlainObject","mastraDBMessageToSignal","createSignal","JSONParseError","NoObjectGeneratedError","TypeValidationError","MastraError","ErrorDomain","ErrorCategory","EntityType","isAgentWorkflowTool","isValidationError","sanitizeToolName","isPlainObject","normalizePredicatePath","MISSING","MastraError","ErrorDomain","ErrorCategory","createSignal","APICallError","RESPONSE_ITEM_ID_PROVIDERS","RESPONSE_RESULT_ITEM_ID_KEY","getResponseProviderItemIdFromPart","EntityType","messagesAreEqual","createObservabilityContext","executeWithContext","RequestContext","MastraError","MessageList","resolveObservabilityContext","resolveModelConfig","isStandardSchemaWithJSON","standardSchemaToJSONSchema","applyCompatLayer","AnthropicSchemaCompatLayer","isZodType","MastraError","ErrorDomain","ErrorCategory","parsePartialJson","isDeepEqualData","standardSchemaToJSONSchema","toStandardSchema","TransformStream","convertMessages","isDataChunk","convertMessages","coreContentToString","MastraBase","EventEmitter","getRootExportSpan","resolveObservabilityContext","TransformStream","getErrorFromUnknown","MastraError","ErrorDomain","ErrorCategory","consumeStream","ReadableStream","resolveObservabilityContext","ReadableStream","primaryUsageKeys","EventEmitter","WritableStream","ReadableStream","ReadableStream","isUrlString","DefaultGeneratedFile","DefaultGeneratedFileWithType","TransformStream"],"sources":["../src/mastra/run-scope.ts","../src/stream/base/input.ts","../src/stream/aisdk/v5/compat/ui-message.ts","../src/stream/aisdk/v5/compat/delayed-promise.ts","../src/stream/aisdk/v5/compat/consume-stream.ts","../src/loop/timeout.ts","../src/agent/state-signals.ts","../src/agent/utils.ts","../src/processors/is-processor-workflow.ts","../src/loop/shared/normalize-model-output.ts","../src/loop/shared/steps/tool-result-commit-core.ts","../src/memory/types.ts","../src/storage/domains/workflows/state-patch.ts","../src/storage/domains/workflows/journal.ts","../src/storage/domains/workflows/snapshot-memory-info.ts","../src/workflows/step.ts","../src/workflows/mapping-template.ts","../src/workflows/step-refs.ts","../src/workflows/run-journal.ts","../src/processors/send-signal.ts","../src/processors/span-declaration.ts","../src/processors/span-payload.ts","../src/processors/stream-reprocess.ts","../src/processors/provider-history-compat.ts","../src/processors/trailing-assistant-guard.ts","../src/processors/runner.ts","../src/stream/signal-exclusions.ts","../src/stream/base/schema.ts","../src/stream/base/output-format-handlers.ts","../src/stream/base/output-processed.ts","../src/stream/base/produced-at.ts","../src/stream/base/step-message-mirrors.ts","../src/stream/base/step-request-dedupe.ts","../src/stream/base/output.ts","../src/agent/trip-wire.ts","../src/stream/base/consume-stream.ts","../src/stream/RunOutput.ts","../src/stream/MastraAgentNetworkStream.ts","../src/stream/aisdk/v5/transform.ts","../src/stream/caching-transform-stream.ts","../src/stream/smooth-stream.ts"],"sourcesContent":["/**\n * RunScope — per-run bag of *non-serializable* runtime state.\n *\n * The evented workflow engine routes step inputs/outputs through `JSON.stringify`\n * (storage snapshots, `UnixSocketPubSub` frames). Live class instances, function\n * closures, abort controllers, and stream transports cannot survive that round\n * trip even with the Phase 2 codec. RunScope keeps those values off the wire:\n * step factories read and write through a typed key-value bag keyed by `runId`\n * and held on the parent `Mastra` instance. Nothing in the scope is ever\n * persisted or published.\n *\n * Scopes are refcounted alongside the internal-workflow registry on `Mastra`:\n * `__registerInternalWorkflow` / `__unregisterInternalWorkflow` hold and\n * release them, and call sites that need a scope before registration pair\n * `__createRunScope` with `__releaseRunScope`. They share the same TTL sweep\n * as the run-scoped workflow registrations they back, so a scope dies with its\n * run.\n *\n * Never put RunScope values on step input/output schemas. Step I/O crosses the\n * wire and must stay JSON-safe: the codec in `events/codec` round-trips a fixed\n * set of built-ins and registered classes at the `UnixSocketPubSub` boundary,\n * but live handles and closures are dropped.\n *\n * Keys are branded symbols carrying their value type as a phantom parameter,\n * so `scope.get(SAVE_QUEUE_MANAGER)` returns `SaveQueueManager | undefined`\n * without any cast at the call site. Concrete key registries live next to the\n * consumers (see `loop/run-scope-keys.ts`, `agent/workflows/prepare-stream/\n * run-scope-keys.ts`) to avoid pulling domain types into the `mastra` layer.\n */\n\n/**\n * A typed handle to a slot in a {@link RunScope}. The phantom `__t` parameter\n * carries the value type so `get` / `set` are inferred correctly without an\n * explicit type argument.\n */\nexport interface RunScopeKey<T> extends Symbol {\n  /** Phantom marker — never read at runtime. */\n  readonly __t?: T;\n}\n\n/**\n * Create a new {@link RunScopeKey}. Each call produces a fresh `Symbol`, so two\n * keys with the same label do not collide.\n */\nexport function createRunScopeKey<T>(label: string): RunScopeKey<T> {\n  return Symbol(label) as RunScopeKey<T>;\n}\n\nexport interface RunScope {\n  get<T>(key: RunScopeKey<T>): T | undefined;\n  /**\n   * Read a required slot. Throws if missing — use this to make a missing\n   * invariant fail loudly instead of producing a downstream `undefined`.\n   */\n  getOrThrow<T>(key: RunScopeKey<T>): T;\n  set<T>(key: RunScopeKey<T>, value: T): void;\n  delete<T>(key: RunScopeKey<T>): void;\n  has<T>(key: RunScopeKey<T>): boolean;\n  /** Test-only: number of slots currently populated. */\n  readonly size: number;\n}\n\nclass MapRunScope implements RunScope {\n  readonly #slots = new Map<symbol, unknown>();\n\n  get<T>(key: RunScopeKey<T>): T | undefined {\n    return this.#slots.get(key as unknown as symbol) as T | undefined;\n  }\n\n  getOrThrow<T>(key: RunScopeKey<T>): T {\n    const sym = key as unknown as symbol;\n    if (!this.#slots.has(sym)) {\n      throw new Error(`RunScope: missing required slot ${sym.toString()}`);\n    }\n    return this.#slots.get(sym) as T;\n  }\n\n  set<T>(key: RunScopeKey<T>, value: T): void {\n    this.#slots.set(key as unknown as symbol, value);\n  }\n\n  delete<T>(key: RunScopeKey<T>): void {\n    this.#slots.delete(key as unknown as symbol);\n  }\n\n  has<T>(key: RunScopeKey<T>): boolean {\n    return this.#slots.has(key as unknown as symbol);\n  }\n\n  get size(): number {\n    return this.#slots.size;\n  }\n}\n\nexport function createRunScope(): RunScope {\n  return new MapRunScope();\n}\n","import type { LanguageModelV2StreamPart } from '@ai-sdk/provider-v5';\nimport { MastraBase } from '../../base';\nimport { attachModelStreamTransport, readModelStreamTransport } from '../types';\nimport type { ChunkType, CreateStream, OnResult } from '../types';\n\n/**\n * Safely enqueue a chunk into a ReadableStreamDefaultController.\n * Returns true if the enqueue succeeded, false if the controller was already closed/errored.\n *\n * Prefer this over checking desiredSize before enqueue, because desiredSize === 0\n * indicates backpressure (queue full, stream still open) — not closure.\n * Guarding on desiredSize would silently drop chunks under normal backpressure.\n */\nexport function safeEnqueue<T>(controller: ReadableStreamDefaultController<T>, chunk: T): boolean {\n  try {\n    controller.enqueue(chunk);\n    return true;\n  } catch {\n    return false;\n  }\n}\n\n/**\n * Safely close a ReadableStreamDefaultController.\n * Returns true if the close succeeded, false if the controller was already closed/errored.\n */\nexport function safeClose(controller: ReadableStreamDefaultController<any>): boolean {\n  try {\n    controller.close();\n    return true;\n  } catch {\n    return false;\n  }\n}\n\n/**\n * Safely signal an error on a ReadableStreamDefaultController.\n * Returns true if the error succeeded, false if the controller was already closed/errored.\n */\nexport function safeError(controller: ReadableStreamDefaultController<any>, error: unknown): boolean {\n  try {\n    controller.error(error);\n    return true;\n  } catch {\n    return false;\n  }\n}\n\nexport abstract class MastraModelInput extends MastraBase {\n  abstract transform({\n    runId,\n    stream,\n    controller,\n  }: {\n    runId: string;\n    stream: ReadableStream<LanguageModelV2StreamPart | Record<string, unknown>>;\n    controller: ReadableStreamDefaultController<ChunkType>;\n  }): Promise<void>;\n\n  initialize({ runId, createStream, onResult }: { createStream: CreateStream; runId: string; onResult: OnResult }) {\n    const self = this;\n\n    let outputStream: ReadableStream<ChunkType>;\n    outputStream = new ReadableStream<ChunkType>({\n      async start(controller) {\n        try {\n          const stream = await createStream();\n          attachModelStreamTransport(outputStream, readModelStreamTransport(stream));\n\n          const initialChunks = onResult({\n            warnings: stream.warnings,\n            request: stream.request,\n            rawResponse: stream.rawResponse || stream.response || {},\n          });\n          if (initialChunks) {\n            for (const chunk of Array.isArray(initialChunks) ? initialChunks : [initialChunks]) {\n              controller.enqueue(chunk);\n            }\n          }\n\n          await self.transform({\n            runId,\n            stream: stream.stream,\n            controller,\n          });\n\n          safeClose(controller);\n        } catch (error) {\n          safeError(controller, error);\n        }\n      },\n    });\n\n    return outputStream;\n  }\n}\n","import type { InferUIMessageChunk, TextStreamPart, ToolSet, UIMessage, IdGenerator } from '@internal/ai-sdk-v5';\nimport { isUrlString } from './content';\n\nexport function getResponseUIMessageId({\n  originalMessages,\n  responseMessageId,\n}: {\n  originalMessages: UIMessage[] | undefined;\n  responseMessageId: string | IdGenerator | undefined;\n}) {\n  // when there are no original messages (i.e. no persistence),\n  // the assistant message id generation is handled on the client side.\n  if (originalMessages == null) {\n    return undefined;\n  }\n\n  const lastMessage = originalMessages[originalMessages.length - 1];\n\n  return lastMessage?.role === 'assistant'\n    ? lastMessage.id\n    : typeof responseMessageId === 'function'\n      ? responseMessageId()\n      : responseMessageId;\n}\n\nexport function convertFullStreamChunkToUIMessageStream<UI_MESSAGE extends UIMessage>({\n  part,\n  messageMetadataValue,\n  sendReasoning,\n  sendSources,\n  onError,\n  sendStart,\n  sendFinish,\n  responseMessageId,\n}: {\n  // tool-output is a custom mastra chunk type used in ToolStream\n  part: TextStreamPart<ToolSet> | { type: 'tool-output'; toolCallId: string; output: any };\n  messageMetadataValue?: unknown;\n  sendReasoning?: boolean;\n  sendSources?: boolean;\n  onError: (error: unknown) => string;\n  sendStart?: boolean;\n  sendFinish?: boolean;\n  responseMessageId?: string;\n}): InferUIMessageChunk<UI_MESSAGE> | undefined {\n  const partType = part.type;\n\n  switch (partType) {\n    case 'text-start': {\n      return {\n        type: 'text-start',\n        id: part.id,\n        ...(part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}),\n      };\n    }\n\n    case 'text-delta': {\n      return {\n        type: 'text-delta',\n        id: part.id,\n        delta: part.text,\n        ...(part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}),\n      };\n    }\n\n    case 'text-end': {\n      return {\n        type: 'text-end',\n        id: part.id,\n        ...(part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}),\n      };\n    }\n\n    case 'reasoning-start': {\n      return {\n        type: 'reasoning-start',\n        id: part.id,\n        ...(part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}),\n      };\n    }\n\n    case 'reasoning-delta': {\n      if (sendReasoning) {\n        return {\n          type: 'reasoning-delta',\n          id: part.id,\n          delta: part.text,\n          ...(part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}),\n        };\n      }\n      return;\n    }\n\n    case 'reasoning-end': {\n      return {\n        type: 'reasoning-end',\n        id: part.id,\n        ...(part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}),\n      };\n    }\n\n    case 'file': {\n      // URL-backed generated files store the URL string where base64 normally\n      // lives; emit it as the url directly instead of a broken data URI.\n      const base64 = part.file.base64;\n      return {\n        type: 'file',\n        mediaType: part.file.mediaType,\n        url: isUrlString(base64) ? base64 : `data:${part.file.mediaType};base64,${base64}`,\n      };\n    }\n\n    case 'source': {\n      if (sendSources && part.sourceType === 'url') {\n        return {\n          type: 'source-url',\n          sourceId: part.id,\n          url: part.url,\n          title: part.title,\n          ...(part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}),\n        };\n      }\n\n      if (sendSources && part.sourceType === 'document') {\n        return {\n          type: 'source-document',\n          sourceId: part.id,\n          mediaType: part.mediaType,\n          title: part.title,\n          filename: part.filename,\n          ...(part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}),\n        };\n      }\n      return;\n    }\n\n    case 'tool-input-start': {\n      return {\n        type: 'tool-input-start',\n        toolCallId: part.id,\n        toolName: part.toolName,\n        ...(part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {}),\n        ...(part.dynamic != null ? { dynamic: part.dynamic } : {}),\n      };\n    }\n\n    case 'tool-input-delta': {\n      return {\n        type: 'tool-input-delta',\n        toolCallId: part.id,\n        inputTextDelta: part.delta,\n      };\n    }\n\n    case 'tool-call': {\n      return {\n        type: 'tool-input-available',\n        toolCallId: part.toolCallId,\n        toolName: part.toolName,\n        input: part.input,\n        ...(part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {}),\n        ...(part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}),\n        ...(part.dynamic != null ? { dynamic: part.dynamic } : {}),\n      };\n    }\n\n    case 'tool-result': {\n      return {\n        type: 'tool-output-available',\n        toolCallId: part.toolCallId,\n        output: part.output,\n        ...(part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {}),\n        ...(part.dynamic != null ? { dynamic: part.dynamic } : {}),\n        ...(part.preliminary != null ? { preliminary: part.preliminary } : {}),\n      };\n    }\n\n    case 'tool-output': {\n      return {\n        ...part.output,\n      };\n    }\n\n    case 'tool-error': {\n      return {\n        type: 'tool-output-error',\n        toolCallId: part.toolCallId,\n        errorText: onError(part.error),\n        ...(part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {}),\n        ...(part.dynamic != null ? { dynamic: part.dynamic } : {}),\n      };\n    }\n\n    case 'error': {\n      return {\n        type: 'error',\n        errorText: onError(part.error),\n      };\n    }\n\n    case 'start-step': {\n      return { type: 'start-step' };\n    }\n\n    case 'finish-step': {\n      return { type: 'finish-step' };\n    }\n\n    case 'start': {\n      if (sendStart) {\n        return {\n          type: 'start' as const,\n          ...(messageMetadataValue != null ? { messageMetadata: messageMetadataValue } : {}),\n          ...(responseMessageId != null ? { messageId: responseMessageId } : {}),\n        } as InferUIMessageChunk<UI_MESSAGE>;\n      }\n      return;\n    }\n\n    case 'finish': {\n      if (sendFinish) {\n        return {\n          type: 'finish' as const,\n          // Matches the AI SDK UI converter, which keeps the finish reason on the terminal chunk.\n          ...(part.finishReason != null ? { finishReason: part.finishReason } : {}),\n          ...(messageMetadataValue != null ? { messageMetadata: messageMetadataValue } : {}),\n        } as InferUIMessageChunk<UI_MESSAGE>;\n      }\n      return;\n    }\n\n    case 'abort': {\n      return part;\n    }\n\n    case 'tool-input-end': {\n      return undefined;\n    }\n\n    case 'raw': {\n      // Raw chunks are not included in UI message streams\n      // as they contain provider-specific data for developer use\n      return;\n    }\n\n    default: {\n      const exhaustiveCheck: never = partType;\n      throw new Error(`Unknown chunk type: ${exhaustiveCheck}`);\n    }\n  }\n}\n","/**\n * Delayed promise. It is only constructed once the value is accessed.\n * This is useful to avoid unhandled promise rejections when the promise is created\n * but not accessed.\n */\nexport class DelayedPromise<T> {\n  public status: { type: 'pending' } | { type: 'resolved'; value: T } | { type: 'rejected'; error: unknown } = {\n    type: 'pending',\n  };\n  private _promise: Promise<T> | undefined;\n  private _resolve: undefined | ((value: T) => void) = undefined;\n  private _reject: undefined | ((error: unknown) => void) = undefined;\n\n  get promise(): Promise<T> {\n    if (this._promise) {\n      return this._promise;\n    }\n\n    this._promise = new Promise<T>((resolve, reject) => {\n      if (this.status.type === 'resolved') {\n        resolve(this.status.value);\n        return;\n      }\n      if (this.status.type === 'rejected') {\n        reject(this.status.error);\n        return;\n      }\n\n      this._resolve = resolve;\n      this._reject = reject;\n    });\n\n    return this._promise;\n  }\n\n  resolve(value: T): void {\n    this.status = { type: 'resolved', value };\n\n    if (!this._promise) return;\n\n    if (this._resolve) {\n      const resolve = this._resolve;\n      this._resolve = undefined;\n      resolve(value);\n      return;\n    }\n\n    // Already settled. A durable stream publishes usage at suspension, then the\n    // resumed finish replaces it. Chain onto the promise itself so a later await\n    // of the getter sees the latest value, not the provisional one.\n    this._promise = this._promise.then(() => value);\n  }\n\n  reject(error: unknown): void {\n    this.status = { type: 'rejected', error };\n\n    if (this._promise) {\n      this._reject?.(error);\n    }\n  }\n}\n","import type { IMastraLogger } from '../../../../logger';\n\nexport type ConsumeStreamOptions = {\n  onError?: (error: unknown) => void;\n  logger?: IMastraLogger;\n};\n\nexport async function consumeStream({\n  stream,\n  onError,\n  logger,\n}: {\n  stream: ReadableStream;\n  onError?: (error: unknown) => void;\n  logger?: IMastraLogger;\n}): Promise<void> {\n  // Acquire the reader inside the try: a stream that is already locked by another\n  // consumer must surface through onError, not as a rejection of this promise.\n  let reader: ReadableStreamDefaultReader | undefined;\n  try {\n    reader = stream.getReader();\n    while (true) {\n      const { done } = await reader.read();\n      if (done) break;\n    }\n  } catch (error) {\n    logger?.error('consumeStream error', error);\n    onError?.(error);\n  } finally {\n    reader?.releaseLock();\n  }\n}\n","/**\n * Error thrown when a Mastra execution budget (`modelSettings.timeout`) is exceeded.\n *\n * This is distinct from a caller-supplied abort so that timeouts can be reported as\n * failures rather than treated as clean cancellations.\n */\nexport type MastraTimeoutType = 'step' | 'total' | 'firstChunk';\n\nexport class MastraTimeoutError extends Error {\n  readonly timeoutType: MastraTimeoutType;\n  readonly timeoutMs: number;\n\n  constructor({ timeoutType, timeoutMs }: { timeoutType: MastraTimeoutType; timeoutMs: number }) {\n    super(\n      timeoutType === 'total'\n        ? `Agent execution timed out after ${timeoutMs}ms (modelSettings.timeout.totalMs)`\n        : timeoutType === 'firstChunk'\n          ? `Model call timed out before first content after ${timeoutMs}ms (modelSettings.timeout.firstChunkMs)`\n          : `Model call timed out after ${timeoutMs}ms (modelSettings.timeout.stepMs)`,\n    );\n    this.name = 'MastraTimeoutError';\n    this.timeoutType = timeoutType;\n    this.timeoutMs = timeoutMs;\n  }\n}\n\n/**\n * How long a total deadline's memory save may hold back the deadline error. A save that takes longer\n * (a hung store) finishes in the background; the caller still sees the deadline on time.\n */\nexport const DEADLINE_SAVE_WAIT_MS = 1_000;\n\n/** How long a durable run keeps its claim waiting for that save, so a hung store cannot block a later run with the same ID. */\nexport const DEADLINE_SAVE_CLAIM_HOLD_MS = 30_000;\n\n/** Resolves when `promise` settles or `ms` passes, whichever is first. Never rejects. */\nexport function settledOrElapsed(promise: Promise<unknown>, ms: number): Promise<void> {\n  let timer: ReturnType<typeof setTimeout> | undefined;\n  return Promise.race([\n    promise.then(\n      () => {},\n      () => {},\n    ),\n    new Promise<void>(resolve => {\n      timer = setTimeout(resolve, ms);\n    }),\n  ]).finally(() => clearTimeout(timer));\n}\n\nexport function isMastraTimeoutError(error: unknown): error is MastraTimeoutError {\n  return error instanceof MastraTimeoutError;\n}\n\n/**\n * Returns the abort reason of a signal, if it has been aborted.\n */\nexport function getAbortReason(signal?: AbortSignal): unknown {\n  return signal?.aborted ? signal.reason : undefined;\n}\n\nexport type TimeoutAbortSignal = {\n  /** The signal to pass downstream. Identical to `parentSignal` when no timeout is configured. */\n  signal: AbortSignal | undefined;\n  /** Rejects with a `MastraTimeoutError` when the budget elapses. Undefined when no timeout is configured. */\n  timeoutPromise?: Promise<never>;\n  /** Clears the timer and, unless `detachParentOnCleanup` is false, detaches the parent listener. Safe to call more than once. */\n  cleanup: () => void;\n};\n\n/**\n * Composes a caller-supplied abort signal with a time budget.\n *\n * When `timeoutMs` is undefined this is a pass-through: the parent signal is returned\n * unchanged and no timer is created.\n *\n * Set `detachParentOnCleanup: false` when the parent signal lives no longer than the\n * derived signal and `cleanup` may run while consumers still hold the derived signal:\n * cleanup then only clears the timer, so a later parent abort still propagates.\n */\nexport function createTimeoutAbortSignal({\n  parentSignal,\n  timeoutMs,\n  timeoutType,\n  detachParentOnCleanup = true,\n}: {\n  parentSignal?: AbortSignal;\n  timeoutMs?: number;\n  timeoutType: MastraTimeoutType;\n  detachParentOnCleanup?: boolean;\n}): TimeoutAbortSignal {\n  if (typeof timeoutMs !== 'number' || !Number.isFinite(timeoutMs) || timeoutMs <= 0) {\n    return { signal: parentSignal, cleanup: () => {} };\n  }\n\n  const controller = new AbortController();\n\n  let rejectTimeout: ((error: MastraTimeoutError) => void) | undefined;\n  const timeoutPromise = new Promise<never>((_resolve, reject) => {\n    rejectTimeout = reject;\n  });\n  // The race loser is never observed by callers, so pre-attach a handler.\n  timeoutPromise.catch(() => {});\n\n  const timer = setTimeout(() => {\n    const error = new MastraTimeoutError({ timeoutType, timeoutMs });\n    controller.abort(error);\n    rejectTimeout?.(error);\n  }, timeoutMs);\n  // Never hold the process open on account of a pending budget.\n  timer.unref?.();\n\n  const onParentAbort = () => {\n    controller.abort(parentSignal?.reason);\n  };\n\n  if (parentSignal) {\n    if (parentSignal.aborted) {\n      onParentAbort();\n    } else {\n      parentSignal.addEventListener('abort', onParentAbort, { once: true });\n    }\n  }\n\n  return {\n    signal: controller.signal,\n    timeoutPromise,\n    cleanup: () => {\n      clearTimeout(timer);\n      if (detachParentOnCleanup) {\n        parentSignal?.removeEventListener('abort', onParentAbort);\n      }\n    },\n  };\n}\n\n/**\n * Rejects as soon as `signal` aborts, otherwise resolves with `promise`.\n *\n * Guards against providers that ignore `abortSignal` and would otherwise hang past\n * their budget.\n */\n/**\n * Keeps a budget in force while a stream is consumed.\n *\n * Establishing a stream is rarely the slow part — a provider can open one and then stall\n * mid-emission — so the budget has to stay armed until the stream ends. Errors the stream\n * with the abort reason if the signal fires before it completes, and cancels the upstream\n * so the provider connection is not left dangling.\n *\n * `onSettled` runs exactly once, whether the stream completes, errors or aborts.\n */\nexport function guardStreamWithAbort<T>(\n  stream: ReadableStream<T>,\n  signal?: AbortSignal,\n  onSettled?: () => void,\n): ReadableStream<T> {\n  if (!signal) {\n    if (!onSettled) return stream;\n    return stream.pipeThrough(\n      new TransformStream<T, T>({\n        flush: () => onSettled(),\n      }) as any,\n    );\n  }\n\n  const reader = stream.getReader();\n  let settled = false;\n  const settle = () => {\n    if (settled) return;\n    settled = true;\n    onSettled?.();\n  };\n\n  return new ReadableStream<T>({\n    async pull(controller) {\n      try {\n        const { done, value } = await raceAgainstAbort(reader.read(), signal);\n        if (done) {\n          settle();\n          controller.close();\n          return;\n        }\n        controller.enqueue(value);\n      } catch (error) {\n        settle();\n        reader.cancel(error).catch(() => {});\n        controller.error(error);\n      }\n    },\n    cancel(reason) {\n      settle();\n      return reader.cancel(reason);\n    },\n  });\n}\n\nexport function guardStreamUntilMatch<T>(\n  stream: ReadableStream<T>,\n  signal: AbortSignal | undefined,\n  matches: (chunk: T) => boolean,\n  onMatchedOrSettled: () => void,\n): ReadableStream<T> {\n  if (!signal) return stream;\n\n  const reader = stream.getReader();\n  let active = true;\n  const settle = () => {\n    if (!active) return;\n    active = false;\n    onMatchedOrSettled();\n  };\n\n  return new ReadableStream<T>({\n    async pull(controller) {\n      try {\n        const result = active ? await raceAgainstAbort(reader.read(), signal) : await reader.read();\n        if (result.done) {\n          settle();\n          controller.close();\n          return;\n        }\n        if (matches(result.value)) settle();\n        controller.enqueue(result.value);\n      } catch (error) {\n        settle();\n        reader.cancel(error).catch(() => {});\n        controller.error(error);\n      }\n    },\n    cancel(reason) {\n      settle();\n      return reader.cancel(reason);\n    },\n  });\n}\n\nexport function raceAgainstAbort<T>(promise: Promise<T>, signal?: AbortSignal): Promise<T> {\n  if (!signal) return promise;\n\n  if (signal.aborted) {\n    promise.catch(() => {});\n    return Promise.reject(signal.reason ?? new Error('Aborted'));\n  }\n\n  return new Promise<T>((resolve, reject) => {\n    const onAbort = () => {\n      reject(signal.reason ?? new Error('Aborted'));\n    };\n    signal.addEventListener('abort', onAbort, { once: true });\n\n    promise.then(\n      value => {\n        signal.removeEventListener('abort', onAbort);\n        resolve(value);\n      },\n      error => {\n        signal.removeEventListener('abort', onAbort);\n        reject(error);\n      },\n    );\n  });\n}\n","import type { MastraMemory } from '../memory/memory';\nimport type { MemoryConfigInternal, StorageThreadType } from '../memory/types';\nimport type { MessageList } from './message-list';\nimport type { MastraDBMessage } from './message-list/state/types';\nimport { createSignal, mastraDBMessageToSignal } from './signals';\nimport type { AgentStateSignalInput, CreatedAgentSignal } from './signals';\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nexport type StateSignalTracking = {\n  currentCacheKey?: string;\n  currentMode?: 'snapshot' | 'delta';\n  version?: number;\n  lastSignalId?: string;\n  lastSnapshotSignalId?: string;\n  updatedAt?: string;\n  activeCopies?: Array<{ id: string; cacheKey?: string; mode?: 'snapshot' | 'delta'; version?: number }>;\n};\n\nexport type ActiveStateSignal = CreatedAgentSignal & {\n  type: 'state';\n  metadata?: Record<string, unknown> & {\n    state?: {\n      id?: string;\n      threadId?: string;\n      cacheKey?: string;\n      version?: number;\n      mode?: 'snapshot' | 'delta';\n    };\n  };\n};\n\nexport type StateSignalHistory = {\n  activeStateSignals: ActiveStateSignal[];\n  contextWindow: {\n    hasSnapshot: boolean;\n  };\n  lastSnapshot?: ActiveStateSignal;\n  deltasSinceSnapshot: ActiveStateSignal[];\n};\n\nexport type ApplyStateSignalResult =\n  | { skipped: true; reason: 'unchanged'; stateId: string; tracking?: StateSignalTracking }\n  | { skipped: false; signal: CreatedAgentSignal; stateId: string; version: number; tracking: StateSignalTracking };\n\nexport function getStateSignalsMetadata(threadMetadata?: Record<string, unknown>): Record<string, StateSignalTracking> {\n  if (!threadMetadata) return {};\n  const mastra = threadMetadata.mastra;\n  if (!isPlainObject(mastra)) return {};\n  const stateSignals = mastra.stateSignals;\n  return isPlainObject(stateSignals) ? (stateSignals as Record<string, StateSignalTracking>) : {};\n}\n\nexport function setStateSignalMetadata(\n  threadMetadata: Record<string, unknown> | undefined,\n  stateId: string,\n  tracking: StateSignalTracking,\n): Record<string, unknown> {\n  const existing = threadMetadata ?? {};\n  const existingMastra = isPlainObject(existing.mastra) ? existing.mastra : {};\n  const existingStateSignals = isPlainObject(existingMastra.stateSignals) ? existingMastra.stateSignals : {};\n\n  return {\n    ...existing,\n    mastra: {\n      ...existingMastra,\n      stateSignals: {\n        ...existingStateSignals,\n        [stateId]: tracking,\n      },\n    },\n  };\n}\n\nfunction signalCreatedAt(signal: ActiveStateSignal): number {\n  const createdAt = signal.createdAt instanceof Date ? signal.createdAt : new Date(signal.createdAt);\n  const timestamp = createdAt.getTime();\n  return Number.isNaN(timestamp) ? 0 : timestamp;\n}\n\nexport function sortStateSignals(signals: ActiveStateSignal[]): ActiveStateSignal[] {\n  return signals\n    .map((signal, index) => ({ signal, index }))\n    .sort((left, right) => signalCreatedAt(left.signal) - signalCreatedAt(right.signal) || left.index - right.index)\n    .map(({ signal }) => signal);\n}\n\nexport function dbMessagesToStateSignals(\n  messages: MastraDBMessage[],\n  stateId: string | undefined,\n  threadId: string,\n): ActiveStateSignal[] {\n  return sortStateSignals(\n    messages\n      .filter(message => message.role === 'signal')\n      .map(message => {\n        try {\n          return mastraDBMessageToSignal(message);\n        } catch {\n          return undefined;\n        }\n      })\n      .filter(\n        (signal): signal is ActiveStateSignal =>\n          signal?.type === 'state' &&\n          isPlainObject(signal.metadata?.state) &&\n          (!stateId || signal.metadata.state.id === stateId) &&\n          signal.metadata.state.threadId === threadId,\n      ),\n  );\n}\n\nexport function getActiveStateSignals(\n  messageList: MessageList,\n  stateId: string | undefined,\n  threadId: string,\n): ActiveStateSignal[] {\n  return dbMessagesToStateSignals(messageList.get.all.db(), stateId, threadId);\n}\n\nexport function mergeStateSignals(...signalGroups: ActiveStateSignal[][]): ActiveStateSignal[] {\n  const signalsById = new Map<string, ActiveStateSignal>();\n  for (const signal of signalGroups.flat()) {\n    signalsById.set(signal.id, signal);\n  }\n  return sortStateSignals([...signalsById.values()]);\n}\n\nexport function deriveStateSignalHistory(activeStateSignals: ActiveStateSignal[]): StateSignalHistory {\n  const sortedStateSignals = sortStateSignals(activeStateSignals);\n  const lastSnapshotIndex = sortedStateSignals.findLastIndex(signal => signal.metadata?.state?.mode === 'snapshot');\n  const lastSnapshot = lastSnapshotIndex >= 0 ? sortedStateSignals[lastSnapshotIndex] : undefined;\n  const deltasSinceSnapshot = sortedStateSignals\n    .slice(lastSnapshotIndex + 1)\n    .filter(signal => signal.metadata?.state?.mode === 'delta');\n\n  return {\n    activeStateSignals: sortedStateSignals,\n    contextWindow: {\n      hasSnapshot: Boolean(lastSnapshot),\n    },\n    lastSnapshot,\n    deltasSinceSnapshot,\n  };\n}\n\nexport async function resolveStateSignalHistory({\n  messageList,\n  memory,\n  threadId,\n  stateId,\n  tracking,\n}: {\n  messageList: MessageList;\n  memory: MastraMemory;\n  threadId: string;\n  stateId: string;\n  tracking?: StateSignalTracking;\n}): Promise<StateSignalHistory> {\n  const localStateSignals = getActiveStateSignals(messageList, stateId, threadId);\n  const localHistory = deriveStateSignalHistory(localStateSignals);\n  const contextWindow = localHistory.contextWindow;\n\n  if (localHistory.contextWindow.hasSnapshot || !tracking?.lastSnapshotSignalId) {\n    return { ...localHistory, contextWindow };\n  }\n\n  const memoryStore = await memory.storage.getStore('memory');\n  if (!memoryStore) return { ...localHistory, contextWindow };\n\n  const trackedSignalIds = new Set<string>();\n  for (const activeCopy of tracking.activeCopies ?? []) {\n    trackedSignalIds.add(activeCopy.id);\n  }\n  trackedSignalIds.add(tracking.lastSnapshotSignalId);\n\n  if (trackedSignalIds.size === 0 || typeof memoryStore.listMessagesById !== 'function') {\n    return { ...localHistory, contextWindow };\n  }\n\n  const storedMessages = await memoryStore.listMessagesById({ messageIds: [...trackedSignalIds] });\n  const storedStateSignals = dbMessagesToStateSignals(storedMessages.messages, stateId, threadId);\n  const resolvedStateSignals = mergeStateSignals(storedStateSignals, localStateSignals);\n\n  return {\n    ...deriveStateSignalHistory(resolvedStateSignals.length > 0 ? resolvedStateSignals : localStateSignals),\n    contextWindow,\n  };\n}\n\nexport function createStateSignalInput(\n  input: AgentStateSignalInput | (Omit<AgentStateSignalInput, 'id'> & { id?: string }),\n  options?: { defaultId?: string; acceptedAt?: Date },\n): {\n  stateId: string;\n  signal: Extract<CreatedAgentSignal, { type: 'state' }>;\n  mode: 'snapshot' | 'delta';\n  cacheKey: string;\n} {\n  const stateId = input.id ?? options?.defaultId;\n  if (!stateId) {\n    throw new Error('state signal id is required');\n  }\n  if (!input.cacheKey) {\n    throw new Error('state signal cacheKey is required');\n  }\n\n  const mode = input.mode ?? 'snapshot';\n  const { id: _stateId, cacheKey, mode: _mode, value, delta, metadata, ...signalInput } = input;\n  const signal = createSignal({\n    ...signalInput,\n    type: 'state',\n    tagName: signalInput.tagName ?? 'state',\n    acceptedAt: options?.acceptedAt,\n    metadata: {\n      ...metadata,\n      state: {\n        ...(isPlainObject(metadata?.state) ? metadata.state : {}),\n        id: stateId,\n        cacheKey,\n        mode,\n      },\n      ...(value !== undefined ? { value } : {}),\n      ...(delta !== undefined ? { delta } : {}),\n    },\n  });\n\n  return { stateId, signal, mode, cacheKey };\n}\n\nexport async function applyStateSignal({\n  input,\n  memory,\n  thread,\n  resourceId,\n  threadId,\n  memoryConfig,\n  messageList,\n  activeStateSignals,\n  defaultId,\n  acceptedAt,\n  beforeAddSignal,\n  writeSignal,\n}: {\n  input: AgentStateSignalInput | (Omit<AgentStateSignalInput, 'id'> & { id?: string });\n  memory: MastraMemory;\n  thread: StorageThreadType;\n  resourceId: string;\n  threadId: string;\n  memoryConfig?: MemoryConfigInternal;\n  messageList?: MessageList;\n  activeStateSignals?: ActiveStateSignal[];\n  defaultId?: string;\n  acceptedAt?: Date;\n  beforeAddSignal?: () => void;\n  writeSignal?: (signal: CreatedAgentSignal) => Promise<void> | void;\n}): Promise<ApplyStateSignalResult> {\n  const { stateId, signal, cacheKey, mode } = createStateSignalInput(input, { defaultId, acceptedAt });\n  const activeSignals =\n    activeStateSignals ?? (messageList ? getActiveStateSignals(messageList, stateId, threadId) : []);\n  const tracking = getStateSignalsMetadata(thread.metadata)[stateId];\n\n  const usesActiveWindow = Boolean(messageList || activeStateSignals);\n  const hasActiveCopy = activeSignals.some(\n    signal => signal.metadata?.state?.cacheKey === cacheKey && signal.metadata?.state?.mode === mode,\n  );\n  const matchesCurrentState =\n    tracking?.currentCacheKey === cacheKey &&\n    (tracking.currentMode === mode || (!tracking.currentMode && hasActiveCopy));\n  if (matchesCurrentState && (!usesActiveWindow || hasActiveCopy)) {\n    return { skipped: true, reason: 'unchanged', stateId, tracking };\n  }\n\n  const previousVersion = typeof tracking?.version === 'number' ? tracking.version : 0;\n  const version = matchesCurrentState ? previousVersion || 1 : previousVersion + 1;\n  const updatedSignal = createSignal({\n    ...signal,\n    metadata: {\n      ...signal.metadata,\n      state: {\n        ...(isPlainObject(signal.metadata?.state) ? signal.metadata.state : {}),\n        id: stateId,\n        threadId,\n        cacheKey,\n        version,\n        mode,\n      },\n    },\n  });\n\n  beforeAddSignal?.();\n  if (messageList) {\n    messageList.addSignal(updatedSignal);\n  }\n  await writeSignal?.(updatedSignal);\n\n  const updatedAt = new Date().toISOString();\n  const updatedActiveSignals = [...activeSignals, updatedSignal];\n  const nextTracking: StateSignalTracking = {\n    currentCacheKey: cacheKey,\n    currentMode: mode,\n    version,\n    lastSignalId: updatedSignal.id,\n    lastSnapshotSignalId: mode === 'snapshot' ? updatedSignal.id : tracking?.lastSnapshotSignalId,\n    updatedAt,\n    activeCopies: updatedActiveSignals.map(activeSignal => {\n      const activeStateMetadata = isPlainObject(activeSignal.metadata?.state) ? activeSignal.metadata.state : {};\n      return {\n        id: activeSignal.id,\n        ...(typeof activeStateMetadata.cacheKey === 'string' ? { cacheKey: activeStateMetadata.cacheKey } : {}),\n        ...(activeStateMetadata.mode === 'snapshot' || activeStateMetadata.mode === 'delta'\n          ? { mode: activeStateMetadata.mode }\n          : {}),\n        ...(typeof activeStateMetadata.version === 'number' ? { version: activeStateMetadata.version } : {}),\n      };\n    }),\n  };\n\n  await memory.saveThread({\n    thread: {\n      ...thread,\n      id: threadId,\n      resourceId: thread.resourceId ?? resourceId,\n      createdAt: thread.createdAt ?? new Date(),\n      updatedAt: new Date(updatedAt),\n      metadata: setStateSignalMetadata(thread.metadata, stateId, nextTracking),\n    },\n    memoryConfig,\n  });\n\n  return { skipped: false, signal: updatedSignal, stateId, version, tracking: nextTracking };\n}\n","import { JSONParseError, NoObjectGeneratedError, TypeValidationError } from '@internal/ai-sdk-v5';\n\nimport { ErrorCategory, ErrorDomain, MastraError } from '../error';\nimport type { MastraLegacyLanguageModel, MastraLanguageModel } from '../llm/model/shared.types';\nimport type { StorageThreadType } from '../memory';\nimport type { StandardSchemaWithJSON, InferStandardSchemaOutput } from '../schema';\nimport type { FullOutput } from '../stream/base/output';\nimport type { Agent } from './agent';\nimport type { AgentExecutionOptions, AgentExecutionOptionsBase } from './agent.types';\nimport type { MessageListInput } from './message-list';\nimport type { StructuredOutputOptions } from './types';\n\nexport const supportedLanguageModelSpecifications = ['v2', 'v3', 'v4'];\nexport const isSupportedLanguageModel = (\n  model: MastraLanguageModel | MastraLegacyLanguageModel,\n): model is MastraLanguageModel => {\n  return supportedLanguageModelSpecifications.includes(model.specificationVersion);\n};\n\nfunction isStructuredOutputFormatError(error: unknown): boolean {\n  return (\n    JSONParseError.isInstance(error) ||\n    NoObjectGeneratedError.isInstance(error) ||\n    TypeValidationError.isInstance(error) ||\n    (error instanceof MastraError &&\n      (error.id === 'STRUCTURED_OUTPUT_OBJECT_UNDEFINED' ||\n        error.id === 'STRUCTURED_OUTPUT_SCHEMA_VALIDATION_FAILED' ||\n        error.id === 'STRUCTURED_OUTPUT_TRUNCATED'))\n  );\n}\n\nexport async function tryGenerateWithJsonFallback<\n  SCHEMA extends StandardSchemaWithJSON,\n  OUTPUT extends InferStandardSchemaOutput<SCHEMA>,\n>(agent: Agent, prompt: MessageListInput, options: AgentExecutionOptions<OUTPUT>): Promise<FullOutput<OUTPUT>>;\nexport async function tryGenerateWithJsonFallback<OUTPUT extends {}>(\n  agent: Agent,\n  prompt: MessageListInput,\n  options: AgentExecutionOptions<OUTPUT>,\n): Promise<FullOutput<OUTPUT>>;\nexport async function tryGenerateWithJsonFallback<OUTPUT>(\n  agent: Agent,\n  prompt: MessageListInput,\n  options: AgentExecutionOptions<OUTPUT>,\n): Promise<FullOutput<OUTPUT>> {\n  if (!options.structuredOutput?.schema) {\n    throw new MastraError({\n      id: 'STRUCTURED_OUTPUT_OPTIONS_REQUIRED',\n      domain: ErrorDomain.AGENT,\n      category: ErrorCategory.USER,\n      text: 'structuredOutput is required to use tryGenerateWithJsonFallback',\n    });\n  }\n\n  try {\n    const result = await agent.generate(prompt, options);\n    // Some models resolve without throwing but produce no parseable structured\n    // object (empty/malformed JSON). Treat that the same as a thrown error so the\n    // caller still gets the json-prompt-injection retry instead of a downstream\n    // crash when it reads `result.object`. Mirrors tryStreamWithJsonFallback.\n    if (result.object === undefined) {\n      throw new MastraError({\n        id: 'STRUCTURED_OUTPUT_OBJECT_UNDEFINED',\n        domain: ErrorDomain.AGENT,\n        category: ErrorCategory.USER,\n        text: 'structuredOutput object is undefined',\n      });\n    }\n    return result;\n  } catch (error) {\n    if (!isStructuredOutputFormatError(error)) throw error;\n\n    agent.__getLogger().warn('Error in tryGenerateWithJsonFallback. Attempting fallback.', error);\n    const result = await agent.generate(prompt, {\n      ...options,\n      structuredOutput: {\n        ...options.structuredOutput,\n        jsonPromptInjection:\n          options.structuredOutput.jsonPromptInjection === 'inline' ||\n          options.structuredOutput.jsonPromptInjection === 'system'\n            ? options.structuredOutput.jsonPromptInjection\n            : true,\n      },\n    });\n    if (result.object === undefined) {\n      throw new MastraError({\n        id: 'STRUCTURED_OUTPUT_OBJECT_UNDEFINED',\n        domain: ErrorDomain.AGENT,\n        category: ErrorCategory.USER,\n        text: 'structuredOutput object is undefined',\n      });\n    }\n    return result;\n  }\n}\n\nexport async function tryStreamWithJsonFallback<OUTPUT extends {}>(\n  agent: Agent,\n  prompt: MessageListInput,\n  options: AgentExecutionOptionsBase<OUTPUT> & {\n    structuredOutput: StructuredOutputOptions<OUTPUT>;\n    /** Override injection placement only for the structured-output retry. */\n    fallbackJsonPromptInjection?: 'system' | 'inline';\n    onStream?: (stream: Awaited<ReturnType<Agent['stream']>>) => void | Promise<void>;\n    /** Called immediately before each primary or fallback stream invocation. */\n    onStreamAttempt?: () => void | Promise<void>;\n    /** Called after each stream invocation is consumed, including a failed structured-output attempt. */\n    onStreamFinish?: (stream: Awaited<ReturnType<Agent['stream']>>) => void | Promise<void>;\n  },\n) {\n  if (!options.structuredOutput?.schema) {\n    throw new MastraError({\n      id: 'STRUCTURED_OUTPUT_OPTIONS_REQUIRED',\n      domain: ErrorDomain.AGENT,\n      category: ErrorCategory.USER,\n      text: 'structuredOutput is required to use tryStreamWithJsonFallback',\n    });\n  }\n\n  const { onStream, onStreamAttempt, onStreamFinish, fallbackJsonPromptInjection, ...streamOptions } = options;\n\n  try {\n    await onStreamAttempt?.();\n    const result = await agent.stream(prompt, streamOptions);\n    void onStream?.(result as unknown as Awaited<ReturnType<Agent['stream']>>);\n    try {\n      const object = await result.object;\n      if (object === undefined) {\n        throw new MastraError({\n          id: 'STRUCTURED_OUTPUT_OBJECT_UNDEFINED',\n          domain: ErrorDomain.AGENT,\n          category: ErrorCategory.USER,\n          text: 'structuredOutput object is undefined',\n        });\n      }\n      return result;\n    } finally {\n      await onStreamFinish?.(result as unknown as Awaited<ReturnType<Agent['stream']>>);\n    }\n  } catch (error) {\n    if (!isStructuredOutputFormatError(error)) throw error;\n\n    agent.__getLogger().warn('Error in tryStreamWithJsonFallback. Attempting fallback.', error);\n    await onStreamAttempt?.();\n    const result = await agent.stream(prompt, {\n      ...streamOptions,\n      structuredOutput: {\n        ...streamOptions.structuredOutput,\n        jsonPromptInjection:\n          fallbackJsonPromptInjection ??\n          (streamOptions.structuredOutput.jsonPromptInjection === 'inline' ||\n          streamOptions.structuredOutput.jsonPromptInjection === 'system'\n            ? streamOptions.structuredOutput.jsonPromptInjection\n            : true),\n      },\n    });\n    void onStream?.(result as unknown as Awaited<ReturnType<Agent['stream']>>);\n    try {\n      const object = await result.object;\n      if (object === undefined) {\n        throw new MastraError({\n          id: 'STRUCTURED_OUTPUT_OBJECT_UNDEFINED',\n          domain: ErrorDomain.AGENT,\n          category: ErrorCategory.USER,\n          text: 'structuredOutput object is undefined',\n        });\n      }\n      return result;\n    } finally {\n      await onStreamFinish?.(result as unknown as Awaited<ReturnType<Agent['stream']>>);\n    }\n  }\n}\n\n/**\n * Sentinel strings some models emit for the optional `suspendedToolRunId` auto-resume\n * field when they mean \"no value\". These are serialization artifacts, not run ids —\n * treating them as real ids defeats every falsy-based guard downstream (#23739).\n */\nconst SUSPENDED_TOOL_RUN_ID_SENTINELS = new Set(['null', 'undefined', 'none', 'nil']);\n\n/**\n * Normalizes a model-supplied `suspendedToolRunId` at the LLM trust boundary.\n * Returns `undefined` for non-strings, empty/whitespace-only strings, and known\n * serialization sentinels (`\"null\"`, `\"undefined\"`, `\"none\"`, `\"nil\"`, case-insensitive)\n * so callers can treat them exactly as if the model had omitted the field.\n * Any other string is returned unchanged (it may be a framework-persisted or\n * hook-supplied run id, which are not required to be UUIDs).\n */\nexport function resolveSuspendedToolRunId(value: unknown): string | undefined {\n  if (typeof value !== 'string') return undefined;\n  const trimmed = value.trim();\n  if (!trimmed) return undefined;\n  if (SUSPENDED_TOOL_RUN_ID_SENTINELS.has(trimmed.toLowerCase())) return undefined;\n  return value;\n}\n\nexport function resolveThreadIdFromArgs(args: {\n  memory?: { thread?: string | { id: string } };\n  threadId?: string;\n  overrideId?: string;\n}): (Partial<StorageThreadType> & { id: string }) | undefined {\n  let resolved: (Partial<StorageThreadType> & { id: string }) | undefined;\n\n  if (args?.memory?.thread) {\n    if (typeof args.memory.thread === 'string') {\n      resolved = { id: args.memory.thread };\n    } else if (typeof args.memory.thread === 'object' && args.memory.thread.id) {\n      resolved = args.memory.thread as Partial<StorageThreadType> & { id: string };\n    }\n  }\n  if (!resolved && args?.threadId) {\n    resolved = { id: args.threadId };\n  }\n\n  if (args.overrideId) {\n    return { ...(resolved || {}), id: args.overrideId };\n  }\n\n  return resolved;\n}\n","import type { ProcessorWorkflow } from './index';\n\n/**\n * Type guard to check if an object is a Workflow that can be used as a processor.\n *\n * Extracted to its own module so that `runner.ts` (and by extension\n * `stream/base/output.ts`) can use it without loading the full processors\n * barrel — which re-exports every built-in processor, many of which import\n * from the agent barrel and create ESM init-time cycles.\n */\nexport function isProcessorWorkflow(obj: unknown): obj is ProcessorWorkflow {\n  return (\n    obj !== null &&\n    typeof obj === 'object' &&\n    'id' in obj &&\n    typeof (obj as Record<string, unknown>).id === 'string' &&\n    'inputSchema' in obj &&\n    'outputSchema' in obj &&\n    'execute' in obj &&\n    typeof (obj as Record<string, unknown>).execute === 'function' &&\n    !('processInput' in obj) &&\n    !('processInputStep' in obj) &&\n    !('processOutputStream' in obj) &&\n    !('processOutputResult' in obj) &&\n    !('processOutputStep' in obj) &&\n    !('processToolResult' in obj) &&\n    !('processLLMRequest' in obj) &&\n    !('processAPIError' in obj)\n  );\n}\n","import type { ModelFacingValidationError } from '../../tools/validation';\n\n/**\n * Normalize modelOutput from toModelOutput() into the lossless V2-authored\n * storage shape kept in `providerMetadata.mastra.modelOutput`.\n *\n * Base64 payloads (`image-data`/`file-data`, and `image-url` parts carrying a\n * `data:` URI) are stored as the V2 `media` content type. Remote-URL parts\n * (`image-url`/`file-url`) are kept as-is because `media.data` is Base64-only —\n * the spec-boundary prompt converters (aiV5PromptToAIV6Prompt /\n * aiV5PromptToAIV7Prompt) emit the correct URL-shaped part for the target\n * model's specification version.\n *\n * `providerOptions` and any other author-supplied keys are preserved.\n */\nexport function normalizeModelOutput(output: unknown): unknown {\n  if (output == null || typeof output !== 'object') return output;\n\n  const obj = output as Record<string, unknown>;\n  if (obj.type !== 'content' || !Array.isArray(obj.value)) return output;\n\n  return {\n    ...obj,\n    value: (obj.value as unknown[]).map(item => {\n      if (item == null || typeof item !== 'object') return item;\n      const part = item as Record<string, unknown>;\n      if (part.type === 'image-url' && typeof part.url === 'string') {\n        // Remote URLs can't be represented as `media` (Base64-only `data`).\n        // Keep the part untouched — url, mediaType and providerOptions intact.\n        // Scheme matching is case-insensitive per RFC 3986.\n        if (!/^data:/i.test(part.url)) return part;\n        // data: URIs are Base64 payloads, so `media` is the right storage shape.\n        const mediaType =\n          typeof part.mediaType === 'string' && part.mediaType\n            ? part.mediaType\n            : part.url.slice(5, part.url.indexOf(';')) || 'image/jpeg';\n        const rest = { ...part };\n        delete rest.url;\n        return { ...rest, type: 'media', data: part.url, mediaType };\n      }\n      if (part.type === 'image-data' && typeof part.data === 'string') {\n        return { ...part, type: 'media', mediaType: part.mediaType ?? 'image/jpeg' };\n      }\n      if (part.type === 'file-data' && typeof part.data === 'string') {\n        return { ...part, type: 'media', mediaType: part.mediaType ?? 'application/octet-stream' };\n      }\n      return part;\n    }),\n  };\n}\n\n/**\n * Model output for a tool that declares `toModelOutput` but resolved with a\n * validation error that Mastra's own validation produced (input, request\n * context, suspend data or output validation failed).\n *\n * The mapper is typed to receive only the tool's output, so it is skipped and\n * the model receives the model-facing form of the error, which leaves out the\n * raw values the full error quotes. Tagging it `error-json` keeps the\n * provider-level error flag (for example Anthropic's `is_error`) so the model\n * treats the call as failed and can retry.\n */\nexport function validationErrorModelOutput(error: ModelFacingValidationError): {\n  type: 'error-json';\n  value: ModelFacingValidationError;\n} {\n  return { type: 'error-json', value: error };\n}\n","import type { MessageList } from '../../../agent/message-list';\nimport { sanitizeToolName } from '../../../agent/message-list/utils/tool-name';\nimport { EntityType, SpanType } from '../../../observability';\nimport { isProcessorWorkflow } from '../../../processors/is-processor-workflow';\nimport type { ProviderMetadata } from '../../../stream/types';\nimport { isAgentWorkflowTool } from '../../../tools/toolchecks';\nimport { isValidationError } from '../../../tools/validation';\nimport type { ModelFacingValidationError } from '../../../tools/validation';\nimport { normalizeModelOutput, validationErrorModelOutput } from '../normalize-model-output';\n\n/** Minimal span surface for the MAPPING child span; both engines' spans satisfy it. */\ninterface MappingSpan {\n  end(options?: unknown): void;\n  error(options: unknown): void;\n}\n\nexport interface ToolMappingParentSpan {\n  createChildSpan(options: unknown): MappingSpan | undefined;\n}\n\n/**\n * Shared `toModelOutput` computation for the tool-result commit.\n *\n * Runs the tool's `toModelOutput` mapper under a MAPPING child span, normalizes\n * media parts into the AI SDK's LanguageModelV2ToolResultOutput shape, and\n * merges the mapped output into `providerMetadata.mastra.modelOutput`.\n *\n * A validation error Mastra produced for this call (`validationError`) is not\n * the tool's output, so it skips the mapper: `toModelOutput` is typed to\n * receive only successful output, and the model must see the error to retry.\n * Its model-facing form, without the raw values the full error quotes, is\n * stored as an `error-json` model output instead. A result that merely has a\n * validation error's fields is mapped like any other result.\n *\n * A nullish mapping result means \"no special mapping needed\" — the raw result\n * is already what the model should see. The key is not written in that case,\n * because MessageList keys off its presence and would otherwise override the\n * real result with `undefined`, producing a tool message with no output.\n *\n * Mapping failures propagate so a broken `toModelOutput` fails the run.\n *\n * A result from a tool an agent built from its `workflows` also gets\n * `mastra.workflowTool: true`. Workflow tools can't define `toModelOutput`, so\n * this per-call marker is how tracing knows it may show their result in the\n * next MODEL_STEP input (#30219). The tool output the model receives is unchanged.\n *\n * Deliberately NOT consolidated with the background-task path\n * (`background-task-result-core.ts`), which always overwrites\n * `mastra.modelOutput` (null included) to clear the placeholder-derived value\n * and runs without a tracing span. The presence-keyed omit here vs the\n * always-overwrite there are both load-bearing; see its docblock.\n */\nexport async function computeModelOutputProviderMetadata(deps: {\n  /** Pre-resolved tool. Engines own the lookup: run-scope stepTools / static\n   * tools on main, the in-process registry on durable. */\n  tool: { toModelOutput?: (output: unknown) => unknown } | undefined;\n  toolName: string;\n  toolCallId?: string;\n  result: unknown;\n  /** Set only when Mastra's own validation rejected this call, read from the\n   * result in the process that ran the tool (`getModelFacingValidationError`).\n   * Never derived from the result's shape. */\n  validationError?: ModelFacingValidationError;\n  existingProviderMetadata?: Record<string, unknown>;\n  /** Parent for the MAPPING child span (main: current tracing span; durable:\n   * the MODEL_STEP span rebuilt from serialized state). */\n  parentSpan?: ToolMappingParentSpan;\n}): Promise<Record<string, unknown> | undefined> {\n  const { tool, result } = deps;\n  let modelOutput: unknown;\n  if (tool?.toModelOutput && deps.validationError) {\n    modelOutput = validationErrorModelOutput(deps.validationError);\n  } else if (tool?.toModelOutput && result != null) {\n    const mappingSpan = deps.parentSpan?.createChildSpan({\n      type: SpanType.MAPPING,\n      name: `tool output mapping: '${deps.toolName}'`,\n      entityType: EntityType.TOOL,\n      entityId: deps.toolName,\n      entityName: deps.toolName,\n      input: result,\n      attributes: {\n        mappingType: 'toModelOutput',\n        toolCallId: deps.toolCallId,\n      },\n    });\n    try {\n      modelOutput = await tool.toModelOutput(result);\n      modelOutput = normalizeModelOutput(modelOutput);\n      mappingSpan?.end({ output: modelOutput });\n    } catch (err) {\n      mappingSpan?.error({ error: err as Error, endSpan: true });\n      throw err;\n    }\n  }\n\n  const existingMastra = (deps.existingProviderMetadata as { mastra?: Record<string, unknown> } | undefined)?.mastra;\n  const providerMetadata = withAgentWorkflowToolMarker(\n    {\n      ...deps.existingProviderMetadata,\n      ...(modelOutput != null ? { mastra: { ...existingMastra, modelOutput } } : {}),\n    },\n    tool,\n  );\n  return providerMetadata && Object.keys(providerMetadata).length > 0 ? providerMetadata : undefined;\n}\n\n/**\n * Adds `mastra.workflowTool: true` to a result's provider metadata when `tool`\n * is one an agent built from its `workflows`; otherwise returns it unchanged.\n * Shared by every engine path that records a tool result (#30219). The stored\n * tool-invocation part holds call and result together, so prompts carry the\n * marker on both the tool-call and tool-result parts, under `providerOptions.mastra`,\n * which provider adapters don't read.\n */\nexport function withAgentWorkflowToolMarker<T extends Record<string, any> | undefined>(\n  providerMetadata: T,\n  tool: unknown,\n): T | Record<string, any> {\n  if (!isAgentWorkflowTool(tool)) return providerMetadata;\n  return { ...providerMetadata, mastra: { ...providerMetadata?.mastra, workflowTool: true } };\n}\n\n/** The mapped `toModelOutput` value carried in `providerMetadata.mastra.modelOutput`, if any. */\nexport function readModelOutput(providerMetadata: Record<string, unknown> | undefined): unknown {\n  return (providerMetadata as { mastra?: { modelOutput?: unknown } } | undefined)?.mastra?.modelOutput;\n}\n\n/** Whether any output processor (or processor workflow) can run `processToolResult`. */\nexport function hasToolResultProcessor(processors: readonly unknown[] | undefined): boolean {\n  return (\n    processors?.some(\n      processor =>\n        isProcessorWorkflow(processor) ||\n        typeof (processor as { processToolResult?: unknown } | null)?.processToolResult === 'function',\n    ) ?? false\n  );\n}\n\n/**\n * A content snapshot of a tool result taken before `processToolResult` runs, so a\n * processor that edits the result in place (same object, new contents) is still\n * seen as having changed it. Undefined when the result can't be serialized; then\n * only a replaced object counts as a change.\n */\nexport function snapshotToolResult(result: unknown): string | undefined {\n  try {\n    return JSON.stringify(result);\n  } catch {\n    return undefined;\n  }\n}\n\n/**\n * The mapped output the next `processToolResult` should see: the one an earlier\n * processor committed in `providerMetadata.mastra.modelOutput` (undefined when it\n * cleared it), otherwise `fallback`, the output mapped before the hook.\n */\nexport function latestProcessedModelOutput(messageList: MessageList, toolCallId: string, fallback: unknown): unknown {\n  const mastra = (\n    findCommittedToolInvocationPart(messageList, toolCallId)?.providerMetadata as\n      | { mastra?: Record<string, unknown> }\n      | undefined\n  )?.mastra;\n  if (!mastra || !('modelOutput' in mastra)) return fallback;\n  return normalizeModelOutput(mastra.modelOutput) ?? undefined;\n}\n\n/**\n * Resolve the model output after `processToolResult` ran.\n *\n * Processors rewrite a tool result by committing a `result`-state part through\n * `messageList.updateToolInvocation`. That part may carry a replacement\n * `providerMetadata.mastra.modelOutput` (e.g. resized or removed images); it\n * then replaces the mapped output. A processor that only replaces the raw\n * `result` gets it re-mapped through `toModelOutput`, so the model never sees\n * the mapping of the value the processor replaced. Without either, the output\n * mapped before the hook stands and `toModelOutput` is not called again. A\n * result edited in place counts as replaced when its contents differ from\n * `resultSnapshotBeforeProcessors`.\n *\n * When the tool resolved with Mastra's own validation error (`validationError`),\n * a rewrite that is still a validation error (say, a redaction pass over every\n * result) skips the mapper and sends the model-facing error, as the mapping\n * before the hook did. A processor that replaced the error with any other value\n * made that value the tool's output, so it is mapped.\n */\nexport async function resolveModelOutputAfterToolResultProcessors(deps: {\n  messageList: MessageList;\n  tool: { toModelOutput?: (output: unknown) => unknown } | undefined;\n  toolName: string;\n  toolCallId: string;\n  /** The result the processors were given. */\n  resultBeforeProcessors: unknown;\n  /** `snapshotToolResult(resultBeforeProcessors)`, taken before the processors ran. */\n  resultSnapshotBeforeProcessors?: string;\n  /** Metadata computed before the processors ran, including the mapped output. */\n  providerMetadata: Record<string, unknown> | undefined;\n  /** Mastra's validation error for `resultBeforeProcessors`, read from the live\n   * result in the process that ran the tool (`getModelFacingValidationError`).\n   * A processor's rewrite is a copy without the marker, so it cannot be read\n   * from the processed result. */\n  validationError?: ModelFacingValidationError;\n  parentSpan?: ToolMappingParentSpan;\n}): Promise<Record<string, unknown> | undefined> {\n  const part = findCommittedToolInvocationPart(deps.messageList, deps.toolCallId);\n\n  const processorMastra = (part?.providerMetadata as { mastra?: Record<string, unknown> } | undefined)?.mastra;\n  const { mastra: previousMastra, ...otherNamespaces } = deps.providerMetadata ?? {};\n  const { modelOutput: _previous, ...mastraWithoutModelOutput } = (previousMastra as Record<string, unknown>) ?? {};\n  const withoutModelOutput: Record<string, unknown> = Object.keys(mastraWithoutModelOutput).length\n    ? { ...otherNamespaces, mastra: mastraWithoutModelOutput }\n    : otherNamespaces;\n\n  if (processorMastra && 'modelOutput' in processorMastra) {\n    const modelOutput = normalizeModelOutput(processorMastra.modelOutput);\n    if (modelOutput == null) {\n      // Cleared: the model reads the (processed) raw result. Drop the key from the\n      // part too, since the commit merges metadata and would otherwise keep it.\n      delete processorMastra.modelOutput;\n      return Object.keys(withoutModelOutput).length ? withoutModelOutput : undefined;\n    }\n    return { ...withoutModelOutput, mastra: { ...mastraWithoutModelOutput, modelOutput } };\n  }\n\n  // Without a committed part, a processor can only have edited the result in place.\n  const resultAfterProcessors = part ? part.toolInvocation.result : deps.resultBeforeProcessors;\n  const resultChanged =\n    resultAfterProcessors !== deps.resultBeforeProcessors ||\n    (deps.resultSnapshotBeforeProcessors !== undefined &&\n      snapshotToolResult(resultAfterProcessors) !== deps.resultSnapshotBeforeProcessors);\n  if (!resultChanged || !deps.tool?.toModelOutput) {\n    return deps.providerMetadata;\n  }\n\n  return computeModelOutputProviderMetadata({\n    tool: deps.tool,\n    toolName: deps.toolName,\n    toolCallId: deps.toolCallId,\n    result: resultAfterProcessors,\n    validationError: isValidationError(resultAfterProcessors) ? deps.validationError : undefined,\n    existingProviderMetadata: Object.keys(withoutModelOutput).length ? withoutModelOutput : undefined,\n    parentSpan: deps.parentSpan,\n  });\n}\n\nfunction findCommittedToolInvocationPart(messageList: MessageList, toolCallId: string) {\n  const messages = messageList.get.all.db();\n  for (let i = messages.length - 1; i >= 0; i--) {\n    const msg = messages[i];\n    if (!msg || msg.role !== 'assistant' || !msg.content?.parts) continue;\n    for (const part of msg.content.parts) {\n      if (\n        part?.type === 'tool-invocation' &&\n        part.toolInvocation?.toolCallId === toolCallId &&\n        part.toolInvocation.state === 'result'\n      ) {\n        return part as typeof part & { toolInvocation: { result?: unknown } };\n      }\n    }\n  }\n  return undefined;\n}\n\n/** Resolved terminal state for one tool call, as recorded to the transcript. */\nexport type ToolResultCommitOutcome =\n  | { kind: 'denied'; approval: { id: string; approved: false; reason?: string } }\n  /** `result` on an error outcome carries a structured payload alongside the\n   * error text — e.g. a failed sub-agent's partial result — so the model can\n   * read what the delegate produced before it failed, not just the message. */\n  | { kind: 'error'; errorText?: string; result?: unknown }\n  | { kind: 'result'; result: unknown };\n\n/**\n * Shared per-result transcript commit: record one resolved\n * tool call on the MessageList as `output-denied`, `output-error`, or\n * `result`. Returns whether a matching invocation was found and updated.\n *\n * Adjudications:\n * - `sanitizeToolName` on every commit: main-only since #13633 (Bedrock\n *   rejects unsanitized hallucinated names on replay); dated drift — durable\n *   adopts via this core.\n * - `errorText` fallback to 'Tool execution failed': same drift class — an\n *   empty error message otherwise persists a failure with no explanation.\n * - `fallbackAppend` (durable true / main false): after a process hop the\n *   merge step may operate on a MessageList rebuilt from serialized state\n *   where the original call part is missing — losing a completed result is\n *   worse than appending a standalone tool message. In main the list is the\n *   same live object that recorded the call, so a miss indicates corruption\n *   and appending would mask the real bug. C1-forced deliberate difference,\n *   not drift.\n */\nexport function commitToolResult(deps: {\n  messageList: MessageList;\n  outcome: ToolResultCommitOutcome;\n  toolCallId: string;\n  toolName: string;\n  toolArgs: unknown;\n  /** Approval decision for an approved approval-gated tool, preserved so it\n   * round-trips on recall (denied outcomes carry their own decision). */\n  approval?: { id: string; approved: boolean; reason?: string };\n  /** Fully-merged metadata for the commit. Engines own the merging: main\n   * layers transform metadata on top from the live chunk; durable layers it\n   * from the `transformMetadata` carried on the serialized step output (L18b). */\n  providerMetadata?: ProviderMetadata;\n  fallbackAppend?: boolean;\n}): boolean {\n  const { messageList, outcome } = deps;\n  const toolName = sanitizeToolName(deps.toolName);\n\n  if (outcome.kind === 'denied') {\n    return messageList.updateToolInvocation({\n      type: 'tool-invocation' as const,\n      toolInvocation: {\n        state: 'output-denied' as const,\n        toolCallId: deps.toolCallId,\n        toolName,\n        args: deps.toolArgs,\n        approval: outcome.approval,\n      },\n    });\n  }\n\n  // Nullish, not truthy: a failure-hook may deliberately replace the error\n  // text with an empty string, and that replacement must survive the commit.\n  const errorText = outcome.kind === 'error' ? (outcome.errorText ?? 'Tool execution failed') : undefined;\n  const updated = messageList.updateToolInvocation({\n    type: 'tool-invocation' as const,\n    toolInvocation: {\n      ...(outcome.kind === 'error'\n        ? {\n            state: 'output-error' as const,\n            errorText: errorText!,\n            ...(outcome.result != null ? { result: outcome.result } : {}),\n          }\n        : { state: 'result' as const, result: outcome.result }),\n      toolCallId: deps.toolCallId,\n      toolName,\n      args: deps.toolArgs,\n      ...(deps.approval ? { approval: deps.approval } : {}),\n    },\n    ...(deps.providerMetadata ? { providerMetadata: deps.providerMetadata } : {}),\n  });\n\n  if (!updated && deps.fallbackAppend) {\n    messageList.add(\n      [\n        {\n          role: 'tool' as const,\n          content: [\n            {\n              type: 'tool-result' as const,\n              toolCallId: deps.toolCallId,\n              toolName,\n              result: outcome.kind === 'error' ? errorText : outcome.result,\n              isError: outcome.kind === 'error',\n            },\n          ],\n        },\n      ],\n      'response',\n    );\n  }\n\n  return updated;\n}\n","import type { AssistantContent, CoreMessage, ToolContent, UserContent } from '@internal/ai-sdk-v4';\n\nimport type { AgentExecutionOptions } from '../agent/agent.types';\nimport type { AgentConfig } from '../agent/types';\nexport type { MastraDBMessage } from '../agent';\nimport type { EmbeddingModelId } from '../llm/model/index.js';\nimport type { ModelRouterModelId } from '../llm/model/provider-registry.js';\nimport type { MastraLanguageModel, MastraModelConfig } from '../llm/model/shared.types';\nimport type { RequestContext } from '../request-context';\nimport type { PublicSchema } from '../schema';\nimport type { MastraCompositeStore } from '../storage';\nimport type { DynamicArgument } from '../types';\nimport type { MastraEmbeddingModel, MastraEmbeddingOptions, MastraVector } from '../vector';\nimport type { VectorFilter } from '../vector/filter/base';\nimport type { MemoryRunStateAccessor } from './run-state';\nimport type { MemoryProcessor } from '.';\n\nexport type { Message as AiMessageType } from '@internal/ai-sdk-v4';\nexport type { MastraLanguageModel };\n\n// Types for the memory system\nexport type MastraMessageV1 = {\n  id: string;\n  content: string | UserContent | AssistantContent | ToolContent;\n  role: 'system' | 'user' | 'assistant' | 'tool' | 'signal';\n  createdAt: Date;\n  threadId?: string;\n  resourceId?: string;\n  toolCallIds?: string[];\n  toolCallArgs?: Record<string, unknown>[];\n  toolNames?: string[];\n  type: 'text' | 'tool-call' | 'tool-result';\n};\n\n/**\n * @deprecated use MastraMessageV1 or MastraDBMessage\n */\nexport type MessageType = MastraMessageV1;\n\nexport type StorageThreadType = {\n  id: string;\n  title?: string;\n  resourceId: string;\n  createdAt: Date;\n  updatedAt: Date;\n  metadata?: Record<string, unknown>;\n};\n\n/**\n * Thread-specific Observational Memory metadata.\n * Stored on thread.metadata.mastra.om to keep thread-specific data\n * separate from the shared resource-level OM record.\n */\nexport type ThreadOMMetadata = {\n  /** The current task being worked on in this thread */\n  currentTask?: string;\n  /** Suggested response for continuing this thread's conversation */\n  suggestedResponse?: string;\n  /** Observer-generated thread title */\n  threadTitle?: string;\n  /** Extracted Observational Memory values keyed by extractor slug */\n  extracted?: Record<string, unknown>;\n  /** Timestamp of the last observed message in this thread (ISO string for JSON serialization) */\n  lastObservedAt?: string;\n  /** Cursor pointing at the last observed message (for replay pruning fallback) */\n  lastObservedMessageCursor?: { createdAt: string; id: string };\n  // Note: Patterns are stored on the ObservationalMemoryRecord (resource-level), not thread metadata\n};\n\n/**\n * Structure for Mastra-specific thread metadata.\n * Stored on thread.metadata.mastra\n */\nexport type ThreadMastraMetadata = {\n  om?: ThreadOMMetadata;\n};\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * Thread metadata flag marking the title as user-pinned. Set by\n * `session.thread.rename()` so Observational Memory's title extractor never\n * overwrites a manual rename, and cleared (set to `false`) when the user\n * explicitly regenerates the title via `generateThreadTitle()`.\n */\nexport const TITLE_PINNED_THREAD_METADATA_KEY = 'titlePinned';\n\n/**\n * Whether the thread's title is pinned against automatic updates.\n */\nexport function isThreadTitlePinned(threadMetadata?: Record<string, unknown>): boolean {\n  return threadMetadata?.[TITLE_PINNED_THREAD_METADATA_KEY] === true;\n}\n\n/**\n * Helper to get OM metadata from a thread's metadata object.\n * Returns undefined if not present or if the structure is invalid.\n */\nexport function getThreadOMMetadata(threadMetadata?: Record<string, unknown>): ThreadOMMetadata | undefined {\n  if (!threadMetadata) return undefined;\n  const mastra = threadMetadata.mastra;\n  if (!isPlainObject(mastra)) return undefined;\n  const om = mastra.om;\n  if (!isPlainObject(om)) return undefined;\n  return om as ThreadOMMetadata;\n}\n\n/**\n * Helper to set OM metadata on a thread's metadata object.\n * Creates the nested structure if it doesn't exist.\n * Returns a new metadata object (does not mutate the original).\n * Safely handles cases where existing mastra/om values are not objects.\n */\nexport function setThreadOMMetadata(\n  threadMetadata: Record<string, unknown> | undefined,\n  omMetadata: ThreadOMMetadata,\n): Record<string, unknown> {\n  const existing = threadMetadata ?? {};\n  const existingMastra = isPlainObject(existing.mastra) ? existing.mastra : {};\n  const existingOM = isPlainObject(existingMastra.om) ? existingMastra.om : {};\n\n  return {\n    ...existing,\n    mastra: {\n      ...existingMastra,\n      om: {\n        ...existingOM,\n        ...omMetadata,\n      },\n    },\n  };\n}\n\n/**\n * Memory-specific context passed via RequestContext under the 'MastraMemory' key\n * This provides processors with access to memory-related execution context\n */\nexport type MemoryRequestContext = {\n  thread?: Partial<StorageThreadType> & { id: string };\n  resourceId?: string;\n  memoryConfig?: MemoryConfigInternal;\n  /** Internal accessor for non-serializable state shared within one agent run. */\n  runState?: MemoryRunStateAccessor;\n};\n\n/**\n * Parse and validate memory runtime context from RequestContext\n * @param requestContext - The RequestContext to extract memory context from\n * @returns The validated MemoryRequestContext or null if not available\n * @throws Error if the context exists but is malformed\n */\nexport function parseMemoryRequestContext(requestContext?: RequestContext): MemoryRequestContext | null {\n  if (!requestContext) {\n    return null;\n  }\n\n  const memoryContext = requestContext.get('MastraMemory');\n  if (!memoryContext) {\n    return null;\n  }\n\n  // Validate the structure\n  if (typeof memoryContext !== 'object' || memoryContext === null) {\n    throw new Error(`Invalid MemoryRequestContext: expected object, got ${typeof memoryContext}`);\n  }\n\n  const ctx = memoryContext as Record<string, unknown>;\n\n  // Validate thread if present\n  if (ctx.thread !== undefined) {\n    if (typeof ctx.thread !== 'object' || ctx.thread === null) {\n      throw new Error(`Invalid MemoryRequestContext.thread: expected object, got ${typeof ctx.thread}`);\n    }\n    const thread = ctx.thread as Record<string, unknown>;\n    if (typeof thread.id !== 'string') {\n      throw new Error(`Invalid MemoryRequestContext.thread.id: expected string, got ${typeof thread.id}`);\n    }\n  }\n\n  // Validate resourceId if present\n  if (ctx.resourceId !== undefined && typeof ctx.resourceId !== 'string') {\n    throw new Error(`Invalid MemoryRequestContext.resourceId: expected string, got ${typeof ctx.resourceId}`);\n  }\n\n  return memoryContext as MemoryRequestContext;\n}\n\nexport type MessageResponse<T extends 'raw' | 'core_message'> = {\n  raw: MastraMessageV1[];\n  core_message: CoreMessage[];\n}[T];\n\ntype BaseWorkingMemory = {\n  enabled: boolean;\n  /**\n   * Scope for working memory storage.\n   * - 'resource': Memory persists across all threads for the same resource/user (default)\n   * - 'thread': Memory is isolated per conversation thread\n   *\n   * @default 'resource'\n   */\n  scope?: 'thread' | 'resource';\n  /**\n   * Experimental: deliver working memory to the model as a state signal instead of folding\n   * it into the system message. Storage is unchanged. When `true`, `Memory` auto-attaches\n   * a state-signal processor that emits snapshots or deltas with dedup via `cacheKey`, and\n   * registers the working-memory tool as `setWorkingMemory` instead of `updateWorkingMemory`.\n   *\n   * Not supported with template working memory `version: 'vnext'`.\n   *\n   * @default false\n   * @see docs/src/content/en/docs/agents/signals.mdx\n   */\n  useStateSignals?: boolean;\n  /**\n   * Whether the main agent manages working memory directly through tool/instruction injection.\n   * Set to false when another path, such as Observational Memory extractors,\n   * owns working memory updates.\n   *\n   * @default true\n   */\n  agentManaged?: boolean;\n  /** @deprecated The `use` option has been removed. Working memory always uses tool-call mode. */\n  use?: never;\n};\n\ntype TemplateWorkingMemory =\n  | (BaseWorkingMemory & {\n      template: string;\n      schema?: never;\n      version?: 'stable';\n    })\n  | (Omit<BaseWorkingMemory, 'useStateSignals'> & {\n      template: string;\n      schema?: never;\n      version: 'vnext';\n      useStateSignals?: false;\n    });\n\ntype SchemaWorkingMemory = BaseWorkingMemory & {\n  schema: PublicSchema;\n  template?: never;\n};\n\ntype WorkingMemoryNone = BaseWorkingMemory & {\n  template?: never;\n  schema?: never;\n};\n\nexport type WorkingMemory = TemplateWorkingMemory | SchemaWorkingMemory | WorkingMemoryNone;\n\n/**\n * Vector index configuration for optimizing semantic recall performance.\n *\n * These settings are primarily supported by PostgreSQL with pgvector extension.\n * Other vector stores (Pinecone, Qdrant, Chroma, etc.) will use their default\n * configurations and ignore these settings.\n *\n * @see https://mastra.ai/docs/memory/semantic-recall#postgresql-index-optimization\n */\nexport type VectorIndexConfig = {\n  /**\n   * Type of vector index to create (PostgreSQL/pgvector only).\n   * - 'ivfflat': Inverted file index, good balance of speed and recall\n   * - 'hnsw': Hierarchical Navigable Small World, best performance for most cases\n   * - 'flat': Exact nearest neighbor search, slow but 100% recall\n   *\n   * @default 'ivfflat'\n   * @example\n   * ```typescript\n   * type: 'hnsw' // Recommended for production\n   * ```\n   */\n  type?: 'ivfflat' | 'hnsw' | 'flat';\n\n  /**\n   * Distance metric for similarity calculations.\n   * - 'cosine': Normalized dot product, good for text similarity\n   * - 'euclidean': L2 distance, geometric distance in vector space\n   * - 'dotproduct': Inner product, best for OpenAI embeddings\n   *\n   * Note: While defined here, most vector stores have their own metric configuration.\n   *\n   * @default 'cosine'\n   * @example\n   * ```typescript\n   * metric: 'dotproduct' // Optimal for OpenAI embeddings\n   * ```\n   */\n  metric?: 'cosine' | 'euclidean' | 'dotproduct';\n\n  /**\n   * Configuration for IVFFlat index (PostgreSQL only).\n   * Controls the number of inverted lists for clustering vectors.\n   */\n  ivf?: {\n    /**\n     * Number of inverted lists (clusters) to create.\n     * Higher values mean better recall but slower build time.\n     * Recommended: rows/1000 for tables with > 1M rows.\n     *\n     * @default 100\n     */\n    lists?: number;\n  };\n\n  /**\n   * Configuration for HNSW index (PostgreSQL only).\n   * Hierarchical graph-based index with superior query performance.\n   */\n  hnsw?: {\n    /**\n     * Maximum number of bi-directional links per node.\n     * Higher values increase recall and index size.\n     *\n     * @default 16\n     * @example\n     * ```typescript\n     * m: 32 // Higher recall, larger index\n     * ```\n     */\n    m?: number;\n\n    /**\n     * Size of dynamic candidate list during index construction.\n     * Higher values mean better recall but slower index creation.\n     *\n     * @default 64\n     * @example\n     * ```typescript\n     * efConstruction: 128 // Better quality, slower build\n     * ```\n     */\n    efConstruction?: number;\n  };\n};\n\n/**\n * Configuration for semantic recall using RAG-based retrieval.\n *\n * Enables agents to retrieve relevant messages from past conversations using vector similarity search.\n * Retrieved messages provide context from beyond the recent conversation history, helping agents\n * maintain continuity across longer interactions.\n *\n * @see https://mastra.ai/docs/memory/semantic-recall\n */\nexport type SemanticRecall = {\n  /**\n   * Number of semantically similar messages to retrieve from the vector database.\n   * Higher values provide more context but increase token usage.\n   *\n   * @example\n   * ```typescript\n   * topK: 3 // Retrieve 3 most similar messages\n   * ```\n   */\n  topK: number;\n\n  /**\n   * Amount of surrounding context to include with each retrieved message.\n   * Can be a single number (same before/after) or an object with separate values.\n   * Helps provide conversational flow around the matched message.\n   *\n   * @example\n   * ```typescript\n   * messageRange: 2 // Include 2 messages before and after\n   * messageRange: { before: 1, after: 3 } // 1 before, 3 after\n   * ```\n   */\n  messageRange: number | { before: number; after: number };\n\n  /**\n   * Scope for semantic search queries.\n   * - 'resource': Search across all threads owned by the same resource/user (default)\n   * - 'thread': Search only within the current conversation thread\n   *\n   * @default 'resource'\n   * @example\n   * ```typescript\n   * scope: 'thread' // Limit recall to current thread only\n   * ```\n   */\n  scope?: 'thread' | 'resource';\n\n  /**\n   * Vector index configuration (PostgreSQL/pgvector specific).\n   * Other vector stores will use their default index configurations.\n   * HNSW indexes typically provide better performance than IVFFlat.\n   *\n   * @example\n   * ```typescript\n   * indexConfig: {\n   *   type: 'hnsw',\n   *   metric: 'dotproduct', // Best for OpenAI embeddings\n   *   hnsw: { m: 16, efConstruction: 64 }\n   * }\n   * ```\n   */\n  indexConfig?: VectorIndexConfig;\n\n  /**\n   * Metadata filter for semantic search queries.\n   * Allows filtering results by metadata fields using MongoDB-style query syntax.\n   * Works in combination with scope-based filtering (resource_id/thread_id).\n   *\n   * @example\n   * ```typescript\n   * filter: {\n   *   projectId: { $eq: 'project-a' },\n   *   category: { $in: ['work', 'personal'] }\n   * }\n   * ```\n   */\n  filter?: VectorFilter;\n\n  /**\n   * Minimum similarity score threshold (0-1).\n   * Messages below this threshold will be filtered out from semantic search results.\n   *\n   * @example\n   * ```typescript\n   * threshold: 0.7 // Only include messages with 70%+ similarity\n   * ```\n   */\n  threshold?: number;\n\n  /**\n   * Index name for the vector store.\n   * If not provided, will be auto-generated based on embedder model.\n   *\n   * @example\n   * ```typescript\n   * indexName: 'my-custom-index'\n   * ```\n   */\n  indexName?: string;\n\n  /**\n   * Largest number of characters of message text sent to the embedder in one input. Longer\n   * messages are split into chunks, each stored as its own vector row.\n   *\n   * Measured in characters because no single tokenizer matches every embedder. The default of\n   * 16,384 is about 4096 English tokens. Chinese, Japanese and Korean text, and code, use more\n   * tokens per character, so lower it when your embedder's input limit is close. When unset and\n   * the embedder declares `maxInputTokens` (as `@mastra/fastembed` models do), the limit is\n   * derived from that instead.\n   *\n   * Only read from the options passed to the `Memory` constructor. Memory options given per\n   * request (for example through `agent.stream(..., { memory: { options } })`) don't change it.\n   *\n   * @default 16384\n   * @example\n   * ```typescript\n   * maxChunkChars: 6000 // Mostly Japanese text with an 8192-token embedder\n   * ```\n   */\n  maxChunkChars?: number;\n};\n\n/**\n * Model settings for Observer/Reflector agents in Observational Memory.\n * Uses the same settings as Agent.generate() modelSettings (temperature, maxOutputTokens, topP, etc.).\n */\nexport type ObservationalMemoryModelSettings = AgentExecutionOptions['modelSettings'];\n\n/**\n * A single idle activation TTL: milliseconds, a duration string like `\"5m\"` or `\"1hr\"`,\n * `\"auto\"` for a provider-aware TTL, or `false` to disable idle activation.\n */\nexport type ObservationalMemoryActivationTTLValue = number | string | 'auto' | false;\n\n/**\n * Per-provider idle activation TTLs. Keys are provider names (e.g. `anthropic`, `openai`),\n * matched case-insensitively against the part of the actor model's provider before the\n * first `.` (so `anthropic` matches `anthropic.messages`). `default` applies to every\n * provider without its own key; without `default`, unmatched providers don't idle-activate.\n *\n * @example { default: 'auto', anthropic: '1h' }\n */\nexport type ObservationalMemoryActivationTTLByProvider = {\n  default?: ObservationalMemoryActivationTTLValue;\n  [provider: string]: ObservationalMemoryActivationTTLValue | undefined;\n};\n\nexport type ObservationalMemoryActivationTTL =\n  | ObservationalMemoryActivationTTLValue\n  | ObservationalMemoryActivationTTLByProvider;\n\n/**\n * Configuration for the observation step in Observational Memory.\n */\nexport interface ObservationalMemoryObservationConfig {\n  /**\n   * Model for the Observer agent.\n   * Can be a model ID string (e.g., 'openai/gpt-4o'), a LanguageModel instance,\n   * a function that returns either (for dynamic model selection),\n   * or an array of ModelWithRetries for fallback support.\n   *\n   * Cannot be set if a top-level `model` is also provided.\n   *\n   * @default the top-level `model`, else `reflection.model`, else `'auto'` — Google's low-cost Gemini\n   * model when Google is usable (`canUseProvider('google')`, or `GOOGLE_GENERATIVE_AI_API_KEY`\n   * when no callback is configured), otherwise a low-cost model from the main model's provider,\n   * otherwise the main model itself.\n   */\n  model?: AgentConfig['model'];\n\n  /** Number of retries after the initial Observer model call. @default 8 */\n  maxRetries?: number;\n\n  /** Terminal policy after Observer model retries are exhausted. @default 'abort' */\n  failurePolicy?: 'abort' | 'continue';\n\n  /**\n   * Manage working memory through Observational Memory extraction.\n   * When enabled alongside `workingMemory.enabled`, Memory supplies defaults that\n   * disable main-agent working memory management and add the WorkingMemoryExtractor.\n   * Set `workingMemory.agentManaged: true` to keep main-agent tools/instructions enabled.\n   *\n   * @default false\n   */\n  manageWorkingMemory?: boolean;\n\n  /**\n   * Token count of unobserved messages that triggers observation.\n   * When unobserved message tokens exceed this, the Observer is called.\n   *\n   * @default 30000\n   */\n  messageTokens?: number;\n\n  /**\n   * Model settings for the Observer agent.\n   * @default { temperature: 0.3, maxOutputTokens: 100_000 }\n   */\n  modelSettings?: ObservationalMemoryModelSettings;\n\n  /**\n   * Provider-specific options passed to the Observer model.\n   * Use this for provider features like thinking budgets, safety settings, etc.\n   *\n   * @example\n   * ```ts\n   * providerOptions: {\n   *   google: { thinkingConfig: { thinkingBudget: 215 } }\n   * }\n   * ```\n   *\n   * @default { google: { thinkingConfig: { thinkingBudget: 215 } } }\n   */\n  providerOptions?: Record<string, Record<string, unknown> | undefined>;\n\n  /**\n   * Maximum tokens per batch when observing multiple threads.\n   * Threads are chunked into batches of this size and processed in parallel.\n   * Lower values = more parallelism but more API calls.\n   * Higher values = fewer API calls but less parallelism.\n   *\n   * @default 10000\n   */\n  maxTokensPerBatch?: number;\n\n  /**\n   * Token interval for async background observation buffering.\n   * Observations run asynchronously in the background at this interval,\n   * storing results in a buffer. When the main `messageTokens` threshold is reached,\n   * buffered observations are activated instantly (no blocking LLM call).\n   *\n   * Can be an absolute token count (e.g. `5_000`) or a fraction of `messageTokens`\n   * (e.g. `0.25` means buffer every 25% of the threshold).\n   *\n   * Set to `false` to explicitly disable async buffering.\n   *\n   * Must resolve to less than `messageTokens`.\n   *\n   * @default 0.2 (buffer every 20% of messageTokens)\n   * @example\n   * ```ts\n   * // Buffer every 5k tokens, activate at 20k\n   * observation: {\n   *   messageTokens: 20_000,\n   *   bufferTokens: 5_000,\n   * }\n   * // Or equivalently, using a fraction:\n   * observation: {\n   *   messageTokens: 20_000,\n   *   bufferTokens: 0.25,\n   * }\n   * // Disable async buffering (use synchronous observation)\n   * observation: {\n   *   bufferTokens: false,\n   * }\n   * ```\n   */\n  bufferTokens?: number | false;\n\n  /**\n   * Ratio (0-1) of buffered observations to activate when threshold is reached.\n   * Setting this below 1 keeps some observations in reserve, which helps maintain\n   * conversation continuity and provides a buffer for the next activation cycle.\n   *\n   * Requires `bufferTokens` to also be set.\n   *\n   * @default 0.8 (activate 80% of buffered observations, keeping 20% in reserve)\n   * @example\n   * ```ts\n   * // Activate 70% of buffered observations, keep 30% in reserve\n   * observation: {\n   *   messageTokens: 20_000,\n   *   bufferTokens: 0.25,\n   *   bufferActivation: 0.7,\n   * }\n   * ```\n   */\n  bufferActivation?: number;\n\n  /**\n   * Time before buffered observations are force-activated after inactivity.\n   * Accepts milliseconds as a number, a duration string like `\"5m\"` or `\"1hr\"`,\n   * `\"auto\"` to choose a provider-aware TTL from the actor model's prompt-cache behavior,\n   * or `false` to disable top-level `activateAfterIdle` for observations.\n   * If unset, top-level `activateAfterIdle` is used for observations.\n   */\n  activateAfterIdle?: ObservationalMemoryActivationTTL;\n\n  /**\n   * Force-activate buffered observations when the actor provider/model changes.\n   * If unset, top-level `activateOnProviderChange` is used for observations.\n   */\n  activateOnProviderChange?: boolean;\n\n  /**\n   * Token threshold at which a synchronous (blocking) observation is allowed.\n   * Between `messageTokens` and `blockAfter`, only async buffering and activation run:\n   * reaching `messageTokens` without a buffered chunk to activate starts background\n   * buffering, and the resulting chunk activates on a later step. A synchronous\n   * observation runs if pending tokens still reach `blockAfter` after buffered activation.\n   * Unobserved messages can therefore grow up to `blockAfter` before an agent step blocks\n   * on the Observer. Set `blockAfter: 1` to observe synchronously at `messageTokens`.\n   *\n   * Above `blockAfter`, activation may also overshoot the retention target: it uses the\n   * smallest set of buffered chunks that reaches the target, even when that overshoots it\n   * by more than the usual safeguard allows. This changes the result only when the\n   * retention floor is above roughly 20,000 tokens.\n   *\n   * Accepts either:\n   * - A **multiplier** (1 ≤ value < 100): multiplied by `messageTokens` (including a\n   *   per-thread `messageTokens` override).\n   *   e.g. `blockAfter: 1.5` with `messageTokens: 20_000` → resolves to 30,000 tokens.\n   * - An **absolute token count** (≥ 100): must be greater than `messageTokens`.\n   *   e.g. `blockAfter: 80_000` → resolves to 80,000 tokens.\n   *\n   * Only relevant when `bufferTokens` is set. When `bufferTokens` is not set,\n   * synchronous observation is used directly at `messageTokens` and this setting has no effect.\n   *\n   * @default 1.2 (120% of `messageTokens`) when `bufferTokens` is set.\n   *\n   * @example\n   * ```ts\n   * // Multiplier: 1.5x messageTokens\n   * observation: {\n   *   messageTokens: 20_000,\n   *   bufferTokens: 0.25,\n   *   blockAfter: 1.5, // resolves to 30,000\n   * }\n   * // Absolute: explicit token count\n   * observation: {\n   *   messageTokens: 20_000,\n   *   bufferTokens: 5_000,\n   *   blockAfter: 80_000,\n   * }\n   * ```\n   */\n  blockAfter?: number;\n\n  /**\n   * Optional token budget for observer context.\n   * When set, the \"Previous Observations\" section is truncated from the end\n   * to keep the most recent observations within this budget, and pending\n   * buffered reflections replace the raw observations they summarized.\n   * Set to `0` for full truncation (omit previous observations entirely), or `false` to disable.\n   *\n   * @default false (previous observations are sent in full)\n   */\n  previousObserverTokens?: number | false;\n\n  /**\n   * Custom instructions appended to the Observer agent's system prompt.\n   * Use this to customize what the Observer focuses on or how it formats observations.\n   *\n   * @example\n   * ```ts\n   * observation: {\n   *   instruction: 'Focus on user dietary preferences and allergies.',\n   * }\n   * ```\n   */\n  instruction?: string;\n\n  /**\n   * When enabled, the Observer suggests a short thread title based on the conversation.\n   * The title is updated on the thread whenever the Observer runs.\n   *\n   * @default false\n   */\n  threadTitle?: boolean;\n\n  /**\n   * Whether image/file attachment parts are forwarded to the Observer LLM.\n   * - `true` forwards every attachment\n   * - `false` drops attachments and leaves placeholder text\n   * - `'auto'` checks model capabilities to decide\n   * - a `string[]` forwards only attachments whose MIME type matches an entry; entries may be\n   *   exact (`'application/pdf'`) or a wildcard (`'image/*'`)\n   *\n   * @default ['image/*', 'application/pdf']\n   */\n  observeAttachments?: 'auto' | boolean | string[];\n}\n\n/**\n * Configuration for the reflection step in Observational Memory.\n */\nexport interface ObservationalMemoryReflectionConfig {\n  /**\n   * Model for the Reflector agent.\n   * Can be a model ID string (e.g., 'openai/gpt-4o'), a LanguageModel instance,\n   * a function that returns either (for dynamic model selection),\n   * or an array of ModelWithRetries for fallback support.\n   *\n   * Cannot be set if a top-level `model` is also provided.\n   *\n   * @default the top-level `model`, else `observation.model`, else `'auto'` — Google's low-cost Gemini\n   * model when Google is usable (`canUseProvider('google')`, or `GOOGLE_GENERATIVE_AI_API_KEY`\n   * when no callback is configured), otherwise a low-cost model from the main model's provider,\n   * otherwise the main model itself.\n   */\n  model?: AgentConfig['model'];\n\n  /** Number of retries after the initial Reflector model call. @default 8 */\n  maxRetries?: number;\n\n  /** Terminal policy after Reflector model retries are exhausted. @default 'abort' */\n  failurePolicy?: 'abort' | 'continue';\n\n  /**\n   * Token count of observations that triggers reflection.\n   * When observation tokens exceed this, the Reflector is called to condense them.\n   *\n   * @default 40000\n   */\n  observationTokens?: number;\n\n  /**\n   * Model settings for the Reflector agent.\n   * @default { temperature: 0, maxOutputTokens: 100_000 }\n   */\n  modelSettings?: ObservationalMemoryModelSettings;\n\n  /**\n   * Provider-specific options passed to the Reflector model.\n   * Use this for provider features like thinking budgets, safety settings, etc.\n   *\n   * @example\n   * ```ts\n   * providerOptions: {\n   *   google: { thinkingConfig: { thinkingBudget: 1024 } }\n   * }\n   * ```\n   *\n   * @default { google: { thinkingConfig: { thinkingBudget: 1024 } } }\n   */\n  providerOptions?: Record<string, Record<string, unknown> | undefined>;\n\n  /**\n   * Token threshold above which synchronous (blocking) reflection is forced.\n   * When set with async reflection enabled, the system will not block for\n   * reflection between `observationTokens` and `blockAfter` — only async\n   * buffering and activation are used in that range. Once observation tokens\n   * exceed `blockAfter`, a synchronous reflection runs as a last resort.\n   *\n   * Accepts either:\n   * - A **multiplier** (1 < value < 2): multiplied by `observationTokens`.\n   *   e.g. `blockAfter: 1.5` with `observationTokens: 30_000` → blocks at 45,000 tokens.\n   * - An **absolute token count** (≥ 2): must be greater than `observationTokens`.\n   *   e.g. `blockAfter: 50_000` → blocks at 50,000 tokens.\n   *\n   * Only relevant when `bufferActivation` is set. When `bufferActivation` is not set,\n   * synchronous reflection is used directly at `observationTokens` and this setting has no effect.\n   *\n   * @default 1.2 (120% of `observationTokens`) when `bufferActivation` is set.\n   */\n  blockAfter?: number;\n\n  /**\n   * Time before buffered reflections are force-activated after inactivity.\n   * Accepts milliseconds as a number, a duration string like `\"5m\"` or `\"1hr\"`,\n   * `\"auto\"` to choose a provider-aware TTL from the actor model's prompt-cache behavior,\n   * or `false` to disable idle activation for reflections.\n   * Reflections do not inherit top-level `activateAfterIdle`; set this explicitly to enable.\n   */\n  activateAfterIdle?: ObservationalMemoryActivationTTL;\n\n  /**\n   * Force-activate buffered reflections when the actor provider/model changes.\n   * Reflections do not inherit top-level `activateOnProviderChange`; set this explicitly to enable.\n   */\n  activateOnProviderChange?: boolean;\n\n  /**\n   * Ratio (0-1) controlling when async reflection buffering starts.\n   * When observation tokens reach `observationTokens * bufferActivation`,\n   * reflection runs asynchronously in the background. When the full\n   * `observationTokens` threshold is reached, the buffered reflection\n   * is spliced into the observation content instantly (no blocking LLM call).\n   *\n   * Only one buffered reflection is maintained at a time. On activation,\n   * the buffered reflection replaces the line range it was generated from,\n   * and any new observations appended after that range are preserved.\n   *\n   * Requires `observation.bufferTokens` to also be set (async observation).\n   *\n   * @example\n   * ```ts\n   * reflection: {\n   *   observationTokens: 30_000,\n   *   bufferActivation: 0.5, // Start buffering at 15k tokens\n   * }\n   * ```\n   */\n  bufferActivation?: number;\n\n  /**\n   * Custom instructions appended to the Reflector agent's system prompt.\n   * Use this to customize how the Reflector consolidates observations.\n   *\n   * @example\n   * ```ts\n   * reflection: {\n   *   instruction: 'Consolidate observations and remove duplicates.',\n   * }\n   * ```\n   */\n  instruction?: string;\n}\n\n/**\n * Configuration for Observational Memory.\n *\n * Observational Memory is a three-tier memory system that uses an Observer agent\n * to extract observations from conversations and a Reflector agent to compress them.\n * This enables efficient long-term memory with minimal context usage.\n *\n * Can be set to `true` to enable with defaults, or an object to customize.\n *\n * @example\n * ```typescript\n * // Enable with defaults\n * observationalMemory: true\n *\n * // Custom configuration\n * observationalMemory: {\n *   model: 'google/gemini-2.5-flash',\n *   observation: {\n *     messageTokens: 20_000,\n *   },\n *   reflection: {\n *     observationTokens: 90_000,\n *   },\n * }\n * ```\n */\nexport interface ObservationalMemoryOptions {\n  /**\n   * Enable or disable Observational Memory.\n   * When omitted, defaults to `true` (enabled).\n   * Only `enabled: false` explicitly disables it.\n   *\n   * @default true\n   */\n  enabled?: boolean;\n\n  /**\n   * Model for both Observer and Reflector agents.\n   * Sets the model for both agents at once. Cannot be used together with\n   * `observation.model` or `reflection.model` — an error will be thrown.\n   *\n   * @default 'auto' — Google's low-cost Gemini model when Google is usable (`canUseProvider('google')`,\n   * or `GOOGLE_GENERATIVE_AI_API_KEY` when no callback is configured), otherwise a low-cost model\n   * from the main model's provider, otherwise the main model itself.\n   */\n  model?: AgentConfig['model'];\n\n  /**\n   * Observation step configuration for extracting observations from conversations.\n   */\n  observation?: ObservationalMemoryObservationConfig;\n\n  /**\n   * Reflection step configuration for compressing observations.\n   */\n  reflection?: ObservationalMemoryReflectionConfig;\n\n  /**\n   * Memory scope for observations.\n   * - 'resource': Observations span all threads for a resource (cross-thread memory)\n   * - 'thread': Observations are per-thread (default)\n   *\n   * @default 'thread'\n   * @deprecated The `scope` option is deprecated. `'resource'` will be removed in a future release because it\n   * works much worse than thread scope for prompt caching and agent understanding, leaving `'thread'` (already\n   * the default) as the only scope. Omit this option to use thread scope. For cross-thread recall, enable\n   * `retrieval`; for durable facts across threads, use resource-scoped working memory. A new knowledge and\n   * subconscious memory primitive will replace resource scope.\n   */\n  scope?: 'resource' | 'thread';\n\n  /**\n   * Time before buffered observations are force-activated after inactivity.\n   * Accepts milliseconds as a number, a duration string like `\"5m\"` or `\"1hr\"`,\n   * or `\"auto\"` to choose a provider-aware TTL from the actor model's prompt-cache behavior.\n   * When the gap between the current time and the last assistant message part's `createdAt`\n   * exceeds this value, buffered observations activate regardless of whether the\n   * token threshold has been reached. Useful to align with prompt cache TTLs.\n   *\n   * Pass an object to set a TTL per provider, with `default` for every other provider.\n   * Use this when your requests set a prompt cache TTL that Mastra can't detect, such as\n   * Anthropic's per-message `cacheControl: { ttl: '1h' }`.\n   *\n   * Reflections do not inherit this setting. Use `reflection.activateAfterIdle` to\n   * opt reflections into idle activation.\n   *\n   * @example 300_000\n   * @example \"5m\"\n   * @example \"1hr\"\n   * @example \"auto\"\n   * @example { default: 'auto', anthropic: '1h' }\n   */\n  activateAfterIdle?: ObservationalMemoryActivationTTL;\n\n  /**\n   * Force-activate buffered observations when the actor provider/model changes.\n   * Useful when switching between models that do not share prompt caches.\n   *\n   * Reflections do not inherit this setting. Use `reflection.activateOnProviderChange`\n   * to opt reflections into provider-change activation.\n   */\n  activateOnProviderChange?: boolean;\n\n  /**\n   * Share the token budget between messages and observations.\n   * When true, the total budget = observation.messageTokens + reflection.observationTokens.\n   * - Messages can use more space when observations are small\n   * - Observations can use more space when messages are small\n   *\n   * This helps maximize context usage by allowing flexible allocation.\n   *\n   * @default false\n   */\n  shareTokenBudget?: boolean;\n\n  /**\n   * When true, inserts temporal-gap reminder markers before new user messages after\n   * significant inactivity. These markers are persisted in memory and also emitted\n   * as inline reminder events for clients that want to render them specially.\n   *\n   * @default false\n   */\n  temporalMarkers?: boolean;\n\n  /**\n   * Enable retrieval-mode observation groups as durable pointers\n   * to raw message history. When enabled, observation groups keep `_range`\n   * metadata visible in context and a `recall` tool is registered so the actor\n   * can inspect raw messages behind a stored observation summary.\n   *\n   * - `true` — recall tool with cross-thread browsing by default\n   * - `{ vector: true }` — also enables semantic search using Memory-level vector/embedder\n   * - `{ scope: 'thread' }` — restricts the recall tool to the current thread only\n   * - `{ vector: true, scope: 'thread' }` — current-thread browsing + semantic search\n   * - `{ instructions: '...' }` — appends application-specific recall guidance after\n   *   Mastra's built-in retrieval instructions (never replaces them)\n   *\n   * `scope` defaults to `'resource'` (cross-thread browsing, thread listing, and search).\n   * Set to `'thread'` to restrict to the current thread only.\n   *\n   * @default false\n   */\n  retrieval?: boolean | { vector?: boolean; scope?: 'thread' | 'resource'; instructions?: string };\n}\n\n/**\n * Check if observational memory is enabled from a `boolean | ObservationalMemoryOptions` value.\n *\n * - `true` → enabled\n * - `false` → disabled\n * - `{ enabled: false }` → disabled\n * - `{ ... }` (without `enabled: false`) → enabled\n * - `undefined` → disabled\n */\nexport function isObservationalMemoryEnabled(\n  config: boolean | ObservationalMemoryOptions | undefined,\n): config is true | ObservationalMemoryOptions {\n  if (config === true) return true;\n  if (config === false || config === undefined) return false;\n  return config.enabled !== false;\n}\n\n/**\n * Configuration for memory behaviors and retrieval strategies.\n *\n * Controls three types of memory: conversation history (recent messages), semantic recall\n * (RAG-based retrieval of relevant past messages), and working memory (persistent user data).\n * All memory types are combined into a single context window for the LLM.\n *\n * @see https://mastra.ai/docs/memory/overview\n */\ntype BaseMemoryConfig = {\n  /**\n   * When true, prevents memory from saving new messages.\n   * Useful for internal agents (like routing agents) that should read memory but not modify it.\n   *\n   * @default false\n   * @example\n   * ```typescript\n   * readOnly: true // Agent can read memory but won't save new messages\n   * ```\n   */\n  readOnly?: boolean;\n\n  /**\n   * Number of recent messages from the current thread to include in context.\n   * Provides short-term conversational continuity.\n   * Set to false to disable conversation history entirely.\n   *\n   * @default 10\n   * @example\n   * ```typescript\n   * lastMessages: 5 // Include last 5 messages\n   * lastMessages: false // Disable conversation history\n   * ```\n   * @deprecated Counting messages is a poor proxy for context size. Prefer `messageHistory`\n   * to bound history by a token budget. `lastMessages: false` still disables history.\n   */\n  lastMessages?: number | false;\n\n  /**\n   * Token budget for conversation history. When set, remembered messages are trimmed\n   * oldest-first until the context fits; system instructions and the current turn are never removed.\n   * Trimmed history stays in storage but is excluded from context on later turns.\n   * When set without a numeric `lastMessages`, history is limited by tokens only.\n   *\n   * @example\n   * ```typescript\n   * messageHistory: { maxTokens: 8000 } // frees 25% of the budget when exceeded\n   * messageHistory: { maxTokens: 8000, atMaxRemoveTokens: 1000 }\n   * ```\n   */\n  messageHistory?: import('./message-history-config').MessageHistoryConfig;\n\n  /**\n   * Semantic recall configuration for RAG-based retrieval of relevant past messages.\n   * Uses vector embeddings for similarity search across conversation history.\n   * Can be a boolean to enable/disable with defaults, or an object for detailed configuration.\n   *\n   * @default false (disabled by default)\n   * @example\n   * ```typescript\n   * semanticRecall: false // Disable semantic recall\n   * semanticRecall: {\n   *   topK: 5,\n   *   messageRange: 2,\n   *   scope: 'resource' // Search across all resource (user) threads\n   * }\n   * ```\n   */\n  semanticRecall?: boolean | SemanticRecall;\n\n  /**\n   * Working memory configuration for persistent user data and preferences.\n   * Maintains a structured record (Markdown or schema-based) that agents update over time.\n   * Can be thread-scoped (per conversation) or resource-scoped (across all user threads).\n   *\n   * @example\n   * ```typescript\n   * workingMemory: {\n   *   enabled: true,\n   *   scope: 'resource', // Persist across all resource (user) conversations\n   *   template: '# User Profile\\n- **Name**:\\n- **Preferences**:',\n   *   schema: z.object({\n   *     name: z.string(),\n   *     preferences: z.object({\n   *       communicationStyle: z.string(),\n   *       projectGoal: z.string(),\n   *       deadlines: z.array(z.string()),\n   *     }),\n   *   }),\n   * }\n   * ```\n   */\n  workingMemory?: WorkingMemory;\n\n  /**\n   * Observational Memory configuration for long-term memory with automatic observation and reflection.\n   *\n   * Uses an Observer agent to extract observations from conversations and a Reflector agent\n   * to compress them when they grow too large. This enables efficient long-term memory\n   * that maintains context across many conversations.\n   *\n   * Set to `true` to enable with defaults, `false` to disable, or an object to customize.\n   *\n   * @example\n   * ```typescript\n   * // Enable with defaults\n   * observationalMemory: true\n   *\n   * // Custom configuration\n   * observationalMemory: {\n   *   scope: 'resource',\n   *   model: 'google/gemini-2.5-flash',\n   *   observation: {\n   *     messageTokens: 20_000,\n   *   },\n   *   reflection: {\n   *     observationTokens: 90_000,\n   *   },\n   * }\n   * ```\n   */\n  observationalMemory?: boolean | ObservationalMemoryOptions;\n\n  /**\n   * Automatically generate descriptive thread titles based on the first user message.\n   * Can be a boolean to enable with defaults, or an object to customize the model and instructions.\n   * Title generation runs asynchronously and doesn't affect response time — unless\n   * `emitEvent` is set on a stream run, in which case the final `finish` chunk is held\n   * until the title is generated and persisted.\n   *\n   * @default false\n   * @example\n   * ```typescript\n   * generateTitle: true // Use agent's model for title generation\n   * generateTitle: {\n   *   model: openai(\"gpt-4o-mini\"),\n   *   instructions: \"Generate a concise title (max 5 words)\"\n   * }\n   * ```\n   */\n  generateTitle?:\n    | boolean\n    | {\n        /**\n         * Language model to use for title generation.\n         * Can be static or a function that receives request context for dynamic selection.\n         * Accepts both Mastra models and standard AI SDK LanguageModelV1/V2.\n         * Defaults to the agent's own model when omitted.\n         */\n        model?: DynamicArgument<MastraModelConfig>;\n        /**\n         * Custom instructions for title generation.\n         * Can be static or a function that receives request context for dynamic customization.\n         */\n        instructions?: DynamicArgument<string>;\n        /**\n         * Minimum number of messages in the thread (user + assistant) before\n         * a title is generated.\n         * @default 1\n         */\n        minMessages?: number;\n        /**\n         * Emit the generated title as a transient `data-thread-title` chunk\n         * (`{ threadId, title }`) on the run's stream immediately before the\n         * `finish` chunk, so HTTP/stream consumers receive it on the same run.\n         * Only applies to `stream()` runs; `generate()` and durable/evented agents\n         * keep persist-only behavior.\n         *\n         * Trade-off: the `finish` chunk (and therefore the response's completion)\n         * is delayed until the title is generated and persisted. If the run is\n         * aborted during that wait, `finish` is released immediately and title\n         * generation continues in the background.\n         *\n         * @default false\n         */\n        emitEvent?: boolean;\n      };\n\n  /**\n   * Whether to filter out incomplete (suspended) tool calls when sending messages to the LLM.\n   * When true, tool calls in `input-available` state are stripped from the prompt,\n   * preventing the agent from seeing its own suspended tool calls in thread history.\n   *\n   * Set to false to allow the agent to see suspended tool calls in context.\n   * This is useful for suspend/resume patterns where the agent should be aware of pending interactions.\n   *\n   * Note: providers reject a tool call that has no matching tool result, so a suspended call kept\n   * in context is paired with a `{ status: 'pending' }` placeholder result before the prompt is sent.\n   *\n   * @default true\n   * @example\n   * ```typescript\n   * filterIncompleteToolCalls: false // Keep suspended tool calls visible in context\n   * ```\n   */\n  filterIncompleteToolCalls?: boolean;\n\n  /**\n   * Whether the request input is processed in full instead of being trimmed to the part\n   * stored history does not already cover.\n   *\n   * By default, when memory loads thread history, only the new messages in the input are\n   * used: the input is trimmed back to the last assistant message (or, when the input ends\n   * with an assistant message, to that message's trailing tool results), and the stored\n   * history is layered underneath. Set this to true when the caller assembled the input\n   * itself and needs the exact message sequence preserved — for example a nested\n   * `useAgent` structuring pass that deliberately replays the parent request so its prompt\n   * keeps the parent's message prefix.\n   *\n   * This controls trimming only. When a memory-sourced message and an input message share\n   * an id, the stored copy stays authoritative: only tool outcomes for calls it still has\n   * pending are taken from the input. Input text, reasoning, and metadata are ignored.\n   *\n   * @default false\n   * @example\n   * ```typescript\n   * retainFullInput: true // Process the request input exactly as supplied\n   * ```\n   */\n  retainFullInput?: boolean;\n\n  /**\n   * Thread management configuration.\n   * @deprecated The `threads` object is deprecated. Use top-level `generateTitle` instead of `threads.generateTitle`.\n   */\n  threads?: {\n    /**\n     * @deprecated Moved to top-level `generateTitle`. Using `threads.generateTitle` will throw an error.\n     */\n    generateTitle?:\n      | boolean\n      | {\n          model: DynamicArgument<MastraModelConfig>;\n          instructions?: DynamicArgument<string>;\n        };\n  };\n};\n\nexport type MemoryConfigInternal = BaseMemoryConfig & {\n  /**\n   * Working memory configuration for persistent user data and preferences.\n   * Maintains a structured record (Markdown or schema-based) that agents update over time.\n   * Can be thread-scoped (per conversation) or resource-scoped (across all user threads).\n   *\n   * @example\n   * ```typescript\n   * workingMemory: {\n   *   enabled: true,\n   *   scope: 'resource', // Persist across all resource (user) conversations\n   *   template: '# User Profile\\n- **Name**:\\n- **Preferences**:',\n   *   schema: z.object({\n   *     name: z.string(),\n   *     preferences: z.object({\n   *       communicationStyle: z.string(),\n   *       projectGoal: z.string(),\n   *       deadlines: z.array(z.string()),\n   *     }),\n   *   }),\n   * }\n   * ```\n   */\n  workingMemory?: WorkingMemory;\n};\n\nexport type MemoryConfig = BaseMemoryConfig & {\n  /**\n   * Working memory configuration for persistent user data and preferences.\n   * Maintains a structured record (Markdown or schema-based) that agents update over time.\n   * Can be thread-scoped (per conversation) or resource-scoped (across all user threads).\n   *\n   * @example\n   * ```typescript\n   * workingMemory: {\n   *   enabled: true,\n   *   scope: 'resource', // Persist across all resource (user) conversations\n   *   template: '# User Profile\\n- **Name**:\\n- **Preferences**:',\n   *   schema: z.object({\n   *     name: z.string(),\n   *     preferences: z.object({\n   *       communicationStyle: z.string(),\n   *       projectGoal: z.string(),\n   *       deadlines: z.array(z.string()),\n   *     }),\n   *   }),\n   * }\n   * ```\n   */\n  workingMemory?: TemplateWorkingMemory | SchemaWorkingMemory | WorkingMemoryNone;\n};\n\n/**\n * Configuration for Mastra's memory system.\n *\n * Enables agents to persist and recall information across conversations using storage providers,\n * vector databases for semantic search, and processors for context management. Memory can be\n * scoped to individual threads or shared across all conversations for a resource (user).\n *\n * @see https://mastra.ai/docs/memory/overview\n */\nexport type SharedMemoryConfig = {\n  /**\n   * Storage adapter for persisting conversation threads, messages, and working memory.\n   *\n   * @example\n   * ```typescript\n   * storage: new LibSQLStore({ id: 'agent-memory-storage', url: \"file:./agent-memory.db\" })\n   * ```\n   */\n  storage?: MastraCompositeStore;\n\n  /**\n   * Configuration for memory behaviors including conversation history, semantic recall,\n   * working memory, and thread management. Controls how messages are retrieved and\n   * what context is included in the LLM's prompt.\n   */\n  options?: MemoryConfigInternal;\n\n  /**\n   * Vector database for semantic recall capabilities using RAG-based search.\n   * Enables retrieval of relevant messages from past conversations based on semantic similarity.\n   * Set to false to disable vector search entirely.\n   *\n   * @example\n   * ```typescript\n   * vector: new PgVector({ connectionString: process.env.DATABASE_URL })\n   * ```\n   */\n  vector?: MastraVector | false;\n\n  /**\n   * Embedding model for converting messages into vector representations for semantic search.\n   * Compatible with any AI SDK embedding model. FastEmbed provides local embeddings,\n   * while providers like OpenAI offer cloud-based models.\n   *\n   * Can be specified as:\n   * - A string in the format \"provider/model\" (e.g., \"openai/text-embedding-3-small\")\n   * - An EmbeddingModel or EmbeddingModelV2 instance\n   *\n   * @example\n   * ```typescript\n   * // Using a string (model router format)\n   * embedder: \"openai/text-embedding-3-small\"\n   *\n   * // Using an AI SDK model directly\n   * embedder: openai.embedding(\"text-embedding-3-small\")\n   * ```\n   */\n  embedder?: EmbeddingModelId | MastraEmbeddingModel<string> | string;\n\n  /**\n   * Options to pass to the embedder when generating embeddings.\n   * Use this to pass provider-specific options like outputDimensionality for Google models.\n   *\n   * @example\n   * ```typescript\n   * // Control embedding dimensions for Google models\n   * embedderOptions: {\n   *   providerOptions: {\n   *     google: {\n   *       outputDimensionality: 768,\n   *       taskType: 'RETRIEVAL_DOCUMENT'\n   *     }\n   *   }\n   * }\n   * ```\n   */\n  embedderOptions?: MastraEmbeddingOptions;\n\n  /**\n   * Output dimension of the embedder, if known. When set, Memory uses it to name the semantic\n   * recall index instead of embedding a probe string on first use, which saves one embedding\n   * call per Memory instance and removes the startup dependency on the embedding provider.\n   * Must be a positive integer that matches the vectors the embedder returns.\n   *\n   * @example\n   * ```typescript\n   * embedder: 'openai/text-embedding-3-small',\n   * embeddingDimension: 1536\n   * ```\n   */\n  embeddingDimension?: number;\n\n  /**\n   * @deprecated This option is deprecated and will throw an error if used.\n   * Use the new Input/Output processor system instead.\n   *\n   * See: https://mastra.ai/en/docs/memory/processors\n   *\n   * @example\n   * ```typescript\n   * // OLD (throws error):\n   * new Memory({\n   *   processors: [new TokenLimiter(100000)]\n   * })\n   *\n   * // NEW (use this):\n   * new Agent({\n   *   memory,\n   *   outputProcessors: [new TokenLimiterProcessor(100000)]\n   * })\n   * ```\n   */\n  processors?: MemoryProcessor[];\n};\n\n/** @deprecated Use the `format` field on `WorkingMemoryTemplate` discriminated union instead. */\nexport type WorkingMemoryFormat = 'json' | 'markdown';\n\nexport type WorkingMemoryTemplate =\n  | { format: 'markdown'; content: string }\n  | { format: 'json'; content: string | Record<string, unknown> };\n\n// Type for flexible message deletion input\nexport type MessageDeleteInput = string[] | { id: string }[];\n\n/**\n * Serialized memory configuration that can be stored in the database\n * This is a subset of SharedMemoryConfig with serializable types only\n */\nexport type SerializedMemoryConfig = {\n  /**\n   * Vector database identifier. The vector instance should be registered\n   * with the Mastra instance to resolve from this ID.\n   * Set to false to disable vector search entirely.\n   */\n  vector?: string | false;\n\n  /**\n   * Configuration for memory behaviors, omitting WorkingMemory and threads\n   */\n  options?: {\n    /** Treat memory as read-only (no new messages stored) */\n    readOnly?: boolean;\n\n    /** Number of recent messages to include, or false to disable */\n    lastMessages?: number | false;\n\n    /** Token budget for conversation history */\n    messageHistory?: import('./message-history-config').MessageHistoryConfig;\n\n    /** Semantic recall configuration */\n    semanticRecall?: boolean | SemanticRecall;\n\n    /** Title generation configuration (serialized form) */\n    generateTitle?:\n      | boolean\n      | {\n          /** Model ID in format provider/model-name; omitted to use the agent's own model */\n          model?: ModelRouterModelId;\n          /** Custom instructions for title generation */\n          instructions?: string;\n          /** Minimum number of messages in the thread before a title is generated */\n          minMessages?: number;\n          /** Emit a transient `data-thread-title` chunk before `finish` on stream runs */\n          emitEvent?: boolean;\n        };\n  };\n\n  /**\n   * Embedding model ID in the format \"provider/model\"\n   * (e.g., \"openai/text-embedding-3-small\")\n   * Can be a predefined EmbeddingModelId or a custom string\n   */\n  embedder?: EmbeddingModelId | string;\n\n  /**\n   * Options to pass to the embedder, omitting telemetry\n   */\n  embedderOptions?: Omit<MastraEmbeddingOptions, 'telemetry'>;\n\n  /**\n   * Serialized observational memory configuration.\n   * `true` to enable with defaults, or a config object for customization.\n   * Only JSON-safe fields are included (model IDs as strings, numeric/boolean settings).\n   */\n  observationalMemory?: boolean | SerializedObservationalMemoryConfig;\n};\n\n/**\n * JSON-serializable subset of ObservationalMemoryOptions for storage.\n * Model references are stored as string IDs (e.g., \"google/gemini-2.5-flash\").\n */\nexport type SerializedObservationalMemoryConfig = {\n  /** Model ID for both Observer and Reflector (e.g., \"google/gemini-2.5-flash\") */\n  model?: string;\n\n  /**\n   * Memory scope: 'resource' or 'thread'\n   * @deprecated The `scope` option is deprecated. `'resource'` will be removed in a future release, leaving\n   * `'thread'` (already the default) as the only scope. Omit this option to use thread scope.\n   */\n  scope?: 'resource' | 'thread';\n\n  /** Inactivity TTL before forcing buffered observation activation */\n  activateAfterIdle?: ObservationalMemoryActivationTTL;\n\n  /** Force-activate buffered observation activation when the actor model changes */\n  activateOnProviderChange?: boolean;\n\n  /** Share the token budget between messages and observations */\n  shareTokenBudget?: boolean;\n\n  /** Persist inline temporal gap markers for long pauses between messages */\n  temporalMarkers?: boolean;\n\n  /**\n   * Enable retrieval-mode observation groups as durable pointers to raw message history.\n   */\n  retrieval?: boolean | { vector?: boolean; scope?: 'thread' | 'resource'; instructions?: string };\n\n  /** Observation step configuration */\n  observation?: SerializedObservationalMemoryObservationConfig;\n\n  /** Reflection step configuration */\n  reflection?: SerializedObservationalMemoryReflectionConfig;\n};\n\n/** Serializable subset of ObservationalMemoryObservationConfig */\nexport type SerializedObservationalMemoryObservationConfig = {\n  /** Observer model ID */\n  model?: string;\n  /** Number of retries after the initial Observer model call */\n  maxRetries?: number;\n  /** Terminal policy after Observer model retries are exhausted */\n  failurePolicy?: 'abort' | 'continue';\n  /** Manage working memory through Observational Memory extraction. */\n  manageWorkingMemory?: boolean;\n\n  /** Token count threshold that triggers observation */\n  messageTokens?: number;\n  /** Model settings (temperature, maxOutputTokens, etc.) */\n  modelSettings?: Record<string, unknown>;\n  /** Provider-specific options */\n  providerOptions?: Record<string, Record<string, unknown> | undefined>;\n  /** Maximum tokens per batch */\n  maxTokensPerBatch?: number;\n  /** Token interval for async buffering, or false to disable */\n  bufferTokens?: number | false;\n  /** Ratio of buffered observations to activate */\n  bufferActivation?: number;\n  /** Inactivity TTL before forcing buffered observation activation */\n  activateAfterIdle?: ObservationalMemoryActivationTTL;\n  /** Force-activate buffered observation activation when the actor model changes */\n  activateOnProviderChange?: boolean;\n  /** Token threshold for synchronous blocking */\n  blockAfter?: number;\n  /** Optional token budget for observer context (0 = full truncation, false = disabled) */\n  previousObserverTokens?: number | false;\n  /** Whether the Observer should suggest thread titles */\n  threadTitle?: boolean;\n  /** Whether image/file attachment parts are forwarded to the Observer LLM */\n  observeAttachments?: 'auto' | boolean | string[];\n};\n\n/** Serializable subset of ObservationalMemoryReflectionConfig */\nexport type SerializedObservationalMemoryReflectionConfig = {\n  /** Reflector model ID */\n  model?: string;\n  /** Number of retries after the initial Reflector model call */\n  maxRetries?: number;\n  /** Terminal policy after Reflector model retries are exhausted */\n  failurePolicy?: 'abort' | 'continue';\n  /** Token count threshold that triggers reflection */\n  observationTokens?: number;\n  /** Model settings (temperature, maxOutputTokens, etc.) */\n  modelSettings?: Record<string, unknown>;\n  /** Provider-specific options */\n  providerOptions?: Record<string, Record<string, unknown> | undefined>;\n  /** Token threshold for synchronous blocking */\n  blockAfter?: number;\n  /** Inactivity TTL before forcing buffered reflection activation */\n  activateAfterIdle?: ObservationalMemoryActivationTTL;\n  /** Force-activate buffered reflection activation when the actor model changes */\n  activateOnProviderChange?: boolean;\n  /** Ratio for async reflection buffering */\n  bufferActivation?: number;\n};\n","/**\n * One change to a storage v2 run's state. `path` addresses a value from the state's root: a\n * number is an array index and a string is an object key. An empty path is the root.\n *\n * Ops are absolute (there is no relative append), so replaying a list of ops onto a state that\n * already contains them changes nothing.\n * @experimental\n */\nexport type StatePatchOp =\n  | { op: 'set'; path: (string | number)[]; value: unknown }\n  | { op: 'delete'; path: (string | number)[] };\n\nfunction isObject(value: unknown): value is Record<string, unknown> {\n  return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\n/**\n * The ops that turn `prev` into `next`. Both must be JSON values (no `undefined`, Dates or class\n * instances). Unchanged values produce no ops.\n * @experimental\n */\nexport function diffState(prev: unknown, next: unknown): StatePatchOp[] {\n  const ops: StatePatchOp[] = [];\n  diffValue(prev, next, [], ops);\n  return ops;\n}\n\nfunction diffValue(prev: unknown, next: unknown, path: (string | number)[], ops: StatePatchOp[]): void {\n  if (prev === next) return;\n  if (Array.isArray(prev) && Array.isArray(next)) {\n    if (next.length < prev.length) {\n      ops.push({ op: 'set', path, value: next });\n      return;\n    }\n    for (let i = 0; i < prev.length; i++) diffValue(prev[i], next[i], [...path, i], ops);\n    for (let i = prev.length; i < next.length; i++) ops.push({ op: 'set', path: [...path, i], value: next[i] });\n    return;\n  }\n  if (isObject(prev) && isObject(next)) {\n    for (const key of Object.keys(prev)) {\n      if (!Object.hasOwn(next, key)) ops.push({ op: 'delete', path: [...path, key] });\n    }\n    for (const key of Object.keys(next)) {\n      if (Object.hasOwn(prev, key)) diffValue(prev[key], next[key], [...path, key], ops);\n      else ops.push({ op: 'set', path: [...path, key], value: next[key] });\n    }\n    return;\n  }\n  ops.push({ op: 'set', path, value: next });\n}\n\nconst OMITTED = Symbol('omitted');\n\n/**\n * `value`, the `key` property of its holder, one level deep as `JSON.stringify` serializes it:\n * `toJSON` applied, boxed primitives unboxed, non-finite numbers as `null`, and `OMITTED` for\n * what it leaves out. Objects and arrays are returned as they are.\n */\nfunction jsonNode(value: unknown, key: string): unknown {\n  if ((typeof value === 'object' && value !== null) || typeof value === 'function' || typeof value === 'bigint') {\n    const toJSON = (value as { toJSON?: unknown }).toJSON;\n    if (typeof toJSON === 'function') value = toJSON.call(value, key);\n  }\n  if (value instanceof Number) value = Number(value);\n  else if (value instanceof String) value = String(value);\n  else if (value instanceof Boolean) value = value.valueOf();\n  switch (typeof value) {\n    case 'string':\n    case 'boolean':\n    case 'object':\n      return value;\n    case 'number':\n      // -0 is written as 0.\n      return Number.isFinite(value) ? value + 0 : null;\n    case 'bigint':\n      throw new TypeError('Do not know how to serialize a BigInt');\n    default:\n      return OMITTED;\n  }\n}\n\nfunction arrayItem(array: unknown[], i: number): unknown {\n  const item = jsonNode(array[i], String(i));\n  return item === OMITTED ? null : item;\n}\n\n/** A JSON copy of a `jsonNode` result. Throws, as `JSON.stringify` does, on a cycle. */\nfunction jsonCopy(node: unknown): unknown {\n  if (typeof node !== 'object' || node === null) return node;\n  // `jsonNode` has already applied this node's `toJSON`; `JSON.stringify` would apply it again.\n  if (typeof (node as { toJSON?: unknown }).toJSON === 'function') {\n    if (Array.isArray(node)) node = node.slice();\n    else {\n      const { toJSON: _, ...rest } = node as Record<string, unknown>;\n      node = rest;\n    }\n  }\n  return JSON.parse(JSON.stringify(node));\n}\n\n/**\n * `diffState(prev, JSON.parse(JSON.stringify(next)))` without copying `next`: `next` can be any\n * JSON-serializable value and is compared as its JSON form, and only the values of `set` ops are\n * copied. `prev` must be a JSON value. Throws a `TypeError`, as `JSON.stringify` does, when\n * `next` has a cycle or a BigInt, or has no JSON form at all.\n * @experimental\n */\nexport function diffStateAsJson(prev: unknown, next: unknown): StatePatchOp[] {\n  const root = jsonNode(next, '');\n  if (root === OMITTED) throw new TypeError(`A ${typeof next} has no JSON form`);\n  const ops: StatePatchOp[] = [];\n  diffJsonValue(prev, root, [], ops);\n  return ops;\n}\n\n/**\n * `diffValue` on `next`'s JSON form, which `jsonNode` gives one level at a time. Every part of\n * `next` is either walked alongside `prev` or copied by `jsonCopy`, and `prev` is finite, so a\n * cycle in `next` always reaches `jsonCopy`, which throws.\n */\nfunction diffJsonValue(prev: unknown, next: unknown, path: (string | number)[], ops: StatePatchOp[]): void {\n  if (typeof next !== 'object' || next === null) {\n    if (prev !== next) ops.push({ op: 'set', path, value: next });\n    return;\n  }\n  if (Array.isArray(next)) {\n    if (!Array.isArray(prev) || next.length < prev.length) {\n      ops.push({ op: 'set', path, value: jsonCopy(next) });\n      return;\n    }\n    for (let i = 0; i < prev.length; i++) diffJsonValue(prev[i], arrayItem(next, i), [...path, i], ops);\n    for (let i = prev.length; i < next.length; i++) {\n      ops.push({ op: 'set', path: [...path, i], value: jsonCopy(arrayItem(next, i)) });\n    }\n    return;\n  }\n  if (!isObject(prev)) {\n    ops.push({ op: 'set', path, value: jsonCopy(next) });\n    return;\n  }\n  const kept = new Map<string, unknown>();\n  for (const key of Object.keys(next)) {\n    const value = jsonNode((next as Record<string, unknown>)[key], key);\n    if (value !== OMITTED) kept.set(key, value);\n  }\n  for (const key of Object.keys(prev)) {\n    if (!kept.has(key)) ops.push({ op: 'delete', path: [...path, key] });\n  }\n  for (const [key, value] of kept) {\n    if (Object.hasOwn(prev, key)) diffJsonValue(prev[key], value, [...path, key], ops);\n    else ops.push({ op: 'set', path: [...path, key], value: jsonCopy(value) });\n  }\n}\n\nfunction childOf(container: any, key: string | number): unknown {\n  return Object.hasOwn(container, key) ? container[key] : undefined;\n}\n\nfunction setChild(container: any, key: string | number, value: unknown): void {\n  // defineProperty, so a `__proto__` key is stored as data rather than replacing the prototype.\n  Object.defineProperty(container, key, { value, writable: true, enumerable: true, configurable: true });\n}\n\n/**\n * Apply `ops` to `root` in order and return the result: `root` itself, mutated, unless an op\n * replaces the root. A `set` creates missing or non-container intermediates (`[]` before a number\n * segment, `{}` before a string); a `delete` whose path doesn't exist does nothing. Set values are\n * copied, so the result shares nothing with `ops`.\n * @experimental\n */\nexport function applyStatePatch<T = Record<string, any>>(root: T, ops: readonly StatePatchOp[]): T {\n  return applyOps(root, ops);\n}\n\n/**\n * `applyStatePatch` that leaves `root` as it is: each object or array an op changes is copied\n * (once) first, so the result shares only what the ops didn't change with `root`.\n * @experimental\n */\nexport function patchState<T = Record<string, any>>(root: T, ops: readonly StatePatchOp[]): T {\n  return applyOps(root, ops, new Set());\n}\n\n/** With `copies`, the containers copied or created so far, which ops can change in place. */\nfunction applyOps(root: any, ops: readonly StatePatchOp[], copies?: Set<object>): any {\n  const own = (value: any) => {\n    if (!copies || typeof value !== 'object' || value === null || copies.has(value)) return value;\n    // Spread defines a `__proto__` key as data, like `setChild`.\n    const copy = Array.isArray(value) ? value.slice() : { ...value };\n    copies.add(copy);\n    return copy;\n  };\n  const copyOf = (value: unknown) => {\n    const copy = structuredClone(value);\n    if (typeof copy === 'object' && copy !== null) copies?.add(copy);\n    return copy;\n  };\n  let result = root;\n  for (const op of ops) {\n    if (op.path.length === 0) {\n      if (op.op === 'set') result = copyOf(op.value);\n      continue;\n    }\n    result = own(result);\n    let container = result;\n    for (let i = 0; i < op.path.length - 1; i++) {\n      const key = op.path[i]!;\n      let child = childOf(container, key);\n      if (typeof child !== 'object' || child === null) {\n        if (op.op === 'delete') {\n          container = undefined;\n          break;\n        }\n        child = typeof op.path[i + 1] === 'number' ? [] : {};\n        copies?.add(child as object);\n        setChild(container, key, child);\n      } else if (copies && !copies.has(child)) {\n        child = own(child);\n        setChild(container, key, child);\n      }\n      container = child;\n    }\n    if (container === undefined) continue;\n    const key = op.path[op.path.length - 1]!;\n    if (op.op === 'set') setChild(container, key, copyOf(op.value));\n    else if (Object.hasOwn(container, key)) delete container[key];\n  }\n  return result;\n}\n","import type { StepResult, StepSuccess, WorkflowRunState } from '../../../workflows';\nimport { applyStatePatch, patchState } from './state-patch';\nimport type { StatePatchOp } from './state-patch';\n\n/**\n * A storage v2 run header: the run's `WorkflowRunState` without `context` and `value`,\n * which are stored as entries.\n * @experimental\n */\nexport type WorkflowRunHeader = Omit<WorkflowRunState, 'context' | 'value'>;\n\n/**\n * A version of a run's state: its state as of `seq`, or with `draft`, the draft written at `seq`.\n * @experimental\n */\nexport type StateVersion = { seq: number; draft?: true };\n\n/**\n * A version of a named run's state, which a nested run's state builds on.\n * @experimental\n */\nexport type StateRef = StateVersion & { workflowName: string; runId: string };\n\n/**\n * One storage v2 entry. A run's entries are append-only and ordered by `seq`, which only\n * increases within a run, also across checkpoints.\n *\n * A step's result is its latest `step` entry, with the later `step-patch` entries for the step\n * applied (see `latestStepResults`). The run's state is a `state` (full) or `state-base` (another\n * run's state version) entry, with the later `state-patch` entries applied. A `state-draft` doesn't\n * change the run's state: it is a version of its live state that nested runs build on (see\n * `materializeState`).\n * @experimental\n */\nexport type WorkflowRunEntry =\n  | { seq: number; kind: 'step'; stepId: string; result: unknown }\n  | { seq: number; kind: 'step-patch'; stepId: string; ops: StatePatchOp[] }\n  | { seq: number; kind: 'state'; state: Record<string, any> }\n  | { seq: number; kind: 'state-patch'; ops: StatePatchOp[] }\n  | { seq: number; kind: 'state-base'; base: StateRef }\n  | { seq: number; kind: 'state-draft'; on: StateVersion; ops: StatePatchOp[] }\n  | { seq: number; kind: 'state-draft'; state: Record<string, any> };\n\n/**\n * A successful step result without its data (`output`, `payload` and the suspend/resume\n * payloads).\n * @experimental\n */\nexport type StepResultSummary = Pick<\n  StepSuccess<any, any, any, any>,\n  'status' | 'startedAt' | 'endedAt' | 'suspendedAt' | 'resumedAt' | 'metadata'\n>;\n\n/**\n * A storage v2 run's header, and the `seq` of its latest entry.\n * @experimental\n */\nexport type StoredWorkflowRunHeader = {\n  header: WorkflowRunHeader;\n  lastSeq: number;\n  /** Opaque stored-run identity, stable until deletion. Distinguishes reused public run IDs. */\n  runToken?: string;\n  /**\n   * The state version the run's current drive started from: the `state` or `state-base` entry its\n   * latest checkpoint wrote, or the `seq` a later append passed as `startStateSeq` (a resumed drive).\n   * Undefined when the store doesn't track it.\n   */\n  startStateSeq?: number;\n  /** The run's resource id. Only `loadWorkflowRunHeader` returns it. */\n  resourceId?: string;\n} & StoredStateColumns;\n\n/**\n * Where a storage v2 run's state chain stands, kept on its header row by every write.\n * @experimental\n */\nexport type StoredStateColumns = {\n  /** The `seq` of the run's latest `state`, `state-base` or `state-patch` entry; 0 before its first. */\n  stateSeq: number;\n  /** The `state-patch` entries after the run's latest `state` or `state-base` entry. */\n  statePatchCount: number;\n  /** Their summed `JSON.stringify(ops).length`. */\n  statePatchBytes: number;\n  /**\n   * `JSON.stringify(state).length` of the latest `state` entry; null when the latest is a\n   * `state-base` (or a deleted base's state copied in its place), so only the patch count applies.\n   */\n  stateBytes: number | null;\n};\n\n/**\n * A storage v2 run as `loadWorkflowRun` returns it.\n * @experimental\n */\nexport type StoredWorkflowRun = StoredWorkflowRunHeader & {\n  /** The run's state, as `materializeState` rebuilds it. */\n  state: Record<string, any>;\n  /** The latest entry per step, in the order each step was first written. */\n  steps: Record<string, StepResult<any, any, any, any> | StepResultSummary>;\n  /** Ids in `steps` that hold a summary rather than the full result. */\n  summarizedStepIds: string[];\n};\n\n/**\n * The header fields of `appendWorkflowRunEntries`. With `header`, the append writes it (with\n * `resourceId` and `threadId`), creating the run if it isn't stored. Without, the append keeps the\n * stored header, only bumping `updatedAt` and shallow-merging `requestContext` into the header's\n * `requestContext`, and writes nothing when the run isn't stored.\n * @experimental\n */\nexport type WorkflowRunAppendHeader =\n  | { header: WorkflowRunHeader; resourceId?: string; threadId?: string; requestContext?: undefined }\n  | { header?: undefined; resourceId?: undefined; threadId?: undefined; requestContext?: Record<string, any> };\n\n/**\n * The fields of a successful step result that its summary keeps. Exported for adapters that\n * summarize in their query rather than with `summarizeStepResult`.\n * @experimental\n */\nexport const STEP_RESULT_SUMMARY_FIELDS = [\n  'status',\n  'startedAt',\n  'endedAt',\n  'suspendedAt',\n  'resumedAt',\n  'metadata',\n] as const satisfies readonly (keyof StepResultSummary)[];\n\n/**\n * The summary of a successful step result. Shared so every adapter summarizes the same way.\n * @experimental\n */\nexport function summarizeStepResult(result: StepResultSummary): StepResultSummary {\n  const summary: Record<string, unknown> = {};\n  for (const field of STEP_RESULT_SUMMARY_FIELDS) {\n    if (result[field] !== undefined) summary[field] = result[field];\n  }\n  return summary as StepResultSummary;\n}\n\n/**\n * Once a run's state has this many patches after its latest `state` or `state-base` entry, its\n * next state write is a full state, so rebuilding the state applies at most this many patches.\n * @experimental\n */\nexport const STATE_CHECKPOINT_PATCHES = 100;\n\n/**\n * How a write changes a run's `StoredStateColumns`: with `reset`, the state starts over (from a\n * full state of `stateBytes`, or from a state base, `stateBytes` null) and the patch columns become\n * `patchCount` and `patchBytes`; without, `patchCount` and `patchBytes` are added to them.\n * @experimental\n */\nexport type StateColumnsWrite = { reset: boolean; stateBytes: number | null; patchCount: number; patchBytes: number };\n\n/**\n * The `StateColumnsWrite` of a write's state fields, entered as `writeWorkflowRunCheckpoint` and\n * `appendWorkflowRunEntries` do: the state or state base (a checkpoint with neither starts over at\n * `{}`), then the patch unless a full state was given. Undefined when the write has no state entry.\n * @experimental\n */\nexport function stateColumnsWrite(\n  { state, stateBase, statePatch }: { state?: Record<string, any>; stateBase?: StateRef; statePatch?: StatePatchOp[] },\n  checkpoint: boolean,\n): StateColumnsWrite | undefined {\n  if (state !== undefined)\n    return { reset: true, stateBytes: JSON.stringify(state).length, patchCount: 0, patchBytes: 0 };\n  const patchCount = statePatch === undefined ? 0 : 1;\n  const patchBytes = statePatch === undefined ? 0 : JSON.stringify(statePatch).length;\n  if (stateBase !== undefined) return { reset: true, stateBytes: null, patchCount, patchBytes };\n  if (checkpoint) return { reset: true, stateBytes: 2, patchCount, patchBytes };\n  if (statePatch !== undefined) return { reset: false, stateBytes: null, patchCount, patchBytes };\n  return undefined;\n}\n\n/**\n * A run's state columns after a write whose last entry is `lastSeq` (a write's state entries come\n * after its steps). `columns` are the run's before it, undefined for a new run.\n * @experimental\n */\nexport function applyStateColumnsWrite(\n  columns: StoredStateColumns | undefined,\n  write: StateColumnsWrite | undefined,\n  lastSeq: number,\n): StoredStateColumns {\n  const before = columns ?? { stateSeq: 0, statePatchCount: 0, statePatchBytes: 0, stateBytes: null };\n  if (!write) {\n    return {\n      stateSeq: before.stateSeq,\n      statePatchCount: before.statePatchCount,\n      statePatchBytes: before.statePatchBytes,\n      stateBytes: before.stateBytes,\n    };\n  }\n  if (write.reset) {\n    return {\n      stateSeq: lastSeq,\n      statePatchCount: write.patchCount,\n      statePatchBytes: write.patchBytes,\n      stateBytes: write.stateBytes,\n    };\n  }\n  return {\n    stateSeq: lastSeq,\n    statePatchCount: before.statePatchCount + write.patchCount,\n    statePatchBytes: before.statePatchBytes + write.patchBytes,\n    stateBytes: before.stateBytes,\n  };\n}\n\n/**\n * Whether a run's state is due a full state entry: `STATE_CHECKPOINT_PATCHES` patches, or patches\n * larger than its latest full state.\n * @experimental\n */\nexport function isStateCheckpointDue(columns: StoredStateColumns): boolean {\n  return (\n    columns.statePatchCount >= STATE_CHECKPOINT_PATCHES ||\n    (columns.stateBytes !== null && columns.statePatchBytes > columns.stateBytes)\n  );\n}\n\n/**\n * `state` with only the given top-level keys (all of it without `keys`). Keys it doesn't have are left out.\n * @experimental\n */\nexport function pickStateKeys(state: Record<string, any>, keys?: readonly string[]): Record<string, any> {\n  if (!keys) return state;\n  const picked: Record<string, any> = {};\n  for (const key of keys) {\n    if (Object.prototype.hasOwnProperty.call(state, key)) picked[key] = state[key];\n  }\n  return picked;\n}\n\ntype StateChain = {\n  /** A full state, another run's state version, or nothing (`{}`). */\n  base: Record<string, any> | StateRef | undefined;\n  baseIsRef: boolean;\n  /** The patches to apply to `base`, in order. */\n  patches: StatePatchOp[][];\n};\n\nfunction stateChain(entries: readonly WorkflowRunEntry[], at: StateVersion | undefined): StateChain {\n  const drafts: StatePatchOp[][] = [];\n  let version = at;\n  while (version?.draft) {\n    const seq = version.seq;\n    const draft = entries.find(entry => entry.seq === seq);\n    if (draft?.kind !== 'state-draft') throw new Error(`Storage v2 state draft ${seq} is not stored`);\n    if ('state' in draft) return { base: draft.state, baseIsRef: false, patches: drafts.reverse() };\n    drafts.push(draft.ops);\n    version = draft.on;\n  }\n  const upTo = version?.seq ?? Infinity;\n  let base: StateChain['base'];\n  let baseIsRef = false;\n  let patches: StatePatchOp[][] = [];\n  for (const entry of entries) {\n    if (entry.seq > upTo) break;\n    if (entry.kind === 'state' || entry.kind === 'state-base') {\n      base = entry.kind === 'state' ? entry.state : entry.base;\n      baseIsRef = entry.kind === 'state-base';\n      patches = [];\n    } else if (entry.kind === 'state-patch') {\n      patches.push(entry.ops);\n    }\n  }\n  return { base, baseIsRef, patches: [...patches, ...drafts.reverse()] };\n}\n\n/**\n * The other run's state version that a run's state (as of `at`, or latest) builds on, if any.\n * Stores resolve it (by this same rule) and pass it to `materializeState` as `base`.\n * @experimental\n */\nexport function stateBaseOf(entries: readonly WorkflowRunEntry[], at?: StateVersion): StateRef | undefined {\n  const chain = stateChain(entries, at);\n  return chain.baseIsRef ? (chain.base as StateRef) : undefined;\n}\n\n/**\n * Rebuild a run's state from its entries (in `seq` order).\n *\n * The latest state (no `at`), or the state as of a `seq`, is the latest `state` or `state-base`\n * entry up to it, with every later `state-patch` up to it applied in order. Drafts are left out. A\n * `state-base` entry's state is `base`, the state the store resolved for `stateBaseOf(entries, at)`.\n * The state of a draft is the version it is `on`, with its patch applied (or its full `state`).\n *\n * Patches are applied copy-on-write: the result shares what they don't change with `entries` and\n * `base`, which are left as they are.\n * @experimental\n */\nexport function materializeState(\n  entries: readonly WorkflowRunEntry[],\n  { at, base }: { at?: StateVersion; base?: Record<string, any> } = {},\n): Record<string, any> {\n  const chain = stateChain(entries, at);\n  const start = (chain.baseIsRef ? base : (chain.base as Record<string, any> | undefined)) ?? {};\n  return patchState(start, chain.patches.flat());\n}\n\n/**\n * The latest result of each step (only of `stepIds` when given), from a run's entries (in `seq`\n * order), keyed in the order each step was first written: its latest `step` entry, with every later\n * `step-patch` entry for the step applied in order. A patch with no earlier `step` entry for its\n * step is ignored. A patched result is a JSON copy; the others are the entries' own objects.\n * Shared so every adapter rebuilds step results the same way.\n * @experimental\n */\nexport function latestStepResults(\n  entries: readonly WorkflowRunEntry[],\n  stepIds?: ReadonlySet<string>,\n): Map<string, unknown> {\n  // A Map keeps each step at its first write while later entries replace the value.\n  const latest = new Map<string, { result: unknown; patches: StatePatchOp[][] }>();\n  for (const entry of entries) {\n    if (entry.kind === 'step') {\n      if (!stepIds || stepIds.has(entry.stepId)) latest.set(entry.stepId, { result: entry.result, patches: [] });\n    } else if (entry.kind === 'step-patch') {\n      latest.get(entry.stepId)?.patches.push(entry.ops);\n    }\n  }\n  const results = new Map<string, unknown>();\n  for (const [stepId, { result, patches }] of latest) {\n    if (!patches.length) {\n      results.set(stepId, result);\n      continue;\n    }\n    let patched = JSON.parse(JSON.stringify(result));\n    for (const ops of patches) patched = applyStatePatch(patched, ops);\n    results.set(stepId, patched);\n  }\n  return results;\n}\n\n/**\n * Rebuild a run's `WorkflowRunState` from its storage v2 header and entries (in `seq` order).\n * `latestStepResults` rebuilds `context`, and `materializeState` rebuilds `value` (`base` as there).\n * @experimental\n */\nexport function materializeWorkflowRun(\n  header: WorkflowRunHeader,\n  entries: readonly WorkflowRunEntry[],\n  base?: Record<string, any>,\n): WorkflowRunState {\n  const context = Object.fromEntries(latestStepResults(entries));\n  return { ...header, context, value: materializeState(entries, { base }) } as WorkflowRunState;\n}\n","import type { WorkflowRunState } from '../../../workflows';\n\n/**\n * Thread/resource memory info embedded in a persisted workflow-run snapshot.\n */\nexport type WorkflowSnapshotMemoryInfo = {\n  threadId?: string;\n  resourceId?: string;\n};\n\n/**\n * Extracts the memory info (threadId/resourceId) embedded in a workflow-run\n * snapshot. This is the canonical extraction: any storage adapter that\n * implements the best-effort `threadId` filter on `listWorkflowRuns` MUST\n * mirror these exact JSON paths in its query predicate (see\n * `StorageListWorkflowRunsInput['threadId']`).\n *\n * The snapshot stores memory info at one of two locations depending on which\n * loop produced it:\n *\n * 1. `agentic-loop` (dynamic step key):\n *    `context.<step where status === 'suspended'>.suspendPayload.__streamState.messageList.memoryInfo`\n * 2. Durable agentic-loop (fixed path):\n *    `context.input.messageListState.memoryInfo`\n *\n * If either path changes, update the SQL predicates in `@mastra/pg` and\n * `@mastra/libsql` (`listWorkflowRuns`) to match — otherwise they will wrongly\n * exclude rows that this extraction would match.\n */\nexport function getSnapshotMemoryInfo(\n  snapshot: WorkflowRunState | null | undefined,\n): WorkflowSnapshotMemoryInfo | undefined {\n  for (const key in snapshot?.context) {\n    const step = snapshot?.context[key];\n    if (step && step.status === 'suspended' && step.suspendPayload?.__streamState) {\n      return step.suspendPayload?.__streamState?.messageList?.memoryInfo;\n    }\n  }\n\n  // Durable agentic-loop snapshots don't embed `__streamState` in suspend\n  // payloads; their thread/resource info lives on the serialized workflow\n  // input's message-list state instead.\n  const durableMemoryInfo = (snapshot?.context as Record<string, any> | undefined)?.input?.messageListState?.memoryInfo;\n  if (durableMemoryInfo && typeof durableMemoryInfo === 'object') {\n    return durableMemoryInfo as WorkflowSnapshotMemoryInfo;\n  }\n\n  return undefined;\n}\n","import type { ActorSignal } from '../auth/ee';\nimport type { MastraScorers } from '../evals';\nimport type { PubSub } from '../events';\nimport type { Mastra } from '../mastra';\nimport type { ObservabilityContext } from '../observability';\nimport type { RequestContext } from '../request-context';\nimport type { InferStandardSchemaOutput, StandardSchemaWithJSON } from '../schema';\nimport type { ToolStream } from '../tools/stream';\nimport type { DynamicArgument } from '../types';\nimport type { PUBSUB_SYMBOL, STREAM_FORMAT_SYMBOL } from './constants';\nimport type { OutputWriter, StepResult, StepMetadata } from './types';\nimport type { Workflow } from './workflow';\n\nexport type SuspendOptions = {\n  resumeLabel?: string | string[];\n} & Record<string, any>;\n\n// Create a unique symbol that only exists at the type level\ndeclare const SuspendBrand: unique symbol;\n\n// Create a branded type that can ONLY be produced by suspend()\nexport type InnerOutput = void & { readonly [SuspendBrand]: never };\n\nexport type ExecuteFunctionParams<\n  TState,\n  TStepInput,\n  TStepOutput,\n  TResume,\n  TSuspend,\n  EngineType,\n  TRequestContext extends Record<string, any> | unknown = unknown,\n> = Partial<ObservabilityContext> & {\n  runId: string;\n  resourceId?: string;\n  workflowId: string;\n  mastra: Mastra;\n  requestContext: RequestContext<TRequestContext>;\n  actor?: ActorSignal;\n  inputData: TStepInput;\n  /** The run's state. On runs with `storageVersion: 2`, reading it throws: use `await getState()` instead. */\n  state: TState;\n  /** Resolves to the run's state, or only its named top-level keys, with this step's `setState` changes. */\n  getState(): Promise<unknown extends TState ? Record<string, any> : TState>;\n  getState<K extends (unknown extends TState ? string : keyof TState & string)>(\n    keys: readonly K[],\n  ): Promise<unknown extends TState ? Record<string, any> : Pick<TState, K & keyof TState>>;\n  setState(state: TState): Promise<void>;\n  /**\n   * Merges the top-level keys it's given into the run's state and validates the merged state.\n   * Keys you don't pass keep their current value; a key set to `undefined` is removed.\n   */\n  updateState(state: Partial<TState>): Promise<void>;\n  resumeData?: TResume;\n  suspendData?: TSuspend;\n  retryCount: number;\n  getInitData<T>(): T extends Workflow<any, any, any, any, any, any, any, any>\n    ? InferStandardSchemaOutput<T['inputSchema']>\n    : T;\n  /**\n   * @deprecated Use `await getStepResultAsync(step)` instead. `getStepResult` will be removed in a future major release.\n   */\n  getStepResult<TOutput>(step: string): TOutput;\n  /**\n   * @deprecated Use `await getStepResultAsync(step)` instead. `getStepResult` will be removed in a future major release.\n   */\n  getStepResult<TStep extends Step<string, any, any, any, any, any, EngineType>>(\n    step: TStep,\n  ): InferStandardSchemaOutput<TStep['outputSchema']>;\n  getStepResultAsync<TOutput>(step: string): Promise<TOutput>;\n  getStepResultAsync<TStep extends Step<string, any, any, any, any, any, EngineType>>(\n    step: TStep,\n  ): Promise<InferStandardSchemaOutput<TStep['outputSchema']>>;\n  suspend: unknown extends TSuspend\n    ? (suspendPayload?: TSuspend, suspendOptions?: SuspendOptions) => InnerOutput | Promise<InnerOutput>\n    : (suspendPayload: TSuspend, suspendOptions?: SuspendOptions) => InnerOutput | Promise<InnerOutput>;\n  bail(result: TStepOutput): InnerOutput;\n  bail<T>(\n    result: T extends Workflow<any, any, any, any, any, infer TWorkflowOutput, any, any> ? TWorkflowOutput : T,\n  ): InnerOutput;\n  abort(): void;\n  resume?: {\n    steps: string[];\n    resumePayload: TResume;\n  };\n  restart?: boolean;\n  [PUBSUB_SYMBOL]: PubSub;\n  [STREAM_FORMAT_SYMBOL]: 'legacy' | 'vnext' | undefined;\n  engine: EngineType;\n  abortSignal: AbortSignal;\n  writer: ToolStream;\n  outputWriter?: OutputWriter;\n  validateSchemas?: boolean;\n};\n\nexport type ConditionFunctionParams<\n  TState,\n  TStepInput,\n  TStepOutput,\n  TResumeSchema,\n  TSuspendSchema,\n  EngineType,\n  TRequestContext extends Record<string, any> | unknown = unknown,\n> = Omit<\n  ExecuteFunctionParams<TState, TStepInput, TStepOutput, TResumeSchema, TSuspendSchema, EngineType, TRequestContext>,\n  'setState' | 'updateState' | 'suspend'\n>;\n\nexport type ExecuteFunction<\n  TState,\n  TStepInput,\n  TStepOutput,\n  TResumeSchema,\n  TSuspendSchema,\n  EngineType,\n  TRequestContext extends Record<string, any> | unknown = unknown,\n> = (\n  params: ExecuteFunctionParams<\n    TState,\n    TStepInput,\n    TStepOutput,\n    TResumeSchema,\n    TSuspendSchema,\n    EngineType,\n    TRequestContext\n  >,\n) => Promise<TStepOutput | InnerOutput>;\n\nexport type ConditionFunction<\n  TState,\n  TStepInput,\n  TStepOutput,\n  TResumeSchema,\n  TSuspendSchema,\n  EngineType,\n  TRequestContext extends Record<string, any> | unknown = unknown,\n> = (\n  params: ConditionFunctionParams<\n    TState,\n    TStepInput,\n    TStepOutput,\n    TResumeSchema,\n    TSuspendSchema,\n    EngineType,\n    TRequestContext\n  >,\n) => Promise<boolean>;\n\nexport type LoopConditionFunction<\n  TState,\n  TStepInput,\n  TStepOutput,\n  TResumeSchema,\n  TSuspendSchema,\n  EngineType,\n  TRequestContext extends Record<string, any> | unknown = unknown,\n> = (\n  params: ConditionFunctionParams<\n    TState,\n    TStepInput,\n    TStepOutput,\n    TResumeSchema,\n    TSuspendSchema,\n    EngineType,\n    TRequestContext\n  > & {\n    iterationCount: number;\n  },\n) => Promise<boolean>;\n\n// Define a Step interface\nexport interface Step<\n  TStepId extends string = string,\n  TState = unknown,\n  TInput = unknown,\n  TOutput = unknown,\n  TResume = unknown,\n  TSuspend = unknown,\n  TEngineType = any,\n  TRequestContext extends Record<string, any> | unknown = unknown,\n> {\n  id: TStepId;\n  description?: string;\n  inputSchema: StandardSchemaWithJSON<TInput>;\n  outputSchema: StandardSchemaWithJSON<TOutput>;\n  resumeSchema?: StandardSchemaWithJSON<TResume>;\n  suspendSchema?: StandardSchemaWithJSON<TSuspend>;\n  stateSchema?: StandardSchemaWithJSON<TState>;\n  /**\n   * Optional schema for validating request context values.\n   * When provided, the request context will be validated against this schema before step execution.\n   */\n  requestContextSchema?: StandardSchemaWithJSON<TRequestContext>;\n  execute: ExecuteFunction<TState, TInput, TOutput, TResume, TSuspend, TEngineType, TRequestContext>;\n  scorers?: DynamicArgument<MastraScorers>;\n  retries?: number;\n  component?: string;\n  metadata?: StepMetadata;\n}\n\nexport const getStepResult = (stepResults: Record<string, StepResult<any, any, any, any>>, step: any) => {\n  let result;\n\n  if (typeof step === 'string') {\n    result = stepResults[step];\n  } else {\n    if (!step?.id) {\n      return null;\n    }\n\n    result = stepResults[step.id];\n  }\n\n  return result?.status === 'success' ? result.output : null;\n};\n\nexport const getStepResultAsync = async (stepResults: Record<string, StepResult<any, any, any, any>>, step: any) =>\n  getStepResult(stepResults, step);\n","/**\n * The `${scope.path}` mapping-template DSL used by `.map()` template sources.\n *\n * Definition-time syntax checks live in {@link validateTemplate}; run-time\n * resolution (path lookup + value coercion) lives in {@link resolveTemplate}.\n * This module has no knowledge of the step-entry union — it is a pure\n * string-DSL interpreter over a step's execute context.\n */\n\n/** Walks a dotted path on an object. `''` or `'.'` returns the root unchanged. */\nexport function traverseMappingPath(root: unknown, path: string, errorLabel: string): unknown {\n  if (path === '' || path === '.') return root;\n  const parts = path.split('.');\n  let value: any = root;\n  for (const part of parts) {\n    if (typeof value === 'object' && value !== null) {\n      value = value[part];\n    } else {\n      throw new Error(`Invalid path ${path} in ${errorLabel}`);\n    }\n  }\n  return value;\n}\n\nconst TEMPLATE_PLACEHOLDER = /\\$\\{([^}]*)\\}/g;\n\nconst TEMPLATE_NAMESPACES = ['inputData', 'initData', 'state', 'requestContext', 'stepResults'] as const;\ntype TemplateScope = (typeof TEMPLATE_NAMESPACES)[number];\n\n/** Common error-message prefix so every template diagnostic points at the exact placeholder. */\nfunction describeBadPlaceholder(template: string, idx: number, rawExpr: string): string {\n  return `Template placeholder #${idx} (\\${${rawExpr}}) in '${template}'`;\n}\n\n/** Split a placeholder body `scope.path.with.dots` into its leading scope and the dotted remainder. */\nfunction parseTemplatePlaceholder(rawExpr: string): { scope: string; rest: string } {\n  const dot = rawExpr.indexOf('.');\n  return {\n    scope: dot === -1 ? rawExpr : rawExpr.slice(0, dot),\n    rest: dot === -1 ? '' : rawExpr.slice(dot + 1),\n  };\n}\n\n/**\n * Validates a `{ template }` source's syntax at workflow-definition time.\n * Throws if any placeholder is empty, whitespace-padded, references an unknown\n * namespace, or is a malformed `stepResults.<stepId>` / `stepResults.<stepId>.<path>` shape.\n *\n * Run-time concerns (does the step actually exist, does the path resolve, is\n * the value a primitive) stay in {@link resolveTemplate}.\n */\nexport function validateTemplate(template: string): void {\n  let idx = 0;\n  for (const match of template.matchAll(TEMPLATE_PLACEHOLDER)) {\n    idx++;\n    const rawExpr = match[1] ?? '';\n    if (rawExpr.length === 0 || rawExpr !== rawExpr.trim()) {\n      throw new Error(\n        `${describeBadPlaceholder(template, idx, rawExpr)} has empty or whitespace-padded contents. ` +\n          `Use \\${<scope>.<path>} with no surrounding whitespace.`,\n      );\n    }\n    const { scope, rest } = parseTemplatePlaceholder(rawExpr);\n    if (scope === 'stepResults') {\n      const innerDot = rest.indexOf('.');\n      const stepId = innerDot === -1 ? rest : rest.slice(0, innerDot);\n      if (!stepId) {\n        throw new Error(\n          `${describeBadPlaceholder(template, idx, rawExpr)} must be of the form \\${stepResults.<stepId>} or \\${stepResults.<stepId>.<path>}.`,\n        );\n      }\n      continue;\n    }\n    if (scope === 'requestContext') {\n      if (!rest) {\n        throw new Error(\n          `${describeBadPlaceholder(template, idx, rawExpr)} requires a request-context key — use \\${requestContext.<key>}.`,\n        );\n      }\n      continue;\n    }\n    if ((TEMPLATE_NAMESPACES as readonly string[]).includes(scope)) continue;\n    throw new Error(\n      `${describeBadPlaceholder(template, idx, rawExpr)} references unknown namespace \"${scope}\". ` +\n        `Use one of: ${TEMPLATE_NAMESPACES.join(', ')}.`,\n    );\n  }\n}\n\n/**\n * Collects the step ids referenced by `${stepResults.<stepId>}` /\n * `${stepResults.<stepId>.<path>}` placeholders in a template. Assumes the\n * template already passed {@link validateTemplate}; malformed placeholders are\n * skipped. Used by validation to scope-check template references against the\n * preceding workflow-local steps.\n */\nexport function collectTemplateStepIds(template: string): string[] {\n  const ids: string[] = [];\n  for (const match of template.matchAll(TEMPLATE_PLACEHOLDER)) {\n    const { scope, rest } = parseTemplatePlaceholder(match[1] ?? '');\n    if (scope !== 'stepResults') continue;\n    const innerDot = rest.indexOf('.');\n    const stepId = innerDot === -1 ? rest : rest.slice(0, innerDot);\n    if (stepId) ids.push(stepId);\n  }\n  return ids;\n}\n\n/** Whether a template reads the run's state through `${state...}` placeholders. */\nexport function templateReadsState(template: string): boolean {\n  for (const match of template.matchAll(TEMPLATE_PLACEHOLDER)) {\n    if (parseTemplatePlaceholder(match[1] ?? '').scope === 'state') return true;\n  }\n  return false;\n}\n\n/**\n * Coerces a resolved placeholder value to a string. Primitives are stringified\n * the normal way; objects and arrays are JSON-encoded so downstream agents can\n * consume complex step outputs (e.g. `foreach(agent)` returns `{ text }[]`)\n * directly in a template. `null`/`undefined` render as empty. If JSON encoding\n * fails (circular references, BigInt, etc.), throws with a hint pointing at\n * the offending placeholder.\n */\nfunction stringifyTemplateValue(v: unknown, template: string, idx: number, rawExpr: string): string {\n  if (v === null || v === undefined) return '';\n  if (typeof v === 'object') {\n    try {\n      return JSON.stringify(v);\n    } catch (err) {\n      throw new Error(\n        `${describeBadPlaceholder(template, idx, rawExpr)} resolved to a value that could not be JSON-stringified ` +\n          `(${(err as Error).message}). Drill into a primitive path (e.g. \\${${rawExpr}.someField}) or reshape the value in a preceding step.`,\n      );\n    }\n  }\n  return String(v);\n}\n\n/**\n * Resolves `${<scope>.<path>}` placeholders against the implicit namespaces\n * available in a step's execute context. See the `.map()` overload signature\n * for the full list of accepted scopes (`inputData`, `initData`, `state`,\n * `requestContext`, `stepResults.<stepId>`).\n *\n * `stepResults.<stepId>` placeholders read `stepOutputs`, which the caller\n * resolves up front for every id from {@link collectTemplateStepIds}.\n */\nexport function resolveTemplate(template: string, ctx: any, stepOutputs: ReadonlyMap<string, unknown>): string {\n  let idx = 0;\n  return template.replace(TEMPLATE_PLACEHOLDER, (_match, rawExpr: string) => {\n    idx++;\n    return resolveTemplatePlaceholder(rawExpr, template, idx, ctx, stepOutputs);\n  });\n}\n\nfunction resolveTemplatePlaceholder(\n  rawExpr: string,\n  template: string,\n  idx: number,\n  ctx: any,\n  stepOutputs: ReadonlyMap<string, unknown>,\n): string {\n  // validateTemplate(template) is called at definition time so we know the\n  // raw expr is well-formed (non-empty, no surrounding whitespace, known\n  // scope). Runtime only cares about path-resolution + value coercion.\n  const { scope, rest } = parseTemplatePlaceholder(rawExpr);\n  const label = describeBadPlaceholder(template, idx, rawExpr);\n  switch (scope as TemplateScope) {\n    case 'inputData':\n      return stringifyTemplateValue(traverseMappingPath(ctx.inputData, rest, label), template, idx, rawExpr);\n    case 'initData':\n      return stringifyTemplateValue(traverseMappingPath(ctx.getInitData(), rest, label), template, idx, rawExpr);\n    case 'state':\n      return stringifyTemplateValue(traverseMappingPath(ctx.state, rest, label), template, idx, rawExpr);\n    case 'requestContext':\n      return stringifyTemplateValue(ctx.requestContext.get(rest), template, idx, rawExpr);\n    case 'stepResults': {\n      const innerDot = rest.indexOf('.');\n      const stepId = innerDot === -1 ? rest : rest.slice(0, innerDot);\n      const subPath = innerDot === -1 ? '' : rest.slice(innerDot + 1);\n      const stepResult = stepOutputs.get(stepId);\n      // Nullish (not just null) so a step that \"succeeded\" with `undefined`\n      // output is reported as missing too — consistent with how predicates\n      // treat nullish step results. Nullish *path values inside* a present\n      // result still render as '' via stringifyTemplateValue.\n      if (stepResult == null) {\n        throw new Error(\n          `${label} references stepResults.${stepId} but step \"${stepId}\" has no successful output ` +\n            `(not run yet, not registered, failed, or produced no output).`,\n        );\n      }\n      return stringifyTemplateValue(traverseMappingPath(stepResult, subPath, label), template, idx, rawExpr);\n    }\n    default:\n      // validateTemplate guarantees this branch is unreachable for well-formed\n      // workflows; this is a safety net for templates that bypassed validation\n      // (e.g. constructed programmatically and pushed into stepFlow).\n      throw new Error(\n        `${label} references unknown namespace \"${scope}\". Use one of: ${TEMPLATE_NAMESPACES.join(', ')}.`,\n      );\n  }\n}\n","import { MISSING, normalizePredicatePath } from '../predicate';\nimport type { PathOrLiteral, Predicate } from '../predicate';\nimport { collectTemplateStepIds } from './mapping-template';\nimport type { MappingConfig } from './types';\n\n/**\n * Declarative readers (`.map()` configs, templates, predicates) list the steps\n * they read up front, then resolve them with `getStepResultAsync` before\n * evaluating anything. That keeps them off the sync `getStepResult`, which\n * can't serve runs whose step results aren't all in memory.\n */\n\n/** Id of a `{ step }` mapping source: a step id string or a step-like object. */\nexport function stepRefId(step: unknown): string | undefined {\n  if (typeof step === 'string') return step;\n  const id = (step as { id?: unknown } | null | undefined)?.id;\n  return typeof id === 'string' && id ? id : undefined;\n}\n\n/**\n * Step ids an object mapping config reads: `{ step }` sources (including every\n * arm of an array) and `${stepResults.<id>}` template placeholders. `value`,\n * `fn`, `requestContextPath` and `initData` sources read no step results.\n * Checks run in the same order `runMappingEntry` applies them.\n */\nexport function collectMappingStepRefs(mapConfig: MappingConfig): string[] {\n  const ids = new Set<string>();\n  for (const mapping of Object.values(mapConfig)) {\n    const m: any = mapping;\n    if (m === null || typeof m !== 'object') continue;\n    if (m.value !== undefined || m.fn !== undefined) continue;\n    if (typeof m.template === 'string') {\n      collectTemplateStepIds(m.template).forEach(id => ids.add(id));\n      continue;\n    }\n    if (m.requestContextPath || m.initData) continue;\n    for (const step of Array.isArray(m.step) ? m.step : [m.step]) {\n      const id = stepRefId(step);\n      if (id) ids.add(id);\n    }\n  }\n\n  return [...ids];\n}\n\n/** The normalized paths a predicate reads. */\nfunction predicatePaths(predicate: Predicate): string[] {\n  const paths: string[] = [];\n  const addPath = (rawPath: string) => {\n    const path = normalizePredicatePath(rawPath);\n    if (path !== MISSING) paths.push(path);\n  };\n  const addRef = (ref: PathOrLiteral) => {\n    if ('path' in ref) addPath(ref.path);\n  };\n  const visit = (p: Predicate) => {\n    switch (p.op) {\n      case 'and':\n      case 'or':\n        p.args.forEach(visit);\n        break;\n      case 'not':\n        visit(p.arg);\n        break;\n      case 'exists':\n      case 'notExists':\n        addPath(p.path);\n        break;\n      case 'truthy':\n      case 'falsy':\n      case 'in':\n      case 'notIn':\n        addRef(p.value);\n        break;\n      default:\n        addRef(p.left);\n        addRef(p.right);\n    }\n  };\n  visit(predicate);\n  return paths;\n}\n\n/** Step ids a predicate reads through `stepResults.<id>` paths. */\nexport function collectPredicateStepRefs(predicate: Predicate): string[] {\n  const ids = new Set<string>();\n  for (const path of predicatePaths(predicate)) {\n    if (!path.startsWith('stepResults.')) continue;\n    const rest = path.slice('stepResults.'.length);\n    const dot = rest.indexOf('.');\n    const id = dot === -1 ? rest : rest.slice(0, dot);\n    if (id) ids.add(id);\n  }\n  return [...ids];\n}\n\n/** Whether a predicate reads the run's state through `state` paths. */\nexport function predicateReadsState(predicate: Predicate): boolean {\n  return predicatePaths(predicate).some(path => path === 'state' || path.startsWith('state.'));\n}\n\n/**\n * Resolves step ids to their outputs in one batch. Values match\n * `getStepResultAsync`: the output of a successful step, `null` otherwise.\n */\nexport async function resolveStepOutputs(\n  ids: readonly string[],\n  getStepResultAsync: (stepId: string) => Promise<unknown>,\n): Promise<Map<string, unknown>> {\n  const outputs = await Promise.all(ids.map(id => getStepResultAsync(id)));\n  return new Map(ids.map((id, i) => [id, outputs[i]]));\n}\n","import { ErrorCategory, ErrorDomain, MastraError } from '../error';\nimport type { WorkflowsStorage } from '../storage/domains/workflows/base';\nimport { STATE_CHECKPOINT_PATCHES, summarizeStepResult } from '../storage/domains/workflows/journal';\nimport type { StateRef, StepResultSummary } from '../storage/domains/workflows/journal';\nimport { getSnapshotMemoryInfo } from '../storage/domains/workflows/snapshot-memory-info';\nimport { diffState } from '../storage/domains/workflows/state-patch';\nimport type { StatePatchOp } from '../storage/domains/workflows/state-patch';\nimport { getStepResult, getStepResultAsync } from './step';\nimport { stepRefId } from './step-refs';\nimport type { StepResult, WorkflowRunState, WorkflowRunStatus } from './types';\n\ntype StepResults = Record<string, StepResult<any, any, any, any>>;\n\ntype StepCopy = { json: unknown; bytes: number; patchBytes: number; write: number };\n\n// Private to this module, so only the journal can make an object count as a stub. A spread or\n// clone of a stub is a new object, so it isn't one.\nconst stubs = new WeakSet<object>();\n\n/**\n * A stand-in for a successful step result that is stored but no longer held in memory: the\n * result's summary fields, without its data. `RunJournal.hydrate` swaps it back for the stored\n * result.\n *\n * @internal\n */\nexport function stubStepResult(result: StepResultSummary): StepResult<any, any, any, any> {\n  const stub = summarizeStepResult(result);\n  stubs.add(stub);\n  // A stub keeps `status: 'success'` but has no `output`, so it isn't a full `StepResult`.\n  // Readers that need more than the summary hydrate it first.\n  return stub as StepResult<any, any, any, any>;\n}\n\n/** @internal */\nexport function isStepResultStub(value: unknown): boolean {\n  return typeof value === 'object' && value !== null && stubs.has(value);\n}\n\n/**\n * A version of a stored run state (possibly another run's), and a JSON copy of that state, which\n * is shared and never edited.\n *\n * @internal\n */\nexport type StateBase = { ref: StateRef; state: Record<string, unknown> };\n\n/**\n * What a storage v2 parent hands a nested workflow step: a stored version of the parent's state\n * for a nested run starting from `state` to build on, undefined when it stores a full copy.\n *\n * @internal\n */\nexport type ParentStateLink = (state: unknown) => Promise<StateBase | undefined>;\n\n/**\n * Tracks what a storage-v2 run has written, so each engine write sends only the\n * step results that changed (and the state's changes) instead of the whole snapshot.\n * It also lets the engine drop stored results from memory (`evict`) and read them back\n * (`hydrate`, `getStepResultAsync`).\n *\n * Step results are replaced, never edited in place, so a step changed when its object\n * differs from the one last written. State can be edited in place, so the journal keeps a\n * JSON copy of the state it last wrote and diffs the live state against it. A change is written\n * as a patch, unless the patches written since the latest full state would outgrow the state:\n * then the full state is written again, so reading the state back never replays more than\n * about twice its size. A step result that is rewritten before it succeeds (a running foreach\n * recording its finished items) is written the same way, as a `step-patch` on the result last\n * written, once it has been written twice.\n *\n * The start writes of a parallel or branch block's steps are in flight at the same time, and\n * the store can commit them in any order. If two of them carried the same step, the older value\n * could commit last while the journal believes storage holds the newer one, and it never resends\n * what it believes is stored. So a write that can overlap others names its steps (`stepIds`) and\n * sends only those, and overlapping writes name different steps. Everything else (other steps'\n * changes, the state, the checkpoint) goes out with boundary writes, which the engine makes only\n * when no other write of the run is in flight (an entry's end, a loop iteration's start, a\n * finished parallel arm or foreach item, sleeps, the run stopping). `write` throws when a write\n * breaks that.\n *\n * @internal\n */\nexport class RunJournal {\n  /** Undefined when Mastra has no storage: nothing is written, so nothing is evicted. */\n  readonly store: WorkflowsStorage | undefined;\n  readonly workflowName: string;\n  readonly runId: string;\n  /** stepId -> the object last written for it (a stub once evicted) */\n  #written: Map<string, unknown>;\n  /**\n   * stepId -> a JSON copy of the result last written for it, the JSON size of the patches stored\n   * after it was last written in full, and the write of the step it came from (see `#stepWrites`).\n   * Only for a result that a later non-success result can be written as a patch on (see `#stepWrite`).\n   */\n  #writtenCopies = new Map<string, StepCopy>();\n  /** stepId -> how many writes that send the step have started */\n  #stepWrites = new Map<string, number>();\n  /** A JSON copy of the stored state. Replaced on each write, never edited. */\n  #writtenState: Record<string, unknown> | undefined;\n  /**\n   * The stored state version `#writtenState` is, when known. Before the checkpoint of a nested run\n   * built on its parent's state, a version of the parent's state.\n   */\n  #writtenRef: StateRef | undefined;\n  /** The version a nested run's checkpoint builds on (`inherited`). */\n  #inheritedRef: StateRef | undefined;\n  /** JSON size of the patches stored after the latest full state. */\n  #patchBytes: number;\n  /** The patches stored after the latest full state or state base. */\n  #patchCount: number;\n  /** The latest draft of the live state written for nested runs to build on, since the last state write. */\n  #draft: StateBase | undefined;\n  /** JSON size of the draft patches chained since the latest full draft or state write. */\n  #draftBytes = 0;\n  /** Serializes `baseFor`, so concurrent nested starts share one draft. */\n  #drafting: Promise<unknown> = Promise.resolve();\n  #needsCheckpoint: boolean;\n  /** A resumed drive's start state version, until an append has recorded it. */\n  #startStateSeq: number | undefined;\n  /** Store writes sent and not yet settled, and whether one of them is a boundary write. */\n  #inFlight = 0;\n  #boundaryInFlight = false;\n  #closed = false;\n  /** The highest `lastSeq` of the run known here: as loaded, or reported by a write or draft. */\n  #lastSeq: number | undefined;\n  #runToken: string | undefined;\n  /** Store calls (writes and drafts) sent and not yet settled. */\n  #pending = new Set<Promise<unknown>>();\n  #resolveSettledLastSeq!: (seq: number | undefined) => void;\n  /**\n   * The run's `lastSeq` once its execution has ended (`close`) and every write and draft sent has\n   * settled: the version a read of its stored steps must still find to see what the execution left.\n   * Undefined when the run wasn't loaded and nothing was stored.\n   */\n  readonly settledLastSeq: Promise<number | undefined>;\n  readonly settledRunToken: Promise<string | undefined>;\n\n  /**\n   * @param seed The step results already in storage (a resumed or restarted run's loaded snapshot\n   * context). Without it, the first boundary write is a checkpoint that replaces whatever is stored.\n   * @param state The state already in storage, with `seed`.\n   * @param storedState What the store reported for `state`: its `lastSeq`, `statePatchBytes` and `statePatchCount`.\n   * @param inherited For a nested run that starts from a version of its parent's state (the parent\n   * journal's `baseFor`): the checkpoint stores that version as the base, and only the changes to it.\n   * @param resumed Set for a resume: the run's new drive starts from `storedState`, which the first\n   * append records as the run's `startStateSeq`.\n   */\n  constructor({\n    store,\n    workflowName,\n    runId,\n    seed,\n    state,\n    storedState,\n    inherited,\n    resumed,\n  }: {\n    store: WorkflowsStorage | undefined;\n    workflowName: string;\n    runId: string;\n    seed?: Record<string, unknown>;\n    state?: unknown;\n    storedState?: { seq: number; patchBytes: number; patchCount: number; runToken?: string };\n    inherited?: StateBase;\n    resumed?: boolean;\n  }) {\n    this.store = store;\n    this.workflowName = workflowName;\n    this.runId = runId;\n    this.#needsCheckpoint = !seed;\n    this.#written = new Map(seed ? Object.entries(seed) : []);\n    if (inherited) {\n      this.#writtenState = inherited.state;\n      this.#writtenRef = inherited.ref;\n      this.#inheritedRef = inherited.ref;\n    } else if (seed && state !== undefined) {\n      this.#writtenState = normalizeState(state).state;\n      if (storedState) this.#writtenRef = { workflowName, runId, seq: storedState.seq };\n    }\n    this.#patchBytes = storedState?.patchBytes ?? 0;\n    this.#patchCount = storedState?.patchCount ?? 0;\n    if (resumed && seed) this.#startStateSeq = storedState?.seq;\n    this.#lastSeq = storedState?.seq;\n    this.#runToken = storedState?.runToken;\n    this.settledLastSeq = new Promise(resolve => {\n      this.#resolveSettledLastSeq = resolve;\n    });\n    this.settledRunToken = this.settledLastSeq.then(() => this.#runToken);\n  }\n\n  /**\n   * Sends a store call, keeping it in `#pending` until it settles and noting the run's `lastSeq` it\n   * reports, so `settledLastSeq` cannot resolve before a settled call's seq is noted.\n   */\n  #send<T>(call: Promise<T>, seqOf: (result: T) => number | undefined): Promise<T> {\n    const tracked = call.then(result => {\n      const seq = seqOf(result);\n      if (seq !== undefined && (this.#lastSeq === undefined || seq > this.#lastSeq)) this.#lastSeq = seq;\n      return result;\n    });\n    this.#pending.add(tracked);\n    const settle = () => this.#pending.delete(tracked);\n    tracked.then(settle, settle);\n    return tracked;\n  }\n\n  /**\n   * A stored version of this run's state, for a nested run starting from `state` to build on: the\n   * stored state or the latest draft when `state` matches it, else a new draft of `state` (a patch\n   * on the latest version, or the full state once the draft patches would outgrow it). Undefined\n   * when there is nothing to build on (no store, the run isn't stored, a state that isn't JSON).\n   *\n   * Drafts don't change the run's state, so a restart never reads them: they only hold the live\n   * state that a block's earlier steps changed, so the nested runs of a foreach or a loop each store\n   * only their own changes.\n   */\n  baseFor(state: unknown): Promise<StateBase | undefined> {\n    const result = this.#drafting.then(() => this.#baseFor(state));\n    this.#drafting = result.catch(() => undefined);\n    return result;\n  }\n\n  async #baseFor(state: unknown): Promise<StateBase | undefined> {\n    const store = this.store;\n    if (!store || this.#closed) return undefined;\n    let next: { state: Record<string, unknown>; bytes: number };\n    try {\n      next = normalizeState(state);\n    } catch {\n      return undefined;\n    }\n    const current: StateBase | undefined =\n      this.#draft ?? (this.#writtenRef && this.#writtenState && { ref: this.#writtenRef, state: this.#writtenState });\n    const ops = current && diffState(current.state, next.state);\n    if (current && !ops!.length) return current;\n\n    const own = current && current.ref.workflowName === this.workflowName && current.ref.runId === this.runId;\n    const opsBytes = ops ? JSON.stringify(ops).length : 0;\n    const chained = own && this.#draftBytes + opsBytes <= next.bytes;\n    let seq: number;\n    try {\n      ({ seq } = await this.#send(\n        store.appendWorkflowRunStateDraft({\n          workflowName: this.workflowName,\n          runId: this.runId,\n          ...(chained\n            ? { on: { seq: current!.ref.seq, draft: current!.ref.draft }, ops: ops! }\n            : { state: next.state }),\n        }),\n        written => written.seq,\n      ));\n    } catch {\n      return undefined;\n    }\n    this.#draftBytes = chained ? this.#draftBytes + opsBytes : 0;\n    this.#draft = { ref: { workflowName: this.workflowName, runId: this.runId, seq, draft: true }, state: next.state };\n    return this.#draft;\n  }\n\n  /**\n   * Called when the run's execution ends. A step of a parallel or branch block can still be\n   * running then (the block's `Promise.all` rejects on the first failure), and its write is dropped.\n   */\n  close(): void {\n    if (this.#closed) return;\n    this.#closed = true;\n    // Nothing is sent once closed, so these are the last calls.\n    void Promise.allSettled(this.#pending).then(() => this.#resolveSettledLastSeq(this.#lastSeq));\n  }\n\n  /**\n   * @param stepIds Set by a write that can be in flight together with other writes of the run (a\n   * step's start write): only these steps are sent, never the state, and no other write in flight\n   * may name them. Leave it unset for a boundary write, made when no other write of the run is in\n   * flight (an entry's end, a loop iteration's start, a finished parallel arm or foreach item,\n   * sleeps, the run stopping): it sends every step result that changed since it was last written,\n   * the state's changes, and the checkpoint when that is still to do.\n   * @param foreachItems Set by a running foreach's progress write: the foreach's result differs\n   * from the one it last wrote only by these indices' `metadata.foreachProgress` entries. When the\n   * last written result can be patched, only those entries are sent, so recording a finished item\n   * costs that item rather than every item finished so far.\n   * @param expectedStatus Sent with the write as the store's compare-and-set guard on the stored status.\n   * @returns False when the store rejected the write because of `expectedStatus`. Nothing was\n   * stored, as with a write that throws.\n   */\n  async write({\n    resourceId,\n    snapshot,\n    stepIds,\n    foreachItems,\n    expectedStatus,\n  }: {\n    resourceId?: string;\n    snapshot: WorkflowRunState;\n    stepIds?: readonly string[];\n    foreachItems?: { stepId: string; indices: readonly number[] };\n    expectedStatus?: WorkflowRunStatus[];\n  }): Promise<boolean> {\n    const store = this.store;\n    if (!store || this.#closed) return true;\n\n    const boundary = stepIds === undefined;\n    // The checkpoint replaces every stored entry, so no other write may be in flight with it. The\n    // writes dropped here don't need resending: the checkpoint sends the whole run.\n    if (!boundary && this.#needsCheckpoint) return true;\n\n    const { context, value, ...header } = snapshot;\n    const results = context as Record<string, unknown>;\n    const checkpoint = this.#needsCheckpoint;\n\n    let sent: string[];\n    if (checkpoint) {\n      sent = Object.keys(results);\n      // A checkpoint replaces every entry, so a stub would replace a stored result with its summary.\n      // Stubs only replace written results and the first write is the checkpoint, so this can't happen.\n      const stubbed = sent.filter(stepId => isStepResultStub(results[stepId]));\n      if (stubbed.length) {\n        throw new MastraError({\n          id: 'WORKFLOW_STORAGE_V2_CHECKPOINT_STUB',\n          domain: ErrorDomain.MASTRA_WORKFLOW,\n          category: ErrorCategory.SYSTEM,\n          text: `Storage v2 run ${this.runId} can't write a checkpoint while step results are evicted (${stubbed.join(', ')}).`,\n        });\n      }\n    } else {\n      // Every stub stands for a result that is already stored. A stub can still differ from the\n      // last written object: a copy of the step results taken before a hydrate holds the stub the\n      // hydrate replaced. Sending it would overwrite the stored result.\n      sent = (stepIds ?? Object.keys(results)).filter(\n        stepId =>\n          stepId in results && results[stepId] !== this.#written.get(stepId) && !isStepResultStub(results[stepId]),\n      );\n    }\n    const steps: StepResults = {};\n    const stepPatches: Record<string, StatePatchOp[]> = {};\n    // Built now: the live step results can change while the write is in flight, and a patch has to\n    // match the copy kept for its step.\n    const sentWrites = sent.map(stepId => {\n      const result = results[stepId] as StepResult<any, any, any, any>;\n      const write = this.#stepWrite(\n        stepId,\n        result,\n        !checkpoint,\n        foreachItems?.stepId === stepId ? foreachItems.indices : undefined,\n      );\n      if (write.ops) stepPatches[stepId] = write.ops;\n      else if (!write.unchanged) steps[stepId] = result;\n      return { stepId, result, copy: write.copy, unchanged: write.unchanged };\n    });\n    const patched = Object.keys(stepPatches).length > 0;\n    if (!boundary && !patched && !Object.keys(steps).length) {\n      // Results that only changed object are stored as they are.\n      this.#recordWritten(sentWrites);\n      return true;\n    }\n\n    // The engine makes boundary writes only where nothing else of the run is running. Failing here\n    // finds an engine path that breaks that before it loses a write.\n    if (this.#boundaryInFlight || (boundary && this.#inFlight > 0)) {\n      throw new MastraError({\n        id: 'WORKFLOW_STORAGE_V2_OVERLAPPING_WRITE',\n        domain: ErrorDomain.MASTRA_WORKFLOW,\n        category: ErrorCategory.SYSTEM,\n        text: `Storage v2 run ${this.runId} started a write while ${boundary ? 'another write' : 'a boundary write'} was in flight.`,\n      });\n    }\n    for (const { stepId, unchanged } of sentWrites) {\n      if (!unchanged) this.#stepWrites.set(stepId, (this.#stepWrites.get(stepId) ?? 0) + 1);\n    }\n\n    let writtenState = this.#writtenState;\n    let patchBytes = this.#patchBytes;\n    let patchCount = this.#patchCount;\n    let state: Record<string, unknown> | undefined;\n    let stateBase: StateRef | undefined;\n    let statePatch: StatePatchOp[] | undefined;\n    if (boundary) {\n      const next = normalizeState(value);\n      if (writtenState === undefined || (checkpoint && !this.#inheritedRef)) {\n        state = next.state;\n      } else {\n        if (checkpoint) {\n          // The checkpoint starts the state over, from the inherited version.\n          stateBase = this.#inheritedRef;\n          patchBytes = 0;\n          patchCount = 0;\n        }\n        const ops = diffState(writtenState, next.state);\n        if (ops.length) {\n          const opsBytes = JSON.stringify(ops).length;\n          // A full state once the patches would outgrow it, or once a cold load would apply too many.\n          if (patchBytes + opsBytes > next.bytes || patchCount >= STATE_CHECKPOINT_PATCHES) {\n            state = next.state;\n            stateBase = undefined;\n          } else {\n            statePatch = ops;\n            patchBytes += opsBytes;\n            patchCount++;\n          }\n        }\n      }\n      if (state) {\n        patchBytes = 0;\n        patchCount = 0;\n      }\n      if (state || statePatch) writtenState = next.state;\n    }\n\n    this.#needsCheckpoint = false;\n    this.#inFlight++;\n    if (boundary) this.#boundaryInFlight = true;\n    let lastSeq: number | undefined;\n    const startStateSeq = this.#startStateSeq;\n    try {\n      // Stubs only replace successful results other than `input`, and the thread comes from a\n      // suspended result or `input`, so the snapshot still holds the whole run's thread.\n      const threadId = getSnapshotMemoryInfo(snapshot)?.threadId;\n      const run = {\n        workflowName: this.workflowName,\n        runId: this.runId,\n        resourceId,\n        threadId,\n        header,\n        steps,\n        state,\n        statePatch,\n        ...(expectedStatus ? { expectedStatus } : {}),\n      };\n      const written = await this.#send(\n        checkpoint\n          ? store.writeWorkflowRunCheckpoint({ ...run, stateBase })\n          : store.appendWorkflowRunEntries({ ...run, ...(patched ? { stepPatches } : {}), startStateSeq }),\n        written => {\n          this.#runToken ??= written?.runToken;\n          return written?.lastSeq;\n        },\n      );\n      if (written === null) {\n        if (checkpoint) this.#needsCheckpoint = true;\n        return false;\n      }\n      lastSeq = written?.lastSeq;\n      this.#startStateSeq = undefined;\n    } catch (error) {\n      if (checkpoint) this.#needsCheckpoint = true;\n      throw error;\n    } finally {\n      this.#inFlight--;\n      if (boundary) this.#boundaryInFlight = false;\n    }\n    this.#recordWritten(sentWrites);\n    if (checkpoint || state || statePatch) {\n      this.#writtenRef =\n        lastSeq === undefined ? undefined : { workflowName: this.workflowName, runId: this.runId, seq: lastSeq };\n    }\n    if (checkpoint) this.#inheritedRef = undefined;\n    // The stored state is the live state now, so drafts of it are stale.\n    if (boundary) {\n      this.#draft = undefined;\n      this.#draftBytes = 0;\n    }\n    this.#writtenState = writtenState;\n    this.#patchBytes = patchBytes;\n    this.#patchCount = patchCount;\n    return true;\n  }\n\n  /**\n   * How a write sends a step's result: as a patch on the result last written (`ops`), not at all\n   * when it holds the same JSON (`unchanged`), else in full. A patch needs both results to be\n   * non-success (only a success is summarized, and a step's start and success writes never pay for\n   * a copy), the new one to be plain JSON (what JSON keeps as it is), every earlier write of the\n   * step to be stored (else the stored result the patch applies to isn't known), and the patches\n   * since the last full write to stay within its size, as for the state. `copy` is what\n   * `#writtenCopies` holds for the step once the write is stored.\n   *\n   * With `foreachItems` (see `write`), the patch is built from those entries alone, without\n   * serializing the whole result.\n   */\n  #stepWrite(\n    stepId: string,\n    result: StepResult<any, any, any, any>,\n    mayPatch: boolean,\n    foreachItems?: readonly number[],\n  ): { ops?: StatePatchOp[]; unchanged?: true; copy: StepCopy | undefined } {\n    const previous = this.#written.get(stepId) as { status?: string } | undefined;\n    const rewritten = previous !== undefined && previous.status !== 'success' && result?.status !== 'success';\n    const started = this.#stepWrites.get(stepId) ?? 0;\n    const prior = this.#writtenCopies.get(stepId);\n    if (foreachItems && rewritten && mayPatch && prior?.write === started) {\n      const progressPatch = foreachProgressPatch(prior, result, foreachItems);\n      if (progressPatch === 'unchanged') return { unchanged: true, copy: prior };\n      if (progressPatch) {\n        const patchBytes = prior.patchBytes + JSON.stringify(progressPatch.ops).length;\n        if (patchBytes <= progressPatch.bytes) {\n          // Updated in place: the copy is only patched on while it is the step's latest write, and\n          // this write becomes that, so a failed write leaves it unused.\n          for (const { key, value } of progressPatch.entries) progressPatch.written[key] = value;\n          return {\n            ops: progressPatch.ops,\n            copy: { json: prior.json, bytes: progressPatch.bytes, patchBytes, write: started + 1 },\n          };\n        }\n      }\n    }\n    const json = rewritten && isPlainJson(result, new Set()) ? JSON.stringify(result) : undefined;\n    if (json === undefined) return { copy: undefined };\n    const next: unknown = JSON.parse(json);\n    if (mayPatch && prior?.write === started) {\n      const ops = diffState(prior.json, next);\n      if (!ops.length) return { unchanged: true, copy: prior };\n      const patchBytes = prior.patchBytes + JSON.stringify(ops).length;\n      if (patchBytes <= json.length) {\n        return { ops, copy: { json: next, bytes: json.length, patchBytes, write: started + 1 } };\n      }\n    }\n    return { copy: { json: next, bytes: json.length, patchBytes: 0, write: started + 1 } };\n  }\n\n  /**\n   * Records what a stored write sent. A copy is kept only from the latest write of its step: an\n   * earlier write that finishes later doesn't hold what the store has last.\n   */\n  #recordWritten(writes: readonly { stepId: string; result: unknown; copy: StepCopy | undefined }[]): void {\n    for (const { stepId, result, copy } of writes) {\n      this.#written.set(stepId, result);\n      if (copy && copy.write !== (this.#stepWrites.get(stepId) ?? 0)) continue;\n      if (copy) this.#writtenCopies.set(stepId, copy);\n      else this.#writtenCopies.delete(stepId);\n    }\n  }\n\n  /**\n   * Replace stored successful results with stubs, except `input` and the steps in `keep`.\n   * Only results that are exactly what was last written are replaced, so nothing the store\n   * doesn't have is dropped.\n   */\n  evict(stepResults: StepResults, keep: readonly string[]): void {\n    if (!this.store) return;\n    const kept = new Set(keep);\n    for (const [stepId, result] of Object.entries(stepResults)) {\n      if (\n        // `getInitData()` reads the run's input synchronously.\n        stepId === 'input' ||\n        kept.has(stepId) ||\n        // Suspended, running and failed results are read synchronously on resume and restart.\n        result?.status !== 'success' ||\n        isStepResultStub(result) ||\n        // Skipped writes (`shouldPersistSnapshot`) and results replaced since the last write\n        // aren't stored as they are in memory.\n        this.#written.get(stepId) !== result\n      ) {\n        continue;\n      }\n      const stub = stubStepResult(result);\n      stepResults[stepId] = stub;\n      // Holding the written object here would keep the result in memory.\n      this.#written.set(stepId, stub);\n    }\n  }\n\n  /** Whether `result` is what the store holds for `stepId`, as of the writes that have settled. */\n  isStored(stepId: string, result: unknown): boolean {\n    return this.#written.get(stepId) === result;\n  }\n\n  /** Swap the stubs among `stepIds` back for their stored results, with one read. */\n  async hydrate(stepResults: StepResults, stepIds: readonly string[] = Object.keys(stepResults)): Promise<void> {\n    const { store, workflowName, runId } = this;\n    // Without storage nothing is evicted, so there are no stubs to load.\n    if (!store) return;\n    const loadSteps = (ids: string[]) => store.loadWorkflowRunSteps({ workflowName, runId, stepIds: ids });\n    const hydrated = await hydrateStepResults({ runId, loadSteps }, stepResults, stepIds);\n    // The loaded results are what's stored, so the next write doesn't resend them.\n    for (const [stepId, result] of hydrated) this.#written.set(stepId, result);\n  }\n\n  /** `getStepResultAsync` for step code: reads an evicted step from storage first. */\n  getStepResultAsync(stepResults: StepResults, step: unknown): Promise<any> {\n    return getHydratedStepResult(stepResults, step, stepIds => this.hydrate(stepResults, stepIds));\n  }\n}\n\n/**\n * `getStepResult` over step results that may hold stubs: a stubbed step is read back with\n * `hydrate` first. The result stays in `stepResults`, so later reads of it are free.\n *\n * @internal\n */\nexport async function getHydratedStepResult(\n  stepResults: StepResults,\n  step: unknown,\n  hydrate: (stepIds: string[]) => Promise<unknown>,\n): Promise<any> {\n  const stepId = stepRefId(step);\n  if (stepId !== undefined && isStepResultStub(stepResults[stepId])) await hydrate([stepId]);\n  return getStepResult(stepResults, step);\n}\n\n/**\n * The `getStepResult` / `getStepResultAsync` pair handed to step code. On storage v2\n * runs, sync `getStepResult` throws: their step results won't always be in memory.\n *\n * @internal\n */\nexport function buildStepResultAccessors(\n  engine: { getRunJournal(runId: string): RunJournal | undefined },\n  runId: string,\n  stepResults: StepResults,\n): { getStepResult: (step: any) => any; getStepResultAsync: (step: any) => Promise<any> } {\n  const journal = engine.getRunJournal(runId);\n  if (!journal) {\n    return {\n      getStepResult: getStepResult.bind(null, stepResults),\n      getStepResultAsync: getStepResultAsync.bind(null, stepResults),\n    };\n  }\n  return storageV2StepResultAccessors(step => journal.getStepResultAsync(stepResults, step));\n}\n\n/**\n * The accessor pair for step code in a storage v2 run: sync `getStepResult` throws, as the run's\n * step results won't always be in memory, and points to `getStepResultAsync`.\n *\n * @internal\n */\nexport function storageV2StepResultAccessors(getStepResultAsync: (step: unknown) => Promise<any>): {\n  getStepResult: (step: any) => never;\n  getStepResultAsync: (step: any) => Promise<any>;\n} {\n  return {\n    getStepResult: (step: unknown): never => {\n      const stepId = stepRefId(step) ?? String(step);\n      throw new MastraError({\n        id: 'WORKFLOW_STORAGE_V2_SYNC_GET_STEP_RESULT',\n        domain: ErrorDomain.MASTRA_WORKFLOW,\n        category: ErrorCategory.USER,\n        text: `getStepResult(\"${stepId}\") isn't available in workflows with storageVersion: 2. Use \\`await getStepResultAsync(\"${stepId}\")\\` instead.`,\n      });\n    },\n    getStepResultAsync,\n  };\n}\n\n/**\n * Swaps the stubs among `stepIds` back for the run's stored results, with one read.\n *\n * @returns The stored results put in, by step id.\n * @internal\n */\nexport async function hydrateStepResults(\n  run: { runId: string; loadSteps: (stepIds: string[]) => Promise<StepResults | null | undefined> },\n  stepResults: StepResults,\n  stepIds: readonly string[] = Object.keys(stepResults),\n): Promise<Map<string, StepResult<any, any, any, any>>> {\n  const hydrated = new Map<string, StepResult<any, any, any, any>>();\n  const stubbed = new Map<string, unknown>();\n  for (const stepId of stepIds) {\n    if (isStepResultStub(stepResults[stepId])) stubbed.set(stepId, stepResults[stepId]);\n  }\n  if (!stubbed.size) return hydrated;\n\n  const loaded = await run.loadSteps([...stubbed.keys()]);\n  for (const [stepId, stub] of stubbed) {\n    // A result that changed while the read was in flight (e.g. a parallel branch hydrated it)\n    // is at least as new as the one read.\n    if (stepResults[stepId] !== stub) continue;\n    const result = loaded?.[stepId];\n    if (!result) {\n      throw new MastraError({\n        id: 'WORKFLOW_STORAGE_V2_STEP_RESULT_MISSING',\n        domain: ErrorDomain.MASTRA_WORKFLOW,\n        category: ErrorCategory.SYSTEM,\n        text: `The stored result of step \"${stepId}\" in run ${run.runId} is missing. The run was deleted or overwritten while it ran.`,\n      });\n    }\n    stepResults[stepId] = result;\n    hydrated.set(stepId, result);\n  }\n  return hydrated;\n}\n\n/**\n * The state as a JSON store keeps it (a `Date` becomes its ISO string, `undefined` keys drop), and\n * its JSON size.\n */\nfunction normalizeState(state: unknown): {\n  state: Record<string, unknown>;\n  bytes: number;\n} {\n  const json = JSON.stringify(state ?? {});\n  return { state: JSON.parse(json), bytes: json.length };\n}\n\n/**\n * Whether JSON keeps `value` as it is: only strings, finite numbers, booleans, null, arrays and\n * plain objects (no `Date`, `Error` or other class instance, and no `undefined` array item). An\n * `undefined` object value is allowed: JSON drops the key, which reads back the same.\n */\n/**\n * The ops that add a running foreach's newly finished items to the copy of its last written result,\n * and the copy's JSON size with them. `'unchanged'` when every item is in the copy already.\n * Undefined when the copy holds no progress or an item isn't plain JSON: the result is then\n * written the general way.\n */\nfunction foreachProgressPatch(\n  prior: StepCopy,\n  result: StepResult<any, any, any, any>,\n  indices: readonly number[],\n):\n  | 'unchanged'\n  | {\n      ops: StatePatchOp[];\n      entries: { key: string; value: unknown }[];\n      written: Record<string, unknown>;\n      bytes: number;\n    }\n  | undefined {\n  const written = (prior.json as { metadata?: { foreachProgress?: unknown } } | null)?.metadata?.foreachProgress;\n  const live = (result as { metadata?: { foreachProgress?: Record<string, unknown> } }).metadata?.foreachProgress;\n  if (typeof written !== 'object' || written === null || !live) return undefined;\n  const progress = written as Record<string, unknown>;\n  const ops: StatePatchOp[] = [];\n  const entries: { key: string; value: unknown }[] = [];\n  let bytes = prior.bytes;\n  for (const index of indices) {\n    const key = String(index);\n    // A finished item's entry never changes, so one in the copy is already stored.\n    if (Object.hasOwn(progress, key) || !Object.hasOwn(live, key)) continue;\n    if (!isPlainJson(live[key], new Set())) return undefined;\n    const json = JSON.stringify(live[key]);\n    const value: unknown = JSON.parse(json);\n    ops.push({ op: 'set', path: ['metadata', 'foreachProgress', key], value });\n    entries.push({ key, value });\n    // `\"key\":value,` in the result's JSON.\n    bytes += key.length + json.length + 4;\n  }\n  return ops.length ? { ops, entries, written: progress, bytes } : 'unchanged';\n}\n\nfunction isPlainJson(value: unknown, ancestors: Set<object>): boolean {\n  switch (typeof value) {\n    case 'string':\n    case 'boolean':\n      return true;\n    case 'number':\n      return Number.isFinite(value);\n    case 'object': {\n      if (value === null) return true;\n      if (ancestors.has(value)) return false;\n      const proto = Object.getPrototypeOf(value);\n      if (!Array.isArray(value) && proto !== Object.prototype && proto !== null) return false;\n      ancestors.add(value);\n      let plain = true;\n      if (Array.isArray(value)) {\n        for (let i = 0; plain && i < value.length; i++) plain = isPlainJson(value[i], ancestors);\n      } else {\n        for (const item of Object.values(value)) {\n          if (item !== undefined && !isPlainJson(item, ancestors)) {\n            plain = false;\n            break;\n          }\n        }\n      }\n      ancestors.delete(value);\n      return plain;\n    }\n    default:\n      return false;\n  }\n}\n\n/** The `steps` loader of a storage v2 result -> the step results it was built from (see `residentStepResults`). */\nconst residentResults = new WeakMap<object, StepResults>();\n\n/**\n * The `steps()` of a storage v2 run's result: its step results as the execution left them, formatted\n * by `format`. The successful results the journal evicted are read from storage on the first call,\n * with one read shared by concurrent calls; the read fails if the run was written to since its\n * execution ended (e.g. resumed or restarted), since storage then no longer holds what the result\n * describes. A failed read isn't cached, so a later call retries.\n *\n * Holds the stubs and the results that weren't evicted until the run's writes settle; then the\n * stored successful results are evicted too, so it holds only stubs, `input` and the results a\n * reader needs without loading (suspended, failed, running). Call it after the run's last write is\n * sent, and close the journal before anything awaits the loader.\n *\n * @internal\n */\nexport function lazyStepResults(\n  journal: RunJournal,\n  stepResults: StepResults,\n  format: (stepResults: StepResults) => StepResults,\n): () => Promise<StepResults> {\n  const results = { ...stepResults };\n  evictOnceStored(journal, results);\n  const { store, workflowName, runId, settledLastSeq, settledRunToken } = journal;\n  return storedStepResults(\n    { store: store!, workflowName, runId, lastSeq: settledLastSeq, runToken: settledRunToken },\n    results,\n    format,\n  );\n}\n\n// Kept apart from `lazyStepResults`, so the loader it returns doesn't hold on to the journal.\nfunction evictOnceStored(journal: RunJournal, results: StepResults): void {\n  void journal.settledLastSeq.then(() => {\n    for (const [stepId, result] of Object.entries(results)) {\n      if (\n        stepId !== 'input' &&\n        result?.status === 'success' &&\n        !isStepResultStub(result) &&\n        journal.isStored(stepId, result)\n      ) {\n        results[stepId] = stubStepResult(result);\n      }\n    }\n  });\n}\n\n/**\n * The `steps()` of a storage v2 result reconstructed from stored state. Holds successful-step\n * stubs and hydrates them on the first call while the stored run identity and `lastSeq` still match.\n *\n * @internal\n */\nexport function loadedStepResults(\n  {\n    store,\n    workflowName,\n    runId,\n    lastSeq,\n    runToken,\n  }: { store: WorkflowsStorage; workflowName: string; runId: string; lastSeq: number; runToken?: string },\n  stepResults: StepResults,\n  format: (stepResults: StepResults) => StepResults,\n): () => Promise<StepResults> {\n  const results: StepResults = {};\n  for (const [stepId, result] of Object.entries(stepResults)) {\n    results[stepId] =\n      stepId !== 'input' && result?.status === 'success' && !isStepResultStub(result) ? stubStepResult(result) : result;\n  }\n  return storedStepResults(\n    { store, workflowName, runId, lastSeq: Promise.resolve(lastSeq), runToken: Promise.resolve(runToken) },\n    results,\n    format,\n  );\n}\n\n/**\n * The `steps()` of a storage v2 result that already holds every step result, so it reads none\n * from storage: an evented run's, whose finish event carries them all.\n *\n * @internal\n */\nexport function residentStepResultsLoader(stepResults: StepResults): () => Promise<StepResults> {\n  const steps = () => Promise.resolve(stepResults);\n  residentResults.set(steps, stepResults);\n  return steps;\n}\n\nfunction storedStepResults(\n  {\n    store,\n    workflowName,\n    runId,\n    lastSeq,\n    runToken,\n  }: {\n    store: WorkflowsStorage;\n    workflowName: string;\n    runId: string;\n    lastSeq: Promise<number | undefined>;\n    runToken: Promise<string | undefined>;\n  },\n  results: StepResults,\n  format: (stepResults: StepResults) => StepResults,\n): () => Promise<StepResults> {\n  let loaded: Promise<StepResults> | undefined;\n\n  const load = async (): Promise<StepResults> => {\n    const expectedLastSeq = await lastSeq;\n    const expectedRunToken = await runToken;\n    const stubbed = Object.keys(results).filter(stepId => isStepResultStub(results[stepId]));\n    if (!stubbed.length && expectedLastSeq === undefined) return format(results);\n\n    const stored = await store.loadWorkflowRunSteps({\n      workflowName,\n      runId,\n      stepIds: stubbed,\n      expectedLastSeq,\n      expectedRunToken,\n    });\n    if (!stored) {\n      throw new MastraError({\n        id: 'WORKFLOW_STORAGE_V2_STEPS_STALE',\n        domain: ErrorDomain.MASTRA_WORKFLOW,\n        category: ErrorCategory.USER,\n        text: `The steps of run ${runId} can't be loaded for this result: the run was written to (e.g. resumed or restarted) or deleted since. Read the run again for its current steps.`,\n      });\n    }\n    const full = { ...results };\n    for (const stepId of stubbed) {\n      const result = stored[stepId];\n      if (!result) {\n        throw new MastraError({\n          id: 'WORKFLOW_STORAGE_V2_STEP_RESULT_MISSING',\n          domain: ErrorDomain.MASTRA_WORKFLOW,\n          category: ErrorCategory.SYSTEM,\n          text: `The stored result of step \"${stepId}\" in run ${runId} is missing.`,\n        });\n      }\n      full[stepId] = result;\n    }\n    return format(full);\n  };\n\n  const steps = () => {\n    loaded ??= load().catch(error => {\n      loaded = undefined;\n      throw error;\n    });\n    return loaded;\n  };\n  residentResults.set(steps, results);\n  return steps;\n}\n\n/**\n * The step results a storage v2 result's `steps` loader holds without reading storage: every result\n * but the successful ones that were evicted, which are stubs. Undefined for anything else (a v1\n * result's `steps` record). For the engine's own reads of a nested run's suspended and failed steps.\n *\n * @internal\n */\nexport function residentStepResults(steps: unknown): StepResults | undefined {\n  return typeof steps === 'function' ? residentResults.get(steps) : undefined;\n}\n\n/**\n * Every step result of a run's result: a storage v2 result's `steps` loader is called, a v1\n * result's record returned as is. For the framework's readers that hand all of them on.\n *\n * @internal\n */\nexport async function loadStepResults(steps: unknown): Promise<StepResults> {\n  return typeof steps === 'function' ? steps() : (steps as StepResults);\n}\n","import type { MessageList } from '../agent/message-list';\nimport { createSignal } from '../agent/signals';\nimport type { AgentSignalInput, CreatedAgentSignal } from '../agent/signals';\nimport { createRunScopeKey } from '../mastra/run-scope';\nimport type { ProcessorStreamWriter } from './index';\n\n/**\n * Where a processor's `sendSignal` goes once the step that created it has\n * returned. Durable engines rebuild the MessageList for every step, so a held\n * `sendSignal` writing into the old list would never reach the model.\n */\nexport interface ProcessorLateSignalSink {\n  isClosed(): boolean;\n  send(signalInput: AgentSignalInput): Promise<CreatedAgentSignal>;\n}\n\nexport const PROCESSOR_LATE_SIGNAL_SINK = createRunScopeKey<ProcessorLateSignalSink>('processor-late-signal-sink');\n\nexport function createProcessorSendSignal(args: {\n  messageList: MessageList;\n  writer?: ProcessorStreamWriter;\n  rotateResponseMessageId?: () => string;\n  lateSink?: ProcessorLateSignalSink;\n}): (signalInput: AgentSignalInput) => Promise<CreatedAgentSignal> {\n  return async signalInput => {\n    if (args.lateSink?.isClosed()) {\n      return args.lateSink.send(signalInput);\n    }\n    const signal = createSignal(signalInput);\n    // Only seal the in-flight response message when a rotation follows. Rotation\n    // marks the boundary itself (MessageList.rotateResponseMessageId); stamping it\n    // WITHOUT rotating leaves the next streamed step on the same message id unable\n    // to merge (MessageMerger blocks on responseBoundary), so the same-id add\n    // falls into the replacement path and destroys already-streamed tool\n    // call/result parts (https://github.com/mastra-ai/mastra/issues/21940).\n    if (args.rotateResponseMessageId) {\n      args.messageList.markResponseMessageBoundary();\n      args.rotateResponseMessageId();\n    }\n    const signalForTranscript = args.messageList.addSignal(signal);\n    await args.writer?.custom(signalForTranscript.toDataPart());\n    return signalForTranscript;\n  };\n}\n","/**\n * Resolution of a processor's declared span identity.\n *\n * A processor may declare the span type, name and attributes it should be\n * traced as (see `Processor.spanType`). Spans for processors are created in two\n * places — the legacy `ProcessorRunner` and the processor-workflow executor —\n * so the resolution lives here and both call it. A declaration honoured by only\n * one executor would apply or not depending on how the agent happened to run\n * its processors.\n */\nimport type { ProcessorSpanPayloadPhase } from '../observability';\nimport type { Processor, ProcessorSpanPhase } from './index';\n\n/**\n * Phase names used by the processor-workflow executor, mapped onto\n * `ProcessorSpanPhase`. The executor distinguishes `outputStream` from\n * `outputResult`; both are the output phase as far as a declaration is\n * concerned, matching how they share one entity type.\n */\nconst WORKFLOW_PHASE_TO_SPAN_PHASE: Record<string, ProcessorSpanPhase> = {\n  input: 'input',\n  inputStep: 'inputStep',\n  llmRequest: 'llmRequest',\n  llmResponse: 'llmResponse',\n  outputStream: 'output',\n  outputResult: 'output',\n  outputStep: 'outputStep',\n  toolResult: 'toolResult',\n  requestError: 'requestError',\n};\n\n/** Map a processor-workflow phase string onto the declaration phase. */\nexport function toProcessorSpanPhase(phase: string): ProcessorSpanPhase {\n  return WORKFLOW_PHASE_TO_SPAN_PHASE[phase] ?? 'output';\n}\n\n/** The span type a processor declared, or `undefined` to use the default. */\nexport function resolveProcessorSpanType(processor: Pick<Processor, 'spanType'>) {\n  return processor.spanType;\n}\n\n/**\n * Resolve a processor's declared span name for the phase the span is being\n * created in, falling back to the caller's default label.\n */\nexport function resolveProcessorSpanName(\n  processor: Pick<Processor, 'spanName'>,\n  phase: ProcessorSpanPhase,\n  fallback: string,\n): string {\n  const declared = processor.spanName;\n  if (typeof declared === 'function') return declared(phase);\n  return declared ?? fallback;\n}\n\n/**\n * Resolve a processor's declared span attributes for this phase, with the phase\n * itself recorded alongside them.\n *\n * The phase is applied last so a declaration cannot misreport which phase ran:\n * readers narrow a processor span's payloads on this attribute, and a processor\n * naming itself into another phase would hand them the wrong shape.\n */\nexport function resolveProcessorSpanAttributes(\n  processor: Pick<Processor, 'spanAttributes'> | undefined,\n  phase: ProcessorSpanPayloadPhase,\n) {\n  const declared = processor?.spanAttributes;\n  // The declaration callback keeps seeing the coarser phase it was written\n  // against; only the recorded attribute distinguishes the two output hooks.\n  const declarationPhase = toProcessorSpanPhase(phase);\n  return {\n    ...(typeof declared === 'function' ? declared(declarationPhase) : declared),\n    processorPhase: phase,\n  };\n}\n","function isPlainObject(value: unknown): value is Record<string, unknown> {\n  if (value === null || typeof value !== 'object' || Array.isArray(value)) {\n    return false;\n  }\n\n  const prototype = Object.getPrototypeOf(value);\n  return prototype === Object.prototype || prototype === null;\n}\n\nfunction readString(value: unknown): string | undefined {\n  return typeof value === 'string' ? value : undefined;\n}\n\ntype ProcessorToolSummary = {\n  id: string;\n  name: string;\n  description?: string;\n};\n\ntype ActiveToolSummary = {\n  id: string;\n  name: string;\n};\n\nfunction summarizeProcessorToolEntry(key: string, value: unknown): ProcessorToolSummary {\n  if (!isPlainObject(value)) {\n    return {\n      id: key,\n      name: key,\n    };\n  }\n\n  const id = readString(value.id) ?? key;\n  const name = readString(value.name) ?? id;\n  const description = readString(value.description);\n\n  return {\n    id,\n    name,\n    ...(description !== undefined ? { description } : {}),\n  };\n}\n\nexport function summarizeProcessorModelForSpan(value: unknown):\n  | {\n      modelId?: string;\n      provider?: string;\n      specificationVersion?: string;\n    }\n  | undefined {\n  if (!isPlainObject(value)) {\n    return undefined;\n  }\n\n  const modelId = readString(value.modelId) ?? readString(value.id);\n  const provider = readString(value.provider);\n  const specificationVersion = readString(value.specificationVersion);\n\n  if (modelId === undefined && provider === undefined && specificationVersion === undefined) {\n    return undefined;\n  }\n\n  return {\n    ...(modelId !== undefined ? { modelId } : {}),\n    ...(provider !== undefined ? { provider } : {}),\n    ...(specificationVersion !== undefined ? { specificationVersion } : {}),\n  };\n}\n\nexport function summarizeProcessorToolsForSpan(tools: unknown): ProcessorToolSummary[] | undefined {\n  if (!isPlainObject(tools)) {\n    return undefined;\n  }\n\n  return Object.entries(tools).map(([key, value]) => summarizeProcessorToolEntry(key, value));\n}\n\nfunction summarizeProcessorToolRegistry(\n  tools: unknown,\n): Array<{ registryKey: string; summary: ProcessorToolSummary }> | undefined {\n  if (!isPlainObject(tools)) {\n    return undefined;\n  }\n\n  const summaries = summarizeProcessorToolsForSpan(tools);\n  if (!summaries) {\n    return undefined;\n  }\n\n  return Object.keys(tools).map((registryKey, index) => ({\n    registryKey,\n    summary: summaries[index]!,\n  }));\n}\n\nfunction resolveToolInRegistry(\n  toolRegistry: Array<{ registryKey: string; summary: ProcessorToolSummary }>,\n  toolKey: string,\n) {\n  return toolRegistry.find(\n    candidate =>\n      candidate.summary.id === toolKey || candidate.summary.name === toolKey || candidate.registryKey === toolKey,\n  );\n}\n\nexport function summarizeActiveToolsForSpan(activeTools: unknown, tools?: unknown): ActiveToolSummary[] | undefined {\n  if (!Array.isArray(activeTools)) {\n    return undefined;\n  }\n\n  const toolRegistry = summarizeProcessorToolRegistry(tools) ?? [];\n  const summaries = activeTools\n    .map(tool => {\n      const toolKey = readString(tool);\n      if (toolKey === undefined) {\n        return undefined;\n      }\n\n      const match = resolveToolInRegistry(toolRegistry, toolKey);\n      return {\n        id: match?.summary.id ?? toolKey,\n        name: match?.summary.name ?? toolKey,\n      };\n    })\n    .filter((tool): tool is ActiveToolSummary => tool !== undefined);\n\n  return summaries;\n}\n\nexport function summarizeToolChoiceForSpan(\n  toolChoice: unknown,\n  tools?: unknown,\n):\n  | {\n      type: string;\n      tool?: ActiveToolSummary;\n    }\n  | undefined {\n  if (typeof toolChoice === 'string') {\n    return { type: toolChoice };\n  }\n\n  if (!isPlainObject(toolChoice)) {\n    return undefined;\n  }\n\n  const type = readString(toolChoice.type);\n  if (type === undefined) {\n    return undefined;\n  }\n\n  if (type !== 'tool') {\n    return { type };\n  }\n\n  const toolKey = readString(toolChoice.toolName) ?? readString(toolChoice.toolId);\n  if (toolKey === undefined) {\n    return { type };\n  }\n\n  const toolRegistry = summarizeProcessorToolRegistry(tools) ?? [];\n  const match = resolveToolInRegistry(toolRegistry, toolKey);\n  const fallbackToolId = readString(toolChoice.toolId) ?? toolKey;\n  const fallbackToolName = readString(toolChoice.toolName) ?? toolKey;\n\n  return {\n    type,\n    tool: match\n      ? {\n          id: match.summary.id,\n          name: match.summary.name,\n        }\n      : {\n          id: fallbackToolId,\n          name: fallbackToolName,\n        },\n  };\n}\n\nexport function summarizeProcessorResultForSpan(value: unknown): Record<string, unknown> | undefined {\n  if (!isPlainObject(value)) {\n    return undefined;\n  }\n\n  const projected: Record<string, unknown> = {};\n  for (const key of [\n    'text',\n    'object',\n    'finishReason',\n    'toolCalls',\n    'toolResults',\n    'warnings',\n    'files',\n    'sources',\n    'reasoning',\n    'reasoningText',\n    'tripwire',\n  ] as const) {\n    if (value[key] !== undefined) {\n      projected[key] = value[key];\n    }\n  }\n\n  if (Array.isArray(value.steps)) {\n    projected.stepCount = value.steps.length;\n  }\n\n  return Object.keys(projected).length > 0 ? projected : undefined;\n}\n","import type { ChunkType } from '../stream';\n\n/**\n * Well-known key a stream output processor can set on its `state` to ask the\n * ProcessorRunner to re-drive an additional part through the full output\n * processor chain after the current part has been emitted.\n *\n * `processOutputStream` can only return a single part, but some processors\n * (e.g. `BatchPartsProcessor`) need to emit two parts for one input: a flushed\n * batch of buffered text plus the non-text part that triggered the flush. The\n * processor returns the flushed batch (so it flows through downstream\n * processors normally) and stashes the non-text part under this key. The runner\n * then re-feeds the stashed part through the whole chain so it also receives\n * downstream processing and is emitted in order — instead of being deferred to\n * a \"next\" call that may never happen (which dropped the part when a `stopWhen`\n * condition stopped the agent on that part — issue #17094).\n */\nexport const REPROCESS_PART_KEY = '__mastraReprocessPart';\n\n/**\n * Well-known key a stream output processor sets on its `state` when it holds\n * parts back until a later part arrives (a batch, a sentence buffer). The value\n * is a function that releases every held part, already processed by the\n * holding processor, and clears the hold.\n *\n * When the stream ends, the runner calls it and pushes the released parts\n * through the processors after the holder, so held text is not dropped when\n * nothing follows the last held part (issue #27523).\n */\nexport const FLUSH_HELD_PARTS_KEY = '__mastraFlushHeldParts';\n\n/**\n * With `discard`, the hold is cleared without running any checks: held content\n * (see {@link withoutHeldContent}) is dropped and only held control parts are\n * returned, since the stream failed or was aborted and its content must not be emitted.\n */\nexport type FlushHeldParts = (options?: { discard?: boolean }) => Promise<ChunkType[]> | ChunkType[];\n\n/** Whether a part marks its model stream as errored or aborted (held parts are then discarded). */\nexport function isFailedStreamChunk<OUTPUT>(part: ChunkType<OUTPUT>): boolean {\n  if (part.type === 'error' || part.type === 'abort') return true;\n  if (part.type !== 'finish') return false;\n  const reason = (part.payload as { stepResult?: { reason?: string } } | undefined)?.stepResult?.reason;\n  return reason === 'error' || reason === 'abort';\n}\n\n/** Drops content parts from a discarded hold, keeping control parts (start, error, finish, ...). */\nexport function withoutHeldContent<T extends { type: string }>(parts: T[]): T[] {\n  return parts.filter(part => part.type !== 'text-delta' && part.type !== 'reasoning-delta');\n}\n\n/** Releases the parts a processor is holding, or none if it holds nothing. */\nexport async function takeHeldParts(\n  state: Record<string, unknown> | undefined,\n  options?: { discard?: boolean },\n): Promise<ChunkType[]> {\n  const flush = state?.[FLUSH_HELD_PARTS_KEY] as FlushHeldParts | undefined;\n  return flush ? await flush(options) : [];\n}\n","import type { LanguageModelV2Prompt } from '@ai-sdk/provider-v5';\nimport { APICallError } from '@internal/ai-sdk-v5';\n\nimport type { MastraDBMessage, MastraMessagePart, MastraToolInvocationPart, MessageList } from '../agent/message-list';\nimport { getResponseProviderItemIdFromPart } from '../agent/message-list';\nimport {\n  RESPONSE_ITEM_ID_PROVIDERS,\n  RESPONSE_RESULT_ITEM_ID_KEY,\n} from '../agent/message-list/utils/response-item-metadata';\nimport type {\n  Processor,\n  ProcessAPIErrorArgs,\n  ProcessAPIErrorResult,\n  ProcessLLMRequestArgs,\n  ProcessLLMRequestResult,\n} from './index';\n\n// ---------------------------------------------------------------------------\n// Compat-rule infrastructure\n// ---------------------------------------------------------------------------\n\n/**\n * A single compatibility rule that resolves a known provider history\n * incompatibility. Rules can resolve issues either:\n *\n * - **Reactively** via {@link CompatRule.fix}: when an API call fails with an\n *   error matching one of {@link CompatRule.errorPatterns}, the fix mutates\n *   the persisted message list and the request is retried. Suitable for\n *   incompatibilities that, once fixed, stay fixed across future turns\n *   (e.g. tool-call ID format).\n *\n * - **Preemptively** via {@link CompatRule.applyToPrompt}: runs in\n *   `processLLMRequest` after `MessageList → LanguageModelV2Prompt` conversion\n *   and before the prompt is sent to the provider. Mutations affect only the\n *   outbound prompt; nothing is persisted to the message list. Suitable for\n *   incompatibilities that would otherwise re-trigger on every turn (e.g.\n *   fields the model adds to its own response that the same provider rejects\n *   on subsequent input).\n *\n * A rule may implement either hook, both, or — rarely — neither (e.g. a\n * placeholder for future error-pattern matching).\n */\nexport interface CompatRule {\n  /** Human-readable identifier for logging/debugging. */\n  name: string;\n  /** Regexes matched against the error message and response body. */\n  errorPatterns?: RegExp[];\n  /** Mutate persisted messages to resolve the incompatibility. Return `true` if changes were made. */\n  fix?: (messages: MastraDBMessage[]) => boolean;\n  /**\n   * Rewrite the outbound LLM request preemptively. Receives the resolved model\n   * so rules can scope themselves to specific providers, and — when the caller\n   * has it — the message list the prompt was built from, for provenance the\n   * converted prompt no longer carries. Return a new prompt to forward, or\n   * `undefined` to leave the prompt unchanged.\n   */\n  applyToPrompt?: (args: {\n    prompt: LanguageModelV2Prompt;\n    model: unknown;\n    /** Provider id of the API the prompt is sent to (see `ProcessLLMRequestArgs.apiProviderId`). */\n    apiProviderId?: string;\n    messageList?: MessageList;\n  }) => LanguageModelV2Prompt | undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction getErrorCandidates(error: APICallError | Error): string[] {\n  const candidates = [error.message];\n\n  if (APICallError.isInstance(error) && typeof error.responseBody === 'string') {\n    candidates.push(error.responseBody);\n  }\n\n  return candidates.filter(Boolean);\n}\n\nfunction matchesRule(error: unknown, rule: CompatRule): boolean {\n  if (!rule.errorPatterns?.length) return false;\n  const matches = (text: string) => rule.errorPatterns!.some(p => p.test(text));\n\n  if (APICallError.isInstance(error)) {\n    return getErrorCandidates(error).some(matches);\n  }\n\n  if (error instanceof Error) {\n    return getErrorCandidates(error).some(matches);\n  }\n\n  return false;\n}\n\n// ---------------------------------------------------------------------------\n// Built-in rule: Anthropic tool-call ID format\n// ---------------------------------------------------------------------------\n\nconst VALID_TOOL_ID_PATTERN = /^[a-zA-Z0-9_-]+$/;\n\nfunction sanitizeToolId(id: string): string {\n  return id.replace(/[^a-zA-Z0-9_-]/g, '_');\n}\n\nfunction buildToolIdMap(messages: MastraDBMessage[]): Map<string, string> {\n  const idMap = new Map<string, string>();\n\n  for (const msg of messages) {\n    if (!msg.content?.parts) continue;\n    for (const part of msg.content.parts) {\n      if (part.type === 'tool-invocation') {\n        const id = part.toolInvocation.toolCallId;\n        if (id && !VALID_TOOL_ID_PATTERN.test(id) && !idMap.has(id)) {\n          idMap.set(id, sanitizeToolId(id));\n        }\n      }\n    }\n\n    if (msg.content.toolInvocations) {\n      for (const inv of msg.content.toolInvocations) {\n        const id = inv.toolCallId;\n        if (id && !VALID_TOOL_ID_PATTERN.test(id) && !idMap.has(id)) {\n          idMap.set(id, sanitizeToolId(id));\n        }\n      }\n    }\n  }\n\n  return idMap;\n}\n\nfunction rewriteToolIds(messages: MastraDBMessage[], idMap: Map<string, string>): void {\n  for (const msg of messages) {\n    if (msg.content?.parts) {\n      for (let i = 0; i < msg.content.parts.length; i++) {\n        const part = msg.content.parts[i] as MastraMessagePart;\n        if (part.type === 'tool-invocation') {\n          const oldId = part.toolInvocation.toolCallId;\n          const newId = idMap.get(oldId);\n          if (newId) {\n            (part as MastraToolInvocationPart).toolInvocation = {\n              ...part.toolInvocation,\n              toolCallId: newId,\n            };\n          }\n        }\n      }\n    }\n\n    if (msg.content?.toolInvocations) {\n      for (const inv of msg.content.toolInvocations) {\n        const newId = idMap.get(inv.toolCallId);\n        if (newId) {\n          inv.toolCallId = newId;\n        }\n      }\n    }\n  }\n}\n\n/**\n * Rewrites invalid tool-call IDs in the outbound prompt, keeping call↔result\n * pairing intact. Nothing is persisted — the prompt is rebuilt, and the\n * original ids stay in the message list.\n *\n * Replacements are assigned per call, in encounter order, and never collide\n * with an id the prompt already carries: a sanitized id that is already\n * claimed — by another original id or by a valid id elsewhere in the prompt —\n * gets `_2`, `_3`, … appended until it is unique. Anthropic rejects duplicate\n * `tool_use.id` values, so uniqueness is what keeps call/result pairing\n * resolvable. Two calls that share one invalid original id still receive\n * distinct replacements; the nth result carrying that id pairs with the nth\n * call, which is the only resolvable reading of an already-degenerate prompt.\n */\nfunction rewritePromptToolIds(prompt: LanguageModelV2Prompt): LanguageModelV2Prompt | undefined {\n  const replacements = new Map<string, string[]>();\n  const claimed = new Set<string>();\n\n  // Every id the prompt carries is unavailable as a replacement target.\n  for (const message of prompt) {\n    if (message.role === 'assistant' && Array.isArray(message.content)) {\n      for (const part of message.content) {\n        if (part.type === 'tool-call') claimed.add(part.toolCallId);\n      }\n      continue;\n    }\n    if (message.role === 'tool') {\n      for (const part of message.content) claimed.add(part.toolCallId);\n    }\n  }\n\n  // Assign a replacement to every call with an invalid id, per occurrence.\n  let assigned = 0;\n  for (const message of prompt) {\n    if (message.role !== 'assistant' || !Array.isArray(message.content)) continue;\n    for (const part of message.content) {\n      if (part.type !== 'tool-call') continue;\n      const id = part.toolCallId;\n      if (VALID_TOOL_ID_PATTERN.test(id)) continue;\n\n      const sanitized = sanitizeToolId(id);\n      let candidate = sanitized;\n      for (let suffix = 2; claimed.has(candidate); suffix++) {\n        candidate = `${sanitized}_${suffix}`;\n      }\n      claimed.add(candidate);\n      const queue = replacements.get(id);\n      if (queue) queue.push(candidate);\n      else replacements.set(id, [candidate]);\n      assigned++;\n    }\n  }\n\n  if (assigned === 0) return undefined;\n\n  // Calls and results interleave in the prompt, so each side tracks its own\n  // occurrence index: the nth result carrying an id pairs with the nth call.\n  const callIndex = new Map<string, number>();\n  const resultIndex = new Map<string, number>();\n  const takeAt = (index: Map<string, number>, id: string): string | undefined => {\n    const queue = replacements.get(id);\n    if (!queue) return undefined;\n    const i = index.get(id) ?? 0;\n    index.set(id, i + 1);\n    return i < queue.length ? queue[i] : undefined;\n  };\n  const takeCall = (id: string) => takeAt(callIndex, id);\n  const takeResult = (id: string) => takeAt(resultIndex, id);\n\n  const rewritten: LanguageModelV2Prompt = prompt.map(message => {\n    if (message.role === 'assistant' && Array.isArray(message.content)) {\n      let changed = false;\n      const content = message.content.map(part => {\n        if (part.type !== 'tool-call') return part;\n        const replacement = takeCall(part.toolCallId);\n        if (!replacement) return part;\n        changed = true;\n        return { ...part, toolCallId: replacement };\n      });\n      return changed ? { ...message, content } : message;\n    }\n\n    if (message.role === 'tool') {\n      let changed = false;\n      const content = message.content.map(part => {\n        const replacement = takeResult(part.toolCallId);\n        if (!replacement) return part;\n        changed = true;\n        return { ...part, toolCallId: replacement };\n      });\n      return changed ? { ...message, content } : message;\n    }\n\n    return message;\n  });\n\n  return rewritten;\n}\n\n/**\n * Anthropic enforces `^[a-zA-Z0-9_-]+$` on tool_use.id values.\n * Tool-call IDs from other providers (e.g. containing `.`, `:`) will be\n * rejected. This rule rewrites offending characters to `_` in the outbound\n * prompt, so the rejection never happens and persisted history keeps its\n * original IDs.\n */\nexport const anthropicToolIdFormat: CompatRule = {\n  name: 'anthropic-tool-id-format',\n  /**\n   * Matches Anthropic's tool_use.id rejection. The preemptive\n   * `applyToPrompt` hook repairs the outbound prompt first, so this pattern\n   * only fires when that hook cannot see the request: Anthropic served\n   * through a provider `isMaybeAnthropic` does not recognize (for example\n   * Vertex- or Bedrock-hosted Claude), or compat configured outside the\n   * agent's prompt path.\n   */\n  errorPatterns: [/tool_use\\.id:.*should match pattern/i, /tool_call_id.*invalid/i],\n  /**\n   * Rewrites invalid tool-call ids in place after a provider rejection.\n   * This is the fallback repair for Anthropic served through a provider the\n   * preemptive `applyToPrompt` check does not recognize (for example Vertex-\n   * or Bedrock-hosted Claude), and the only repair available once an API\n   * call has already been rejected.\n   */\n  fix(messages) {\n    const idMap = buildToolIdMap(messages);\n    if (idMap.size === 0) return false;\n    rewriteToolIds(messages, idMap);\n    return true;\n  },\n  applyToPrompt({ prompt, model }) {\n    if (!isMaybeAnthropic(model)) return undefined;\n    return rewritePromptToolIds(prompt);\n  },\n};\n\n// ---------------------------------------------------------------------------\n// Built-in rule: Cerebras `reasoning_content` strip\n// ---------------------------------------------------------------------------\n\n/**\n * Detects whether a model is (or might be) routed through Cerebras.\n *\n * Cerebras's API rejects assistant messages carrying `reasoning_content`\n * (the field `@ai-sdk/openai-compatible@>=1.0.32` adds when serializing\n * reasoning parts). A flexible matcher is used here because the model arg\n * passed to processors may be a resolved language model, an unresolved\n * model id string, a dynamic function, or a fallback array.\n */\nfunction matchesProviderPrefix(model: unknown, providerPrefix: string): boolean {\n  if (model == null) return false;\n  if (typeof model === 'function') return false;\n\n  if (Array.isArray(model)) {\n    return model.some(m => matchesProviderPrefix((m as { model?: unknown }).model ?? m, providerPrefix));\n  }\n\n  const gatewayPattern = new RegExp(`^${providerPrefix}[/:]`, 'i');\n  const providerPattern = new RegExp(`^${providerPrefix}($|[.\\\\-])`, 'i');\n\n  if (typeof model === 'string') {\n    // Common forms: 'provider/...' (mastra gateway prefix), 'provider:...' (some routers)\n    return gatewayPattern.test(model);\n  }\n\n  if (typeof model === 'object') {\n    const { provider, modelId } = model as { provider?: unknown; modelId?: unknown };\n    if (typeof provider === 'string' && providerPattern.test(provider)) return true;\n    if (typeof modelId === 'string') return gatewayPattern.test(modelId);\n  }\n\n  return false;\n}\n\n/**\n * Extract the exact provider id from a resolved model — the same value\n * `buildResponseModelMetadata` stamps onto each persisted assistant turn.\n * Returns `undefined` for unresolved string ids and dynamic functions, where\n * no reliable provider identity exists.\n */\nfunction getModelProviderId(model: unknown): string | undefined {\n  if (model == null || typeof model === 'function' || typeof model === 'string') return undefined;\n\n  if (Array.isArray(model)) {\n    for (const entry of model) {\n      const provider = getModelProviderId((entry as { model?: unknown }).model ?? entry);\n      if (provider) return provider;\n    }\n    return undefined;\n  }\n\n  if (typeof model === 'object') {\n    const provider = (model as { provider?: unknown }).provider;\n    return typeof provider === 'string' && provider.length > 0 ? provider : undefined;\n  }\n\n  return undefined;\n}\n\nexport function isMaybeCerebras(\n  model:\n    | string\n    | { provider?: string; modelId?: string }\n    | ((...args: any[]) => any)\n    | { model: any; enabled?: boolean }[]\n    | unknown,\n): boolean {\n  return matchesProviderPrefix(model, 'cerebras');\n}\n\nexport function isMaybeAnthropic(\n  model:\n    | string\n    | { provider?: string; modelId?: string }\n    | ((...args: any[]) => any)\n    | { model: any; enabled?: boolean }[]\n    | unknown,\n): boolean {\n  return matchesProviderPrefix(model, 'anthropic');\n}\n\ntype ProviderFamily = 'anthropic' | 'openai' | 'google';\n\nfunction getModelProviderFamily(model: unknown): ProviderFamily | undefined {\n  if (matchesProviderPrefix(model, 'anthropic')) return 'anthropic';\n  if (matchesProviderPrefix(model, 'openai') || matchesProviderPrefix(model, 'azure')) return 'openai';\n  if (matchesProviderPrefix(model, 'google') || matchesProviderPrefix(model, 'vertex')) return 'google';\n  return undefined;\n}\n\nfunction getPartProviderFamily(part: { providerOptions?: unknown }): ProviderFamily | undefined {\n  if (!part.providerOptions || typeof part.providerOptions !== 'object') return undefined;\n  const providers = Object.keys(part.providerOptions);\n  if (providers.some(provider => provider === 'anthropic')) return 'anthropic';\n  if (providers.some(provider => provider === 'openai' || provider === 'azure')) return 'openai';\n  if (providers.some(provider => provider === 'google' || provider === 'vertex')) return 'google';\n  return undefined;\n}\n\n/**\n * Provider-executed tools are provider-owned continuation state. A foreign\n * provider cannot resolve their IDs, so remove the call and paired result from\n * the outbound prompt while leaving persisted history untouched.\n */\nexport const stripForeignProviderExecutedTools: CompatRule = {\n  name: 'strip-foreign-provider-executed-tools',\n  applyToPrompt({ prompt, model }) {\n    const destinationProvider = getModelProviderFamily(model);\n    if (!destinationProvider) return undefined;\n\n    const foreignToolCallIds = new Set<string>();\n    for (const message of prompt) {\n      if (message.role !== 'assistant' || !Array.isArray(message.content)) continue;\n      for (const part of message.content) {\n        if (part.type !== 'tool-call' || !part.providerExecuted) continue;\n        const sourceProvider = getPartProviderFamily(part);\n        if (sourceProvider && sourceProvider !== destinationProvider) {\n          foreignToolCallIds.add(part.toolCallId);\n        }\n      }\n    }\n\n    if (foreignToolCallIds.size === 0) return undefined;\n\n    const rewritten: LanguageModelV2Prompt = [];\n    for (const message of prompt) {\n      if (message.role === 'assistant') {\n        const content = message.content.filter(\n          part =>\n            (part.type !== 'tool-call' && part.type !== 'tool-result') || !foreignToolCallIds.has(part.toolCallId),\n        );\n        if (content.length > 0) rewritten.push({ ...message, content });\n        continue;\n      }\n\n      if (message.role === 'tool') {\n        const content = message.content.filter(part => !foreignToolCallIds.has(part.toolCallId));\n        if (content.length > 0) rewritten.push({ ...message, content });\n        continue;\n      }\n\n      rewritten.push(message);\n    }\n    return rewritten;\n  },\n};\n\nconst CLAUDE_VERSION_PATTERN = /claude-(?:(?:opus|sonnet|haiku)-)?(\\d+)(?:[.-](\\d+))?/i;\n\nfunction supportsAssistantPrefill(modelId: string): boolean | undefined {\n  const match = CLAUDE_VERSION_PATTERN.exec(modelId);\n  if (!match) return undefined;\n\n  const major = Number(match[1]);\n  const minor = Number(match[2] ?? 0);\n  return major < 4 || (major === 4 && minor < 6);\n}\n\nconst GEMINI_VERSION_PATTERN = /gemini-(\\d+)/i;\n\nfunction supportsTrailingModelTurn(modelId: string): boolean | undefined {\n  const match = GEMINI_VERSION_PATTERN.exec(modelId);\n  if (!match) return undefined;\n\n  return Number(match[1]) < 3;\n}\n\n/**\n * Detects Anthropic models that removed assistant-message prefill support.\n * Claude 4.6 and later reject assistant-prefill requests, while earlier\n * models retain support. Unknown Anthropic model versions are matched\n * conservatively so a new model cannot silently bypass compatibility guards.\n */\nexport function isMaybeAnthropicWithoutAssistantPrefill(model: unknown): boolean {\n  if (typeof model === 'function') return true;\n\n  if (Array.isArray(model)) {\n    return model.some(entry => isMaybeAnthropicWithoutAssistantPrefill((entry as { model?: unknown }).model ?? entry));\n  }\n\n  if (!isMaybeAnthropic(model)) return false;\n\n  const modelId =\n    typeof model === 'string'\n      ? model\n      : model && typeof model === 'object' && typeof (model as { modelId?: unknown }).modelId === 'string'\n        ? (model as { modelId: string }).modelId\n        : undefined;\n\n  if (!modelId) return true;\n  return supportsAssistantPrefill(modelId) !== true;\n}\n\n/**\n * Detects Google models that reject a request ending on a model turn.\n *\n * Gemini 3 and later return 400 \"Requests ending with a model turn are not\n * supported\"; Gemini 2.x accepted the same prompt, including under native\n * structured output. Unknown Google model versions are matched conservatively\n * so a new model cannot silently bypass compatibility guards.\n *\n * @see https://github.com/mastra-ai/mastra/issues/23320\n */\nexport function isMaybeGoogleWithoutTrailingModelTurn(model: unknown): boolean {\n  if (typeof model === 'function') return true;\n\n  if (Array.isArray(model)) {\n    return model.some(entry => isMaybeGoogleWithoutTrailingModelTurn((entry as { model?: unknown }).model ?? entry));\n  }\n\n  if (getModelProviderFamily(model) !== 'google') return false;\n\n  const modelId =\n    typeof model === 'string'\n      ? model\n      : model && typeof model === 'object' && typeof (model as { modelId?: unknown }).modelId === 'string'\n        ? (model as { modelId: string }).modelId\n        : undefined;\n\n  if (!modelId) return true;\n  return supportsTrailingModelTurn(modelId) !== true;\n}\n\nexport function isMaybeAzure(\n  model:\n    | string\n    | { provider?: string; modelId?: string }\n    | ((...args: any[]) => any)\n    | { model: any; enabled?: boolean }[]\n    | unknown,\n): boolean {\n  if (Array.isArray(model)) {\n    return model.some(entry => isMaybeAzure((entry as { model?: unknown }).model ?? entry));\n  }\n\n  if (model && typeof model === 'object') {\n    const { provider, modelId } = model as { provider?: unknown; modelId?: unknown };\n    if (typeof provider === 'string' && /^(?:azure|azure-openai)(?:\\.[a-z0-9_-]+)?$/i.test(provider)) {\n      return true;\n    }\n\n    return (\n      typeof modelId === 'string' &&\n      (matchesProviderPrefix(modelId, 'azure') || matchesProviderPrefix(modelId, 'azure-openai'))\n    );\n  }\n\n  return matchesProviderPrefix(model, 'azure') || matchesProviderPrefix(model, 'azure-openai');\n}\n\n/**\n * Detects providers that reject a conversation whose first non-system turn is\n * the assistant's: Amazon Bedrock (\"A conversation must start with a user\n * message\") and Google/Vertex Gemini. OpenAI, Anthropic, Groq, Mistral,\n * DeepSeek and Cerebras accept that shape, so they are left alone.\n *\n * @see https://github.com/mastra-ai/mastra/issues/5465\n * @see https://github.com/mastra-ai/mastra/issues/8053\n */\nexport function isMaybeRequiringUserFirstTurn(model: unknown): boolean {\n  return (\n    getModelProviderFamily(model) === 'google' ||\n    matchesProviderPrefix(model, 'amazon') ||\n    matchesProviderPrefix(model, 'amazon-bedrock') ||\n    matchesProviderPrefix(model, 'bedrock')\n  );\n}\n\n/**\n * Inserts a minimal user turn ahead of a leading assistant turn for providers\n * that require conversations to start with the user (see\n * {@link isMaybeRequiringUserFirstTurn}). History windows commonly start on an\n * assistant turn — agents that greet first, or `lastMessages` cutting into a\n * thread — and those providers reject the whole request otherwise.\n */\nexport const ensureUserFirstTurn = {\n  name: 'ensure-user-first-turn',\n  applyToPrompt({\n    prompt,\n    model,\n  }: {\n    prompt: LanguageModelV2Prompt;\n    model: unknown;\n  }): LanguageModelV2Prompt | undefined {\n    if (!isMaybeRequiringUserFirstTurn(model)) return undefined;\n\n    const firstTurnIndex = prompt.findIndex(message => message.role !== 'system');\n    if (firstTurnIndex === -1 || prompt[firstTurnIndex]!.role !== 'assistant') return undefined;\n\n    return [\n      ...prompt.slice(0, firstTurnIndex),\n      { role: 'user', content: [{ type: 'text', text: '.' }] },\n      ...prompt.slice(firstTurnIndex),\n    ];\n  },\n} satisfies CompatRule;\n\n/**\n * Returns the index of the trailing assistant message whose thinking blocks\n * Anthropic verifies byte-for-byte: the last message when it is an assistant\n * message, or the assistant message that only has tool messages after it (an\n * active tool-use continuation). Returns `-1` when no such message exists —\n * e.g. when the prompt ends with a fresh user turn, in which case Anthropic\n * ignores thinking blocks on earlier assistant messages.\n */\nfunction getProtectedAssistantIndex(prompt: LanguageModelV2Prompt): number {\n  for (let i = prompt.length - 1; i >= 0; i--) {\n    const role = prompt[i]!.role;\n    if (role === 'assistant') return i;\n    if (role !== 'tool') return -1;\n  }\n  return -1;\n}\n\n/**\n * Returns a copy of the prompt with selected `reasoning` parts stripped from\n * assistant messages, dropping any assistant message left with no content.\n * Returns `undefined` if no changes were necessary.\n *\n * `skipIndex` excludes one message from stripping — used to protect the\n * trailing assistant message of an active tool-use continuation, which\n * Anthropic requires to be replayed unmodified (\"`thinking` or\n * `redacted_thinking` blocks in the latest assistant message cannot be\n * modified\").\n */\nfunction stripReasoningFromPrompt(\n  prompt: LanguageModelV2Prompt,\n  shouldStrip: (\n    part: Extract<\n      Extract<LanguageModelV2Prompt[number], { role: 'assistant' }>['content'][number],\n      { type: 'reasoning' }\n    >,\n  ) => boolean = () => true,\n  skipIndex = -1,\n): LanguageModelV2Prompt | undefined {\n  let mutated = false;\n  const next: LanguageModelV2Prompt = [];\n  for (let index = 0; index < prompt.length; index++) {\n    const message = prompt[index]!;\n    if (\n      index === skipIndex ||\n      message.role !== 'assistant' ||\n      typeof message.content === 'string' ||\n      !Array.isArray(message.content)\n    ) {\n      next.push(message);\n      continue;\n    }\n    const filtered = message.content.filter(part => part.type !== 'reasoning' || !shouldStrip(part as any));\n    if (filtered.length === message.content.length) {\n      next.push(message);\n      continue;\n    }\n    mutated = true;\n    // A reasoning-only turn is emptied by the strip. Processors run after\n    // conversion, so the empty-content filter in MessageList no longer\n    // applies — Anthropic rejects empty assistant content, so drop the\n    // message itself (same idiom as anthropicStripForeignSignedReasoning).\n    if (filtered.length === 0) continue;\n    next.push({ ...message, content: filtered });\n  }\n  return mutated ? next : undefined;\n}\n\nfunction isAnthropicReasoningPart(part: { providerOptions?: unknown; providerMetadata?: unknown }): boolean {\n  const providerOptions = part.providerOptions;\n  if (providerOptions && typeof providerOptions === 'object' && 'anthropic' in providerOptions) return true;\n\n  const providerMetadata = part.providerMetadata;\n  if (providerMetadata && typeof providerMetadata === 'object' && 'anthropic' in providerMetadata) return true;\n\n  return false;\n}\n\nfunction getProtectedAnthropicAssistantIndex(prompt: LanguageModelV2Prompt): number {\n  const index = getProtectedAssistantIndex(prompt);\n  if (index === -1) return -1;\n\n  const message = prompt[index]!;\n  if (message.role !== 'assistant' || !Array.isArray(message.content)) return -1;\n\n  return message.content.some(part => part.type === 'reasoning' && isAnthropicReasoningPart(part)) ? index : -1;\n}\n\nfunction getProviderMetadataForProvider(metadata: unknown, provider: string): Record<string, unknown> | undefined {\n  if (!metadata || typeof metadata !== 'object') return undefined;\n  const value = (metadata as Record<string, unknown>)[provider];\n  return value && typeof value === 'object' ? (value as Record<string, unknown>) : undefined;\n}\n\nfunction isEmptySignedReasoning(part: MastraDBMessage['content']['parts'][number]): boolean {\n  if (part.type !== 'reasoning') return false;\n  const signature = getProviderMetadataForProvider(part.providerMetadata, 'anthropic')?.signature;\n  if (typeof signature !== 'string' || signature.length === 0) return false;\n  const hasText =\n    (typeof part.reasoning === 'string' && part.reasoning.length > 0) ||\n    (part.details ?? []).some(detail => detail.type === 'text' && detail.text.length > 0);\n  return !hasText;\n}\n\n/**\n * Cerebras's API rejects assistant messages carrying a `reasoning_content`\n * field with HTTP 400 (`property '...reasoning_content' is unsupported`).\n *\n * Starting in `@ai-sdk/openai-compatible@1.0.32` (https://github.com/vercel/ai/pull/12049),\n * which `@ai-sdk/cerebras` depends on, reasoning parts on assistant messages\n * are unconditionally serialized as `reasoning_content` on outbound requests.\n * That breaks multi-turn tool calls with reasoning enabled (e.g.\n * `cerebras/zai-glm-4.7`) on the second-or-later assistant turn.\n *\n * This rule preemptively strips `reasoning` parts from assistant messages\n * in the outbound prompt when the resolved model is Cerebras. The strip\n * runs in `processLLMRequest` so it affects only what is sent to Cerebras —\n * the persisted message list (memory, UI, observability) keeps the full\n * reasoning trace, and other providers (e.g. Z.ai's coding-plan endpoint,\n * which *requires* `reasoning_content` echoed back for its preserved-thinking\n * feature) are unaffected because the rule is provider-scoped.\n *\n * It can't be reactive (`processAPIError`) because the model emits a fresh\n * reasoning part on every turn — a reactive rule would cause one\n * failed-and-retried request per turn.\n *\n * Once https://github.com/vercel/ai/pull/11278 lands a per-provider\n * `sendReasoning` opt-out, this rule can be replaced with `sendReasoning: false`\n * on the cerebras provider config.\n */\nexport const cerebrasStripReasoningContent: CompatRule = {\n  name: 'cerebras-strip-reasoning-content',\n  applyToPrompt({ prompt, model }) {\n    if (!isMaybeCerebras(model)) return undefined;\n    return stripReasoningFromPrompt(prompt);\n  },\n};\n\n/**\n * Legacy records could contain Anthropic signed thinking metadata with an\n * empty reasoning text. Anthropic signs the exact thinking text, so replaying\n * that mismatched pair is rejected with the \"thinking blocks cannot be\n * modified\" 400.\n *\n * Reactive, because an empty text with a signature is not by itself a sign of\n * corruption: Claude 5.x returns exactly that for every thinking block when\n * `display` is left at its default (`omitted`). Stripping those up front would\n * change the prompt prefix on every step and break prompt caching, so the\n * blocks are only dropped, from earlier assistant messages, once Anthropic has\n * actually rejected the history.\n *\n * @see https://github.com/mastra-ai/mastra/issues/28309\n */\nexport const anthropicStripEmptySignedReasoningContent: CompatRule = {\n  name: 'anthropic-strip-empty-signed-reasoning-content',\n  errorPatterns: [/thinking`? or `?redacted_thinking`? blocks in the latest assistant message cannot be modified/i],\n  fix(messages) {\n    let mutated = false;\n    // The trailing assistant message of an active tool continuation is the one\n    // Anthropic requires unmodified, so it is never touched.\n    const protectedIndex = messages.at(-1)?.role === 'assistant' ? messages.length - 1 : -1;\n\n    messages.forEach((message, index) => {\n      const parts = message.content?.parts;\n      if (message.role !== 'assistant' || index === protectedIndex || !parts?.length) return;\n\n      const kept = parts.filter(part => !isEmptySignedReasoning(part));\n      if (kept.length === parts.length) return;\n      parts.splice(0, parts.length, ...kept);\n      mutated = true;\n    });\n\n    return mutated;\n  },\n};\n\n/**\n * Anthropic accepts its own thinking/reasoning history, but rejects reasoning\n * parts emitted by other providers. Strip only foreign reasoning parts at the\n * Anthropic provider boundary so persisted history remains intact and native\n * Anthropic thinking can still round-trip.\n */\nexport const anthropicStripForeignReasoningContent: CompatRule = {\n  name: 'anthropic-strip-foreign-reasoning-content',\n  applyToPrompt({ prompt, model }) {\n    if (!isMaybeAnthropic(model)) return undefined;\n    return stripReasoningFromPrompt(\n      prompt,\n      part => !isAnthropicReasoningPart(part),\n      getProtectedAnthropicAssistantIndex(prompt),\n    );\n  },\n};\n\n/**\n * Replays of signed `thinking`/`redacted_thinking` blocks to a provider other\n * than the one that signed them are rejected — Anthropic returns\n * `Invalid \\`signature\\` in \\`thinking\\` block`.\n *\n * Several providers are served through `@ai-sdk/anthropic` and therefore write\n * their reasoning metadata under the same `anthropic` key — Kimi For Coding\n * talks to `api.kimi.com` over the Anthropic wire format — so a signature's\n * `anthropic` key alone cannot tell which provider signed it. The durable\n * provenance is the `provider` each assistant turn was stamped with by\n * `buildResponseModelMetadata`, which only the persisted message list carries.\n *\n * Reasoning parts whose signature came from a turn stamped with a provider\n * different from the current target are dropped from the outbound prompt, so\n * the rejection never happens. Unstamped history is left untouched — turns\n * persisted before their provider had a distinct identity stay ambiguous and\n * are forwarded as-is. Turns emptied of all content by the drop are removed\n * from the prompt (Anthropic rejects empty assistant content).\n */\nexport const anthropicStripForeignSignedReasoning: CompatRule = {\n  name: 'anthropic-strip-foreign-signed-reasoning',\n  applyToPrompt({ prompt, model, messageList }) {\n    if (!messageList) return undefined;\n    const targetProvider = getModelProviderId(model);\n    if (!targetProvider) return undefined;\n\n    // Collect the signatures of every signed reasoning block whose origin\n    // turn was stamped with a provider different from this request's target.\n    const foreign = new Map<string, string>(); // signature -> origin provider\n    for (const dbMessage of messageList.get.all.db()) {\n      if (dbMessage.role !== 'assistant') continue;\n      if (dbMessage.content?.format !== 2) continue;\n      const origin = dbMessage.content.metadata?.provider;\n      if (typeof origin !== 'string' || origin === targetProvider) continue;\n      for (const part of dbMessage.content.parts ?? []) {\n        if (part.type !== 'reasoning') continue;\n        const anthropic = part.providerMetadata?.anthropic as\n          | { signature?: unknown; redactedData?: unknown }\n          | undefined;\n        for (const value of [anthropic?.signature, anthropic?.redactedData]) {\n          if (typeof value === 'string' && value && !foreign.has(value)) foreign.set(value, origin);\n        }\n      }\n    }\n    if (foreign.size === 0) return undefined;\n\n    let dropped = 0;\n    const next: LanguageModelV2Prompt = [];\n    for (const message of prompt) {\n      if (message.role !== 'assistant' || !Array.isArray(message.content)) {\n        next.push(message);\n        continue;\n      }\n      const content = message.content.filter(part => {\n        if (part.type !== 'reasoning') return true;\n        const anthropic = part.providerOptions?.anthropic as\n          | { signature?: unknown; redactedData?: unknown }\n          | undefined;\n        const signature = anthropic?.signature ?? anthropic?.redactedData;\n        if (typeof signature === 'string' && foreign.has(signature)) {\n          dropped++;\n          return false;\n        }\n        return true;\n      });\n      if (content.length === message.content.length) {\n        next.push(message);\n        continue;\n      }\n      // A turn that held only foreign signed thinking is emptied by the drop.\n      // Processors run after conversion, so the empty-content filter in\n      // MessageList no longer applies — Anthropic rejects empty assistant\n      // content, so drop the message itself (same idiom as\n      // stripForeignProviderExecutedTools).\n      if (content.length > 0) next.push({ ...message, content });\n    }\n\n    return dropped > 0 ? next : undefined;\n  },\n};\n\nconst SYSTEM_REMINDER_OPEN_TAG = /<system-reminder(?=\\s|\\/?>)([^>]*)>/g;\nconst SYSTEM_REMINDER_CLOSE_TAG = /<\\/system-reminder>/g;\n\nfunction rewriteSystemReminderTags(text: string): string {\n  return text\n    .replace(SYSTEM_REMINDER_OPEN_TAG, '<memory-context$1>')\n    .replace(SYSTEM_REMINDER_CLOSE_TAG, '</memory-context>');\n}\n\n/**\n * Azure OpenAI's content moderation can classify `<system-reminder>` wrappers\n * in user messages as prompt injection. Rename the wrapper at the provider\n * boundary while leaving persisted history and other providers unchanged.\n */\nexport const azureSystemReminderTransform: CompatRule = {\n  name: 'azure-system-reminder-transform',\n  applyToPrompt({ prompt, model }) {\n    if (!isMaybeAzure(model)) return undefined;\n\n    let mutated = false;\n    const next: LanguageModelV2Prompt = prompt.map(message => {\n      if (message.role === 'system') {\n        const content = rewriteSystemReminderTags(message.content);\n        if (content === message.content) return message;\n        mutated = true;\n        return { ...message, content };\n      }\n\n      if (message.role !== 'user') return message;\n\n      let messageMutated = false;\n      const content = message.content.map(part => {\n        if (part.type !== 'text') return part;\n        const text = rewriteSystemReminderTags(part.text);\n        if (text === part.text) return part;\n        mutated = true;\n        messageMutated = true;\n        return { ...part, text };\n      });\n\n      return messageMutated ? { ...message, content } : message;\n    });\n\n    return mutated ? next : undefined;\n  },\n};\n\n// ---------------------------------------------------------------------------\n// Built-in rule: orphaned Responses message itemId (OpenAI / Azure)\n// ---------------------------------------------------------------------------\n\nfunction hasReasoningPart(message: MastraDBMessage): boolean {\n  return (message.content?.parts ?? []).some(p => p.type === 'reasoning');\n}\n\n/**\n * True when `message` looks like the leading half of a turn that storage split across two\n * assistant rows: it carries a reasoning item and has not yet produced text of its own. A\n * following text row is then covered by that reasoning item.\n *\n * Deliberately not \"has any reasoning part\" — a previous row that already paired its own\n * reasoning with its own text says nothing about the row after it, and treating it as cover\n * would leave a genuine orphan unrepaired. The retry would then hit the same 400, and\n * `processAPIError` stops after its second pass, turning a recoverable turn into a hard failure.\n */\nfunction isUnpairedReasoningRow(message: MastraDBMessage): boolean {\n  const parts = message.content?.parts ?? [];\n  return parts.some(p => p.type === 'reasoning') && !parts.some(p => p.type === 'text');\n}\n\n/**\n * Strips `itemId` and its result-side partner from every Responses namespace a\n * part carries, in both metadata containers, leaving every other field (cache\n * counts, reasoning-token counts, logprobs) intact. Mirrors the narrow\n * destructure in `client-sdks/ai-sdk/src/helpers.ts` (PR #23323).\n *\n * {@link RESPONSE_RESULT_ITEM_ID_KEY} has to go with it: a merged tool part\n * keeps the result half of the pair under that key, and\n * `splitResponsesToolItemReferences` turns it back into an `itemId` on the\n * tool-result part during conversion. Dropping only `itemId` would leave a\n * live reference into the very response that was rejected.\n *\n * Both `providerMetadata` and `providerOptions` are cleared because\n * {@link getResponseProviderItemIdFromPart} reads an id from either, so\n * leaving one behind would report a part as still item-bearing — and would\n * leave the unsatisfiable reference in the prompt, which is the whole failure.\n *\n * Returns true when it removed an id.\n */\nfunction stripResponseItemIds(part: MastraMessagePart): boolean {\n  const containers = [\n    (part as { providerMetadata?: Record<string, unknown> }).providerMetadata,\n    (part as { providerOptions?: Record<string, unknown> }).providerOptions,\n  ];\n\n  let stripped = false;\n  for (const container of containers) {\n    if (!container) continue;\n    for (const provider of RESPONSE_ITEM_ID_PROVIDERS) {\n      const namespace = container[provider] as Record<string, unknown> | undefined;\n      if (!namespace) continue;\n      if (!('itemId' in namespace) && !(RESPONSE_RESULT_ITEM_ID_KEY in namespace)) continue;\n      const { itemId: _itemId, [RESPONSE_RESULT_ITEM_ID_KEY]: _resultItemId, ...rest } = namespace;\n      container[provider] = rest;\n      stripped = true;\n    }\n  }\n  return stripped;\n}\n\n/**\n * OpenAI's Responses API replays a persisted assistant message by reference\n * (`item_reference`) when the message carries an `itemId` (`msg_…`). If that\n * message has no accompanying `reasoning` item, the request is rejected with a\n * non-retryable 400:\n *\n * ```\n * Item 'msg_…' of type 'message' was provided without its required 'reasoning' item: 'rs_…'\n * ```\n *\n * Because the offending message is already persisted, that 400 repeats on every\n * subsequent turn, and the thread stops working. This rule is a recovery\n * seatbelt for histories that are *already* corrupted: dropping the `itemId`\n * makes the message replay by value instead of by reference, which OpenAI\n * accepts. The content the user sees is unchanged.\n *\n * The repair is in-memory for the current turn: a message sourced from storage\n * is not re-drained, so a later turn on the same thread spends one rejected\n * request before recovering again. Same property as `anthropicToolIdFormat`.\n *\n * Reactive by design — it fires only after OpenAI has actually rejected the\n * request, so a legitimately reasoning-free message (e.g.\n * `reasoning.effort: 'none'`, or a non-reasoning model) is untouched on any\n * thread that has not already hit this 400. Once it has, see the collateral\n * note below.\n *\n * Deliberately narrow:\n * - Matches only the `of type 'message'` phrasing. The sibling `function_call`\n *   (`fc_…`) variant is a different failure, addressed by PR #19408. Matching\n *   narrowly is not the same as repairing narrowly, though: once a message is\n *   established as an orphan, every item reference it carries is unsatisfiable\n *   for the same reason, so the repair covers all of them. A message whose\n *   `msg_…` id was dropped while its `fc_…` id stayed would simply fail on the\n *   next item in the list, spending the one available retry to arrive at the\n *   same error.\n * - Strips only the item-reference keys (`itemId` and its result-side partner\n *   `resultItemId`); all other fields in the namespace survive.\n * - Reads and strips through the shared Responses helpers, so the `azure`\n *   namespace is covered on the same footing as `openai` — the repo treats\n *   them as one Responses family, and Azure raises this same 400.\n * - Skips a message whose reasoning lives on the immediately preceding\n *   assistant row, when that row has reasoning and no text of its own. Stored\n *   history can split one turn across adjacent assistant rows (adjacent rows\n *   are merged when streamed, but not when loaded from storage), and in that\n *   case the reasoning item *is* present in the prompt — stripping the id\n *   there would fix nothing and would discard a valid reference. A preceding\n *   row that already paired its own reasoning with its own text is not cover\n *   and does not suppress the repair.\n *\n * Not covered by that guard, deliberately: the `assistant[reasoning, tool-call]\n * → tool[result] → assistant[text]` shape, where the preceding entry is a tool\n * message. If OpenAI rejected the text item there, its reference is genuinely\n * unsatisfiable and stripping is the right repair.\n *\n * The rule repairs every orphan-shaped message in the history rather than only\n * the id named in the error, because `fix` does not receive the error and the\n * error names only the first item OpenAI tripped over. Healing that one id\n * would trade a permanent failure for N sequential ones, and there is a single\n * retry available, not N.\n *\n * The cost of that breadth: in a thread that mixes a reasoning model with a\n * non-reasoning Responses model, the non-reasoning turns are also orphan-shaped\n * (an `itemId`, no reasoning) but are perfectly valid, and they lose their item\n * references too. Ordinary text and tool parts still replay correctly — by\n * value instead of by reference — so for them the effect is a lost item\n * reference, not a failure.\n *\n * One part type pays more than a reference. A hosted `tool_search` call cannot\n * be replayed by value at all, so `isUnreplayableHostedToolSearchPart`\n * (`output-converter.ts`) drops it from the prompt once its ids are gone. On a\n * genuinely orphaned message that is the right outcome — the ids pointed into\n * the rejected response. On a swept-along valid message it costs the model that\n * search result, and it would have to search again. That is accepted: the\n * asymmetry is still deliberate, because under-stripping ends the turn outright\n * while over-stripping costs a reference, or at worst one hosted search.\n *\n * Known limitation: the guard reasons about message *shape*, because the\n * required `rs_…` id named in the error is not available to `fix`. A turn whose\n * reasoning row belongs to a different turn could in principle be skipped\n * when it should have been repaired. That case degrades to today's behavior — the turn\n * fails as it already does — so the guard can cost a recovery, never cause a\n * new failure.\n *\n * This is a seatbelt, not the cure: the path that produces these orphans is\n * fixed separately in the processor-retry rollback (#22291).\n */\nexport const openaiOrphanItemId: CompatRule = {\n  name: 'openai-orphan-item-id',\n  errorPatterns: [/Item '[^']*' of type 'message' was provided without its required 'reasoning' item/i],\n  fix(messages) {\n    let mutated = false;\n\n    messages.forEach((message, index) => {\n      if (message.role !== 'assistant') return;\n\n      const parts = message.content?.parts;\n      if (!parts?.length) return;\n      if (hasReasoningPart(message)) return;\n\n      // Split-history guard: the reasoning item for this turn may sit on the\n      // preceding assistant row, in which case the reference is satisfiable.\n      const previous = messages[index - 1];\n      if (previous?.role === 'assistant' && isUnpairedReasoningRow(previous)) return;\n\n      for (const part of parts) {\n        if (!getResponseProviderItemIdFromPart(part)) continue;\n        mutated = stripResponseItemIds(part) || mutated;\n      }\n    });\n\n    return mutated;\n  },\n};\n\n// ---------------------------------------------------------------------------\n// Built-in rule: Anthropic orphaned thinking step (reactive)\n// ---------------------------------------------------------------------------\n\n/**\n * Removes steps that hold nothing but reasoning when more assistant content\n * follows them. The step's other parts were lost (older `@mastra/memory`\n * releases stripped an `updateWorkingMemory` call and kept its thinking), so\n * `@ai-sdk/anthropic` merges the leftover signed thinking into the next\n * assistant step — a shape Anthropic rejects on every later turn.\n *\n * Reactive (matches Anthropic's \"cannot be modified\" 400); a recovery seatbelt\n * for history saved before the strip was fixed.\n *\n * @see https://github.com/mastra-ai/mastra/issues/22798\n */\nexport const anthropicOrphanedThinkingStep: CompatRule = {\n  name: 'anthropic-orphaned-thinking-step',\n  errorPatterns: [/thinking`? or `?redacted_thinking`? blocks in the latest assistant message cannot be modified/i],\n  fix(messages) {\n    let mutated = false;\n\n    messages.forEach((message, index) => {\n      const parts = message.content?.parts;\n      if (message.role !== 'assistant' || !parts?.length) return;\n\n      const followedByAssistant = messages[index + 1]?.role === 'assistant';\n      // A step starts at a `step-start` part, or where a tool part is followed by a\n      // non-tool part (the boundary prompt conversion uses when markers are missing).\n      const steps: (typeof parts)[] = [];\n      parts.forEach((part, i) => {\n        const previous = parts[i - 1];\n        const startsStep =\n          part.type === 'step-start' || (previous?.type === 'tool-invocation' && part.type !== 'tool-invocation');\n        if (startsStep || steps.length === 0) steps.push([]);\n        steps[steps.length - 1]!.push(part);\n      });\n\n      const kept = steps.filter((step, i) => {\n        const content = step.filter(\n          part => part.type !== 'step-start' && !(part.type === 'text' && !part.text?.trim()),\n        );\n        const reasoningOnly = content.length > 0 && content.every(part => part.type === 'reasoning');\n        return !reasoningOnly || (i === steps.length - 1 && !followedByAssistant);\n      });\n\n      if (kept.length === steps.length) return;\n      parts.splice(0, parts.length, ...kept.flat());\n      mutated = true;\n    });\n\n    return mutated;\n  },\n};\n\n// ---------------------------------------------------------------------------\n// Built-in rule: single leading system message for Chat Completions\n// ---------------------------------------------------------------------------\n\n/**\n * Merges the leading system messages of a Chat Completions request into one.\n *\n * Whether a server accepts several system messages depends on the host's chat template, not the\n * model or provider: the same Qwen3.5 weights are accepted by some hosts and rejected with\n * `System message must be at the beginning` by others. One leading system message is valid\n * everywhere.\n *\n * Applies when the API provider id ends in `.chat` (`openai.chat`, `groq.chat`, `<name>.chat`\n * from `createOpenAICompatible`, ...). Native APIs with a dedicated system field (`anthropic`,\n * `google.generative-ai`, `bedrock`) and Responses APIs never do. Prompts are left unchanged when\n * any merged message other than the last carries `providerOptions` (e.g. a cache breakpoint),\n * since merging would drop it.\n *\n * @see https://github.com/mastra-ai/mastra/issues/25435\n */\nexport const chatCompletionsSingleSystemMessage: CompatRule = {\n  name: 'chat-completions-single-system-message',\n  applyToPrompt({ prompt, model, apiProviderId }) {\n    if (!(apiProviderId ?? getModelProviderId(model))?.endsWith('.chat')) return undefined;\n\n    let leading = 0;\n    while (leading < prompt.length && prompt[leading]!.role === 'system') leading++;\n    if (leading < 2) return undefined;\n\n    const leadingMessages = prompt.slice(0, leading) as Extract<LanguageModelV2Prompt[number], { role: 'system' }>[];\n    if (leadingMessages.slice(0, -1).some(m => m.providerOptions)) return undefined;\n\n    const content = leadingMessages\n      .map(m => m.content)\n      .filter(text => text.length > 0)\n      .join('\\n\\n');\n    const { providerOptions } = leadingMessages[leading - 1]!;\n    return [{ role: 'system', content, ...(providerOptions ? { providerOptions } : {}) }, ...prompt.slice(leading)];\n  },\n};\n\n// ---------------------------------------------------------------------------\n// Built-in rule: tool calls without input\n// ---------------------------------------------------------------------------\n\n/**\n * Sends an assistant tool call that has no input (`undefined` or `null`) as `{}`.\n *\n * A call whose arguments could not be parsed is stored as an `output-error` tool part with no\n * `args`. Replayed as-is, providers reject every later request on the thread (Anthropic:\n * `tool_use.input: Field required`; OpenAI-compatible: `function.arguments must be defined`).\n * The error result stays paired with the call; only the call's input is filled in. An empty string\n * is a real stored input, not a missing one, and is left as it is.\n *\n * Applies to every provider, runs in `processLLMRequest` so the stored message keeps its shape.\n */\nexport const toolCallEmptyInput: CompatRule = {\n  name: 'tool-call-empty-input',\n  applyToPrompt({ prompt }) {\n    const isEmpty = (part: { type: string; input?: unknown }) =>\n      part.type === 'tool-call' && (part.input === undefined || part.input === null);\n    if (!prompt.some(m => m.role === 'assistant' && Array.isArray(m.content) && m.content.some(isEmpty))) {\n      return undefined;\n    }\n\n    return prompt.map(message =>\n      message.role === 'assistant' && Array.isArray(message.content)\n        ? { ...message, content: message.content.map(part => (isEmpty(part) ? { ...part, input: {} } : part)) }\n        : message,\n    ) as LanguageModelV2Prompt;\n  },\n};\n\n// ---------------------------------------------------------------------------\n// Default rule set\n// ---------------------------------------------------------------------------\n\n/**\n * All built-in compat rules. Extend by passing additional rules to the\n * `ProviderHistoryCompat` constructor.\n */\nexport const DEFAULT_COMPAT_RULES: CompatRule[] = [\n  stripForeignProviderExecutedTools,\n  anthropicToolIdFormat,\n  cerebrasStripReasoningContent,\n  // Both reactive Anthropic rules match the same \"cannot be modified\" 400 and `processAPIError` stops\n  // at the first rule that changes history. The orphaned-step repair goes first: it only removes a\n  // step that is provably broken, whereas the empty-signed strip also removes blocks that may be\n  // valid (Claude 5.x), so it must only run when no orphaned step explains the 400.\n  anthropicOrphanedThinkingStep,\n  anthropicStripEmptySignedReasoningContent,\n  anthropicStripForeignReasoningContent,\n  anthropicStripForeignSignedReasoning,\n  azureSystemReminderTransform,\n  openaiOrphanItemId,\n  chatCompletionsSingleSystemMessage,\n  toolCallEmptyInput,\n  // Last, so it sees the prompt after other rules have dropped emptied turns.\n  ensureUserFirstTurn,\n];\n\n// ---------------------------------------------------------------------------\n// Processor\n// ---------------------------------------------------------------------------\n\n/**\n * Handles provider-specific history incompatibilities by applying a registry\n * of {@link CompatRule}s. Rules can rewrite the outbound prompt preemptively\n * via `processLLMRequest`, or react to non-retryable API rejections via\n * `processAPIError`.\n *\n * Built-in rules:\n * - **anthropic-tool-id-format** — rewrites tool-call IDs that contain\n *   characters outside `[a-zA-Z0-9_-]` (e.g. `.` or `:` from other\n *   providers). Preemptive; runs in `processLLMRequest` so the persisted\n *   message list keeps its original IDs. Both the call and its paired result\n *   are rewritten together, and a sanitized ID that would collide with an ID\n *   already in the prompt gets a `_2`/`_3`… suffix. The reactive fallback\n *   (matching a 400 response body and retrying with sanitized IDs) covers\n *   providers the preemptive check doesn't recognize, such as Vertex-hosted\n *   Claude.\n * - **cerebras-strip-reasoning-content** — strips `reasoning` parts from\n *   assistant messages in the outbound prompt when the resolved model is\n *   Cerebras, to avoid the `@ai-sdk/openai-compatible@>=1.0.32` regression\n *   that serializes them as `reasoning_content` (a field Cerebras's API\n *   rejects). Preemptive; runs in `processLLMRequest` so the persisted\n *   message list keeps the reasoning trace.\n * - **anthropic-strip-empty-signed-reasoning-content** — strips legacy\n *   Anthropic signed reasoning blocks whose text was lost before replay.\n *   Reactive (matches the \"thinking blocks cannot be modified\" 400), because\n *   Claude 5.x returns empty-text signed blocks as normal output and they must\n *   be replayed untouched to keep the prompt cache.\n * - **anthropic-strip-foreign-reasoning-content** — strips non-Anthropic\n *   `reasoning` parts from assistant messages in the outbound prompt when the\n *   resolved model is Anthropic. Anthropic-native reasoning parts are kept.\n * - **anthropic-strip-foreign-signed-reasoning** — drops signed thinking\n *   blocks from the outbound prompt when their origin turn was stamped with a\n *   provider different from the current target (preemptive). Turns emptied of\n *   all content by the drop are removed from the prompt. Unstamped history is\n *   left untouched.\n * - **openai-orphan-item-id** — drops the Responses `itemId` (`openai` and\n *   `azure` namespaces alike) from every item-bearing part of an assistant\n *   message that carries one but has no `reasoning` part, so it replays by\n *   value instead of as an unsatisfiable `item_reference`. Reactive (matches\n *   the specific `of type 'message' … without its required 'reasoning' item`\n *   400); a recovery seatbelt for already-corrupted history.\n * - **anthropic-orphaned-thinking-step** — drops steps left with only signed\n *   reasoning when more assistant content follows them, so Anthropic doesn't\n *   see that thinking merged into the next step. Reactive (matches the\n *   \"thinking blocks ... cannot be modified\" 400); a recovery seatbelt for\n *   already-corrupted history.\n * - **chat-completions-single-system-message** — merges the leading system\n *   messages into one for Chat Completions providers (API provider id ending\n *   in `.chat`), whose hosted chat templates often reject a second system\n *   message. Skipped when an earlier one carries its own `providerOptions`.\n *   Preemptive.\n * - **tool-call-empty-input** — sends an assistant tool call whose input is\n *   `undefined` or `null` as `{}`, keeping its paired result, so a stored\n *   call with unparseable arguments can't make every later request fail.\n *   Preemptive; the stored message keeps its shape.\n * - **ensure-user-first-turn** — inserts a `.` user turn ahead of a leading\n *   assistant turn for Amazon Bedrock and Google/Vertex, which reject\n *   assistant-first conversations. Preemptive; the turn is never persisted.\n *\n * To add custom rules, pass them to the constructor:\n * ```ts\n * new ProviderHistoryCompat({\n *   additionalRules: [myCustomRule],\n * })\n * ```\n */\nexport class ProviderHistoryCompat implements Processor<'provider-history-compat'> {\n  readonly id = 'provider-history-compat' as const;\n  readonly name = 'Provider History Compat';\n\n  private rules: CompatRule[];\n\n  constructor(opts?: { additionalRules?: CompatRule[] }) {\n    this.rules = [...DEFAULT_COMPAT_RULES, ...(opts?.additionalRules ?? [])];\n  }\n\n  processLLMRequest({ prompt, model, apiProviderId, messageList }: ProcessLLMRequestArgs): ProcessLLMRequestResult {\n    let current = prompt;\n    let mutated = false;\n    for (const rule of this.rules) {\n      if (!rule.applyToPrompt) continue;\n      const next = rule.applyToPrompt({ prompt: current, model, apiProviderId, messageList });\n      if (next) {\n        current = next;\n        mutated = true;\n      }\n    }\n    return mutated ? { prompt: current } : undefined;\n  }\n\n  async processAPIError({\n    error,\n    messageList,\n    retryCount,\n  }: ProcessAPIErrorArgs): Promise<ProcessAPIErrorResult | void> {\n    // Two passes, not one: a legacy history can need two repairs that raise the same error (an\n    // orphaned thinking step and an empty signed block), and only the first rule that changes\n    // history runs per pass. A pass retries only when a rule actually changed something, so\n    // the second pass is a no-op once nothing is left to repair.\n    if (retryCount > 1) return;\n\n    const messages = messageList.get.all.db();\n\n    for (const rule of this.rules) {\n      if (!rule.fix) continue;\n      if (matchesRule(error, rule)) {\n        const changed = rule.fix(messages);\n        if (changed) {\n          return { retry: true };\n        }\n      }\n    }\n  }\n}\n","import type { MastraDBMessage, MessageList } from '../agent/message-list';\nimport {\n  isMaybeAnthropicWithoutAssistantPrefill,\n  isMaybeGoogleWithoutTrailingModelTurn,\n} from './provider-history-compat';\nimport type { Processor, ProcessInputStepArgs, ProcessInputStepResult } from './index';\n\nconst SETTLED_TOOL_STATES = new Set(['result', 'output-error']);\n\n/** Metadata key that marks the synthetic user turn appended by {@link TrailingAssistantGuard}. */\nexport const TRAILING_ASSISTANT_GUARD_CONTINUATION_KEY = 'trailingAssistantGuardContinuation';\n\n/** Whether `message` is the synthetic user turn appended by {@link TrailingAssistantGuard}. */\nexport function isTrailingAssistantGuardContinuation(message: MastraDBMessage): boolean {\n  return message.content.metadata?.[TRAILING_ASSISTANT_GUARD_CONTINUATION_KEY] === true;\n}\n\n/**\n * Drop the guard's synthetic user turn once the step's prompt has been built. It only has\n * to reach the provider; left in the list it sits between the trailing assistant message\n * and the reply, so the reply is saved as a separate assistant message (#27520).\n */\nexport function removeTrailingAssistantGuardContinuations(messageList: MessageList): void {\n  const ids = messageList.get.all\n    .db()\n    .filter(isTrailingAssistantGuardContinuation)\n    .map(message => message.id);\n  if (ids.length > 0) messageList.removeByIds(ids);\n}\n\n/**\n * Whether a step needs `TrailingAssistantGuard` attached.\n *\n * True when the model as configured rejects a prompt ending on a model turn\n * (Anthropic 4.6+ assistant prefill, Gemini 3+), or when any input processors are\n * configured, since a processor may swap `model` mid-step. In the latter case the\n * attach is speculative: the runner asks {@link TrailingAssistantGuard.appliesTo}\n * against the final step model before running the guard, and skips it entirely\n * (no processor span) when the provider does not need it.\n *\n * Used both where the `ProcessorRunner` is created for a step and where the\n * runner assembles its processor list, so an agent with no input processors\n * still gets a runner and that runner still appends the guard.\n */\nexport function needsTrailingAssistantGuard(model: unknown, inputProcessors: readonly unknown[]): boolean {\n  return (\n    inputProcessors.length > 0 ||\n    isMaybeAnthropicWithoutAssistantPrefill(model) ||\n    isMaybeGoogleWithoutTrailingModelTurn(model)\n  );\n}\n\n/**\n * Whether the guard can have any effect for `model`. Cheap provider/version\n * check the runner uses to skip a speculatively attached guard without\n * recording a processor span for it.\n */\nexport function trailingAssistantGuardAppliesTo(model: unknown): boolean {\n  return isMaybeGoogleWithoutTrailingModelTurn(model) || isMaybeAnthropicWithoutAssistantPrefill(model);\n}\n\n/**\n * Whether the prompt built from this message will end on a model turn.\n *\n * Mirrors prompt conversion: a settled tool invocation becomes an assistant\n * tool-call turn followed by a tool-result turn, so the prompt already ends on a\n * non-model turn and appending a user message would inject a spurious turn into\n * every agentic-loop step after a tool call. A still-pending invocation is either\n * dropped from the prompt (default `MessageList` behaviour) — in which case the\n * preceding content decides — or paired with a placeholder result, which also\n * ends on a tool turn. `step-start` parts are loop markers, not content.\n */\nfunction endsOnModelTurn(message: MastraDBMessage, pendingCallsDropped: boolean): boolean {\n  if (message.role !== 'assistant') return false;\n\n  for (let index = message.content.parts.length - 1; index >= 0; index--) {\n    const part = message.content.parts[index]!;\n    if (part.type === 'step-start') continue;\n    if (part.type !== 'tool-invocation') return true;\n    if (SETTLED_TOOL_STATES.has(part.toolInvocation.state) || !pendingCallsDropped) return false;\n  }\n\n  // Nothing survives conversion; the message is dropped from the prompt entirely.\n  return false;\n}\n\n/**\n * Guards against requests that would end on an assistant message for providers\n * that reject that shape.\n *\n * - Anthropic reads a trailing assistant message as response prefill. That is a\n *   legitimate feature outside structured output, so the guard only intervenes when\n *   native structured output (`responseFormat`) is in play, where Anthropic rejects it.\n * - Gemini 3 and later return 400 \"Requests ending with a model turn are not\n *   supported\" for any request, structured output or not, so the guard always\n *   intervenes for those models.\n *\n * In both cases a short user message is appended so the request ends on a user turn.\n * Provider and version gating for *attaching* the processor lives at the attach\n * sites; this class only decides when the appended turn is needed.\n *\n * @see https://github.com/mastra-ai/mastra/issues/12800\n * @see https://github.com/mastra-ai/mastra/issues/23320\n */\nexport class TrailingAssistantGuard implements Processor<'trailing-assistant-guard'> {\n  readonly id = 'trailing-assistant-guard' as const;\n  readonly name = 'Trailing Assistant Guard';\n\n  appliesTo(model: unknown): boolean {\n    return trailingAssistantGuardAppliesTo(model);\n  }\n\n  processInputStep({\n    messages,\n    messageList,\n    structuredOutput,\n    model,\n  }: ProcessInputStepArgs): ProcessInputStepResult | undefined {\n    const willUseResponseFormat = Boolean(\n      structuredOutput?.schema && !structuredOutput?.model && !structuredOutput?.jsonPromptInjection,\n    );\n    const rejectsTrailingModelTurn = isMaybeGoogleWithoutTrailingModelTurn(model);\n\n    if (!rejectsTrailingModelTurn && !(willUseResponseFormat && this.appliesTo(model))) return;\n\n    const lastMessage = messages[messages.length - 1];\n    if (!lastMessage || !endsOnModelTurn(lastMessage, messageList?.dropsIncompleteToolCalls ?? true)) return;\n\n    // MessageList orders by createdAt and may have nudged the trailing assistant\n    // message ahead of wall-clock time to keep it after its predecessor. Timestamp\n    // strictly after it so the appended turn cannot sort before the message it guards.\n    const lastCreatedAt = new Date(lastMessage.createdAt).getTime();\n    const createdAt = new Date(Math.max(Date.now(), (Number.isNaN(lastCreatedAt) ? 0 : lastCreatedAt) + 1));\n\n    const continuation: MastraDBMessage = {\n      id: globalThis.crypto.randomUUID(),\n      role: 'user',\n      content: {\n        format: 2,\n        parts: [{ type: 'text', text: willUseResponseFormat ? 'Generate the structured response.' : 'Continue.' }],\n        metadata: { [TRAILING_ASSISTANT_GUARD_CONTINUATION_KEY]: true },\n      },\n      createdAt,\n    };\n\n    // The synthetic turn exists only to satisfy the provider on this request. Adding it as\n    // `context` keeps it in the prompt but out of the messages memory persists, so threads\n    // do not accumulate \"Continue.\" turns that were never said by the user.\n    if (messageList) {\n      messageList.add(continuation, 'context');\n      return { messageList };\n    }\n\n    return { messages: [...messages, continuation] };\n  }\n}\n","import type { LanguageModelV2Prompt, LanguageModelV2CallWarning } from '@ai-sdk/provider-v5';\nimport type { StepResult } from '@internal/ai-sdk-v5';\nimport type { Agent } from '../agent';\nimport type { MastraDBMessage, MessageInput } from '../agent/message-list';\nimport { MessageList, messagesAreEqual } from '../agent/message-list';\nimport type { AgentStateSignalInput } from '../agent/signals';\nimport { applyStateSignal, getStateSignalsMetadata, resolveStateSignalHistory } from '../agent/state-signals';\nimport { TripWire } from '../agent/trip-wire';\nimport type { TripWireOptions } from '../agent/trip-wire';\nimport { isSupportedLanguageModel, supportedLanguageModelSpecifications } from '../agent/utils';\nimport { MastraError } from '../error';\nimport { resolveModelConfig } from '../llm';\nimport type { IMastraLogger } from '../logger';\nimport { latestProcessedModelOutput } from '../loop/shared/steps/tool-result-commit-core';\nimport type { MastraMemory } from '../memory/memory';\nimport { parseMemoryRequestContext } from '../memory/types';\nimport {\n  EntityType,\n  InternalSpans,\n  SpanType,\n  createObservabilityContext,\n  resolveObservabilityContext,\n} from '../observability';\nimport type { AnySpan, ObservabilityContext, ProcessorSpanType, Span } from '../observability';\nimport type { TracingContext } from '../observability/types';\nimport { executeWithContext } from '../observability/utils';\nimport { RequestContext } from '../request-context';\nimport type { ChunkType } from '../stream';\nimport type { MastraModelOutput } from '../stream/base/output';\nimport type { LanguageModelUsage, ProviderMetadata } from '../stream/types';\nimport { residentStepResults } from '../workflows/run-journal';\nimport type { OutputWriter } from '../workflows/types';\nimport type { AnyWorkspace } from '../workspace/workspace';\nimport { isProcessorWorkflow } from './is-processor-workflow';\nimport { createProcessorSendSignal, PROCESSOR_LATE_SIGNAL_SINK } from './send-signal';\nimport type { ProcessorLateSignalSink } from './send-signal';\nimport { resolveProcessorSpanAttributes, resolveProcessorSpanName } from './span-declaration';\nimport {\n  summarizeActiveToolsForSpan,\n  summarizeProcessorModelForSpan,\n  summarizeProcessorResultForSpan,\n  summarizeProcessorToolsForSpan,\n  summarizeToolChoiceForSpan,\n} from './span-payload';\nimport type { ProcessorStepOutput } from './step-schema';\nimport { isFailedStreamChunk, REPROCESS_PART_KEY, takeHeldParts } from './stream-reprocess';\nimport { needsTrailingAssistantGuard, TrailingAssistantGuard } from './trailing-assistant-guard';\nimport type {\n  CachedLLMStepChunk,\n  CachedLLMStepResponse,\n  ComputeStateSignalResult,\n  ErrorProcessorOrWorkflow,\n  OutputResult,\n  ProcessInputStepResult,\n  Processor,\n  ProcessorMessageResult,\n  ProcessorStreamWriter,\n  ProcessorViolation,\n  ProcessorWorkflow,\n  RunProcessInputStepArgs,\n  RunProcessInputStepResult,\n  ToolCallInfo,\n} from './index';\n\n/**\n * Safely invoke a processor's onViolation callback when a TripWire is caught.\n * Errors from the callback are silently caught.\n */\nasync function invokeOnViolation(processor: Processor, error: TripWire): Promise<void> {\n  if (!processor.onViolation) return;\n  try {\n    const violation: ProcessorViolation = {\n      processorId: error.processorId ?? processor.id,\n      message: error.message,\n      detail: error.options?.metadata,\n    };\n    await processor.onViolation(violation);\n  } catch {\n    // onViolation errors are silently caught\n  }\n}\n\nfunction getProcessableResponseMessages(messageList: MessageList): MastraDBMessage[] {\n  const liveMessages = messageList.get.response.db();\n  const persistedMessages = messageList.getPersisted.response.db();\n\n  if (persistedMessages.length === 0) {\n    return [...liveMessages];\n  }\n  if (liveMessages.length === 0) {\n    return [...persistedMessages];\n  }\n\n  const messagesById = new Map(persistedMessages.map(message => [message.id, message]));\n  for (const message of liveMessages) {\n    messagesById.set(message.id, message);\n  }\n\n  return messageList.get.all\n    .db()\n    .filter(message => messagesById.has(message.id))\n    .map(message => messagesById.get(message.id)!);\n}\n\n/**\n * Implementation of processor state management\n */\n/**\n * Tracks state for stream processing across chunks.\n * Used by both legacy processors and workflow processors.\n */\nexport class ProcessorState<OUTPUT = undefined> {\n  private inputAccumulatedText = '';\n  private outputAccumulatedText = '';\n  private outputChunkCount = 0;\n  public customState: Record<string, unknown> = {};\n  public streamParts: ChunkType<OUTPUT>[] = [];\n  public span?: Span<ProcessorSpanType>;\n  /**\n   * Milliseconds spent inside `processOutputStream`, summed across every\n   * chunk. The span itself lasts for the whole stream, so its duration is\n   * dominated by the model's inter-chunk latency; this is the processor's own\n   * share of that window.\n   */\n  public hookDurationMs = 0;\n\n  constructor(\n    options?: {\n      processorName?: string;\n      processorIndex?: number;\n      createSpan?: boolean;\n      /**\n       * The processor this state belongs to, so a span created here honours\n       * its span declaration. `processOutputStream` is the one processor\n       * method whose span is created from this constructor rather than from\n       * one of the runner's own call sites, so without this a processor that\n       * declares a span type would keep it everywhere except its streaming\n       * phase.\n       */\n      processor?: Pick<Processor, 'id' | 'spanType' | 'spanName' | 'spanAttributes'>;\n    } & Partial<ObservabilityContext>,\n  ) {\n    // Only create span if explicitly requested (legacy processors)\n    // Workflow processors handle span creation in workflow.ts\n    if (!options?.createSpan || !options.processorName) {\n      return;\n    }\n\n    const processor = options.processor;\n    const currentSpan = options.tracingContext?.currentSpan;\n    const parentSpan = currentSpan?.findParent(SpanType.AGENT_RUN) || currentSpan?.parent || currentSpan;\n    this.span = parentSpan?.createChildSpan({\n      type: processor?.spanType ?? SpanType.PROCESSOR_RUN,\n      name: processor\n        ? resolveProcessorSpanName(processor, 'output', `output stream processor: ${options.processorName}`)\n        : `output stream processor: ${options.processorName}`,\n      entityType: EntityType.OUTPUT_PROCESSOR,\n      entityId: processor?.id,\n      entityName: options.processorName,\n      attributes: {\n        ...resolveProcessorSpanAttributes(processor, 'outputStream'),\n        processorExecutor: 'legacy',\n        processorIndex: options.processorIndex ?? 0,\n      },\n      input: {\n        totalChunks: 0,\n      },\n    });\n  }\n\n  /** Track incoming chunk (before processor transformation) */\n  addInputPart(part: ChunkType<OUTPUT>): void {\n    // Extract text from text-delta chunks for accumulated text\n    if (part.type === 'text-delta') {\n      this.inputAccumulatedText += part.payload.text;\n    }\n    this.streamParts.push(part);\n\n    if (this.span) {\n      this.span.input = {\n        totalChunks: this.streamParts.length,\n        accumulatedText: this.inputAccumulatedText,\n      };\n    }\n  }\n\n  /** Track outgoing chunk (after processor transformation) */\n  addOutputPart(part: ChunkType<OUTPUT> | null | undefined): void {\n    if (!part) return;\n    this.outputChunkCount++;\n    // Extract text from text-delta chunks for accumulated text\n    if (part.type === 'text-delta') {\n      this.outputAccumulatedText += part.payload.text;\n    }\n  }\n\n  /** Get final output for span */\n  getFinalOutput(): { totalChunks: number; accumulatedText: string } {\n    return {\n      totalChunks: this.outputChunkCount,\n      accumulatedText: this.outputAccumulatedText,\n    };\n  }\n\n  /** Attributes attached on every end path of the span. */\n  getFinalAttributes(): { hookDurationMs: number } {\n    return { hookDurationMs: this.hookDurationMs };\n  }\n}\n\n/**\n * Key under which the workflow-processor stream path keeps its accumulated\n * hook time on the shared processor state, next to `__outputStreamSpan_<id>`.\n */\nexport const OUTPUT_STREAM_HOOK_DURATION_KEY_PREFIX = '__outputStreamHookDurationMs_';\n\n/**\n * The MODEL_STEP an output stream processor span belongs under: `span` itself\n * (a step's stream passes its step span) or its nearest step ancestor. Stops at\n * the first agent run, so a nested agent's stream never attaches to its\n * caller's step.\n */\nexport function findOwnModelStepSpan(span: AnySpan | undefined): AnySpan | undefined {\n  for (let current = span; current && current.type !== SpanType.AGENT_RUN; current = current.parent) {\n    if (current.type === SpanType.MODEL_STEP) {\n      return current;\n    }\n  }\n  return undefined;\n}\n\n/** Chunk types that end the model step an output stream processor span sits under. */\nconst STEP_END_CHUNK_TYPES = new Set(['step-finish', 'error', 'abort']);\n\nfunction endStoredOutputStreamSpan(state: Record<string, unknown>, processorId: string, totalChunks: number): void {\n  const spanKey = `__outputStreamSpan_${processorId}`;\n  const hookDurationKey = `${OUTPUT_STREAM_HOOK_DURATION_KEY_PREFIX}${processorId}`;\n  (state[spanKey] as Span<SpanType.PROCESSOR_RUN> | undefined)?.end({\n    output: { totalChunks },\n    attributes: { hookDurationMs: (state[hookDurationKey] as number | undefined) ?? 0 },\n  });\n  delete state[spanKey];\n  delete state[hookDurationKey];\n}\n\n/**\n * When a step's stream starts, ends the stored output stream processor span if\n * it was opened outside that step (e.g. by a tool result replayed on resume,\n * before any step started), so it does not carry into the step.\n */\nexport function endOutputStreamSpanOutsideStep(\n  state: Record<string, unknown>,\n  processorId: string,\n  part: ChunkType,\n  stepSpan: AnySpan | undefined,\n  totalChunks: number,\n): void {\n  const span = state[`__outputStreamSpan_${processorId}`] as AnySpan | undefined;\n  if (span && part.type === 'step-start' && stepSpan?.type === SpanType.MODEL_STEP && span.parent?.id !== stepSpan.id) {\n    endStoredOutputStreamSpan(state, processorId, totalChunks);\n  }\n}\n\n/**\n * Ends the stored output stream processor span when the model step it sits\n * under ends. The span outlives the step's model stream so the step's tool\n * results land in it too.\n */\nexport function endOutputStreamSpanAtStepEnd(\n  state: Record<string, unknown>,\n  processorId: string,\n  part: ChunkType,\n  totalChunks: number,\n): void {\n  const span = state[`__outputStreamSpan_${processorId}`] as AnySpan | undefined;\n  if (span?.parent?.type === SpanType.MODEL_STEP && STEP_END_CHUNK_TYPES.has(part.type)) {\n    endStoredOutputStreamSpan(state, processorId, totalChunks);\n  }\n}\n\n/**\n * Union type for processor or workflow that can be used as a processor\n */\ntype ProcessorOrWorkflow = Processor | ProcessorWorkflow;\n\nfunction areProcessorMessageArraysEqual(before: unknown[] | undefined, after: unknown[] | undefined): boolean {\n  if (before === after) {\n    return true;\n  }\n\n  if (!before || !after) {\n    return before === after;\n  }\n\n  return (\n    before.length === after.length &&\n    before.every((message, index) => messagesAreEqual(message as MessageInput, after[index] as MessageInput))\n  );\n}\n\nfunction buildProcessInputStepSpanInput(args: {\n  messages: MastraDBMessage[];\n  systemMessages: unknown[];\n  stepNumber: number;\n  messageId?: string;\n  retryCount: number;\n  model: unknown;\n  tools?: unknown;\n  toolChoice?: unknown;\n  activeTools?: unknown;\n}) {\n  const summarizedModel = summarizeProcessorModelForSpan(args.model);\n  const summarizedTools = summarizeProcessorToolsForSpan(args.tools);\n  const summarizedToolChoice = summarizeToolChoiceForSpan(args.toolChoice, args.tools);\n  const summarizedActiveTools = summarizeActiveToolsForSpan(args.activeTools, args.tools);\n\n  return {\n    messages: args.messages,\n    systemMessages: args.systemMessages,\n    stepNumber: args.stepNumber,\n    ...(args.messageId ? { messageId: args.messageId } : {}),\n    retryCount: args.retryCount,\n    ...(summarizedModel ? { model: summarizedModel } : {}),\n    ...(summarizedTools ? { tools: summarizedTools } : {}),\n    ...(summarizedToolChoice ? { toolChoice: summarizedToolChoice } : {}),\n    ...(summarizedActiveTools ? { activeTools: summarizedActiveTools } : {}),\n  };\n}\n\nfunction buildProcessInputStepSpanOutput(args: {\n  result: RunProcessInputStepResult;\n  beforeStepInput: Pick<RunProcessInputStepResult, 'messageId' | 'model' | 'tools' | 'toolChoice' | 'activeTools'>;\n  afterStepInput: RunProcessInputStepResult;\n  beforeMessages: MastraDBMessage[];\n  beforeSystemMessages: unknown[];\n  messages: MastraDBMessage[];\n  systemMessages: unknown[];\n}) {\n  const output: Record<string, unknown> = {};\n\n  if (!areProcessorMessageArraysEqual(args.beforeMessages, args.messages)) {\n    output.messages = args.messages;\n  }\n\n  if (!areProcessorMessageArraysEqual(args.beforeSystemMessages, args.systemMessages)) {\n    output.systemMessages = args.systemMessages;\n  }\n\n  if (args.afterStepInput.messageId !== args.beforeStepInput.messageId) {\n    output.messageId = args.afterStepInput.messageId;\n  }\n\n  if (args.result.model !== undefined || args.afterStepInput.model !== args.beforeStepInput.model) {\n    const model = summarizeProcessorModelForSpan(args.afterStepInput.model);\n    if (model) {\n      output.model = model;\n    }\n  }\n\n  if (args.result.tools !== undefined || args.afterStepInput.tools !== args.beforeStepInput.tools) {\n    const tools = summarizeProcessorToolsForSpan(args.afterStepInput.tools);\n    if (tools) {\n      output.tools = tools;\n    }\n  }\n\n  if (\n    args.result.toolChoice !== undefined ||\n    args.afterStepInput.toolChoice !== args.beforeStepInput.toolChoice ||\n    args.afterStepInput.tools !== args.beforeStepInput.tools\n  ) {\n    const toolChoice = summarizeToolChoiceForSpan(args.afterStepInput.toolChoice, args.afterStepInput.tools);\n    if (toolChoice) {\n      output.toolChoice = toolChoice;\n    }\n  }\n\n  if (\n    args.result.activeTools !== undefined ||\n    args.afterStepInput.activeTools !== args.beforeStepInput.activeTools ||\n    args.afterStepInput.tools !== args.beforeStepInput.tools\n  ) {\n    const activeTools = summarizeActiveToolsForSpan(args.afterStepInput.activeTools, args.afterStepInput.tools);\n    if (activeTools) {\n      output.activeTools = activeTools;\n    }\n  }\n\n  if (args.result.retryCount !== undefined) {\n    output.retryCount = args.result.retryCount;\n  }\n\n  return output;\n}\n\nexport class ProcessorRunner {\n  public readonly inputProcessors: ProcessorOrWorkflow[];\n  public readonly outputProcessors: ProcessorOrWorkflow[];\n  public readonly errorProcessors: ErrorProcessorOrWorkflow[];\n  private readonly logger: IMastraLogger;\n  private readonly agentName: string;\n  private readonly agent?: Agent<any, any, any, any>;\n  /**\n   * Shared processor state that persists across loop iterations.\n   * Used by all processor methods (input and output) to share state.\n   * Keyed by processor ID.\n   */\n  private readonly processorStates: Map<string, ProcessorState>;\n  private readonly lateSignalSink?: ProcessorLateSignalSink;\n\n  constructor({\n    inputProcessors,\n    outputProcessors,\n    errorProcessors,\n    logger,\n    agentName,\n    agent,\n    processorStates,\n    lateSignalSink,\n  }: {\n    inputProcessors?: ProcessorOrWorkflow[];\n    outputProcessors?: ProcessorOrWorkflow[];\n    errorProcessors?: ErrorProcessorOrWorkflow[];\n    logger: IMastraLogger;\n    agentName: string;\n    agent?: Agent<any, any, any, any>;\n    processorStates?: Map<string, ProcessorState>;\n    /** Receives `sendSignal` calls made after the creating step returned (durable engines). */\n    lateSignalSink?: ProcessorLateSignalSink;\n  }) {\n    this.inputProcessors = inputProcessors ?? [];\n    this.outputProcessors = outputProcessors ?? [];\n    this.errorProcessors = errorProcessors ?? [];\n    this.logger = logger;\n    this.agentName = agentName;\n    this.agent = agent;\n    this.processorStates = processorStates ?? new Map();\n    this.lateSignalSink = lateSignalSink;\n  }\n\n  /**\n   * Get or create ProcessorState for the given processor ID.\n   * This state persists across loop iterations and is shared between\n   * all processor methods (input and output).\n   */\n  private getProcessorState(processorId: string): ProcessorState {\n    let state = this.processorStates.get(processorId);\n    if (!state) {\n      state = new ProcessorState();\n      this.processorStates.set(processorId, state);\n    }\n    return state;\n  }\n\n  private async runComputeStateSignal({\n    processor,\n    messageList,\n    stepNumber,\n    steps,\n    requestContext,\n    writer,\n    abort,\n    processorState,\n    memory,\n    resourceId,\n    threadId,\n    abortSignal,\n    retryCount,\n    rotateResponseMessageId,\n    observabilityContext,\n  }: {\n    processor: Processor;\n    messageList: MessageList;\n    stepNumber: number;\n    steps: Array<StepResult<any>>;\n    requestContext?: RequestContext;\n    writer?: ProcessorStreamWriter;\n    abort: (reason?: string, options?: TripWireOptions) => never;\n    processorState: ProcessorState;\n    observabilityContext?: Partial<ObservabilityContext>;\n    memory?: MastraMemory;\n    resourceId?: string;\n    threadId?: string;\n    abortSignal?: AbortSignal;\n    retryCount: number;\n    rotateResponseMessageId?: () => string;\n  }): Promise<void> {\n    const computeStateSignal = processor.computeStateSignal?.bind(processor);\n    if (!computeStateSignal) return;\n\n    const memoryContext = parseMemoryRequestContext(requestContext);\n    const resolvedMemory = memory;\n    const resolvedThreadId = threadId ?? memoryContext?.thread?.id;\n    const resolvedResourceId = resourceId ?? memoryContext?.resourceId;\n\n    if (!resolvedMemory) {\n      throw new Error(\n        `[Processor:${processor.id}] computeStateSignal requires Mastra memory with an active resourceId and threadId`,\n      );\n    }\n\n    // Memory is configured but this invocation has no thread/resource identity\n    // (e.g. an ephemeral workflow agent step). State signals are thread-scoped,\n    // so skip rather than throw.\n    if (!resolvedThreadId || !resolvedResourceId) {\n      this.logger.debug(\n        `[Processor:${processor.id}] computeStateSignal skipped — no threadId/resourceId resolved for this invocation`,\n      );\n      return;\n    }\n\n    const loadedThread = (await resolvedMemory.getThreadById({ threadId: resolvedThreadId })) ?? memoryContext?.thread;\n    if (!loadedThread) {\n      throw new Error(`[Processor:${processor.id}] computeStateSignal could not load thread ${resolvedThreadId}`);\n    }\n    let thread = {\n      ...loadedThread,\n      id: resolvedThreadId,\n      resourceId: loadedThread.resourceId ?? resolvedResourceId,\n      createdAt: loadedThread.createdAt ?? new Date(),\n      updatedAt: loadedThread.updatedAt ?? new Date(),\n      metadata: loadedThread.metadata,\n    };\n\n    const stateId = processor.stateId ?? processor.id;\n    const beforeAddStateSignal = rotateResponseMessageId;\n    const trackingById = getStateSignalsMetadata(thread.metadata);\n    const tracking = trackingById[stateId];\n    const { activeStateSignals, contextWindow, lastSnapshot, deltasSinceSnapshot } = await resolveStateSignalHistory({\n      messageList,\n      memory: resolvedMemory,\n      threadId: resolvedThreadId,\n      stateId,\n      tracking,\n    });\n    const result = (await computeStateSignal({\n      // The args type extends ProcessorContext, so `tracingContext` has always\n      // been part of the contract — it was simply never passed, leaving it\n      // permanently undefined for every implementer.\n      ...createObservabilityContext({ currentSpan: observabilityContext?.tracingContext?.currentSpan }),\n      messages: messageList.get.all.db(),\n      messageList,\n      stepNumber,\n      steps,\n      state: processorState.customState,\n      requestContext,\n      writer,\n      abortSignal,\n      abort,\n      retryCount,\n      resourceId: resolvedResourceId,\n      threadId: resolvedThreadId,\n      activeStateSignals,\n      contextWindow,\n      lastSnapshot,\n      deltasSinceSnapshot,\n      tracking,\n      sendStateSignal: async stateSignal => {\n        const sendResult = await applyStateSignal({\n          input: stateSignal,\n          memory: resolvedMemory,\n          thread,\n          resourceId: resolvedResourceId,\n          threadId: resolvedThreadId,\n          memoryConfig: memoryContext?.memoryConfig,\n          messageList,\n          defaultId: stateId,\n          beforeAddSignal: beforeAddStateSignal,\n          writeSignal: signal => writer?.custom(signal.toDataPart()),\n        });\n        if (!sendResult.skipped) {\n          const updated = await resolvedMemory.getThreadById({ threadId: resolvedThreadId });\n          if (updated) thread = { ...thread, metadata: updated.metadata };\n        }\n        return sendResult.skipped ? sendResult : sendResult.signal;\n      },\n    })) as ComputeStateSignalResult;\n\n    if (!result) return;\n\n    await applyStateSignal({\n      input: result,\n      memory: resolvedMemory,\n      thread,\n      resourceId: resolvedResourceId,\n      threadId: resolvedThreadId,\n      memoryConfig: memoryContext?.memoryConfig,\n      messageList,\n      defaultId: stateId,\n      beforeAddSignal: beforeAddStateSignal,\n      writeSignal: signal => writer?.custom(signal.toDataPart()),\n    });\n\n    // Record the emission as an event: a signal is a point-in-time fact about\n    // what entered the model's context, and the work of computing it is already\n    // timed by the enclosing processor span. Reached only when a signal was\n    // produced, so a step where the lane computed no change stays silent.\n    observabilityContext?.tracingContext?.currentSpan?.createEventSpan<SpanType.AGENT_SIGNAL>({\n      type: SpanType.AGENT_SIGNAL,\n      name: `signal: ${result.id ?? stateId}`,\n      attributes: {\n        stateId: result.id ?? stateId,\n        mode: result.mode,\n        tagName: result.tagName,\n        processorId: processor.id,\n      },\n      output: { attributes: result.attributes, hasDelta: Boolean(result.delta) },\n    });\n  }\n\n  private async runWorkflowComputeStateSignals({\n    workflow,\n    messageList,\n    stepNumber,\n    steps,\n    requestContext,\n    writer,\n    memory,\n    resourceId,\n    threadId,\n    abortSignal,\n    retryCount,\n    rotateResponseMessageId,\n    observabilityContext,\n  }: {\n    workflow: ProcessorWorkflow;\n    messageList: MessageList;\n    stepNumber: number;\n    steps: Array<StepResult<any>>;\n    requestContext?: RequestContext;\n    writer?: ProcessorStreamWriter;\n    observabilityContext?: Partial<ObservabilityContext>;\n    memory?: MastraMemory;\n    resourceId?: string;\n    threadId?: string;\n    abortSignal?: AbortSignal;\n    retryCount: number;\n    rotateResponseMessageId?: () => string;\n  }): Promise<void> {\n    for (const processor of workflow.__stateSignalProcessors ?? []) {\n      const abort = <TMetadata = unknown>(reason?: string, options?: TripWireOptions<TMetadata>): never => {\n        throw new TripWire(reason || `Tripwire triggered by ${processor.id}`, options, processor.id);\n      };\n\n      await this.runComputeStateSignal({\n        processor,\n        messageList,\n        stepNumber,\n        steps,\n        requestContext,\n        writer,\n        abort,\n        processorState: this.getProcessorState(processor.id),\n        observabilityContext,\n        memory,\n        resourceId,\n        threadId,\n        abortSignal,\n        retryCount,\n        rotateResponseMessageId,\n      });\n    }\n  }\n\n  /**\n   * Execute a workflow as a processor and handle the result.\n   * Returns the processed messages and any tripwire information.\n   */\n  private async executeWorkflowAsProcessor(\n    workflow: ProcessorWorkflow,\n    input: ProcessorStepOutput & { llmRequestProcessorIds?: ReadonlySet<string> },\n    observabilityContext?: ObservabilityContext,\n    requestContext?: RequestContext,\n    writer?: ProcessorStreamWriter,\n    abortSignal?: AbortSignal,\n  ): Promise<ProcessorStepOutput> {\n    // Explicit workflows run once per streamed chunk, with the full\n    // accumulated `streamParts` as input. Persisting a snapshot (and tracing a public\n    // span) for every one of those transient runs makes a stream of n chunks cost O(n²)\n    // in storage writes and serialized payload (#19605). Internal processor workflows\n    // built by the agent already opt out via their workflow options (#17344); a\n    // user-supplied processor workflow keeps the persisting defaults, so the opt-out is\n    // applied per run here — leaving the same workflow's standalone runs untouched.\n    const isPerChunkPhase = input.phase === 'outputStream';\n\n    const inputData = {\n      ...input,\n      processorStates: this.processorStates,\n      abortSignal,\n      agent: this.agent,\n      lateSignalSink: this.lateSignalSink,\n    };\n    const outputWriter: OutputWriter | undefined = writer\n      ? (chunk, options) => writer.custom(chunk, options)\n      : undefined;\n    if (isPerChunkPhase && workflow.__executeOutputStream) {\n      const execute = workflow.__executeOutputStream;\n      return executeWithContext({\n        span: observabilityContext?.tracingContext?.currentSpan,\n        fn: () =>\n          execute({\n            inputData,\n            ...observabilityContext,\n            requestContext: requestContext ?? new RequestContext(),\n            outputWriter,\n          }),\n      });\n    }\n\n    // Create a run and start the workflow\n    const run = await workflow.createRun(\n      isPerChunkPhase\n        ? {\n            shouldPersistSnapshot: () => false,\n            tracingPolicy: { internal: InternalSpans.WORKFLOW },\n          }\n        : undefined,\n    );\n    // Workflow schemas strip unknown fields. Keep the live callback off\n    // step payloads so chained processors can recover it from their run.\n    const scope = this.lateSignalSink ? workflow.mastra?.__createRunScope(run.runId) : undefined;\n    if (this.lateSignalSink) scope?.set(PROCESSOR_LATE_SIGNAL_SINK, this.lateSignalSink);\n    const result = await (async () => {\n      try {\n        return await run.start({ inputData, ...observabilityContext, requestContext, outputWriter });\n      } finally {\n        if (scope) workflow.mastra?.__releaseRunScope(run.runId);\n      }\n    })();\n\n    // Check for tripwire status - this means a processor in the workflow called abort()\n    if (result.status === 'tripwire') {\n      const tripwireData = (\n        result as { tripwire?: { reason?: string; retry?: boolean; metadata?: unknown; processorId?: string } }\n      ).tripwire;\n      // Re-throw as TripWire so the agent handles it properly\n      throw new TripWire(\n        tripwireData?.reason || `Tripwire triggered in workflow ${workflow.id}`,\n        {\n          retry: tripwireData?.retry,\n          metadata: tripwireData?.metadata,\n        },\n        tripwireData?.processorId || workflow.id,\n      );\n    }\n\n    // Check for execution failure\n    if (result.status !== 'success') {\n      // Collect error details from the workflow result and failed steps\n      const details: string[] = [];\n      // A storage v2 result's `steps` is a loader; it holds the failed results without reading storage.\n      const steps = residentStepResults(result.steps) ?? result.steps;\n      if (result.status === 'failed') {\n        if (result.error) {\n          details.push(result.error.message || JSON.stringify(result.error));\n        }\n        for (const [stepId, step] of Object.entries(steps)) {\n          if (step.status === 'failed' && step.error?.message) {\n            details.push(`step ${stepId}: ${step.error.message}`);\n          }\n        }\n      }\n      const detailStr = details.length > 0 ? ` — ${details.join('; ')}` : '';\n      // Keep the underlying failure reachable: without it callers only see the\n      // flattened status text and lose the original error, stack and type.\n      let failedStepError: Error | undefined;\n      if (result.status === 'failed') {\n        for (const step of Object.values(steps)) {\n          if (step.status === 'failed' && step.error) {\n            failedStepError = step.error;\n            break;\n          }\n        }\n      }\n      throw new MastraError(\n        {\n          category: 'USER',\n          domain: 'AGENT',\n          id: 'PROCESSOR_WORKFLOW_FAILED',\n          text: `Processor workflow ${workflow.id} failed with status: ${result.status}${detailStr}`,\n        },\n        // The step's error is the live object; `result.error` is the engine's\n        // serialized copy and has no stack or original class.\n        result.status === 'failed' ? (failedStepError ?? result.error) : undefined,\n      );\n    }\n\n    // Extract and validate the output from the workflow result\n    const output = result.result;\n\n    if (!output || typeof output !== 'object') {\n      // No output means no changes - return input unchanged\n      return input;\n    }\n\n    // Validate it has the expected ProcessorStepOutput shape\n    if (!('phase' in output) || !('messages' in output || 'part' in output || 'messageList' in output)) {\n      throw new MastraError({\n        category: 'USER',\n        domain: 'AGENT',\n        id: 'PROCESSOR_WORKFLOW_INVALID_OUTPUT',\n        text: `Processor workflow ${workflow.id} returned invalid output format. Expected ProcessorStepOutput.`,\n      });\n    }\n\n    return output as ProcessorStepOutput;\n  }\n\n  async runOutputProcessors(\n    messageList: MessageList,\n    observabilityContext?: ObservabilityContext,\n    requestContext?: RequestContext,\n    retryCount: number = 0,\n    writer?: ProcessorStreamWriter,\n    result?: OutputResult,\n  ): Promise<MessageList> {\n    for (const [index, processorOrWorkflow] of this.outputProcessors.entries()) {\n      let processableMessages = getProcessableResponseMessages(messageList);\n      const idsBeforeProcessing = processableMessages.map((m: MastraDBMessage) => m.id);\n      const check = messageList.makeMessageSourceChecker();\n\n      // Handle workflow as processor\n      if (isProcessorWorkflow(processorOrWorkflow)) {\n        await this.executeWorkflowAsProcessor(\n          processorOrWorkflow,\n          {\n            phase: 'outputResult',\n            messages: processableMessages,\n            messageList,\n            retryCount,\n            result,\n          },\n          observabilityContext,\n          requestContext,\n          writer,\n        );\n        continue;\n      }\n\n      // Handle regular processor\n      const processor = processorOrWorkflow;\n      const abort = <TMetadata = unknown>(reason?: string, options?: TripWireOptions<TMetadata>): never => {\n        throw new TripWire(reason || `Tripwire triggered by ${processor.id}`, options, processor.id);\n      };\n\n      // Use the processOutputResult method if available\n      const processMethod = processor.processOutputResult?.bind(processor);\n\n      if (!processMethod) {\n        // Skip processors that don't implement processOutputResult\n        continue;\n      }\n\n      const outputMessagesBefore = processableMessages;\n      const outputSystemMessagesBefore = messageList.getAllSystemMessages();\n      const defaultResult: OutputResult = {\n        text: '',\n        usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },\n        finishReason: 'unknown',\n        steps: [],\n      };\n      const summarizedResult = result ? summarizeProcessorResultForSpan(result) : undefined;\n      const currentSpan = observabilityContext?.tracingContext?.currentSpan;\n      const parentSpan = currentSpan?.findParent(SpanType.AGENT_RUN) || currentSpan?.parent || currentSpan;\n      const processorSpan = parentSpan?.createChildSpan({\n        type: processor.spanType ?? SpanType.PROCESSOR_RUN,\n        name: resolveProcessorSpanName(processor, 'output', `output processor: ${processor.id}`),\n        entityType: EntityType.OUTPUT_PROCESSOR,\n        entityId: processor.id,\n        entityName: processor.name,\n        attributes: {\n          ...resolveProcessorSpanAttributes(processor, 'outputResult'),\n          processorExecutor: 'legacy',\n          processorIndex: index,\n        },\n        input: {\n          messages: processableMessages,\n          ...(summarizedResult ? { result: summarizedResult } : {}),\n          retryCount,\n        },\n      });\n\n      // Start recording MessageList mutations for this processor\n      messageList.startRecording();\n\n      try {\n        // Get per-processor state that persists across all method calls within this request\n        const processorState = this.getProcessorState(processor.id);\n\n        const processResult = await processMethod({\n          messages: processableMessages,\n          messageList,\n          state: processorState.customState,\n          result: result ?? defaultResult,\n          abort,\n          agent: this.agent,\n          ...createObservabilityContext({ currentSpan: processorSpan }),\n          requestContext,\n          retryCount,\n          writer,\n          sendSignal: createProcessorSendSignal({ messageList, writer, lateSink: this.lateSignalSink }),\n        });\n\n        // Stop recording and get mutations for this processor\n        const mutations = messageList.stopRecording();\n\n        // Handle the new return type - MessageList or MastraDBMessage[]\n        if (processResult instanceof MessageList) {\n          if (processResult !== messageList) {\n            throw new MastraError({\n              category: 'USER',\n              domain: 'AGENT',\n              id: 'PROCESSOR_RETURNED_EXTERNAL_MESSAGE_LIST',\n              text: `Processor ${processor.id} returned a MessageList instance other than the one that was passed in as an argument. New external message list instances are not supported. Use the messageList argument instead.`,\n            });\n          }\n          if (mutations.length > 0) {\n            processableMessages = getProcessableResponseMessages(processResult);\n          }\n        } else if (processResult) {\n          const deletedIds = idsBeforeProcessing.filter(\n            (i: string) => !processResult.some((m: MastraDBMessage) => m.id === i),\n          );\n          if (deletedIds.length) {\n            messageList.removeByIds(deletedIds);\n          }\n          processableMessages = processResult || [];\n          for (const message of processResult) {\n            messageList.removeByIds([message.id]);\n            messageList.add(message, check.getSource(message) || 'response', { merge: false });\n          }\n        }\n\n        processorSpan?.end({\n          output: {\n            ...(!areProcessorMessageArraysEqual(outputMessagesBefore, processableMessages)\n              ? { messages: processableMessages }\n              : {}),\n            ...(!areProcessorMessageArraysEqual(outputSystemMessagesBefore, messageList.getAllSystemMessages())\n              ? { systemMessages: messageList.getAllSystemMessages() }\n              : {}),\n          },\n          attributes: mutations.length > 0 ? { messageListMutations: mutations } : undefined,\n        });\n      } catch (error) {\n        // Stop recording on error\n        messageList.stopRecording();\n\n        if (error instanceof TripWire) {\n          processorSpan?.error({\n            error,\n            endSpan: true,\n            attributes: {\n              tripwireAbort: {\n                reason: error.message,\n                retry: error.options?.retry,\n                metadata: error.options?.metadata,\n              },\n            },\n          });\n          await invokeOnViolation(processor, error);\n          throw error;\n        }\n        processorSpan?.error({ error: error as Error, endSpan: true });\n        throw error;\n      }\n    }\n\n    return messageList;\n  }\n\n  /**\n   * Process a stream part through all output processors with state management\n   */\n  async processPart<OUTPUT>(\n    part: ChunkType<OUTPUT>,\n    processorStates: Map<string, ProcessorState<OUTPUT>>,\n    observabilityContext?: ObservabilityContext,\n    requestContext?: RequestContext,\n    messageList?: MessageList,\n    retryCount: number = 0,\n    writer?: ProcessorStreamWriter,\n    abortSignal?: AbortSignal,\n    /** Skip output processors before this index (the part was released by the one before it). */\n    startIndex: number = 0,\n  ): Promise<{\n    part: ChunkType<OUTPUT> | null | undefined;\n    blocked: boolean;\n    reason?: string;\n    tripwireOptions?: TripWireOptions<unknown>;\n    processorId?: string;\n  }> {\n    if (!this.outputProcessors.length) {\n      return { part, blocked: false };\n    }\n\n    try {\n      let processedPart: ChunkType<OUTPUT> | null | undefined = part;\n      const isFinishChunk = part.type === 'finish';\n\n      for (const [index, processorOrWorkflow] of this.outputProcessors.entries()) {\n        if (index < startIndex) continue;\n        // Handle workflows for stream processing\n        if (isProcessorWorkflow(processorOrWorkflow)) {\n          if (!processedPart) continue;\n\n          // Get or create state for this workflow\n          const workflowId = processorOrWorkflow.id;\n          let state = processorStates.get(workflowId);\n          if (!state) {\n            state = new ProcessorState<OUTPUT>();\n            processorStates.set(workflowId, state);\n          }\n\n          // Track input chunk (before processor transformation)\n          state.addInputPart(processedPart);\n\n          if (processorOrWorkflow.__processOutputStream === false) {\n            state.addOutputPart(processedPart);\n            continue;\n          }\n\n          try {\n            const result = await this.executeWorkflowAsProcessor(\n              processorOrWorkflow,\n              {\n                phase: 'outputStream',\n                part: processedPart,\n                streamParts: state.streamParts as ChunkType[],\n                state: state.customState,\n                messageList,\n                retryCount,\n              },\n              observabilityContext,\n              requestContext,\n              writer,\n              abortSignal,\n            );\n\n            // Extract the processed part from the result if it exists\n            if ('part' in result) {\n              processedPart = result.part as ChunkType<OUTPUT> | null | undefined;\n            }\n            // Track output chunk (after processor transformation or passthrough)\n            state.addOutputPart(processedPart);\n          } catch (error) {\n            if (error instanceof TripWire) {\n              return {\n                part: null,\n                blocked: true,\n                reason: error.message,\n                tripwireOptions: error.options,\n                processorId: error.processorId || workflowId,\n              };\n            }\n            throw error;\n          }\n          continue;\n        }\n\n        const processor = processorOrWorkflow;\n        try {\n          if (processor.processOutputStream && processedPart) {\n            // Get or create state for this processor\n            let state = processorStates.get(processor.id);\n            if (!state) {\n              state = new ProcessorState<OUTPUT>({\n                processorName: processor.name ?? processor.id,\n                ...observabilityContext,\n                processorIndex: index,\n                createSpan: true,\n                processor,\n              });\n              processorStates.set(processor.id, state);\n            }\n\n            // Track input chunk (before processor transformation)\n            state.addInputPart(processedPart);\n\n            // Timed in a finally so a tripwire or error still reports the time spent so far.\n            const hookStart = performance.now();\n            let result: ChunkType | null | undefined;\n            try {\n              result = await processor.processOutputStream({\n                part: processedPart as ChunkType,\n                streamParts: state.streamParts as ChunkType[],\n                state: state.customState,\n                agent: this.agent,\n                abort: <TMetadata = unknown>(reason?: string, options?: TripWireOptions<TMetadata>): never => {\n                  throw new TripWire(reason || `Tripwire triggered by ${processor.id}`, options, processor.id);\n                },\n                ...createObservabilityContext({ currentSpan: state.span }),\n                requestContext,\n                messageList,\n                retryCount,\n                writer,\n                abortSignal,\n              });\n            } finally {\n              state.hookDurationMs += performance.now() - hookStart;\n            }\n\n            // Track output chunk and update processedPart\n            processedPart = result as ChunkType<OUTPUT> | null | undefined;\n            state.addOutputPart(processedPart);\n          }\n        } catch (error) {\n          if (error instanceof TripWire) {\n            // Error span for trip-wire abort so it shows as ERROR in traces\n            const state = processorStates.get(processor.id);\n            state?.span?.error({\n              error,\n              endSpan: true,\n              attributes: {\n                ...state.getFinalAttributes(),\n                tripwireAbort: {\n                  reason: error.message,\n                  retry: error.options?.retry,\n                  metadata: error.options?.metadata,\n                },\n              },\n            });\n            await invokeOnViolation(processor, error);\n            return {\n              part: null,\n              blocked: true,\n              reason: error.message,\n              tripwireOptions: error.options,\n              processorId: processor.id,\n            };\n          }\n          throw error;\n        }\n      }\n\n      // If this was a finish chunk, end all processor spans AFTER processing\n      if (isFinishChunk) {\n        for (const state of processorStates.values()) {\n          if (state.span) {\n            // Set output with accumulated text and chunk count from processor's output\n            state.span.end({ output: state.getFinalOutput(), attributes: state.getFinalAttributes() });\n          }\n        }\n      }\n\n      return { part: processedPart, blocked: false };\n    } catch (error) {\n      this.logger.error('Stream part processing failed', { agent: this.agentName, error });\n      // End all spans on fatal error\n      for (const state of processorStates.values()) {\n        state.span?.error({ error: error as Error, endSpan: true, attributes: state.getFinalAttributes() });\n      }\n      throw error;\n    }\n  }\n\n  endStreamProcessorSpans<OUTPUT>(\n    processorStates: Map<string, ProcessorState<OUTPUT>>,\n    options?: {\n      /**\n       * Leave workflow-path spans parented to a model step open. Set when only\n       * the step's model stream closed: the step's tool results still flow\n       * through the processors, and the span ends with the step's\n       * `step-finish` chunk.\n       */\n      keepStepScopedSpans?: boolean;\n    },\n  ): void {\n    for (const state of processorStates.values()) {\n      state.span?.end({ output: state.getFinalOutput(), attributes: state.getFinalAttributes() });\n\n      for (const [key, value] of Object.entries(state.customState)) {\n        if (key.startsWith('__outputStreamSpan_')) {\n          const span = value as Span<SpanType.PROCESSOR_RUN> | undefined;\n          if (options?.keepStepScopedSpans && span?.parent?.type === SpanType.MODEL_STEP) {\n            continue;\n          }\n          const durationKey = OUTPUT_STREAM_HOOK_DURATION_KEY_PREFIX + key.slice('__outputStreamSpan_'.length);\n          const hookDurationMs = state.customState[durationKey];\n          span?.end(typeof hookDurationMs === 'number' ? { attributes: { hookDurationMs } } : undefined);\n          // Processor state outlives a single LLM step, so a kept reference would\n          // leave later steps writing to an already-ended span parented to the\n          // previous step - dropping their output and any tripwire abort.\n          delete state.customState[key];\n          delete state.customState[durationKey];\n        }\n      }\n    }\n  }\n\n  /**\n   * Re-drive any parts that stream processors stashed for reprocessing through\n   * the full output processor chain.\n   *\n   * A stream processor can only return one part from `processOutputStream`, but\n   * some processors (e.g. `BatchPartsProcessor`) need to emit a second part for\n   * one input — it returns the first part and stashes the second under\n   * `REPROCESS_PART_KEY` on its state. After the primary part has been emitted,\n   * callers invoke this to push each stashed part back through the whole chain\n   * (so it receives downstream processing) and emit the results in order.\n   *\n   * Returns the processed results in emission order. Reprocessing can itself\n   * stash more parts, so this drains until none remain.\n   */\n  async drainReprocessParts<OUTPUT>(\n    processorStates: Map<string, ProcessorState<OUTPUT>>,\n    observabilityContext?: ObservabilityContext,\n    requestContext?: RequestContext,\n    messageList?: MessageList,\n    retryCount: number = 0,\n    writer?: ProcessorStreamWriter,\n    abortSignal?: AbortSignal,\n    minIndex?: number,\n  ): Promise<\n    Array<{\n      part: ChunkType<OUTPUT> | null | undefined;\n      blocked: boolean;\n      reason?: string;\n      tripwireOptions?: TripWireOptions<unknown>;\n      processorId?: string;\n    }>\n  > {\n    const results: Array<{\n      part: ChunkType<OUTPUT> | null | undefined;\n      blocked: boolean;\n      reason?: string;\n      tripwireOptions?: TripWireOptions<unknown>;\n      processorId?: string;\n    }> = [];\n\n    // With `minIndex` (end-of-stream release), a part stashed by the processor at index j\n    // re-enters at j, never upstream: an upstream holder such as BatchPartsProcessor\n    // has already released everything and would hold the part with nothing left to free it.\n    if (minIndex !== undefined) {\n      const takeFrom = (): [ChunkType<OUTPUT>, number] | undefined => {\n        for (let j = minIndex; j < this.outputProcessors.length; j++) {\n          const processor = this.outputProcessors[j]!;\n          if (isProcessorWorkflow(processor)) continue;\n          const custom = processorStates.get(processor.id)?.customState as Record<string, unknown> | undefined;\n          const stashed = custom?.[REPROCESS_PART_KEY];\n          if (stashed) {\n            delete custom![REPROCESS_PART_KEY];\n            return [stashed as ChunkType<OUTPUT>, j];\n          }\n        }\n        return undefined;\n      };\n      let guard = 0;\n      let next = takeFrom();\n      while (next && guard++ < 1000) {\n        const result = await this.processPart(\n          next[0],\n          processorStates,\n          observabilityContext,\n          requestContext,\n          messageList,\n          retryCount,\n          writer,\n          abortSignal,\n          next[1],\n        );\n        results.push(result);\n        if (result.blocked) break;\n        next = takeFrom();\n      }\n      return results;\n    }\n\n    // Pull the next stashed part (if any) from processor states, in processor order.\n    const takeNext = (): ChunkType<OUTPUT> | undefined => {\n      for (const state of processorStates.values()) {\n        const custom = state.customState as Record<string, unknown>;\n        const stashed = custom[REPROCESS_PART_KEY];\n        if (stashed) {\n          delete custom[REPROCESS_PART_KEY];\n          return stashed as ChunkType<OUTPUT>;\n        }\n      }\n      return undefined;\n    };\n\n    // Bound the loop defensively to avoid an infinite cycle if a processor were\n    // to keep restashing the same part.\n    let guard = 0;\n    let next = takeNext();\n    while (next && guard++ < 1000) {\n      const result = await this.processPart(\n        next,\n        processorStates,\n        observabilityContext,\n        requestContext,\n        messageList,\n        retryCount,\n        writer,\n        abortSignal,\n      );\n      results.push(result);\n      if (result.blocked) {\n        break;\n      }\n      next = takeNext();\n    }\n\n    return results;\n  }\n\n  /**\n   * Call when a stream ends. Processors that hold parts until a later part\n   * arrives (`BatchPartsProcessor`, LLM-buffered checks) would otherwise drop\n   * what they hold when nothing follows it. Each held part is released and\n   * pushed through the processors after its holder, then any stashed parts are\n   * drained. Returns the results in emission order, stopping at the first block.\n   */\n  async flushHeldParts<OUTPUT>(\n    processorStates: Map<string, ProcessorState<OUTPUT>>,\n    observabilityContext?: ObservabilityContext,\n    requestContext?: RequestContext,\n    messageList?: MessageList,\n    retryCount: number = 0,\n    writer?: ProcessorStreamWriter,\n    abortSignal?: AbortSignal,\n  ): Promise<\n    Array<{\n      part: ChunkType<OUTPUT> | null | undefined;\n      blocked: boolean;\n      reason?: string;\n      tripwireOptions?: TripWireOptions<unknown>;\n      processorId?: string;\n    }>\n  > {\n    const results: Array<{\n      part: ChunkType<OUTPUT> | null | undefined;\n      blocked: boolean;\n      reason?: string;\n      tripwireOptions?: TripWireOptions<unknown>;\n      processorId?: string;\n    }> = [];\n\n    for (const [index, processorOrWorkflow] of this.outputProcessors.entries()) {\n      let held: ChunkType[];\n      try {\n        if (isProcessorWorkflow(processorOrWorkflow)) {\n          const flush = processorOrWorkflow.__flushOutputStream;\n          if (!flush) continue;\n          const outputWriter: OutputWriter | undefined = writer\n            ? (chunk, options) => writer.custom(chunk, options)\n            : undefined;\n          held = await executeWithContext({\n            span: observabilityContext?.tracingContext?.currentSpan,\n            fn: () =>\n              flush({\n                inputData: {\n                  phase: 'outputStream',\n                  streamParts: [],\n                  state: {},\n                  messageList,\n                  retryCount,\n                  processorStates: this.processorStates,\n                  abortSignal,\n                  agent: this.agent,\n                } as ProcessorStepOutput,\n                ...observabilityContext,\n                requestContext: requestContext ?? new RequestContext(),\n                outputWriter,\n              }),\n          });\n        } else {\n          held = await takeHeldParts(processorStates.get(processorOrWorkflow.id)?.customState);\n        }\n      } catch (error) {\n        if (error instanceof TripWire) {\n          results.push({\n            part: null,\n            blocked: true,\n            reason: error.message,\n            tripwireOptions: error.options,\n            processorId: error.processorId || processorOrWorkflow.id,\n          });\n          return results;\n        }\n        throw error;\n      }\n\n      for (const part of held) {\n        const result = await this.processPart(\n          part as ChunkType<OUTPUT>,\n          processorStates,\n          observabilityContext,\n          requestContext,\n          messageList,\n          retryCount,\n          writer,\n          abortSignal,\n          index + 1,\n        );\n        results.push(result);\n        if (result.blocked) return results;\n        const reprocessed = await this.drainReprocessParts(\n          processorStates,\n          observabilityContext,\n          requestContext,\n          messageList,\n          retryCount,\n          writer,\n          abortSignal,\n          index + 1,\n        );\n        results.push(...reprocessed);\n        if (reprocessed.some(r => r.blocked)) return results;\n      }\n    }\n\n    return results;\n  }\n\n  /**\n   * Call instead of {@link flushHeldParts} when a stream errored or was aborted:\n   * clears what processors hold without emitting or checking it, so a retry\n   * doesn't repeat it and nothing is emitted after cancellation.\n   */\n  /**\n   * Drops what output processors hold after a failed or aborted model stream, without running\n   * any checks. Returns the held control parts (start, error, finish, ...), oldest first.\n   */\n  async discardHeldParts<OUTPUT>(processorStates: Map<string, ProcessorState<OUTPUT>>): Promise<ChunkType<OUTPUT>[]> {\n    // A later processor holds parts that passed the earlier ones first, so it goes first.\n    const kept: ChunkType<OUTPUT>[] = [];\n    for (const processorOrWorkflow of [...this.outputProcessors].reverse()) {\n      const parts = isProcessorWorkflow(processorOrWorkflow)\n        ? ((await processorOrWorkflow.__discardOutputStream?.(this.processorStates)) ?? [])\n        : await takeHeldParts(processorStates.get(processorOrWorkflow.id)?.customState, { discard: true });\n      kept.push(...(parts as ChunkType<OUTPUT>[]));\n    }\n    return kept;\n  }\n\n  async runOutputProcessorsForStream<OUTPUT = undefined>(\n    streamResult: MastraModelOutput<OUTPUT>,\n    observabilityContext?: ObservabilityContext,\n    writer?: ProcessorStreamWriter,\n  ): Promise<ReadableStream<any>> {\n    return new ReadableStream({\n      start: async controller => {\n        const reader = streamResult.fullStream.getReader();\n        const processorStates = new Map<string, ProcessorState<OUTPUT>>();\n\n        // Use provided writer, or create one from the controller\n        const streamWriter = writer ?? {\n          custom: async (data: { type: string }) => controller.enqueue(data),\n        };\n\n        let streamFailed = false;\n        try {\n          while (true) {\n            const { done, value } = await reader.read();\n\n            if (done) {\n              if (streamFailed) {\n                for (const part of await this.discardHeldParts(processorStates)) controller.enqueue(part);\n                controller.close();\n                break;\n              }\n              for (const r of await this.flushHeldParts(\n                processorStates,\n                observabilityContext,\n                undefined,\n                undefined,\n                0,\n                streamWriter,\n              )) {\n                if (r.blocked) {\n                  controller.enqueue({\n                    type: 'tripwire',\n                    payload: {\n                      reason: r.reason || 'Output processor blocked content',\n                      retry: r.tripwireOptions?.retry,\n                      metadata: r.tripwireOptions?.metadata,\n                      processorId: r.processorId,\n                    },\n                  });\n                  break;\n                }\n                if (r.part != null) {\n                  controller.enqueue(r.part);\n                }\n              }\n              controller.close();\n              break;\n            }\n\n            if (isFailedStreamChunk(value)) streamFailed = true;\n\n            // Process all stream parts through output processors\n            const {\n              part: processedPart,\n              blocked,\n              reason,\n              tripwireOptions,\n              processorId,\n            } = await this.processPart(\n              value,\n              processorStates,\n              observabilityContext,\n              undefined,\n              undefined,\n              0,\n              streamWriter,\n            );\n\n            const enqueueTripwire = (r?: string, opts?: TripWireOptions<unknown>, pid?: string) => {\n              this.logger.debug('Stream part blocked by output processor', {\n                agent: this.agentName,\n                reason: r,\n                originalPart: value,\n              });\n              controller.enqueue({\n                type: 'tripwire',\n                payload: {\n                  reason: r || 'Output processor blocked content',\n                  retry: opts?.retry,\n                  metadata: opts?.metadata,\n                  processorId: pid,\n                },\n              });\n            };\n\n            if (blocked) {\n              // Send tripwire part and close stream for abort\n              enqueueTripwire(reason, tripwireOptions, processorId);\n              controller.close();\n              break;\n            } else if (processedPart != null) {\n              // Send processed part only if it's not null/undefined (which indicates don't emit)\n              controller.enqueue(processedPart);\n            }\n            // If processedPart is null/undefined, don't emit anything for this part\n\n            // Emit any parts a processor stashed for reprocessing (e.g. the\n            // non-text part that triggered a BatchPartsProcessor flush), pushing\n            // each back through the whole chain so it gets downstream processing.\n            const reprocessed = await this.drainReprocessParts(\n              processorStates,\n              observabilityContext,\n              undefined,\n              undefined,\n              0,\n              streamWriter,\n            );\n            let aborted = false;\n            for (const r of reprocessed) {\n              if (r.blocked) {\n                enqueueTripwire(r.reason, r.tripwireOptions, r.processorId);\n                controller.close();\n                aborted = true;\n                break;\n              }\n              if (r.part != null) {\n                controller.enqueue(r.part);\n              }\n            }\n            if (aborted) {\n              break;\n            }\n          }\n        } catch (error) {\n          controller.error(error);\n          await reader.cancel(error).catch(() => {});\n        }\n      },\n    });\n  }\n\n  async runInputProcessors(\n    messageList: MessageList,\n    observabilityContext?: ObservabilityContext,\n    requestContext?: RequestContext,\n    retryCount: number = 0,\n  ): Promise<MessageList> {\n    for (const [index, processorOrWorkflow] of this.inputProcessors.entries()) {\n      let processableMessages: MastraDBMessage[] = messageList.get.input.db();\n      const inputIds = processableMessages.map((m: MastraDBMessage) => m.id);\n      const check = messageList.makeMessageSourceChecker();\n\n      // Handle workflow as processor\n      if (isProcessorWorkflow(processorOrWorkflow)) {\n        const currentSystemMessages = messageList.getSystemMessages();\n        await this.executeWorkflowAsProcessor(\n          processorOrWorkflow,\n          {\n            phase: 'input',\n            messages: processableMessages,\n            messageList,\n            systemMessages: currentSystemMessages,\n            retryCount,\n          },\n          observabilityContext,\n          requestContext,\n        );\n        continue;\n      }\n\n      // Handle regular processor\n      const processor = processorOrWorkflow;\n      const abort = <TMetadata = unknown>(reason?: string, options?: TripWireOptions<TMetadata>): never => {\n        throw new TripWire(reason || `Tripwire triggered by ${processor.id}`, options, processor.id);\n      };\n\n      // Use the processInput method if available\n      const processMethod = processor.processInput?.bind(processor);\n\n      if (!processMethod) {\n        // Skip processors that don't implement processInput\n        continue;\n      }\n\n      const currentSystemMessages = messageList.getSystemMessages();\n      const inputMessagesBefore = processableMessages;\n      const inputSystemMessagesBefore = currentSystemMessages;\n      const currentSpan = observabilityContext?.tracingContext?.currentSpan;\n      const parentSpan = currentSpan?.findParent(SpanType.AGENT_RUN) || currentSpan?.parent || currentSpan;\n      const processorSpan = parentSpan?.createChildSpan({\n        type: processor.spanType ?? SpanType.PROCESSOR_RUN,\n        name: resolveProcessorSpanName(processor, 'input', `input processor: ${processor.id}`),\n        entityType: EntityType.INPUT_PROCESSOR,\n        entityId: processor.id,\n        entityName: processor.name,\n        attributes: {\n          ...resolveProcessorSpanAttributes(processor, 'input'),\n          processorExecutor: 'legacy',\n          processorIndex: index,\n        },\n        input: {\n          messages: processableMessages,\n          systemMessages: currentSystemMessages,\n        },\n      });\n\n      // Start recording MessageList mutations for this processor\n      messageList.startRecording();\n\n      try {\n        // Get per-processor state that persists across all method calls within this request\n        const processorState = this.getProcessorState(processor.id);\n\n        const result = await processMethod({\n          messages: processableMessages,\n          systemMessages: currentSystemMessages,\n          state: processorState.customState,\n          abort,\n          agent: this.agent,\n          ...createObservabilityContext({ currentSpan: processorSpan }),\n          messageList,\n          requestContext,\n          retryCount,\n          sendSignal: createProcessorSendSignal({ messageList, lateSink: this.lateSignalSink }),\n        });\n\n        // Handle MessageList, MastraDBMessage[], or { messages, systemMessages } return types\n        let mutations: Array<{\n          type: 'add' | 'addSystem' | 'removeByIds' | 'clear';\n          source?: string;\n          count?: number;\n          ids?: string[];\n          text?: string;\n          tag?: string;\n          message?: any;\n        }>;\n\n        if (result instanceof MessageList) {\n          if (result !== messageList) {\n            throw new MastraError({\n              category: 'USER',\n              domain: 'AGENT',\n              id: 'PROCESSOR_RETURNED_EXTERNAL_MESSAGE_LIST',\n              text: `Processor ${processor.id} returned a MessageList instance other than the one that was passed in as an argument. New external message list instances are not supported. Use the messageList argument instead.`,\n            });\n          }\n          // Stop recording and capture mutations\n          mutations = messageList.stopRecording();\n          if (mutations.length > 0) {\n            // Processor returned a MessageList - it has been modified in place\n            // Update processableMessages to reflect ALL current messages for next processor\n            processableMessages = messageList.get.input.db();\n          }\n        } else if (this.isProcessInputResultWithSystemMessages(result)) {\n          // Processor returned { messages, systemMessages } - handle both\n          mutations = messageList.stopRecording();\n\n          messageList.replaceAllSystemMessages(result.systemMessages);\n\n          // Handle regular messages\n          const regularMessages = result.messages;\n          if (regularMessages) {\n            const deletedIds = inputIds.filter(i => !regularMessages.some(m => m.id === i));\n            if (deletedIds.length) {\n              messageList.removeByIds(deletedIds);\n            }\n\n            // Separate any new system messages from other messages (backward compat)\n            const newSystemMessages = regularMessages.filter(m => m.role === 'system');\n            const nonSystemMessages = regularMessages.filter(m => m.role !== 'system');\n\n            // Add any new system messages from the messages array\n            for (const sysMsg of newSystemMessages) {\n              const systemText =\n                (sysMsg.content.content as string | undefined) ??\n                sysMsg.content.parts?.map(p => (p.type === 'text' ? p.text : '')).join('\\n') ??\n                '';\n              messageList.addSystem(systemText);\n            }\n\n            // Add non-system messages normally\n            if (nonSystemMessages.length > 0) {\n              for (const message of nonSystemMessages) {\n                messageList.removeByIds([message.id]);\n                messageList.add(message, check.getSource(message) || 'input', { merge: false });\n              }\n            }\n          }\n\n          processableMessages = messageList.get.input.db();\n        } else {\n          // Processor returned an array - stop recording before clear/add (that's just internal plumbing)\n          mutations = messageList.stopRecording();\n\n          if (result) {\n            // Clear and re-add since processor worked with array. clear all messages, the new result array is all messages in the list (new input but also any messages added by other processors, memory for ex)\n            const deletedIds = inputIds.filter(i => !result.some(m => m.id === i));\n            if (deletedIds.length) {\n              messageList.removeByIds(deletedIds);\n            }\n\n            // Separate system messages from other messages since they need different handling\n            const systemMessages = result.filter(m => m.role === 'system');\n            const nonSystemMessages = result.filter(m => m.role !== 'system');\n\n            // Add system messages using addSystem\n            for (const sysMsg of systemMessages) {\n              const systemText =\n                (sysMsg.content.content as string | undefined) ??\n                sysMsg.content.parts?.map(p => (p.type === 'text' ? p.text : '')).join('\\n') ??\n                '';\n              messageList.addSystem(systemText);\n            }\n\n            // Add non-system messages normally\n            if (nonSystemMessages.length > 0) {\n              for (const message of nonSystemMessages) {\n                messageList.removeByIds([message.id]);\n                messageList.add(message, check.getSource(message) || 'input', { merge: false });\n              }\n            }\n\n            // Use messageList.get.input.db() for consistency with MessageList return type\n            processableMessages = messageList.get.input.db();\n          }\n        }\n\n        processorSpan?.end({\n          output: {\n            ...(!areProcessorMessageArraysEqual(inputMessagesBefore, processableMessages)\n              ? { messages: processableMessages }\n              : {}),\n            ...(!areProcessorMessageArraysEqual(inputSystemMessagesBefore, messageList.getSystemMessages())\n              ? { systemMessages: messageList.getSystemMessages() }\n              : {}),\n          },\n          attributes: mutations.length > 0 ? { messageListMutations: mutations } : undefined,\n        });\n      } catch (error) {\n        // Stop recording on error\n        messageList.stopRecording();\n\n        if (error instanceof TripWire) {\n          processorSpan?.error({\n            error,\n            endSpan: true,\n            attributes: {\n              tripwireAbort: {\n                reason: error.message,\n                retry: error.options?.retry,\n                metadata: error.options?.metadata,\n              },\n            },\n          });\n          await invokeOnViolation(processor, error);\n          throw error;\n        }\n        processorSpan?.error({ error: error as Error, endSpan: true });\n        throw error;\n      }\n    }\n\n    return messageList;\n  }\n\n  /**\n   * Run processInputStep for all processors that implement it.\n   * Called at each step of the agentic loop, before the LLM is invoked.\n   *\n   * Unlike processInput which runs once at the start, this runs at every step\n   * (including tool call continuations). This is useful for:\n   * - Transforming message types between steps (e.g., AI SDK 'reasoning' -> Anthropic 'thinking')\n   * - Modifying messages based on step context\n   * - Implementing per-step message transformations\n   *\n   * @param args.messages - The current messages to be sent to the LLM (MastraDBMessage format)\n   * @param args.messageList - MessageList instance for managing message sources\n   * @param args.stepNumber - The current step number (0-indexed)\n   * @param args.tracingContext - Optional tracing context for observability\n   * @param args.requestContext - Optional runtime context with execution metadata\n   *\n   * @returns The processed MessageList\n   */\n  async runProcessInputStep(args: RunProcessInputStepArgs): Promise<RunProcessInputStepResult> {\n    const { messageList, stepNumber, steps, requestContext, writer } = args;\n    const observabilityContext = resolveObservabilityContext(args);\n\n    // Initialize with all provided values - processors will modify this object in order\n    const stepInput: RunProcessInputStepResult = {\n      messageId: args.messageId,\n      tools: args.tools,\n      toolChoice: args.toolChoice,\n      model: args.model,\n      activeTools: args.activeTools,\n      providerOptions: args.providerOptions,\n      modelSettings: args.modelSettings,\n      structuredOutput: args.structuredOutput,\n      retryCount: args.retryCount ?? 0,\n    };\n\n    const processors =\n      stepInput.model && needsTrailingAssistantGuard(stepInput.model, this.inputProcessors)\n        ? [...this.inputProcessors, new TrailingAssistantGuard()]\n        : this.inputProcessors;\n\n    // Run through all input processors that have processInputStep\n    for (const [index, processorOrWorkflow] of processors.entries()) {\n      const processableMessages: MastraDBMessage[] = messageList.get.all.db();\n      const idsBeforeProcessing = processableMessages.map((m: MastraDBMessage) => m.id);\n      const check = messageList.makeMessageSourceChecker();\n\n      // Handle workflow as processor with inputStep phase\n      if (isProcessorWorkflow(processorOrWorkflow)) {\n        const currentSystemMessages = messageList.getSystemMessages();\n        const result = await this.executeWorkflowAsProcessor(\n          processorOrWorkflow,\n          {\n            phase: 'inputStep',\n            messages: processableMessages,\n            messageList,\n            stepNumber,\n            runId: args.runId,\n            steps,\n            systemMessages: currentSystemMessages,\n            rotateResponseMessageId: args.rotateResponseMessageId\n              ? () => {\n                  const nextMessageId = args.rotateResponseMessageId!();\n                  stepInput.messageId = nextMessageId;\n                  return nextMessageId;\n                }\n              : undefined,\n            llmRequestProcessorIds: args.llmRequestProcessorIds,\n            ...stepInput,\n          },\n          observabilityContext,\n          requestContext,\n          writer,\n          args.abortSignal,\n        );\n        Object.assign(stepInput, result);\n        await this.runWorkflowComputeStateSignals({\n          workflow: processorOrWorkflow,\n          messageList,\n          stepNumber,\n          steps,\n          requestContext,\n          writer,\n          observabilityContext,\n          memory: args.memory,\n          resourceId: args.resourceId,\n          threadId: args.threadId,\n          abortSignal: args.abortSignal,\n          retryCount: args.retryCount ?? 0,\n          rotateResponseMessageId: args.rotateResponseMessageId\n            ? () => {\n                const nextMessageId = args.rotateResponseMessageId!();\n                stepInput.messageId = nextMessageId;\n                return nextMessageId;\n              }\n            : undefined,\n        });\n        continue;\n      }\n\n      // Handle regular processor\n      const processor = processorOrWorkflow as Processor;\n      const processMethod = processor.processInputStep?.bind(processor);\n      const computeStateSignal = processor.computeStateSignal?.bind(processor);\n      if (!processMethod && !computeStateSignal) {\n        // Skip processors that don't implement per-step input hooks\n        continue;\n      }\n\n      // The guard is attached speculatively whenever a processor could have swapped the\n      // model. Now that every user processor has run, `stepInput.model` is final: skip the\n      // guard before creating a span so a no-op never shows up in exported traces.\n      if (processorOrWorkflow instanceof TrailingAssistantGuard && !processorOrWorkflow.appliesTo(stepInput.model)) {\n        continue;\n      }\n\n      const abort = <TMetadata = unknown>(reason?: string, options?: TripWireOptions<TMetadata>): never => {\n        throw new TripWire(reason || `Tripwire triggered by ${processor.id}`, options, processor.id);\n      };\n\n      // Pass only the untagged system messages — tagged buckets belong to\n      // their owning processors and are merged back in at final model assembly.\n      const currentSystemMessages = messageList.getSystemMessages();\n\n      const inputData = {\n        messages: processableMessages,\n        runId: args.runId,\n        stepNumber,\n        steps,\n        messageId: stepInput.messageId,\n        systemMessages: currentSystemMessages,\n        tools: stepInput.tools,\n        toolChoice: stepInput.toolChoice,\n        model: stepInput.model!,\n        activeTools: stepInput.activeTools,\n        providerOptions: stepInput.providerOptions,\n        modelSettings: stepInput.modelSettings,\n        structuredOutput: stepInput.structuredOutput,\n        requestContext,\n        agent: this.agent,\n      };\n\n      // Use the current span (the step span) as the parent for processor spans\n      const currentSpan = observabilityContext.tracingContext?.currentSpan;\n      const processorSpan = currentSpan?.createChildSpan({\n        type: processor.spanType ?? SpanType.PROCESSOR_RUN,\n        name: resolveProcessorSpanName(processor, 'inputStep', `input step processor: ${processor.id}`),\n        entityType: EntityType.INPUT_STEP_PROCESSOR,\n        entityId: processor.id,\n        entityName: processor.name,\n        attributes: {\n          ...resolveProcessorSpanAttributes(processor, 'inputStep'),\n          processorExecutor: 'legacy',\n          processorIndex: index,\n        },\n        input: buildProcessInputStepSpanInput({\n          messages: inputData.messages,\n          systemMessages: inputData.systemMessages,\n          stepNumber: inputData.stepNumber,\n          messageId: inputData.messageId,\n          retryCount: args.retryCount ?? 0,\n          model: inputData.model,\n          tools: inputData.tools,\n          toolChoice: inputData.toolChoice,\n          activeTools: inputData.activeTools,\n        }),\n      });\n\n      // Start recording MessageList mutations for this processor\n      messageList.startRecording();\n\n      try {\n        // Get per-processor state that persists across all method calls within this request\n        const processorState = this.getProcessorState(processor.id);\n        const beforeStepInput = {\n          messageId: inputData.messageId,\n          model: inputData.model,\n          tools: inputData.tools,\n          toolChoice: inputData.toolChoice,\n          activeTools: inputData.activeTools,\n        };\n\n        const rotateResponseMessageId = args.rotateResponseMessageId\n          ? () => {\n              const nextMessageId = args.rotateResponseMessageId!();\n              stepInput.messageId = nextMessageId;\n              return nextMessageId;\n            }\n          : undefined;\n\n        const processMethodArgs = {\n          messageList,\n          ...inputData,\n          state: processorState.customState,\n          llmRequestStage: args.llmRequestProcessorIds?.has(processor.id) || undefined,\n          abort,\n          ...(rotateResponseMessageId ? { rotateResponseMessageId } : {}),\n          ...createObservabilityContext({ currentSpan: processorSpan }),\n          retryCount: args.retryCount ?? 0,\n          writer,\n          abortSignal: args.abortSignal,\n          agent: this.agent,\n          sendSignal: createProcessorSendSignal({\n            messageList,\n            writer,\n            rotateResponseMessageId,\n            lateSink: this.lateSignalSink,\n          }),\n          sendStateSignal: async (\n            stateSignal: AgentStateSignalInput | (Omit<AgentStateSignalInput, 'id'> & { id?: string }),\n          ) => {\n            const memoryContext = parseMemoryRequestContext(requestContext);\n            const resolvedMemory = args.memory;\n            const resolvedThreadId = args.threadId ?? memoryContext?.thread?.id;\n            const resolvedResourceId = args.resourceId ?? memoryContext?.resourceId;\n            if (!resolvedMemory || !resolvedThreadId || !resolvedResourceId) {\n              throw new Error(\n                `[Processor:${processor.id}] sendStateSignal requires Mastra memory with an active resourceId and threadId`,\n              );\n            }\n            const loadedThread =\n              (await resolvedMemory.getThreadById({ threadId: resolvedThreadId })) ?? memoryContext?.thread;\n            if (!loadedThread) {\n              throw new Error(`[Processor:${processor.id}] sendStateSignal could not load thread ${resolvedThreadId}`);\n            }\n            const thread = {\n              ...loadedThread,\n              id: resolvedThreadId,\n              resourceId: loadedThread.resourceId ?? resolvedResourceId,\n              createdAt: loadedThread.createdAt ?? new Date(),\n              updatedAt: loadedThread.updatedAt ?? new Date(),\n              metadata: loadedThread.metadata,\n            };\n            const result = await applyStateSignal({\n              input: stateSignal,\n              memory: resolvedMemory,\n              thread,\n              resourceId: resolvedResourceId,\n              threadId: resolvedThreadId,\n              memoryConfig: memoryContext?.memoryConfig,\n              messageList,\n              defaultId: processor.stateId ?? processor.id,\n              beforeAddSignal: rotateResponseMessageId,\n              writeSignal: signal => writer?.custom(signal.toDataPart()),\n            });\n            return result.skipped ? result : result.signal;\n          },\n        };\n\n        const result = processMethod\n          ? await ProcessorRunner.validateAndFormatProcessInputStepResult(await processMethod(processMethodArgs), {\n              messageList,\n              processor,\n              stepNumber,\n            })\n          : {};\n        const { messages, systemMessages, ...rest } = result;\n        if (messages) {\n          ProcessorRunner.applyMessagesToMessageList(messages, messageList, idsBeforeProcessing, check);\n        }\n        if (systemMessages) {\n          messageList.replaceAllSystemMessages(systemMessages);\n        }\n        Object.assign(stepInput, rest);\n\n        await this.runComputeStateSignal({\n          processor,\n          messageList,\n          stepNumber,\n          steps,\n          requestContext,\n          writer,\n          abort,\n          processorState,\n          // Parent the signal event on this processor's own span so the emission\n          // sits inside the processor that produced it.\n          observabilityContext: createObservabilityContext({ currentSpan: processorSpan }),\n          memory: args.memory,\n          resourceId: args.resourceId,\n          threadId: args.threadId,\n          abortSignal: args.abortSignal,\n          retryCount: args.retryCount ?? 0,\n          rotateResponseMessageId,\n        });\n\n        // Stop recording and get mutations for this processor\n        const mutations = messageList.stopRecording();\n\n        processorSpan?.end({\n          output: buildProcessInputStepSpanOutput({\n            result,\n            beforeStepInput,\n            afterStepInput: stepInput,\n            beforeMessages: inputData.messages,\n            beforeSystemMessages: inputData.systemMessages,\n            messages: messageList.get.all.db(),\n            systemMessages: messageList.getSystemMessages(),\n          }),\n          attributes: mutations.length > 0 ? { messageListMutations: mutations } : undefined,\n        });\n      } catch (error) {\n        // Stop recording on error\n        messageList.stopRecording();\n\n        if (error instanceof TripWire) {\n          processorSpan?.error({\n            error,\n            endSpan: true,\n            attributes: {\n              tripwireAbort: {\n                reason: error.message,\n                retry: error.options?.retry,\n                metadata: error.options?.metadata,\n              },\n            },\n          });\n          await invokeOnViolation(processor, error);\n          throw error;\n        }\n        processorSpan?.error({ error: error as Error, endSpan: true });\n        throw error;\n      }\n    }\n\n    return stepInput;\n  }\n\n  /**\n   * IDs of the processors that `runProcessLLMRequest` will call for these input processors.\n   * Pass the result to `runProcessInputStep` as `llmRequestProcessorIds`.\n   */\n  static getLLMRequestProcessorIds(processors: readonly ProcessorOrWorkflow[]): Set<string> {\n    const ids = new Set<string>();\n    for (const processor of processors) {\n      if (!isProcessorWorkflow(processor) && processor.processLLMRequest) ids.add(processor.id);\n    }\n    return ids;\n  }\n\n  /**\n   * Run processLLMRequest for all processors that implement it.\n   *\n   * Called *after* `MessageList` has been converted to `LanguageModelV2Prompt`\n   * and immediately *before* the prompt is forwarded to the provider.\n   * Mutations are scoped to this single call — they do not affect the\n   * persisted message list, memory, UI, or future model swaps.\n   */\n  async runProcessLLMRequest(args: {\n    prompt: LanguageModelV2Prompt;\n    model: unknown;\n    apiProviderId?: string;\n    messageList?: MessageList;\n    workspace?: AnyWorkspace;\n    stepNumber: number;\n    steps: Array<StepResult<any>>;\n    requestContext?: RequestContext;\n    retryCount?: number;\n    abortSignal?: AbortSignal;\n    tracingContext?: TracingContext;\n    writer?: ProcessorStreamWriter;\n  }): Promise<{ prompt: LanguageModelV2Prompt; response?: CachedLLMStepResponse }> {\n    const observabilityContext = resolveObservabilityContext({ tracingContext: args.tracingContext });\n\n    let currentPrompt = args.prompt;\n    let cachedResponse: CachedLLMStepResponse | undefined;\n\n    for (const [index, processorOrWorkflow] of this.inputProcessors.entries()) {\n      // Workflows do not currently participate in processLLMRequest.\n      if (isProcessorWorkflow(processorOrWorkflow)) continue;\n      const processor = processorOrWorkflow;\n      const processMethod = processor.processLLMRequest?.bind(processor);\n      if (!processMethod) continue;\n\n      const abort = <TMetadata = unknown>(reason?: string, options?: TripWireOptions<TMetadata>): never => {\n        throw new TripWire(reason || `Tripwire triggered by ${processor.id}`, options, processor.id);\n      };\n\n      // Use the current span (the step/model span) as the parent for processor spans\n      const currentSpan = observabilityContext.tracingContext?.currentSpan;\n      const processorSpan = currentSpan?.createChildSpan({\n        type: processor.spanType ?? SpanType.PROCESSOR_RUN,\n        name: resolveProcessorSpanName(processor, 'llmRequest', `llm request processor: ${processor.id}`),\n        entityType: EntityType.INPUT_PROCESSOR,\n        entityId: processor.id,\n        entityName: processor.name,\n        attributes: {\n          ...resolveProcessorSpanAttributes(processor, 'llmRequest'),\n          processorExecutor: 'legacy',\n          processorIndex: index,\n        },\n        input: {\n          prompt: currentPrompt,\n          stepNumber: args.stepNumber,\n          retryCount: args.retryCount ?? 0,\n        },\n      });\n\n      try {\n        const processorState = this.getProcessorState(processor.id);\n        const promptBefore = currentPrompt;\n\n        const result = await processMethod({\n          prompt: currentPrompt,\n          // The Processor interface types `model` as `MastraLanguageModel`, but\n          // the runner accepts the looser `unknown` to match other call paths\n          // (e.g. unresolved string ids or function-typed dynamic models).\n          model: args.model as never,\n          apiProviderId: args.apiProviderId,\n          messageList: args.messageList,\n          workspace: args.workspace,\n          stepNumber: args.stepNumber,\n          steps: args.steps,\n          state: processorState.customState,\n          retryCount: args.retryCount ?? 0,\n          requestContext: args.requestContext,\n          agent: this.agent,\n          abort,\n          abortSignal: args.abortSignal,\n          writer: args.writer,\n          ...createObservabilityContext({ currentSpan: processorSpan }),\n        });\n\n        if (result && typeof result === 'object') {\n          // Use property presence (not truthiness) so a processor can\n          // intentionally pass an empty prompt without it being silently\n          // ignored.\n          if (Object.prototype.hasOwnProperty.call(result, 'prompt')) {\n            currentPrompt = result.prompt as LanguageModelV2Prompt;\n          }\n          if (result.response && !cachedResponse) {\n            // First processor to short-circuit wins. Subsequent processors\n            // still see their `processLLMRequest` invoked so per-request side\n            // effects (telemetry, key derivation) run, but they cannot\n            // override an already-resolved cached response.\n            cachedResponse = result.response;\n          }\n        }\n\n        processorSpan?.end({\n          output: {\n            ...(currentPrompt !== promptBefore ? { prompt: currentPrompt } : {}),\n            shortCircuited: Boolean(result && typeof result === 'object' && result.response),\n          },\n        });\n      } catch (error) {\n        if (error instanceof TripWire) {\n          processorSpan?.error({\n            error,\n            endSpan: true,\n            attributes: {\n              tripwireAbort: {\n                reason: error.message,\n                retry: error.options?.retry,\n                metadata: error.options?.metadata,\n              },\n            },\n          });\n          await invokeOnViolation(processor, error);\n          throw error;\n        }\n        processorSpan?.error({ error: error as Error, endSpan: true });\n        throw error;\n      }\n    }\n\n    return { prompt: currentPrompt, response: cachedResponse };\n  }\n\n  /**\n   * Run processLLMResponse for all processors that implement it.\n   *\n   * Called *after* the LLM step completes (or after a cached response is\n   * replayed) and *after* output processors have collected the response\n   * chunks. The shared `state` object is the same instance passed to\n   * `processLLMRequest` for the same step, allowing processors to correlate\n   * pre- and post-call work (e.g. cache key stash, then cache write).\n   */\n  async runProcessLLMResponse(args: {\n    chunks: CachedLLMStepChunk[];\n    model: unknown;\n    stepNumber: number;\n    steps: Array<StepResult<any>>;\n    warnings?: LanguageModelV2CallWarning[];\n    request?: unknown;\n    rawResponse?: unknown;\n    fromCache: boolean;\n    requestContext?: RequestContext;\n    retryCount?: number;\n    abortSignal?: AbortSignal;\n    tracingContext?: TracingContext;\n    writer?: ProcessorStreamWriter;\n  }): Promise<void> {\n    const observabilityContext = resolveObservabilityContext({ tracingContext: args.tracingContext });\n\n    for (const [index, processorOrWorkflow] of this.inputProcessors.entries()) {\n      // Workflows do not currently participate in processLLMResponse.\n      if (isProcessorWorkflow(processorOrWorkflow)) continue;\n      const processor = processorOrWorkflow;\n      const processMethod = processor.processLLMResponse?.bind(processor);\n      if (!processMethod) continue;\n\n      const abort = <TMetadata = unknown>(reason?: string, options?: TripWireOptions<TMetadata>): never => {\n        throw new TripWire(reason || `Tripwire triggered by ${processor.id}`, options, processor.id);\n      };\n\n      // Use the current span (the step/model span) as the parent for processor spans\n      const currentSpan = observabilityContext.tracingContext?.currentSpan;\n      const processorSpan = currentSpan?.createChildSpan({\n        type: processor.spanType ?? SpanType.PROCESSOR_RUN,\n        name: resolveProcessorSpanName(processor, 'llmResponse', `llm response processor: ${processor.id}`),\n        entityType: EntityType.INPUT_PROCESSOR,\n        entityId: processor.id,\n        entityName: processor.name,\n        attributes: {\n          ...resolveProcessorSpanAttributes(processor, 'llmResponse'),\n          processorExecutor: 'legacy',\n          processorIndex: index,\n        },\n        input: {\n          stepNumber: args.stepNumber,\n          retryCount: args.retryCount ?? 0,\n          fromCache: args.fromCache,\n          chunkCount: args.chunks.length,\n        },\n      });\n\n      try {\n        const processorState = this.getProcessorState(processor.id);\n\n        await processMethod({\n          chunks: args.chunks,\n          model: args.model as never,\n          stepNumber: args.stepNumber,\n          steps: args.steps,\n          state: processorState.customState,\n          warnings: args.warnings,\n          request: args.request,\n          rawResponse: args.rawResponse,\n          fromCache: args.fromCache,\n          retryCount: args.retryCount ?? 0,\n          requestContext: args.requestContext,\n          agent: this.agent,\n          abort,\n          abortSignal: args.abortSignal,\n          writer: args.writer,\n          ...createObservabilityContext({ currentSpan: processorSpan }),\n        });\n\n        processorSpan?.end({ output: {} });\n      } catch (error) {\n        if (error instanceof TripWire) {\n          processorSpan?.error({\n            error,\n            endSpan: true,\n            attributes: {\n              tripwireAbort: {\n                reason: error.message,\n                retry: error.options?.retry,\n                metadata: error.options?.metadata,\n              },\n            },\n          });\n          await invokeOnViolation(processor, error);\n          throw error;\n        }\n        processorSpan?.error({ error: error as Error, endSpan: true });\n        throw error;\n      }\n    }\n  }\n\n  /**\n   * Type guard to check if result is { messages, systemMessages }\n   */\n  private isProcessInputResultWithSystemMessages(\n    result: unknown,\n  ): result is { messages: MastraDBMessage[]; systemMessages: unknown[] } {\n    return (\n      result !== null &&\n      typeof result === 'object' &&\n      'messages' in result &&\n      'systemMessages' in result &&\n      Array.isArray((result as any).messages) &&\n      Array.isArray((result as any).systemMessages)\n    );\n  }\n\n  /**\n   * Run processOutputStep for all processors that implement it.\n   * Called after each LLM response in the agentic loop, before tool execution.\n   *\n   * Unlike processOutputResult which runs once at the end, this runs at every step.\n   * This is the ideal place to implement guardrails that can trigger retries.\n   *\n   * @param args.messages - The current messages including the LLM response\n   * @param args.messageList - MessageList instance for managing message sources\n   * @param args.stepNumber - The current step number (0-indexed)\n   * @param args.finishReason - The finish reason from the LLM\n   * @param args.toolCalls - Tool calls made in this step (if any)\n   * @param args.text - Generated text from this step\n   * @param args.tracingContext - Optional tracing context for observability\n   * @param args.requestContext - Optional runtime context with execution metadata\n   * @param args.retryCount - Number of times processors have triggered retry\n   *\n   * @returns The processed MessageList\n   */\n  async runProcessOutputStep(\n    args: {\n      steps: Array<StepResult<any>>;\n      messages: MastraDBMessage[];\n      messageList: MessageList;\n      stepNumber: number;\n      finishReason?: string;\n      providerMetadata?: ProviderMetadata;\n      toolCalls?: ToolCallInfo[];\n      text?: string;\n      usage?: LanguageModelUsage;\n      requestContext?: RequestContext;\n      retryCount?: number;\n      writer?: ProcessorStreamWriter;\n    } & Partial<ObservabilityContext>,\n  ): Promise<MessageList> {\n    const {\n      steps,\n      messageList,\n      stepNumber,\n      finishReason,\n      providerMetadata,\n      toolCalls,\n      text,\n      usage,\n      requestContext,\n      retryCount = 0,\n      writer,\n    } = args;\n    const observabilityContext = resolveObservabilityContext(args);\n\n    // Run through all output processors that have processOutputStep\n    for (const [index, processorOrWorkflow] of this.outputProcessors.entries()) {\n      const processableMessages: MastraDBMessage[] = messageList.get.all.db();\n      const idsBeforeProcessing = processableMessages.map((m: MastraDBMessage) => m.id);\n      const check = messageList.makeMessageSourceChecker();\n\n      // Handle workflow as processor with outputStep phase\n      if (isProcessorWorkflow(processorOrWorkflow)) {\n        const currentSystemMessages = messageList.getSystemMessages();\n        await this.executeWorkflowAsProcessor(\n          processorOrWorkflow,\n          {\n            phase: 'outputStep',\n            messages: processableMessages,\n            messageList,\n            stepNumber,\n            finishReason,\n            providerMetadata,\n            toolCalls,\n            text,\n            usage,\n            systemMessages: currentSystemMessages,\n            steps,\n            retryCount,\n          },\n          observabilityContext,\n          requestContext,\n          writer,\n        );\n        continue;\n      }\n\n      // Handle regular processor\n      const processor = processorOrWorkflow;\n      const processMethod = processor.processOutputStep?.bind(processor);\n\n      if (!processMethod) {\n        // Skip processors that don't implement processOutputStep\n        continue;\n      }\n\n      const abort = <TMetadata = unknown>(reason?: string, options?: TripWireOptions<TMetadata>): never => {\n        throw new TripWire(reason || `Tripwire triggered by ${processor.id}`, options, processor.id);\n      };\n\n      const currentSystemMessages = messageList.getSystemMessages();\n      const defaultUsage: LanguageModelUsage = {\n        inputTokens: undefined,\n        outputTokens: undefined,\n        totalTokens: undefined,\n      };\n      const currentSpan = observabilityContext.tracingContext?.currentSpan;\n      const parentSpan = currentSpan?.findParent(SpanType.AGENT_RUN) || currentSpan?.parent || currentSpan;\n      const processorSpan = parentSpan?.createChildSpan({\n        type: processor.spanType ?? SpanType.PROCESSOR_RUN,\n        name: resolveProcessorSpanName(processor, 'outputStep', `output step processor: ${processor.id}`),\n        entityType: EntityType.OUTPUT_STEP_PROCESSOR,\n        entityId: processor.id,\n        entityName: processor.name,\n        attributes: {\n          ...resolveProcessorSpanAttributes(processor, 'outputStep'),\n          processorExecutor: 'legacy',\n          processorIndex: index,\n        },\n        input: {\n          messages: processableMessages,\n          systemMessages: currentSystemMessages,\n          stepNumber,\n          ...(finishReason !== undefined ? { finishReason } : {}),\n          ...(toolCalls !== undefined ? { toolCalls } : {}),\n          ...(text !== undefined ? { text } : {}),\n        },\n      });\n\n      // Start recording MessageList mutations for this processor\n      messageList.startRecording();\n\n      // Get or create processor state (persists across steps within a request)\n      const processorState = this.getProcessorState(processor.id);\n\n      try {\n        const result = await processMethod({\n          messages: processableMessages,\n          messageList,\n          stepNumber,\n          finishReason,\n          providerMetadata,\n          toolCalls,\n          text,\n          usage: usage ?? defaultUsage,\n          systemMessages: currentSystemMessages,\n          steps,\n          state: processorState.customState,\n          abort,\n          ...createObservabilityContext({ currentSpan: processorSpan }),\n          requestContext,\n          agent: this.agent,\n          retryCount,\n          writer,\n          sendSignal: createProcessorSendSignal({ messageList, writer, lateSink: this.lateSignalSink }),\n        });\n\n        // Stop recording and get mutations for this processor\n        const mutations = messageList.stopRecording();\n\n        // Handle the return type - MessageList or MastraDBMessage[]\n        if (result instanceof MessageList) {\n          if (result !== messageList) {\n            throw new MastraError({\n              category: 'USER',\n              domain: 'AGENT',\n              id: 'PROCESSOR_RETURNED_EXTERNAL_MESSAGE_LIST',\n              text: `Processor ${processor.id} returned a MessageList instance other than the one that was passed in as an argument. New external message list instances are not supported. Use the messageList argument instead.`,\n            });\n          }\n          // Processor returned the same messageList - mutations have been applied\n        } else if (result) {\n          // Processor returned an array - apply changes to messageList\n          const deletedIds = idsBeforeProcessing.filter(\n            (i: string) => !result.some((m: MastraDBMessage) => m.id === i),\n          );\n          if (deletedIds.length) {\n            messageList.removeByIds(deletedIds);\n          }\n\n          // Re-add messages with correct sources\n          for (const message of result) {\n            messageList.removeByIds([message.id]);\n            if (message.role === 'system') {\n              const systemText =\n                (message.content.content as string | undefined) ??\n                message.content.parts?.map((p: any) => (p.type === 'text' ? p.text : '')).join('\\n') ??\n                '';\n              messageList.addSystem(systemText);\n            } else {\n              messageList.add(message, check.getSource(message) || 'response', { merge: false });\n            }\n          }\n        }\n\n        processorSpan?.end({\n          output: {\n            ...(!areProcessorMessageArraysEqual(processableMessages, messageList.get.all.db())\n              ? { messages: messageList.get.all.db() }\n              : {}),\n            ...(!areProcessorMessageArraysEqual(currentSystemMessages, messageList.getSystemMessages())\n              ? { systemMessages: messageList.getSystemMessages() }\n              : {}),\n          },\n          attributes: mutations.length > 0 ? { messageListMutations: mutations } : undefined,\n        });\n      } catch (error) {\n        // Stop recording on error\n        messageList.stopRecording();\n\n        if (error instanceof TripWire) {\n          processorSpan?.error({\n            error,\n            endSpan: true,\n            attributes: {\n              tripwireAbort: {\n                reason: error.message,\n                retry: error.options?.retry,\n                metadata: error.options?.metadata,\n              },\n            },\n          });\n          await invokeOnViolation(processor, error);\n          throw error;\n        }\n        processorSpan?.error({ error: error as Error, endSpan: true });\n        throw error;\n      }\n    }\n\n    return messageList;\n  }\n\n  /**\n   * Run processToolResult on all output processors that implement it.\n   * Called after tool.execute() returns and before the result is appended to\n   * the message list / fed to the next LLM call.\n   *\n   * Symmetric with runProcessOutputStep — same TripWire/abort/state plumbing.\n   * Processors mutate via messageList.updateToolInvocation. The caller is\n   * responsible for re-reading the post-mutation result and syncing it into\n   * the downstream stream chunk so streaming clients see the processed value.\n   */\n  async runProcessToolResult(\n    args: {\n      steps: Array<StepResult<any>>;\n      messages: MastraDBMessage[];\n      messageList: MessageList;\n      stepNumber: number;\n      toolName: string;\n      toolCallId: string;\n      toolArgs: unknown;\n      result: unknown;\n      modelOutput?: unknown;\n      providerExecuted?: boolean;\n      requestContext?: RequestContext;\n      retryCount?: number;\n      writer?: ProcessorStreamWriter;\n      abortSignal?: AbortSignal;\n    } & Partial<ObservabilityContext>,\n  ): Promise<MessageList> {\n    const {\n      steps,\n      messageList,\n      stepNumber,\n      toolName,\n      toolCallId,\n      toolArgs,\n      result,\n      modelOutput,\n      providerExecuted,\n      requestContext,\n      retryCount = 0,\n      writer,\n      abortSignal,\n    } = args;\n    const observabilityContext = resolveObservabilityContext(args);\n\n    // Run through all output processors that have processToolResult\n    for (const [index, processorOrWorkflow] of this.outputProcessors.entries()) {\n      // Each processor sees the mapping an earlier processor committed, not the original.\n      const currentModelOutput = latestProcessedModelOutput(messageList, toolCallId, modelOutput);\n      const processableMessages: MastraDBMessage[] = messageList.get.all.db();\n      const idsBeforeProcessing = processableMessages.map((m: MastraDBMessage) => m.id);\n      const check = messageList.makeMessageSourceChecker();\n\n      // Handle workflow as processor with toolResult phase\n      if (isProcessorWorkflow(processorOrWorkflow)) {\n        const currentSystemMessages = messageList.getAllSystemMessages();\n        await this.executeWorkflowAsProcessor(\n          processorOrWorkflow,\n          {\n            phase: 'toolResult',\n            messages: processableMessages,\n            messageList,\n            stepNumber,\n            toolName,\n            toolCallId,\n            args: toolArgs,\n            // Carry the tool return value via toolResultValue to avoid colliding\n            // with the OutputResult `result` field used by outputResult phase.\n            toolResultValue: result,\n            modelOutput: currentModelOutput,\n            providerExecuted,\n            systemMessages: currentSystemMessages,\n            steps,\n            retryCount,\n          },\n          observabilityContext,\n          requestContext,\n          writer,\n          abortSignal,\n        );\n        continue;\n      }\n\n      // Handle regular processor\n      const processor = processorOrWorkflow;\n      const processMethod = processor.processToolResult?.bind(processor);\n\n      if (!processMethod) {\n        // Skip processors that don't implement processToolResult\n        continue;\n      }\n\n      const abort = <TMetadata = unknown>(reason?: string, options?: TripWireOptions<TMetadata>): never => {\n        throw new TripWire(reason || `Tripwire triggered by ${processor.id}`, options, processor.id);\n      };\n\n      const currentSystemMessages = messageList.getAllSystemMessages();\n      const currentSpan = observabilityContext.tracingContext?.currentSpan;\n      const parentSpan = currentSpan?.findParent(SpanType.AGENT_RUN) || currentSpan?.parent || currentSpan;\n      const processorSpan = parentSpan?.createChildSpan({\n        type: processor.spanType ?? SpanType.PROCESSOR_RUN,\n        name: resolveProcessorSpanName(processor, 'toolResult', `tool result processor: ${processor.id}`),\n        entityType: EntityType.TOOL_RESULT_PROCESSOR,\n        entityId: processor.id,\n        entityName: processor.name,\n        attributes: {\n          ...resolveProcessorSpanAttributes(processor, 'toolResult'),\n          processorExecutor: 'legacy',\n          processorIndex: index,\n        },\n        input: {\n          toolName,\n          toolCallId,\n          stepNumber,\n          ...(providerExecuted !== undefined ? { providerExecuted } : {}),\n        },\n      });\n\n      // Start recording MessageList mutations for this processor\n      messageList.startRecording();\n\n      // Get or create processor state (persists across calls within a request)\n      const processorState = this.getProcessorState(processor.id);\n\n      try {\n        const processorResult = await processMethod({\n          messages: processableMessages,\n          messageList,\n          stepNumber,\n          toolName,\n          toolCallId,\n          args: toolArgs,\n          result,\n          modelOutput: currentModelOutput,\n          providerExecuted,\n          systemMessages: currentSystemMessages,\n          steps,\n          state: processorState.customState,\n          abort,\n          ...createObservabilityContext({ currentSpan: processorSpan }),\n          requestContext,\n          retryCount,\n          writer,\n          abortSignal,\n        });\n\n        // Stop recording and get mutations for this processor\n        const mutations = messageList.stopRecording();\n\n        // Handle the return type — MessageList or MastraDBMessage[]\n        if (processorResult instanceof MessageList) {\n          if (processorResult !== messageList) {\n            throw new MastraError({\n              category: 'USER',\n              domain: 'AGENT',\n              id: 'PROCESSOR_RETURNED_EXTERNAL_MESSAGE_LIST',\n              text: `Processor ${processor.id} returned a MessageList instance other than the one that was passed in as an argument. New external message list instances are not supported. Use the messageList argument instead.`,\n            });\n          }\n          // Processor returned the same messageList — mutations have been applied\n        } else if (processorResult) {\n          // Processor returned an array — apply changes to messageList\n          ProcessorRunner.applyMessagesToMessageList(\n            processorResult as MastraDBMessage[],\n            messageList,\n            idsBeforeProcessing,\n            check,\n            'response',\n          );\n        }\n\n        processorSpan?.end({\n          output: {\n            ...(!areProcessorMessageArraysEqual(processableMessages, messageList.get.all.db())\n              ? { messages: messageList.get.all.db() }\n              : {}),\n            ...(!areProcessorMessageArraysEqual(currentSystemMessages, messageList.getAllSystemMessages())\n              ? { systemMessages: messageList.getAllSystemMessages() }\n              : {}),\n          },\n          attributes: mutations.length > 0 ? { messageListMutations: mutations } : undefined,\n        });\n      } catch (error) {\n        // Stop recording on error\n        messageList.stopRecording();\n\n        if (error instanceof TripWire) {\n          processorSpan?.error({\n            error,\n            endSpan: true,\n            attributes: {\n              tripwireAbort: {\n                reason: error.message,\n                retry: error.options?.retry,\n                metadata: error.options?.metadata,\n              },\n            },\n          });\n          throw error;\n        }\n        processorSpan?.error({ error: error as Error, endSpan: true });\n        throw error;\n      }\n    }\n\n    return messageList;\n  }\n\n  /**\n   * Run processAPIError on all processors that implement it.\n   * Called when an LLM API call fails with a non-retryable error.\n   * Iterates through both input and output processors.\n   *\n   * @returns { retry: boolean } indicating whether to retry the LLM call\n   */\n  async runProcessAPIError(\n    args: {\n      error: unknown;\n      messages: MastraDBMessage[];\n      messageList: MessageList;\n      stepNumber: number;\n      steps: Array<StepResult<any>>;\n      messageId?: string;\n      requestContext?: RequestContext;\n      retryCount?: number;\n      writer?: ProcessorStreamWriter;\n      abortSignal?: AbortSignal;\n      rotateResponseMessageId?: () => string;\n    } & Partial<ObservabilityContext>,\n  ): Promise<{ retry: boolean }> {\n    const { error, messageList, stepNumber, steps, requestContext, retryCount = 0, writer, abortSignal } = args;\n    const observabilityContext = resolveObservabilityContext(args);\n\n    const allProcessors: ProcessorOrWorkflow[] = [\n      ...this.inputProcessors,\n      ...this.outputProcessors,\n      ...this.errorProcessors,\n    ];\n\n    for (const [index, processorOrWorkflow] of allProcessors.entries()) {\n      // Skip workflows — processAPIError is only available on Processor instances\n      if (isProcessorWorkflow(processorOrWorkflow)) {\n        continue;\n      }\n\n      const processor = processorOrWorkflow;\n      const processMethod = processor.processAPIError?.bind(processor);\n\n      if (!processMethod) {\n        continue;\n      }\n\n      const abort = <TMetadata = unknown>(reason?: string, options?: TripWireOptions<TMetadata>): never => {\n        throw new TripWire(reason || `Tripwire triggered by ${processor.id}`, options, processor.id);\n      };\n\n      const processableMessages: MastraDBMessage[] = messageList.get.all.db();\n      const systemMessagesBefore = messageList.getAllSystemMessages();\n      const messageIdBefore = args.messageId;\n      let messageIdAfter = args.messageId;\n      const currentSpan = observabilityContext.tracingContext?.currentSpan;\n      // The failed call's MODEL_STEP is still open here, so the span sits under it\n      // like the step's other processor spans, not flat under the agent run.\n      const parentSpan =\n        findOwnModelStepSpan(currentSpan) ??\n        (currentSpan?.findParent(SpanType.AGENT_RUN) || currentSpan?.parent || currentSpan);\n      const processorSpan = parentSpan?.createChildSpan({\n        type: processor.spanType ?? SpanType.PROCESSOR_RUN,\n        name: resolveProcessorSpanName(processor, 'requestError', `request error processor: ${processor.id}`),\n        entityType: EntityType.OUTPUT_STEP_PROCESSOR,\n        entityId: processor.id,\n        entityName: processor.name,\n        attributes: {\n          ...resolveProcessorSpanAttributes(processor, 'requestError'),\n          processorExecutor: 'legacy',\n          processorIndex: index,\n        },\n        input: {\n          messages: processableMessages,\n          error: error instanceof Error ? error.message : String(error),\n          stepNumber,\n          ...(args.messageId ? { messageId: args.messageId } : {}),\n          retryCount,\n        },\n      });\n\n      // Start recording MessageList mutations for this processor\n      messageList.startRecording();\n\n      // Get or create processor state (persists across steps within a request)\n      const processorState = this.getProcessorState(processor.id);\n\n      try {\n        const rotateResponseMessageId = args.rotateResponseMessageId\n          ? () => {\n              const nextMessageId = args.rotateResponseMessageId!();\n              messageIdAfter = nextMessageId;\n              return nextMessageId;\n            }\n          : undefined;\n\n        const result = await processMethod({\n          messages: processableMessages,\n          messageList,\n          stepNumber,\n          steps,\n          state: processorState.customState,\n          error,\n          abort,\n          ...createObservabilityContext({ currentSpan: processorSpan }),\n          requestContext,\n          agent: this.agent,\n          retryCount,\n          writer,\n          abortSignal,\n          messageId: args.messageId,\n          ...(rotateResponseMessageId ? { rotateResponseMessageId } : {}),\n          sendSignal: createProcessorSendSignal({\n            messageList,\n            writer,\n            rotateResponseMessageId,\n            lateSink: this.lateSignalSink,\n          }),\n        });\n\n        // Stop recording and get mutations for this processor\n        const mutations = messageList.stopRecording();\n        const messagesAfter = messageList.get.all.db();\n        const systemMessagesAfter = messageList.getAllSystemMessages();\n        const output: Record<string, unknown> = {\n          retry: result?.retry ?? false,\n        };\n\n        if (!areProcessorMessageArraysEqual(processableMessages, messagesAfter)) {\n          output.messages = messagesAfter;\n        }\n\n        if (!areProcessorMessageArraysEqual(systemMessagesBefore, systemMessagesAfter)) {\n          output.systemMessages = systemMessagesAfter;\n        }\n\n        if (messageIdAfter !== messageIdBefore) {\n          output.messageId = messageIdAfter;\n        }\n\n        processorSpan?.end({\n          output,\n          attributes: mutations.length > 0 ? { messageListMutations: mutations } : undefined,\n        });\n\n        if (result?.retry) {\n          return { retry: true };\n        }\n      } catch (processorError) {\n        // Stop recording on error\n        messageList.stopRecording();\n\n        if (processorError instanceof TripWire) {\n          processorSpan?.error({\n            error: processorError,\n            endSpan: true,\n            attributes: {\n              tripwireAbort: {\n                reason: processorError.message,\n                retry: processorError.options?.retry,\n                metadata: processorError.options?.metadata,\n              },\n            },\n          });\n          await invokeOnViolation(processor, processorError);\n          throw processorError;\n        }\n\n        processorSpan?.error({ error: processorError as Error, endSpan: true });\n        this.logger.error(\n          `[Agent:${this.agentName}] - Request error processor ${processor.id} failed:`,\n          processorError,\n        );\n        // Don't re-throw — if the error processor itself fails, fall through to original error handling\n      }\n    }\n\n    return { retry: false };\n  }\n\n  static applyMessagesToMessageList(\n    messages: MastraDBMessage[],\n    messageList: MessageList,\n    idsBeforeProcessing: string[],\n    check: ReturnType<MessageList['makeMessageSourceChecker']>,\n    defaultSource: 'input' | 'response' = 'input',\n  ) {\n    const deletedIds = idsBeforeProcessing.filter(i => !messages.some(m => m.id === i));\n    if (deletedIds.length) {\n      messageList.removeByIds(deletedIds);\n    }\n\n    const currentById = new Map(messageList.get.all.db().map(message => [message.id, message]));\n\n    // Re-add messages with correct sources\n    for (const message of messages) {\n      if (currentById.get(message.id) === message) {\n        continue;\n      }\n\n      messageList.removeByIds([message.id]);\n      if (message.role === 'system') {\n        const systemText =\n          (message.content.content as string | undefined) ??\n          message.content.parts?.map(p => (p.type === 'text' ? p.text : '')).join('\\n') ??\n          '';\n        messageList.addSystem(systemText);\n      } else {\n        messageList.add(message, check.getSource(message) || defaultSource, { merge: false });\n      }\n    }\n  }\n\n  static async validateAndFormatProcessInputStepResult(\n    result: ProcessInputStepResult | Awaited<ProcessorMessageResult> | undefined | void,\n    {\n      messageList,\n      processor,\n      stepNumber,\n    }: {\n      messageList: MessageList;\n      processor: Processor;\n      stepNumber: number;\n    },\n  ): Promise<RunProcessInputStepResult> {\n    if (result instanceof MessageList) {\n      if (result !== messageList) {\n        throw new MastraError({\n          category: 'USER',\n          domain: 'AGENT',\n          id: 'PROCESSOR_RETURNED_EXTERNAL_MESSAGE_LIST',\n          text: `Processor ${processor.id} returned a MessageList instance other than the one that was passed in as an argument. New external message list instances are not supported. Use the messageList argument instead.`,\n        });\n      }\n      return {\n        messageList: result,\n      };\n    } else if (Array.isArray(result)) {\n      return {\n        messages: result,\n      };\n    } else if (result) {\n      if (result.messageList && result.messageList !== messageList) {\n        throw new MastraError({\n          category: 'USER',\n          domain: 'AGENT',\n          id: 'PROCESSOR_RETURNED_EXTERNAL_MESSAGE_LIST',\n          text: `Processor ${processor.id} returned a MessageList instance other than the one that was passed in as an argument. New external message list instances are not supported. Use the messageList argument instead.`,\n        });\n      }\n      if (result.messages && result.messageList) {\n        throw new MastraError({\n          category: 'USER',\n          domain: 'AGENT',\n          id: 'PROCESSOR_RETURNED_MESSAGES_AND_MESSAGE_LIST',\n          text: `Processor ${processor.id} returned both messages and messageList. Only one of these is allowed.`,\n        });\n      }\n      const { model: _model, ...rest } = result;\n      if (result.model) {\n        const resolvedModel = await resolveModelConfig(result.model);\n        const isSupported = isSupportedLanguageModel(resolvedModel);\n        if (!isSupported) {\n          throw new MastraError({\n            category: 'USER',\n            domain: 'AGENT',\n            id: 'PROCESSOR_RETURNED_UNSUPPORTED_MODEL',\n            text: `Processor ${processor.id} returned an unsupported model version ${resolvedModel.specificationVersion} in step ${stepNumber}. Only ${supportedLanguageModelSpecifications.join(', ')} models are supported in processInputStep.`,\n          });\n        }\n\n        return {\n          model: resolvedModel,\n          ...rest,\n        };\n      }\n\n      return rest;\n    }\n\n    return {};\n  }\n}\n","import type { AgentSignalCategory, AgentSignalType } from '../agent/signals';\n\nfunction canonicalSignalType(type: unknown): AgentSignalCategory | undefined {\n  switch (type) {\n    case 'system-reminder':\n      return 'reactive';\n    case 'user-message':\n      return 'user';\n    case 'user':\n    case 'state':\n    case 'reactive':\n    case 'notification':\n      return type;\n    default:\n      return undefined;\n  }\n}\n\n/** @internal Caller-local policy; never apply to shared buffers or model messages. */\nexport function isSignalChunkExcluded(\n  chunk: unknown,\n  hideSignals: boolean | readonly AgentSignalType[] | undefined,\n): boolean {\n  if (!hideSignals || !chunk || typeof chunk !== 'object') return false;\n  if (\n    !('type' in chunk) ||\n    (chunk.type !== 'data-signal' && chunk.type !== 'data-user-message' && chunk.type !== 'data-user-message-pending')\n  )\n    return false;\n  if (!('data' in chunk) || !chunk.data || typeof chunk.data !== 'object' || Array.isArray(chunk.data)) return false;\n  if (!('type' in chunk.data)) return false;\n  const type = canonicalSignalType(chunk.data.type);\n  return (\n    type !== undefined && (hideSignals === true || hideSignals.some(excluded => canonicalSignalType(excluded) === type))\n  );\n}\n","import type { JSONSchema7, Schema } from '@internal/ai-sdk-v5';\nimport { AnthropicSchemaCompatLayer, applyCompatLayer } from '@mastra/schema-compat';\nimport type { z as z3 } from 'zod/v3';\nimport type { z as z4 } from 'zod/v4';\nimport type { PublicSchema, StandardSchemaWithJSON } from '../../schema';\nimport { isStandardSchemaWithJSON, standardSchemaToJSONSchema } from '../../schema';\n\nexport type PartialSchemaOutput<OUTPUT = undefined> = OUTPUT extends undefined ? undefined : Partial<OUTPUT>;\n\n/**\n * @deprecated Use StandardSchemaWithJSON from '../../schema' instead\n */\nexport type OutputSchema<OBJECT = any> =\n  | z4.ZodType<OBJECT, any>\n  | z3.Schema<OBJECT, z3.ZodTypeDef, any>\n  | Schema<OBJECT>\n  | JSONSchema7\n  | undefined;\n\n/**\n * @deprecated Use StandardSchemaWithJSON from '../../schema' instead\n * Legacy type for schema validation.\n */\nexport type SchemaWithValidation<T = any> = z4.ZodType<T, any> | z3.Schema<T, z3.ZodTypeDef, any>;\n\n/**\n * @deprecated Use InferPublicSchema or InferStandardSchemaOutput from '../../schema' instead\n * Infer the output type from a schema\n */\nexport type InferSchemaOutput<T> =\n  T extends z4.ZodType<infer O, any>\n    ? O\n    : T extends z3.Schema<infer O, z3.ZodTypeDef, any>\n      ? O\n      : T extends Schema<infer O>\n        ? O\n        : unknown;\n\n/**\n * @deprecated Use PublicSchema from '../../schema' instead\n */\nexport type InferZodLikeSchema<T> =\n  T extends z4.ZodType<infer O, any> ? O : T extends z3.Schema<infer O, z3.ZodTypeDef, any> ? O : unknown;\n\nexport type ZodLikePartialSchema<T = any> =\n  | (z4.core.$ZodType<Partial<T>, any> & {\n      safeParse(value: unknown): { success: boolean; data?: Partial<T>; error?: any };\n    })\n  | (z3.ZodType<Partial<T>, z3.ZodTypeDef, any> & {\n      safeParse(value: unknown): { success: boolean; data?: Partial<T>; error?: any };\n    });\n\nexport function asJsonSchema(schema: StandardSchemaWithJSON | undefined): JSONSchema7 | undefined {\n  if (!schema) {\n    return undefined;\n  }\n\n  // Handle StandardSchemaWithJSON\n  if (isStandardSchemaWithJSON(schema)) {\n    // Use 'input' IO mode to get the schema BEFORE transforms are applied\n    // This is critical for OpenAI compat transforms that add .transform()\n    // which can't be properly represented in JSON Schema\n    //\n    // Use 'draft-07' target for maximum compatibility with LLM providers\n    const jsonSchema = standardSchemaToJSONSchema(schema, { io: 'input', target: 'draft-07' });\n\n    return jsonSchema;\n  }\n\n  return schema;\n}\n\ntype SchemaModelInfo = {\n  provider: string;\n  modelId: string;\n  supportsStructuredOutputs: boolean;\n};\n\nexport function getTransformedSchema<OUTPUT = undefined>(\n  schema?: StandardSchemaWithJSON<OUTPUT>,\n  options?: { model?: SchemaModelInfo },\n) {\n  if (!schema) {\n    return undefined;\n  }\n\n  const jsonSchema = options?.model\n    ? (applyCompatLayer({\n        schema: schema as PublicSchema<OUTPUT>,\n        compatLayers: [new AnthropicSchemaCompatLayer(options.model)],\n        mode: 'jsonSchema',\n      }) as JSONSchema7)\n    : asJsonSchema(schema);\n\n  if (!jsonSchema) {\n    return undefined;\n  }\n\n  const { $schema, ...itemSchema } = jsonSchema;\n  if (itemSchema.type === 'array') {\n    const innerElement = itemSchema.items;\n    const arrayOutputSchema: JSONSchema7 = {\n      $schema: $schema,\n      type: 'object',\n      properties: {\n        elements: { type: 'array', items: innerElement },\n      },\n      required: ['elements'],\n      additionalProperties: false,\n    };\n\n    return {\n      jsonSchema: arrayOutputSchema,\n      outputFormat: 'array',\n    };\n  }\n\n  // Handle enum schemas - wrap in object like AI SDK does\n  if (itemSchema.enum && Array.isArray(itemSchema.enum)) {\n    const enumOutputSchema: JSONSchema7 = {\n      $schema: $schema,\n      type: 'object',\n      properties: {\n        result: { type: itemSchema.type || 'string', enum: itemSchema.enum },\n      },\n      required: ['result'],\n      additionalProperties: false,\n    };\n\n    return {\n      jsonSchema: enumOutputSchema,\n      outputFormat: 'enum',\n    };\n  }\n\n  return {\n    jsonSchema: jsonSchema,\n    outputFormat: jsonSchema.type, // 'object'\n  };\n}\n\nexport function getResponseFormat(\n  schema?: StandardSchemaWithJSON,\n  options?: { model?: SchemaModelInfo },\n):\n  | {\n      type: 'text';\n    }\n  | {\n      type: 'json';\n      /**\n       * JSON schema that the generated output should conform to.\n       */\n      schema?: JSONSchema7;\n    } {\n  if (schema) {\n    const transformedSchema = getTransformedSchema(schema, options);\n    return {\n      type: 'json',\n      schema: transformedSchema?.jsonSchema,\n    };\n  }\n\n  // response format 'text' for everything else\n  return {\n    type: 'text',\n  };\n}\n","import { TransformStream } from 'node:stream/web';\nimport { isDeepEqualData, parsePartialJson } from '@internal/ai-sdk-v5';\nimport { isZodType } from '@mastra/schema-compat';\nimport type { StructuredOutputOptions } from '../../agent/types';\nimport { ErrorCategory, ErrorDomain, MastraError } from '../../error';\nimport type { IMastraLogger } from '../../logger';\nimport type { ZodType, PublicSchema, StandardSchemaWithJSON } from '../../schema';\nimport { toStandardSchema, standardSchemaToJSONSchema } from '../../schema';\nimport type { ValidationResult } from '../aisdk/v5/compat';\nimport { ChunkFrom } from '../types';\nimport type { ChunkType, MastraFinishReason } from '../types';\nimport { getTransformedSchema } from './schema';\nimport type { ZodLikePartialSchema } from './schema';\n\ntype StreamTransformerStructuredOutput<OUTPUT> = Omit<StructuredOutputOptions<OUTPUT>, 'schema'> & {\n  schema: PublicSchema<OUTPUT>;\n};\n\n/**\n * Escapes unescaped newlines, carriage returns, and tabs within JSON string values.\n *\n * LLMs often output actual newline characters inside JSON strings instead of properly\n * escaped \\n sequences, which breaks JSON parsing. This function fixes that by:\n * 1. Tracking whether we're inside a JSON string (after an unescaped quote)\n * 2. Replacing literal newlines/tabs with their escape sequences only inside strings\n * 3. Preserving already-escaped sequences like \\\\n\n *\n * @param text - Raw JSON text that may contain unescaped control characters in strings\n * @returns JSON text with control characters properly escaped inside string values\n */\nexport function escapeUnescapedControlCharsInJsonStrings(text: string): string {\n  let result = '';\n  let inString = false;\n  let i = 0;\n\n  while (i < text.length) {\n    const char = text[i];\n\n    // Check for escape sequences\n    if (char === '\\\\' && i + 1 < text.length) {\n      // This is an escape sequence - pass through both characters\n      result += char + text[i + 1];\n      i += 2;\n      continue;\n    }\n\n    // Track string boundaries (unescaped quotes)\n    if (char === '\"') {\n      inString = !inString;\n      result += char;\n      i++;\n      continue;\n    }\n\n    // If inside a string, escape control characters\n    if (inString) {\n      if (char === '\\n') {\n        result += '\\\\n';\n        i++;\n        continue;\n      }\n      if (char === '\\r') {\n        result += '\\\\r';\n        i++;\n        continue;\n      }\n      if (char === '\\t') {\n        result += '\\\\t';\n        i++;\n        continue;\n      }\n    }\n\n    result += char;\n    i++;\n  }\n\n  return result;\n}\n\nfunction extractBalancedJsonObject(text: string): string | undefined {\n  const trimmed = text.trim();\n  if (trimmed.startsWith('{') || trimmed.startsWith('[')) return undefined;\n\n  let start = -1;\n  let depth = 0;\n  let inString = false;\n  let escaped = false;\n  let lastBalanced: string | undefined;\n\n  for (let i = 0; i < text.length; i++) {\n    const char = text[i];\n\n    if (escaped) {\n      escaped = false;\n      continue;\n    }\n\n    if (char === '\\\\') {\n      escaped = true;\n      continue;\n    }\n\n    if (char === '\"') {\n      inString = !inString;\n      continue;\n    }\n\n    if (inString) continue;\n\n    if (char === '{') {\n      if (depth === 0) start = i;\n      depth++;\n      continue;\n    }\n\n    if (char === '}' && depth > 0) {\n      depth--;\n      if (depth === 0 && start !== -1) {\n        lastBalanced = text.slice(start, i + 1);\n      }\n    }\n  }\n\n  return lastBalanced;\n}\n\ninterface ProcessPartialChunkParams {\n  /** Text accumulated from streaming so far */\n  accumulatedText: string;\n  /** Previously parsed object from last emission */\n  previousObject: unknown;\n  /** Previous processing result (handler-specific state) */\n  previousResult?: unknown;\n}\n\ninterface ProcessPartialChunkResult {\n  /** Whether a new value should be emitted */\n  shouldEmit: boolean;\n  /** The value to emit if shouldEmit is true */\n  emitValue?: unknown;\n  /** New previous result state for next iteration */\n  newPreviousResult?: unknown;\n}\n\ntype ValidateAndTransformFinalResult<OUTPUT = undefined> =\n  | {\n      /** Whether validation succeeded */\n      success: true;\n      /**\n       * The validated and transformed value if successful\n       */\n      value: OUTPUT;\n    }\n  | {\n      /** Whether validation succeeded */\n      success: false;\n      /**\n       * Error if validation failed\n       */\n      error: Error;\n    };\n\n/**\n * Base class for all output format handlers.\n * Each handler implements format-specific logic for processing partial chunks\n * and validating final results.\n */\nabstract class BaseFormatHandler<OUTPUT = undefined> {\n  abstract readonly type: 'object' | 'array' | 'enum';\n  /**\n   * The original user-provided schema (Zod, JSON Schema, or AI SDK Schema).\n   */\n  readonly schema: StandardSchemaWithJSON<OUTPUT> | undefined;\n  /**\n   * Validate partial chunks as they are streamed. @planned\n   */\n  readonly validatePartialChunks: boolean = false;\n  readonly partialSchema?: ZodLikePartialSchema<OUTPUT> | undefined;\n\n  constructor(schema?: StandardSchemaWithJSON<OUTPUT>, options: { validatePartialChunks?: boolean } = {}) {\n    this.schema = schema;\n\n    if (\n      options.validatePartialChunks &&\n      this.isZodSchema(schema) &&\n      'partial' in schema &&\n      typeof schema.partial === 'function'\n    ) {\n      this.partialSchema = schema.partial() as ZodLikePartialSchema<OUTPUT>;\n      this.validatePartialChunks = true;\n    }\n  }\n\n  /**\n   * Checks if the original schema is a Zod schema with safeParse method.\n   */\n  protected isZodSchema(schema: unknown): schema is ZodType {\n    return isZodType(schema);\n  }\n\n  /**\n   * Validates a value against the schema using StandardSchemaWithJSON's validate method.\n   */\n  protected async validateValue(value: unknown, diagnosticValue: unknown = value): Promise<ValidationResult<OUTPUT>> {\n    if (!this.schema) {\n      return {\n        success: true,\n        value: value as OUTPUT,\n      };\n    }\n\n    if (this.isZodSchema(this.schema)) {\n      // Use Standard Schema for consistent error message format + safeParse for ZodError cause\n      try {\n        const ssResult = await this.schema['~standard'].validate(value);\n\n        if (!ssResult.issues) {\n          return {\n            success: true,\n            value: ssResult.value as OUTPUT,\n          };\n        }\n\n        // Format error message from Standard Schema issues\n        const errorMessages = ssResult.issues.map(e => `- ${e.path?.join('.') || 'root'}: ${e.message}`).join('\\n');\n\n        // Also use safeParse to get ZodError as cause (for backward compatibility with tests)\n        const zodResult = this.schema.safeParse(value);\n        const zodError = !zodResult.success ? zodResult.error : undefined;\n\n        return {\n          success: false,\n          error: new MastraError(\n            {\n              domain: ErrorDomain.AGENT,\n              category: ErrorCategory.SYSTEM,\n              id: 'STRUCTURED_OUTPUT_SCHEMA_VALIDATION_FAILED',\n              text: `Structured output validation failed: ${errorMessages}`,\n              details: {\n                value: typeof diagnosticValue === 'object' ? JSON.stringify(diagnosticValue) : String(diagnosticValue),\n              },\n            },\n            zodError,\n          ),\n        };\n      } catch (error) {\n        return {\n          success: false,\n          error: error instanceof Error ? error : new Error('Zod validation failed', { cause: error }),\n        };\n      }\n    }\n\n    // For non-Zod StandardSchemaWithJSON schemas (JSON Schema, AI SDK Schema, ArkType, etc.)\n    // All schemas are wrapped via toStandardSchema() before reaching here,\n    // so we can use ~standard.validate() uniformly.\n    try {\n      const ssResult = await this.schema['~standard'].validate(value);\n\n      if (!ssResult.issues) {\n        return {\n          success: true,\n          value: ssResult.value as OUTPUT,\n        };\n      }\n\n      const errorMessages = ssResult.issues.map(e => `- ${e.path?.join('.') || 'root'}: ${e.message}`).join('\\n');\n\n      return {\n        success: false,\n        error: new MastraError({\n          domain: ErrorDomain.AGENT,\n          category: ErrorCategory.SYSTEM,\n          id: 'STRUCTURED_OUTPUT_SCHEMA_VALIDATION_FAILED',\n          text: `Structured output validation failed: ${errorMessages}`,\n          details: {\n            value: typeof diagnosticValue === 'object' ? JSON.stringify(diagnosticValue) : String(diagnosticValue),\n          },\n        }),\n      };\n    } catch (error) {\n      return {\n        success: false,\n        error: error instanceof Error ? error : new Error('Validation failed', { cause: error }),\n      };\n    }\n  }\n\n  /**\n   * Processes a partial chunk of accumulated text and determines if a new value should be emitted.\n   * @param params - Processing parameters\n   * @param params.accumulatedText - Text accumulated from streaming so far\n   * @param params.previousObject - Previously parsed object from last emission\n   * @param params.previousResult - Previous processing result (handler-specific state)\n   * @returns Promise resolving to processing result with emission decision\n   */\n  abstract processPartialChunk(params: ProcessPartialChunkParams): Promise<ProcessPartialChunkResult>;\n\n  /**\n   * Validates and transforms the final parsed value when streaming completes.\n   * @param finalValue - The final parsed value to validate\n   * @returns Promise resolving to validation result\n   */\n  abstract validateAndTransformFinal(finalValue: string): Promise<ValidateAndTransformFinalResult<OUTPUT>>;\n\n  /**\n   * Preprocesses accumulated text to handle LLMs that wrap JSON in code blocks\n   * and fix common JSON formatting issues like unescaped newlines in strings.\n   * Extracts content from the first complete valid ```json...``` code block or removes opening ```json prefix if no complete code block is found (streaming chunks).\n   * @param accumulatedText - Raw accumulated text from streaming\n   * @returns Processed text ready for JSON parsing\n   */\n  protected preprocessText(accumulatedText: string): string {\n    let processedText = accumulatedText;\n\n    // Some LLMs (e.g., LMStudio with jsonPromptInjection) wrap JSON in special tokens\n    // Format: '<|channel|>final <|constrain|>JSON<|message|>{\"key\":\"value\"}'\n    if (processedText.includes('<|message|>')) {\n      const match = processedText.match(/<\\|message\\|>([\\s\\S]+)$/);\n      if (match && match[1]) {\n        processedText = match[1];\n      }\n    }\n\n    // Some LLMs wrap the entire JSON response in a ```json code block.\n    // Only unwrap when the accumulated text itself starts with that fence so\n    // embedded examples inside valid JSON string values are preserved.\n    const trimmedStart = processedText.trimStart();\n    if (/^```json\\b/.test(trimmedStart)) {\n      const match = trimmedStart.match(/^```json\\s*\\n?([\\s\\S]*?)\\n?\\s*```\\s*$/);\n      if (match && match[1]) {\n        // Complete code block found - use content between tags\n        processedText = match[1].trim();\n      } else {\n        // No complete code block yet - just remove the opening ```json prefix\n        processedText = trimmedStart.replace(/^```json\\s*\\n?/, '');\n      }\n    }\n\n    const extractedObject = extractBalancedJsonObject(processedText);\n    if (extractedObject) {\n      processedText = extractedObject;\n    }\n\n    // LLMs often output actual newlines/tabs inside JSON strings instead of\n    // properly escaped \\n sequences. Fix this before parsing.\n    processedText = escapeUnescapedControlCharsInJsonStrings(processedText);\n\n    return processedText;\n  }\n}\n\n/**\n * Handles object format streaming. Emits parsed objects when they change during streaming.\n * This is the simplest format - objects are parsed and emitted directly without wrapping.\n */\nclass ObjectFormatHandler<OUTPUT = undefined> extends BaseFormatHandler<OUTPUT> {\n  readonly type = 'object' as const;\n\n  async processPartialChunk({\n    accumulatedText,\n    previousObject,\n  }: ProcessPartialChunkParams): Promise<ProcessPartialChunkResult> {\n    const processedAccumulatedText = this.preprocessText(accumulatedText);\n    const { value: currentObjectJson, state } = await parsePartialJson(processedAccumulatedText);\n\n    // TODO: test partial object chunk validation with schema.partial()\n    if (this.validatePartialChunks && this.partialSchema) {\n      const result = this.partialSchema?.safeParse(currentObjectJson);\n      if (result.success && result.data && result.data !== undefined && !isDeepEqualData(previousObject, result.data)) {\n        return {\n          shouldEmit: true,\n          emitValue: result.data,\n          newPreviousResult: result.data,\n        };\n      }\n      /**\n       * TODO: emit error chunk if partial validation fails?\n       * maybe we need to either not emit the object chunk,\n       * emit our error chunk, or wait until final parse to emit the error chunk?\n       */\n      return { shouldEmit: false };\n    }\n\n    if (\n      currentObjectJson !== undefined &&\n      currentObjectJson !== null &&\n      typeof currentObjectJson === 'object' &&\n      !isDeepEqualData(previousObject, currentObjectJson) // avoid emitting duplicates\n    ) {\n      return {\n        shouldEmit: ['successful-parse', 'repaired-parse'].includes(state),\n        emitValue: currentObjectJson,\n        newPreviousResult: currentObjectJson,\n      };\n    }\n    return { shouldEmit: false };\n  }\n\n  async validateAndTransformFinal(finalRawValue: string): Promise<ValidateAndTransformFinalResult<OUTPUT>> {\n    if (!finalRawValue) {\n      return {\n        success: false,\n        error: new Error('No object generated: could not parse the response.'),\n      };\n    }\n    const rawValue = this.preprocessText(finalRawValue);\n    const { value } = await parsePartialJson(rawValue);\n\n    return this.validateValue(value, value === undefined ? rawValue : value);\n  }\n}\n\n/**\n * Handles array format streaming. Arrays are wrapped in {elements: [...]} objects by the LLM\n * for better generation reliability. This handler unwraps them and filters incomplete elements.\n * Emits progressive array states as elements are completed.\n */\nclass ArrayFormatHandler<OUTPUT = undefined> extends BaseFormatHandler<OUTPUT> {\n  readonly type = 'array' as const;\n  /** Previously filtered array to track changes */\n  private textPreviousFilteredArray: unknown[] = [];\n  /** Whether we've emitted the initial empty array */\n  private hasEmittedInitialArray = false;\n\n  async processPartialChunk({\n    accumulatedText,\n    previousObject,\n  }: ProcessPartialChunkParams): Promise<ProcessPartialChunkResult> {\n    const processedAccumulatedText = this.preprocessText(accumulatedText);\n    const { value: currentObjectJson, state: parseState } = await parsePartialJson(processedAccumulatedText);\n    // TODO: parse/validate partial array elements, emit error chunk if validation fails\n    // using this.partialSchema / this.validatePartialChunks\n    if (currentObjectJson !== undefined && !isDeepEqualData(previousObject, currentObjectJson)) {\n      // For arrays, extract and filter elements\n      const rawElements =\n        currentObjectJson &&\n        typeof currentObjectJson === 'object' &&\n        'elements' in currentObjectJson &&\n        Array.isArray(currentObjectJson.elements)\n          ? currentObjectJson.elements\n          : [];\n      const filteredElements: Partial<OUTPUT>[] = [];\n\n      for (let i = 0; i < rawElements.length; i++) {\n        const element = rawElements[i];\n\n        if (i === rawElements.length - 1 && parseState !== 'successful-parse') {\n          // The last element may still be streaming. Partial objects are emitted\n          // once they have content; primitives (e.g. a truncated string or number)\n          // are withheld until the parse completes.\n          if (element && typeof element === 'object' && Object.keys(element).length > 0) {\n            filteredElements.push(element as Partial<OUTPUT>);\n          }\n        } else if (element !== undefined) {\n          // Non-last elements are complete: include them regardless of type\n          filteredElements.push(element as Partial<OUTPUT>);\n        }\n      }\n\n      // Emit initial empty array if this is the first time we see any JSON structure\n      if (!this.hasEmittedInitialArray) {\n        this.hasEmittedInitialArray = true;\n        if (filteredElements.length === 0) {\n          this.textPreviousFilteredArray = [];\n          return {\n            shouldEmit: true,\n            emitValue: [] as unknown as Partial<OUTPUT>,\n            newPreviousResult: currentObjectJson as Partial<OUTPUT>,\n          };\n        }\n      }\n\n      // Only emit if the filtered array has actually changed\n      if (!isDeepEqualData(this.textPreviousFilteredArray, filteredElements)) {\n        this.textPreviousFilteredArray = [...filteredElements];\n        return {\n          shouldEmit: true,\n          emitValue: filteredElements as unknown as Partial<OUTPUT>,\n          newPreviousResult: currentObjectJson as Partial<OUTPUT>,\n        };\n      }\n    }\n\n    return { shouldEmit: false };\n  }\n\n  async validateAndTransformFinal(finalRawValue: string): Promise<ValidateAndTransformFinalResult<OUTPUT>> {\n    if (!finalRawValue) {\n      return {\n        success: false,\n        error: new Error('No object generated: could not parse the response.'),\n      };\n    }\n\n    // Validate the elements from the final text rather than the streaming-filtered\n    // array so nothing withheld during partial parsing is lost at the end.\n    const { value } = await parsePartialJson(this.preprocessText(finalRawValue));\n    const resultValue =\n      value && typeof value === 'object' && 'elements' in value && Array.isArray(value.elements)\n        ? value.elements\n        : this.textPreviousFilteredArray;\n\n    return this.validateValue(resultValue);\n  }\n}\n\n/**\n * Handles enum format streaming. Enums are wrapped in {result: \"\"} objects by the LLM\n * for better generation reliability. This handler unwraps them and provides partial matching.\n * Emits progressive enum states as they are completed.\n * Validates the final result against the user-provided schema.\n */\nclass EnumFormatHandler<OUTPUT = undefined> extends BaseFormatHandler<OUTPUT> {\n  readonly type = 'enum' as const;\n  /** Previously emitted enum result to avoid duplicate emissions */\n  private textPreviousEnumResult?: string;\n\n  /**\n   * Finds the best matching enum value for a partial result string.\n   * If multiple values match, returns the partial string. If only one matches, returns that value.\n   * @param partialResult - Partial enum string from streaming\n   * @returns Best matching enum value or undefined if no matches\n   */\n  private findBestEnumMatch(partialResult: string): string | undefined {\n    if (!this.schema) {\n      return undefined;\n    }\n\n    // Get enum values from the schema using StandardSchemaWithJSON's jsonSchema conversion\n    const outputJsonSchema = standardSchemaToJSONSchema(this.schema);\n    const enumValues = outputJsonSchema?.enum;\n\n    if (!enumValues) {\n      return undefined;\n    }\n\n    const possibleEnumValues = enumValues\n      .filter((value: unknown): value is string => typeof value === 'string')\n      .filter((enumValue: string) => enumValue.startsWith(partialResult));\n\n    if (possibleEnumValues.length === 0) {\n      return undefined;\n    }\n\n    // Emit the most specific result - if there's exactly one match, use it; otherwise use partial\n    const firstMatch = possibleEnumValues[0];\n    return possibleEnumValues.length === 1 && firstMatch !== undefined ? firstMatch : partialResult;\n  }\n\n  async processPartialChunk({\n    accumulatedText,\n    previousObject,\n  }: ProcessPartialChunkParams): Promise<ProcessPartialChunkResult> {\n    const processedAccumulatedText = this.preprocessText(accumulatedText);\n    const { value: currentObjectJson } = await parsePartialJson(processedAccumulatedText);\n    if (\n      currentObjectJson !== undefined &&\n      currentObjectJson !== null &&\n      typeof currentObjectJson === 'object' &&\n      !Array.isArray(currentObjectJson) &&\n      'result' in currentObjectJson &&\n      typeof currentObjectJson.result === 'string' &&\n      !isDeepEqualData(previousObject, currentObjectJson)\n    ) {\n      const partialResult = currentObjectJson.result as string;\n      const bestMatch = this.findBestEnumMatch(partialResult);\n\n      // Only emit if we have valid partial matches and the result isn't empty\n      if (partialResult.length > 0 && bestMatch && bestMatch !== this.textPreviousEnumResult) {\n        this.textPreviousEnumResult = bestMatch;\n        return {\n          shouldEmit: true,\n          emitValue: bestMatch,\n          newPreviousResult: currentObjectJson,\n        };\n      }\n    }\n\n    return { shouldEmit: false };\n  }\n\n  async validateAndTransformFinal(rawFinalValue: string): Promise<ValidateAndTransformFinalResult<OUTPUT>> {\n    const processedValue = this.preprocessText(rawFinalValue);\n    const { value } = await parsePartialJson(processedValue);\n    if (!(typeof value === 'object' && value !== null && 'result' in value)) {\n      return {\n        success: false,\n        error: new Error('Invalid enum format: expected object with result property'),\n      };\n    }\n    const finalValue = value as { result: OUTPUT };\n\n    // For enums, check the wrapped format and unwrap\n    if (!finalValue || typeof finalValue !== 'object' || typeof finalValue.result !== 'string') {\n      return {\n        success: false,\n        error: new Error('Invalid enum format: expected object with result property'),\n      };\n    }\n\n    // Validate the unwrapped enum value\n    return this.validateValue(finalValue.result);\n  }\n}\n\n/**\n * Factory function to create the appropriate output format handler based on schema.\n * Analyzes the transformed schema format and returns the corresponding handler instance.\n * @param schema - Original user-provided schema (e.g., Zod schema from agent.stream({output: z.object({})}))\n * @param transformedSchema - Wrapped/transformed schema used for LLM generation (arrays wrapped in {elements: []}, enums in {result: \"\"})\n * @returns Handler instance for the detected format type\n */\nexport function createOutputHandler<OUTPUT = undefined>({ schema }: { schema?: PublicSchema<OUTPUT> }) {\n  // Direct transformer callers can pass any PublicSchema; normalize it before\n  // selecting the format-specific handler.\n  const normalizedSchema = schema ? toStandardSchema(schema) : undefined;\n\n  const transformedSchema = getTransformedSchema(normalizedSchema);\n  switch (transformedSchema?.outputFormat) {\n    case 'array':\n      return new ArrayFormatHandler(normalizedSchema);\n    case 'enum':\n      return new EnumFormatHandler(normalizedSchema);\n    case 'object':\n    default:\n      return new ObjectFormatHandler(normalizedSchema);\n  }\n}\n\n/**\n * Errors this transformer emits itself (validation, truncation, malformed enum), as opposed to\n * errors the provider streamed. They are enqueued before the model's `finish` chunk.\n */\nconst structuredOutputErrors = new WeakSet<object>();\n\nexport function isStructuredOutputError(error: unknown): boolean {\n  return typeof error === 'object' && error !== null && structuredOutputErrors.has(error);\n}\n\n/**\n * Transforms raw text-delta chunks into structured object chunks for JSON mode streaming.\n *\n * For JSON response formats, this transformer:\n * - Accumulates text deltas and parses them as partial JSON\n * - Emits 'object' chunks when the parsed structure changes\n * - For arrays: filters incomplete elements and unwraps from {elements: [...]} wrapper\n * - For objects: emits the parsed object directly\n * - For enums: unwraps from {result: \"\"} wrapper and provides partial matching\n * - Always passes through original chunks for downstream processing\n */\nexport function createObjectStreamTransformer<OUTPUT = undefined>({\n  structuredOutput,\n  logger,\n}: {\n  structuredOutput?: StreamTransformerStructuredOutput<OUTPUT>;\n  logger?: IMastraLogger;\n}) {\n  const handler = createOutputHandler<OUTPUT>({ schema: structuredOutput?.schema });\n\n  let accumulatedText = '';\n  let previousObject: unknown = undefined;\n  let currentRunId: string | undefined;\n  let finalResult: ValidateAndTransformFinalResult<OUTPUT> | undefined;\n  let finishReason: MastraFinishReason | undefined;\n  let hasPendingToolCalls = false;\n\n  return new TransformStream<ChunkType<OUTPUT>, ChunkType<OUTPUT>>({\n    async transform(chunk, controller) {\n      if (chunk.runId) {\n        // save runId to use in error chunks\n        currentRunId = chunk.runId;\n      }\n\n      // A single transformer can span several model steps (durable agents pipe the whole run through\n      // one stream). Only the terminal step's text is the structured answer, so start each step fresh.\n      if (chunk.type === 'step-start') {\n        accumulatedText = '';\n        previousObject = undefined;\n        finalResult = undefined;\n        finishReason = undefined;\n        hasPendingToolCalls = false;\n      }\n\n      if (chunk.type === 'tool-call' && !chunk.payload?.providerExecuted) {\n        hasPendingToolCalls = true;\n      }\n\n      if (chunk.type === 'text-delta' && typeof chunk.payload?.text === 'string') {\n        accumulatedText += chunk.payload.text;\n\n        const result = await handler.processPartialChunk({\n          accumulatedText,\n          previousObject,\n        });\n\n        if (result.shouldEmit) {\n          previousObject = result.newPreviousResult ?? previousObject;\n          const chunkData = {\n            from: chunk.from,\n            runId: chunk.runId,\n            type: 'object',\n            object: result.emitValue as Partial<OUTPUT>, // TODO: handle partial runtime type validation of json chunks\n          };\n\n          controller.enqueue(chunkData as ChunkType<OUTPUT>);\n        }\n      }\n\n      // Resolve structured output before finish: thread subscribers stop reading at that boundary.\n      // Providers that omit finish are handled by the flush fallback below.\n      if (chunk.type === 'finish') {\n        finishReason = chunk.payload.stepResult.reason;\n        await finalize(controller);\n      }\n\n      // Always pass through the original chunk for downstream processing\n      controller.enqueue(chunk);\n    },\n\n    async flush(controller) {\n      await finalize(controller);\n    },\n  });\n\n  async function finalize(controller: TransformStreamDefaultController<ChunkType<OUTPUT>>) {\n    if (!accumulatedText?.trim() || finalResult || finishReason === 'error') {\n      return;\n    }\n\n    // Text from a step that calls client-executed tools is narration before the tools run, not the\n    // final answer. Truncated steps still fall through so the truncation is reported; an error finish\n    // already surfaces its own error, so its narration must not become an object result.\n    if (hasPendingToolCalls && finishReason !== 'length' && finishReason !== 'content-filter') {\n      return;\n    }\n\n    if (finishReason === 'length' || finishReason === 'content-filter') {\n      finalResult = {\n        success: false,\n        error: new MastraError({\n          domain: ErrorDomain.AGENT,\n          category: ErrorCategory.SYSTEM,\n          id: 'STRUCTURED_OUTPUT_TRUNCATED',\n          text: `Structured output was truncated because the model finished with reason \"${finishReason}\".`,\n          details: {\n            finishReason,\n            value: accumulatedText,\n          },\n        }),\n      };\n    } else {\n      finalResult = await handler.validateAndTransformFinal(accumulatedText);\n    }\n\n    if (finalResult.success) {\n      controller.enqueue({\n        from: ChunkFrom.AGENT,\n        runId: currentRunId ?? '',\n        type: 'object-result',\n        object: finalResult.value,\n      });\n    } else {\n      handleValidationError(finalResult.error, controller);\n    }\n  }\n\n  /**\n   * Handle validation errors based on error strategy\n   */\n  function handleValidationError(error: Error, controller: TransformStreamDefaultController<ChunkType<OUTPUT>>) {\n    if (structuredOutput?.errorStrategy === 'warn') {\n      logger?.warn(error.message);\n    } else if (structuredOutput?.errorStrategy === 'fallback') {\n      controller.enqueue({\n        from: ChunkFrom.AGENT,\n        runId: currentRunId ?? '',\n        type: 'object-result',\n        object: structuredOutput.fallbackValue as OUTPUT,\n        metadata: { fallback: true },\n      });\n    } else {\n      structuredOutputErrors.add(error);\n      controller.enqueue({\n        from: ChunkFrom.AGENT,\n        runId: currentRunId ?? '',\n        type: 'error',\n        payload: {\n          error,\n        },\n      });\n    }\n  }\n}\n\n/**\n * Transforms object chunks into JSON text chunks for streaming.\n *\n * This transformer:\n * - For arrays: emits opening bracket, new elements, and closing bracket\n * - For objects/no-schema: emits the object as JSON\n */\nexport function createJsonTextStreamTransformer<OUTPUT = undefined>(schema?: StandardSchemaWithJSON<OUTPUT>) {\n  let emittedCount = 0;\n  let latestArray: unknown[] = [];\n  let hasStartedArray = false;\n  const emitElements = (controller: TransformStreamDefaultController<string>, array: unknown[], end: number) => {\n    for (; emittedCount < end; emittedCount++) {\n      const elementJson = JSON.stringify(array[emittedCount]);\n      controller.enqueue(emittedCount > 0 ? ',' + elementJson : elementJson);\n    }\n  };\n  // The first array chunk is held back instead of being emitted immediately.\n  // A single object chunk may already contain the complete array (coarse or\n  // batched provider deltas), in which case it should be emitted as one closed\n  // JSON string. But the same first chunk can also be the first slice of a\n  // longer incremental sequence, so we can only decide once the next chunk\n  // arrives or the stream ends. Emitting it closed too early produced invalid\n  // JSON like a closed array followed by more elements (see #18758).\n  let pendingFirstArrayChunk: unknown[] | undefined;\n  const outputSchema = getTransformedSchema(schema);\n\n  return new TransformStream<ChunkType<OUTPUT>, string>({\n    transform(chunk, controller) {\n      if (chunk.type !== 'object' || !chunk.object) {\n        return;\n      }\n\n      if (outputSchema?.outputFormat === 'array' && Array.isArray(chunk.object)) {\n        if (pendingFirstArrayChunk !== undefined) {\n          // A second chunk arrived, so the buffered chunk was only the first\n          // slice. Switch to incremental mode.\n          controller.enqueue('[');\n          hasStartedArray = true;\n          pendingFirstArrayChunk = undefined;\n        } else if (!hasStartedArray) {\n          // First chunk -- buffer it and wait to see whether the stream ends here.\n          pendingFirstArrayChunk = chunk.object;\n          return;\n        }\n\n        latestArray = chunk.object;\n        // The trailing element may still be partial: a later chunk can complete\n        // it in place at the same index. Only emit elements followed by another\n        // element; the rest are emitted on flush.\n        emitElements(controller, chunk.object, chunk.object.length - 1);\n      } else {\n        // For non-array objects, just emit as JSON\n        controller.enqueue(JSON.stringify(chunk.object));\n      }\n    },\n    flush(controller) {\n      if (outputSchema?.outputFormat !== 'array') {\n        return;\n      }\n      if (pendingFirstArrayChunk !== undefined) {\n        // The stream ended after a single array chunk: it was the complete\n        // array, so emit it as one closed JSON string. An empty single chunk\n        // still needs a well-formed '[]'.\n        const firstChunk = pendingFirstArrayChunk;\n        pendingFirstArrayChunk = undefined;\n        controller.enqueue(firstChunk.length > 0 ? JSON.stringify(firstChunk) : '[]');\n      } else if (hasStartedArray) {\n        // Emit the held-back trailing element(s), then close the array.\n        emitElements(controller, latestArray, latestArray.length);\n        controller.enqueue(']');\n      }\n    },\n  });\n}\n","/**\n * Chunks that already ran through the run's output processors before they\n * reached this stream (durable tool chunks, processed in the tool-call step\n * before publishing). MastraModelOutput passes them through without running\n * the processors again.\n */\nconst outputProcessedChunks = new WeakSet<object>();\n\nexport function markChunkOutputProcessed(chunk: unknown) {\n  if (chunk && typeof chunk === 'object') outputProcessedChunks.add(chunk);\n}\n\nexport function isChunkOutputProcessed(chunk: unknown): boolean {\n  return !!chunk && typeof chunk === 'object' && outputProcessedChunks.has(chunk);\n}\n","/**\n * Epoch ms at which a model output produced each chunk. Recorded when the\n * chunk is emitted, before any consumer can queue it, so thread history can\n * compare it with storage stamps regardless of how long publishing took.\n */\nconst chunkProducedAt = new WeakMap<object, number>();\n\nexport function stampChunkProducedAt(chunk: unknown, at: number) {\n  if (chunk && typeof chunk === 'object') chunkProducedAt.set(chunk, at);\n}\n\nexport function getChunkProducedAt(chunk: unknown): number | undefined {\n  return chunk && typeof chunk === 'object' ? chunkProducedAt.get(chunk) : undefined;\n}\n","/**\n * Every buffered step of a run carries the response messages of the run *so\n * far*, three times over: `response.messages` (the model-format messages),\n * `response.dbMessages` and `response.uiMessages` are all cumulative snapshots\n * of the same growing conversation, not per-step deltas. Persisting them on\n * every step makes a suspended snapshot grow quadratically in step count: a\n * fifteen-iteration agent run has been observed writing 22 MB of buffered steps\n * over 2 MB of distinct messages.\n *\n * The full conversation is already persisted once, in the serialized\n * `messageList` that sits alongside the buffered steps. So the snapshot stores\n * only the stable IDs of the messages each step referenced, and rebuilds the\n * three mirrors lazily from that list on the way back in. IDs are used instead\n * of a prefix length because processors can promote messages between sources or\n * remove messages after an earlier step was buffered.\n *\n * One behavioural note. A step's `dbMessages` share message objects with the\n * list, and an agentic turn keeps appending parts to the same message, so the\n * mirror a step persisted was never its step-time snapshot to begin with — it\n * was whatever the message had grown into by the time the snapshot was\n * written. `uiMessages` and `messages` were copies and did hold the step-time\n * shape, so after rehydration an earlier step's mirrors now reflect the same\n * content its `dbMessages` always did. The steps stay internally consistent,\n * and the last step — the one a resume continues from — is unchanged.\n *\n * This is purely a storage representation: callers still see populated message\n * mirrors on every step after rehydration. Each mirror is rebuilt and cached\n * only if a caller reads it, so restoring a long run does not eagerly convert\n * every historical prefix.\n */\n\nimport type { AIV5Type, MastraDBMessage, MessageList } from '../../agent/message-list';\nimport { convertMessages } from '../../agent/message-list';\n\nconst RESPONSE_MESSAGE_IDS = '__responseMessageIds' as const;\n\ntype ResponseLike = {\n  dbMessages?: unknown;\n  uiMessages?: unknown;\n  messages?: unknown;\n  [RESPONSE_MESSAGE_IDS]?: string[];\n};\n\ntype StepLike = { response?: unknown };\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return !!value && typeof value === 'object' && !Array.isArray(value);\n}\n\nfunction withoutMessageMirrors(response: Record<string, unknown>): Record<string, unknown> {\n  const rest: Record<string, unknown> = {};\n  for (const key of Object.keys(response)) {\n    if (key === 'dbMessages' || key === 'uiMessages' || key === 'messages' || key === RESPONSE_MESSAGE_IDS) continue;\n    rest[key] = response[key];\n  }\n  return rest;\n}\n\nexport function packStepMessageMirrors<T extends StepLike>(steps: T[]): T[] {\n  if (!Array.isArray(steps)) return steps;\n\n  return steps.map(step => {\n    if (!isRecord(step) || !isRecord(step.response) || !Array.isArray((step.response as ResponseLike).dbMessages)) {\n      return step;\n    }\n\n    const dbMessages = (step.response as ResponseLike).dbMessages as MastraDBMessage[];\n    return {\n      ...step,\n      response: {\n        ...withoutMessageMirrors(step.response),\n        [RESPONSE_MESSAGE_IDS]: dbMessages.map(message => message.id),\n      },\n    } as T;\n  });\n}\n\nexport function unpackStepMessageMirrors<T extends StepLike>(steps: T[], messageList: MessageList): T[] {\n  if (!Array.isArray(steps)) return steps;\n\n  // Snapshots written before this change carry the mirrors inline and need no\n  // rehydration — do not pay for the message list read in that case.\n  const needsRehydration = steps.some(\n    step => isRecord(step) && isRecord(step.response) && RESPONSE_MESSAGE_IDS in step.response,\n  );\n  if (!needsRehydration) return steps;\n\n  let messagesById: Map<string, MastraDBMessage> | undefined;\n\n  return steps.map(step => {\n    if (!isRecord(step) || !isRecord(step.response) || !(RESPONSE_MESSAGE_IDS in step.response)) return step;\n\n    const messageIds = (step.response as ResponseLike)[RESPONSE_MESSAGE_IDS] as string[];\n    const response = withoutMessageMirrors(step.response);\n    let dbMessages: MastraDBMessage[] | undefined;\n    let uiMessages: AIV5Type.UIMessage[] | undefined;\n    let messages: unknown;\n\n    const getDbMessages = () => {\n      if (!dbMessages) {\n        messagesById ??= new Map(messageList.get.all.db().map(message => [message.id, message]));\n        dbMessages = messageIds.flatMap(id => {\n          const message = messagesById!.get(id);\n          return message ? [message] : [];\n        });\n      }\n      return dbMessages;\n    };\n\n    Object.defineProperties(response, {\n      dbMessages: {\n        enumerable: true,\n        get: getDbMessages,\n      },\n      uiMessages: {\n        enumerable: true,\n        get() {\n          // Converting this step's messages — rather than slicing a conversion\n          // of the whole run — is what makes this faithful: conversions merge\n          // adjacent assistant messages, so later messages can change how\n          // earlier ones render.\n          return (uiMessages ??= convertMessages(getDbMessages()).to('AIV5.UI') as AIV5Type.UIMessage[]);\n        },\n      },\n      messages: {\n        enumerable: true,\n        get() {\n          // The model-format view of the same response messages that existed\n          // when the step finished.\n          return (messages ??= convertMessages(getDbMessages()).to('AIV5.Model'));\n        },\n      },\n    });\n\n    return { ...step, response } as unknown as T;\n  });\n}\n","/**\n * Every buffered step of a run carries the request that produced it, and that\n * request's `body` holds the tool schemas plus the system instruction — data\n * that is invariant across the steps of a single run and, in practice,\n * byte-identical. Persisting a full copy per step made a suspended snapshot\n * grow linearly with step count, and a HITL agent that takes a dozen tool calls\n * before its first approval could push a single document past MongoDB's hard\n * 16 MB limit, failing the write and stranding the run.\n *\n * So the snapshot stores each distinct request once and has the steps point at\n * it. This is purely a storage representation: callers still see a `request` on\n * every step after rehydration.\n */\n\nconst REQUEST_REF = '__requestRef' as const;\n\ntype StepLike = { request?: unknown };\n\n/**\n * Whether a value's JSON text identifies it uniquely.\n *\n * Two steps are treated as sharing a request when their JSON text matches, so\n * the text has to be injective over the values we compare. It is not, for the\n * types JSON has no representation of: `Map`, `Set`, `Error` and class\n * instances all render as `{}`, and a key whose value is `undefined` or a\n * function disappears entirely — so two genuinely different requests would\n * collide and one step would resume against the other's request.\n *\n * `Date` is allowed: it renders lossily, but distinct instants still render\n * distinctly, so it cannot collide. Anything else falls back to storing the\n * request inline, which is what every snapshot did before this change.\n */\nfunction hasInjectiveJson(value: unknown, seen = new Set<object>()): boolean {\n  if (value === null) return true;\n\n  const type = typeof value;\n  if (type === 'string' || type === 'boolean') return true;\n  // NaN and ±Infinity all render as `null`.\n  if (type === 'number') return Number.isFinite(value);\n  if (type !== 'object') return false;\n\n  const object = value as object;\n  // A cycle would throw in `JSON.stringify` anyway; refuse it up front rather\n  // than paying for the throw.\n  if (seen.has(object)) return false;\n  seen.add(object);\n\n  try {\n    if (object instanceof Date) return true;\n\n    if (Array.isArray(object)) {\n      // A hole and an explicit `undefined` both render as `null`, as does any\n      // element JSON drops.\n      return object.every((element, index) => index in object && hasInjectiveJson(element, seen));\n    }\n\n    const prototype = Object.getPrototypeOf(object);\n    if (prototype !== Object.prototype && prototype !== null) return false;\n\n    // `toJSON` replaces the value with something we have not inspected.\n    if ('toJSON' in object) return false;\n\n    return Reflect.ownKeys(object).every(key => {\n      // A symbol key is dropped silently; a symbol or function value makes the\n      // whole entry disappear.\n      if (typeof key === 'symbol') return false;\n      return hasInjectiveJson((object as Record<string, unknown>)[key], seen);\n    });\n  } finally {\n    seen.delete(object);\n  }\n}\n\nexport function dedupeStepRequests<T extends StepLike>(steps: T[]): { steps: T[]; requests: unknown[] | undefined } {\n  // With fewer than two steps there is nothing to share, and the extra table\n  // would only add noise to the snapshot.\n  if (!Array.isArray(steps) || steps.length < 2) return { steps, requests: undefined };\n\n  const requests: unknown[] = [];\n  const indexByKey = new Map<string, number>();\n  let sharedAny = false;\n\n  const rewritten = steps.map(step => {\n    if (!step || typeof step !== 'object' || step.request === undefined) return step;\n\n    // The persistence codec preserves types JSON does not (Date, Error, Map,\n    // Set), so a request can legitimately hold one and survive the round trip.\n    // JSON text cannot tell two of those apart, so requests carrying one are\n    // left inline rather than deduplicated against each other.\n    if (!hasInjectiveJson(step.request)) return step;\n\n    let key: string;\n    try {\n      key = JSON.stringify(step.request) ?? 'undefined';\n    } catch {\n      // Defensive: `hasInjectiveJson` already rejects the values that throw\n      // (cycles, BigInt). Leave the request inline if one slips through.\n      return step;\n    }\n\n    let index = indexByKey.get(key);\n    if (index === undefined) {\n      index = requests.length;\n      indexByKey.set(key, index);\n      requests.push(step.request);\n    } else {\n      sharedAny = true;\n    }\n\n    const { request: _dropped, ...rest } = step as StepLike & Record<string, unknown>;\n    return { ...rest, [REQUEST_REF]: index } as unknown as T;\n  });\n\n  // If no two steps shared a request, the table is the same size as the inline\n  // copies were — keep the simpler shape.\n  if (!sharedAny) return { steps, requests: undefined };\n\n  return { steps: rewritten, requests };\n}\n\nexport function rehydrateStepRequests<T extends StepLike>(steps: T[], requests: unknown[] | undefined): T[] {\n  // Snapshots written before this change (and runs with nothing to share) store\n  // the request inline on every step and need no rehydration.\n  if (!Array.isArray(steps) || !Array.isArray(requests)) return steps;\n\n  return steps.map(step => {\n    if (!step || typeof step !== 'object' || !(REQUEST_REF in step)) return step;\n    const { [REQUEST_REF]: index, ...rest } = step as Record<string, unknown>;\n    return { ...rest, request: requests[index as number] } as unknown as T;\n  });\n}\n","import { EventEmitter } from 'node:events';\nimport { ReadableStream, TransformStream } from 'node:stream/web';\nimport type { TransformStreamDefaultController } from 'node:stream/web';\nimport type { StepResult } from '@internal/ai-sdk-v5';\nimport { convertMessages, coreContentToString } from '../../agent/message-list';\nimport type { MessageList, MastraDBMessage } from '../../agent/message-list';\nimport { TripWire } from '../../agent/trip-wire';\nimport { MastraBase } from '../../base';\nimport { ErrorCategory, ErrorDomain, MastraError } from '../../error';\nimport { getErrorFromUnknown } from '../../error/utils.js';\nimport type { ScorerRunInputForAgent, ScorerRunOutputForAgent } from '../../evals';\nimport { DEADLINE_SAVE_WAIT_MS, isMastraTimeoutError, settledOrElapsed } from '../../loop/timeout';\nimport type { ObservabilityContext } from '../../observability';\nimport { getRootExportSpan, resolveObservabilityContext } from '../../observability';\nimport type { OutputResult } from '../../processors';\n// Inlined to avoid importing structured-output.ts which pulls in the agent\n// barrel and creates an ESM init-time cycle.\nconst STRUCTURED_OUTPUT_PROCESSOR_NAME = 'structured-output';\nimport { ProcessorState, ProcessorRunner } from '../../processors/runner';\nimport { isFailedStreamChunk } from '../../processors/stream-reprocess';\nimport type { WorkflowRunStatus } from '../../workflows';\nimport { DelayedPromise, consumeStream } from '../aisdk/v5/compat';\nimport type { ConsumeStreamOptions } from '../aisdk/v5/compat';\nimport { isSignalChunkExcluded } from '../signal-exclusions';\nimport type {\n  ChunkType,\n  LanguageModelUsage,\n  LLMStepResult,\n  MastraModelOutputOptions,\n  MastraOnFinishCallbackArgs,\n  ProviderMetadata,\n  StreamTransport,\n  StepTripwireData,\n  ToolCallChunk,\n} from '../types';\nimport { isDataChunk } from '../types';\nimport { safeClose, safeEnqueue } from './input';\nimport {\n  createJsonTextStreamTransformer,\n  createObjectStreamTransformer,\n  isStructuredOutputError,\n} from './output-format-handlers';\nimport { isChunkOutputProcessed } from './output-processed';\nimport { getChunkProducedAt, stampChunkProducedAt } from './produced-at';\nimport { getTransformedSchema } from './schema';\nimport { packStepMessageMirrors, unpackStepMessageMirrors } from './step-message-mirrors';\nimport { dedupeStepRequests, rehydrateStepRequests } from './step-request-dedupe';\n\nconst primaryUsageCountKeys = ['inputTokens', 'outputTokens', 'totalTokens'] as const satisfies ReadonlyArray<\n  keyof LanguageModelUsage\n>;\nconst detailUsageCountKeys = [\n  'reasoningTokens',\n  'cachedInputTokens',\n  'cacheCreationInputTokens',\n  'cacheCreationInputTokens5m',\n  'cacheCreationInputTokens1h',\n] as const satisfies ReadonlyArray<keyof LanguageModelUsage>;\nconst usageCountKeys = [...primaryUsageCountKeys, ...detailUsageCountKeys] as const;\n\nfunction hasTokenCounts(usage: Partial<LanguageModelUsage> | undefined) {\n  return primaryUsageCountKeys.some(key => usage?.[key] !== undefined);\n}\n\nfunction accumulateUsage(\n  target: Partial<LanguageModelUsage>,\n  missing: Set<(typeof primaryUsageCountKeys)[number]>,\n  usage: Partial<LanguageModelUsage>,\n) {\n  // Primary totals describe the whole request, so any omitted contribution\n  // makes that aggregate incomplete. Explicit zeroes remain valid values.\n  for (const key of primaryUsageCountKeys) {\n    const value = usage[key];\n    if (value === undefined) {\n      missing.add(key);\n      target[key] = undefined;\n    } else if (!missing.has(key)) {\n      target[key] = (target[key] ?? 0) + value;\n    }\n  }\n\n  // Detail counters are present-when-reported and remain additive across\n  // providers that omit unsupported cache or reasoning measurements.\n  for (const key of detailUsageCountKeys) {\n    const value = usage[key];\n    if (value !== undefined) {\n      target[key] = (target[key] ?? 0) + value;\n    }\n  }\n\n  // raw is provider-specific and not summable; keep the latest step's raw\n  if (usage.raw !== undefined) {\n    target.raw = usage.raw;\n  }\n}\n\n/**\n * Helper function to create a destructurable version of MastraModelOutput.\n * This wraps the output to ensure properties maintain their context when destructured.\n */\nexport function createDestructurableOutput<OUTPUT = undefined>(\n  output: MastraModelOutput<OUTPUT>,\n): MastraModelOutput<OUTPUT> {\n  return new Proxy(output, {\n    get(target, prop, _receiver) {\n      // Use target as receiver to preserve private member access\n      const originalValue = Reflect.get(target, prop, target);\n\n      // For methods, return bound version\n      if (typeof originalValue === 'function') {\n        return originalValue.bind(target);\n      }\n\n      // For everything else (including getters), return as-is\n      return originalValue;\n    },\n  }) as MastraModelOutput<OUTPUT>;\n}\n\n/**\n * Persist a non-transient `data-*` chunk emitted by an output processor's\n * `writer.custom()` onto the assistant message, so the chunk survives in\n * thread history instead of being stream-only (#19375). Transient chunks\n * and non-data chunks are left untouched.\n *\n * Exported for the durable engine, whose producer-side processor writers\n * persist into the workflow-side MessageList (the one serialized into\n * `messageListState` and flushed to memory at finalize).\n */\nexport function persistProcessorDataChunk(\n  messageList: MessageList,\n  messageId: string,\n  chunk: { type: string; data?: unknown; id?: string; transient?: boolean },\n): void {\n  if (!isDataChunk(chunk) || chunk.transient) return;\n\n  const message: MastraDBMessage = {\n    id: messageId,\n    role: 'assistant',\n    content: {\n      format: 2,\n      parts: [\n        { type: chunk.type as `data-${string}`, data: chunk.data, ...(chunk.id !== undefined ? { id: chunk.id } : {}) },\n      ],\n    },\n    createdAt: new Date(),\n  };\n  messageList.add(message, 'response');\n}\n\ntype ToolCallStreamingMeta = {\n  toolName: string;\n  providerExecuted?: boolean;\n  providerMetadata?: ProviderMetadata;\n  dynamic?: boolean;\n  title?: string;\n  observability?: ToolCallChunk['payload']['observability'];\n};\n\ntype PromiseResults<OUTPUT = undefined> = Pick<\n  LLMStepResult<OUTPUT>,\n  | 'text'\n  | 'reasoning'\n  | 'sources'\n  | 'files'\n  | 'toolCalls'\n  | 'toolResults'\n  | 'content'\n  | 'usage'\n  | 'warnings'\n  | 'providerMetadata'\n  | 'response'\n  | 'request'\n> & {\n  suspendPayload: any;\n  resumeSchema: any;\n  object: OUTPUT;\n  reasoningText: string | undefined;\n  totalUsage: LLMStepResult<OUTPUT>['usage'];\n  steps: LLMStepResult<OUTPUT>[];\n  finishReason: LLMStepResult<OUTPUT>['finishReason'];\n};\n\ntype DelayedPromises<OUTPUT = undefined> = {\n  [K in keyof PromiseResults<OUTPUT>]: DelayedPromise<PromiseResults<OUTPUT>[K]>;\n};\n\n/**\n * The complete output returned by `getFullOutput()`.\n */\nexport type FullOutput<OUTPUT = undefined> = {\n  /** The text output from all steps, excluding rejected responses */\n  text: string;\n  /** Token usage for the last step */\n  usage: PromiseResults<OUTPUT>['usage'];\n  /** All LLM steps executed during the stream */\n  steps: LLMStepResult<OUTPUT>[];\n  /** The reason the stream finished */\n  finishReason: PromiseResults<OUTPUT>['finishReason'];\n  /** Any warnings from the model */\n  warnings: PromiseResults<OUTPUT>['warnings'];\n  /** Provider-specific metadata */\n  providerMetadata: PromiseResults<OUTPUT>['providerMetadata'];\n  /** The request that was sent to model */\n  request: PromiseResults<OUTPUT>['request'];\n  /** Reasoning details from the model */\n  reasoning: PromiseResults<OUTPUT>['reasoning'];\n  /** Combined reasoning text */\n  reasoningText: string | undefined;\n  /** Tool calls made during execution */\n  toolCalls: PromiseResults<OUTPUT>['toolCalls'];\n  /** Results from tool executions */\n  toolResults: PromiseResults<OUTPUT>['toolResults'];\n  /** Sources referenced by model */\n  sources: PromiseResults<OUTPUT>['sources'];\n  /** Files generated by the model */\n  files: PromiseResults<OUTPUT>['files'];\n  /** Response metadata from the model */\n  response: PromiseResults<OUTPUT>['response'];\n  /** Total token usage across all steps */\n  totalUsage: PromiseResults<OUTPUT>['totalUsage'];\n  /** The structured object output (when using structured output) */\n  object: OUTPUT;\n  /**\n   * True when `object` is the configured `fallbackValue`, substituted because the model\n   * output failed schema validation — or the separate structuring model failed — under\n   * `errorStrategy: 'fallback'`.\n   */\n  usedFallbackValue: boolean;\n  /** Error if the stream failed */\n  error: Error | undefined;\n  /** Tripwire data if content was blocked */\n  tripwire: StepTripwireData | undefined;\n  /** Scoring data for evals (when returnScorerData is enabled) */\n  scoringData?: {\n    input: Omit<ScorerRunInputForAgent, 'runId'>;\n    output: ScorerRunOutputForAgent;\n  };\n  /** Trace ID for this execution. */\n  traceId: string | undefined;\n  /** Root span ID for this execution, identifying the top-level span in the trace. */\n  spanId: string | undefined;\n  /** Run ID for this execution */\n  runId: string | undefined;\n  /** Payload for resuming suspended tool calls */\n  suspendPayload: any;\n  /** Resume schema of suspended step if available */\n  resumeSchema?: any;\n  /** All messages from this execution (input + memory history + response) */\n  messages: MastraDBMessage[];\n  /** Only messages loaded from memory (conversation history) */\n  rememberedMessages: MastraDBMessage[];\n};\n\n/**\n * Resolve the output text from the latest response message, skipping internal\n * completion-check feedback so it can't become the final text.\n * The completionResult metadata only exists on DB-format messages, and the\n * message is converted alone so adjacent assistant messages aren't merged.\n *\n * Converting to model messages splits an assistant message at every tool\n * result, so when the current loop iteration called a tool the last converted\n * message holds only the text after the call, or nothing if the step ended on\n * it. In that case the text is read from the DB message's parts after the\n * iteration's boundary instead. The last `step-start` is not that boundary:\n * one is also inserted inside a single response whenever text follows a tool call.\n *\n * Returns `undefined` only when there is no response message to read text from,\n * so callers can distinguish \"no processed output exists\" from an output\n * processor deliberately clearing the text to `''`. Never collapse the two with\n * a truthiness check: a redacting processor must be able to produce empty text.\n */\nexport function resolveOutputMessageSkippingCompletionChecks(messageList: MessageList): MastraDBMessage | undefined {\n  const responseDbMessages = messageList.get.response.db();\n  return responseDbMessages.some(m => m.content?.metadata?.completionResult)\n    ? responseDbMessages.findLast(m => !m.content?.metadata?.completionResult)\n    : responseDbMessages[responseDbMessages.length - 1];\n}\n\n/**\n * A failed completion check moves the answer to a new message, but this output keeps the id it\n * was built with. Resolve at write time so processor data lands on the answer that is returned.\n */\nexport function resolveProcessorWriterMessageId(\n  messageList: MessageList,\n  fallbackMessageId: string,\n  explicitMessageId?: string,\n): string {\n  if (explicitMessageId) return explicitMessageId;\n  const responseDbMessages = messageList.get.response.db();\n  if (!responseDbMessages.some(m => m.content?.metadata?.completionResult)) return fallbackMessageId;\n  return resolveOutputMessageSkippingCompletionChecks(messageList)?.id ?? fallbackMessageId;\n}\n\nfunction resolveOutputTextSkippingCompletionChecks(messageList: MessageList): string | undefined {\n  const lastRealMessage = resolveOutputMessageSkippingCompletionChecks(messageList);\n  if (!lastRealMessage) return undefined;\n  if (lastRealMessage.role === 'assistant' && lastRealMessage.content?.parts) {\n    const stepParts = messageList.partsSinceStepBoundary(lastRealMessage);\n    if (stepParts.some(p => p.type === 'tool-invocation')) {\n      return stepParts.map(p => (p.type === 'text' ? p.text : '')).join('');\n    }\n  }\n  const hasCompletionCheckMessages = messageList.get.response.db().some(m => m.content?.metadata?.completionResult);\n  const converted = hasCompletionCheckMessages\n    ? convertMessages([lastRealMessage]).to('AIV4.Core')\n    : messageList.get.response.aiV4.core();\n  const lastConverted = converted[converted.length - 1];\n  return lastConverted ? coreContentToString(lastConverted.content) : undefined;\n}\n\n/**\n * A single entry of a stored message's part array.\n */\ntype StepMessagePart = MastraDBMessage['content']['parts'][number];\n\n/**\n * Step text for the current iteration of the message that supplies the resolved output text.\n *\n * The iteration boundary is a property of a message's own part array, so the offset measured before\n * processing must not be transplanted onto a message a processor produced. Resolve the boundary in\n * this order:\n *   1. the message's own `step-start` marker, when it has one;\n *   2. for the same message, the pre-processing step text where it survives (an unchanged in-place\n *      rewrite, or a split of the current iteration's text), the pre-processing offset while the\n *      parts before it are unchanged, then the offset while the part count and part kinds are\n *      unchanged (redaction or other rewrites that keep positions), then the unchanged prefix;\n *   3. for a different message, the trailing text matching the pre-processing step text, which finds\n *      the boundary when a processor replaced the id of the accumulated response;\n *   4. otherwise the whole message, which then holds only this iteration.\n *\n * The rules below are heuristics over the processed parts, so a processor can defeat them. When it\n * rewrites the current iteration's text (so the pre-processing step text no longer appears) *and*\n * moves the boundary while keeping the part count and kinds (for example by merging an earlier\n * iteration's parts and splitting the current one), the measured offset still matches by count and\n * kind and the step text is taken from the wrong position. That information is gone from the parts —\n * only a processor that preserves the boundary (a `step-start` part, or positions it does not move)\n * can be resolved exactly.\n */\nfunction resolveProcessedStepText({\n  processedStepMessage,\n  processedStepParts,\n  originalMessageId,\n  originalIterationPartOffset,\n  originalPartCount,\n  originalParts,\n  originalStepText,\n  outputText,\n}: {\n  processedStepMessage: MastraDBMessage | undefined;\n  processedStepParts: StepMessagePart[] | undefined;\n  originalMessageId: string | undefined;\n  originalIterationPartOffset: number | undefined;\n  originalPartCount: number | undefined;\n  originalParts: StepMessagePart[] | undefined;\n  originalStepText: string | undefined;\n  outputText: string | undefined;\n}): string {\n  if (!processedStepMessage || !processedStepParts) return outputText ?? '';\n\n  const textWithin = (parts: StepMessagePart[]) => parts.map(part => (part.type === 'text' ? part.text : '')).join('');\n  const boundaryIndex = processedStepParts.findLastIndex(part => part.type === 'step-start');\n  if (boundaryIndex !== -1) return textWithin(processedStepParts.slice(boundaryIndex + 1));\n\n  if (processedStepMessage.id === originalMessageId && originalParts) {\n    const sliceFrom = (index: number) => textWithin(processedStepParts.slice(index));\n    const offset = originalIterationPartOffset;\n    const textOffset = findIterationOffsetInParts(processedStepParts, originalStepText);\n    if (textOffset !== undefined) return sliceFrom(textOffset);\n\n    if (\n      offset !== undefined &&\n      offset > 0 &&\n      processedStepParts.length >= offset &&\n      originalParts.slice(0, offset).every((part, index) => partMatches(part, processedStepParts[index]))\n    ) {\n      return sliceFrom(offset);\n    }\n\n    if (\n      offset !== undefined &&\n      originalPartCount !== undefined &&\n      processedStepParts.length === originalPartCount &&\n      originalParts.slice(0, offset).every((part, index) => part?.type === processedStepParts[index]?.type)\n    ) {\n      return sliceFrom(offset);\n    }\n\n    let common = 0;\n    while (\n      common < originalParts.length &&\n      common < processedStepParts.length &&\n      partMatches(originalParts[common], processedStepParts[common])\n    ) {\n      common++;\n    }\n    if (common > 0) return sliceFrom(common);\n\n    return textWithin(processedStepParts);\n  }\n\n  const offset = findIterationOffsetInParts(processedStepParts, originalStepText);\n  return offset !== undefined ? textWithin(processedStepParts.slice(offset)) : textWithin(processedStepParts);\n}\n\nfunction partMatches(a: StepMessagePart | undefined, b: StepMessagePart | undefined): boolean {\n  if (!a || !b || a.type !== b.type) return false;\n  if (a.type === 'text') return a.text === (b as typeof a).text;\n  if (a.type === 'reasoning') return a.reasoning === (b as typeof a).reasoning;\n  if (a.type === 'tool-invocation') {\n    return a.toolInvocation?.toolCallId === (b as typeof a).toolInvocation?.toolCallId;\n  }\n  if (a.type === 'step-start') return Number(a.createdAt) === Number((b as typeof a).createdAt);\n  return true;\n}\n\nfunction findIterationOffsetInParts(parts: StepMessagePart[], stepText: string | undefined): number | undefined {\n  if (!stepText) return undefined;\n\n  let suffixText = '';\n  for (let index = parts.length - 1; index >= 0; index--) {\n    const part = parts[index];\n    if (part?.type === 'text') suffixText = part.text + suffixText;\n    if (suffixText === stepText) return index;\n    if (!stepText.endsWith(suffixText)) return undefined;\n  }\n  return undefined;\n}\n\nfunction findIterationPartOffset(\n  messageList: MessageList,\n  message: MastraDBMessage,\n  stepText: string,\n): number | undefined {\n  const parts = message.content?.parts;\n  if (!parts) return undefined;\n\n  const stepParts = messageList.partsSinceStepBoundary(message);\n  if (stepParts.length < parts.length) return parts.length - stepParts.length;\n  if (!stepText) return undefined;\n\n  let suffixText = '';\n  for (let index = parts.length - 1; index >= 0; index--) {\n    const part = parts[index];\n    if (part?.type === 'text') suffixText = part.text + suffixText;\n    if (suffixText === stepText) return index;\n    if (!stepText.endsWith(suffixText)) return undefined;\n  }\n\n  return undefined;\n}\n\nfunction resolveMessageText(message: MastraDBMessage): string {\n  const converted = convertMessages([message]).to('AIV4.Core');\n  const convertedMessage = converted[converted.length - 1];\n  return convertedMessage ? coreContentToString(convertedMessage.content) : '';\n}\n\n// Enumerable so processor object spreads preserve it; removed before the split response is coalesced.\nconst stepPartIndex = Symbol('stepPartIndex');\n\ntype StepIndexedPart = {\n  [stepPartIndex]?: number;\n};\n\ntype StepPartBoundaries = {\n  offsets: number[];\n};\n\nfunction findStepPartBoundaries<OUTPUT>(\n  message: MastraDBMessage | undefined,\n  steps: LLMStepResult<OUTPUT>[],\n): StepPartBoundaries | undefined {\n  const parts = message?.content.parts;\n  if (!parts) return undefined;\n\n  const offsets = Array<number>(steps.length + 1);\n  offsets[steps.length] = parts.length;\n  let partIndex = parts.length;\n\n  for (let stepIndex = steps.length - 1; stepIndex >= 0; stepIndex--) {\n    const stepText = steps[stepIndex]!.text;\n    let text = '';\n\n    while (partIndex > 0 && text !== stepText) {\n      const part = parts[--partIndex]!;\n      if (part.type === 'text') text = `${part.text}${text}`;\n    }\n\n    if (text !== stepText) return undefined;\n    offsets[stepIndex] = partIndex;\n  }\n\n  for (const [stepIndex] of steps.entries()) {\n    for (const part of parts.slice(offsets[stepIndex], offsets[stepIndex + 1])) {\n      if (part.type === 'text') (part as typeof part & StepIndexedPart)[stepPartIndex] = stepIndex;\n    }\n  }\n\n  return { offsets };\n}\n\nfunction clearStepPartIndexes(messages: MastraDBMessage[]): void {\n  for (const message of messages) {\n    for (const part of message.content.parts) delete (part as typeof part & StepIndexedPart)[stepPartIndex];\n  }\n}\n\nfunction reconcileBufferedStepTexts<OUTPUT>(\n  steps: LLMStepResult<OUTPUT>[],\n  processedText: string,\n  processedMessage?: MastraDBMessage,\n  stepPartBoundaries?: StepPartBoundaries,\n  originalText?: string,\n): void {\n  if (processedText === originalText) return;\n\n  const processedParts = processedMessage?.content.parts;\n  let processedOffsets: number[] | undefined;\n\n  if (processedParts && stepPartBoundaries) {\n    const processedStepTexts = steps.map(() => '');\n    let lastStepIndex = 0;\n    let hasUnknownPart = false;\n\n    for (const part of processedParts) {\n      if (part.type !== 'text') continue;\n      const stepIndex = (part as typeof part & StepIndexedPart)[stepPartIndex];\n      if (stepIndex === undefined || stepIndex < lastStepIndex) {\n        hasUnknownPart = true;\n        break;\n      }\n      processedStepTexts[stepIndex] += part.text;\n      lastStepIndex = stepIndex;\n    }\n\n    if (!hasUnknownPart) {\n      for (const [index, step] of steps.entries()) step.text = processedStepTexts[index]!;\n      return;\n    }\n\n    if (stepPartBoundaries.offsets.at(-1) === processedParts.length) {\n      processedOffsets = stepPartBoundaries.offsets;\n    }\n  }\n\n  if (processedParts && processedOffsets) {\n    for (const [index, step] of steps.entries()) {\n      step.text = processedParts\n        .slice(processedOffsets[index], processedOffsets[index + 1])\n        .map(part => (part.type === 'text' ? part.text : ''))\n        .join('');\n    }\n    return;\n  }\n\n  let offset = 0;\n  let index = 0;\n\n  while (index < steps.length && processedText.startsWith(steps[index]!.text, offset)) {\n    offset += steps[index]!.text.length;\n    index++;\n  }\n\n  if (index === steps.length) return;\n\n  steps[index]!.text = processedText.slice(offset);\n  for (const step of steps.slice(index + 1)) step.text = '';\n}\n\nexport class MastraModelOutput<OUTPUT = undefined> extends MastraBase {\n  #status: WorkflowRunStatus = 'running';\n  #error: Error | undefined;\n  #baseStream: ReadableStream<ChunkType<OUTPUT>>;\n  #bufferedChunks: ChunkType<OUTPUT>[] = [];\n  /**\n   * Set when a continuing goal evaluation arrives while a step is still in\n   * flight (in-process engines emit the goal chunk before the judged turn's\n   * step-finish): the next step-finish belongs to the judged turn and its\n   * buffers are dropped once its stepResult and usage are recorded.\n   */\n  #truncateAtNextStepFinish = false;\n  #streamFinished = false;\n  #finishCallbackSent = false;\n  #emitter = new EventEmitter();\n  #bufferedSteps: LLMStepResult<OUTPUT>[] = [];\n  #bufferedReasoningDetails: Record<string, LLMStepResult<OUTPUT>['reasoning'][number]> = {};\n  /**\n   * Per-step counterpart of `#bufferedReasoningDetails`. Reset on `step-finish`\n   * alongside `#bufferedByStep` so a step result reports only its own reasoning.\n   */\n  #bufferedByStepReasoningDetails: Record<string, LLMStepResult<OUTPUT>['reasoning'][number]> = {};\n  #bufferedByStep: LLMStepResult<OUTPUT> = {\n    text: '',\n    reasoning: [],\n    sources: [],\n    files: [],\n    toolCalls: [],\n    toolResults: [],\n    dynamicToolCalls: [],\n    dynamicToolResults: [],\n    staticToolCalls: [],\n    staticToolResults: [],\n    content: [],\n    usage: { inputTokens: undefined, outputTokens: undefined, totalTokens: undefined },\n    warnings: [],\n    request: {},\n    response: {\n      id: '',\n      timestamp: new Date(),\n      modelId: '',\n      messages: [],\n      uiMessages: [],\n    },\n    reasoningText: '',\n    providerMetadata: undefined,\n    finishReason: undefined,\n  };\n  #bufferedText: LLMStepResult<OUTPUT>['text'][] = [];\n  /** Length of `#bufferedText` when the current step began; rejected or retried steps are cut back to it. */\n  #bufferedTextAtStepStart = 0;\n  #bufferedObject: OUTPUT | undefined;\n  #usedFallbackValue = false;\n  #bufferedTextChunks: Record<string, LLMStepResult<OUTPUT>['text'][]> = {};\n  #bufferedSources: LLMStepResult<OUTPUT>['sources'] = [];\n  #bufferedReasoning: LLMStepResult<OUTPUT>['reasoning'] = [];\n  /** Run-level reasoning as of the last `step-start` that has no `step-finish` yet. */\n  #reasoningAtStepStart?: {\n    length: number;\n    details: Record<string, LLMStepResult<OUTPUT>['reasoning'][number]>;\n  };\n  #bufferedFiles: LLMStepResult<OUTPUT>['files'] = [];\n  /** Run-level sources, files and tool calls as of the last `step-start` that has no `step-finish` yet. */\n  #runOutputAtStepStart?: { sources: number; files: number; toolCalls: number };\n  // Records keyed by provider-supplied tool call IDs have no prototype, so IDs like \"__proto__\"\n  // or \"constructor\" are plain keys.\n  #toolCallArgsDeltas: Record<string, LLMStepResult<OUTPUT>['text'][]> = Object.create(null);\n  #toolCallDeltaIdNameMap: Record<string, string> = Object.create(null);\n  #toolCallStreamingMeta: Record<string, ToolCallStreamingMeta> = Object.create(null);\n  /** Recorded calls whose input streams again in a retry; the retry's tool-call replaces them. */\n  #replaceableToolCallIds = new Set<string>();\n  /** Calls recorded since the last accepted step; only these can be replaced by a retry. */\n  #attemptToolCallIds = new Set<string>();\n  /**\n   * Tool calls whose input stream ended without any deltas. Their args only arrive with the\n   * final `tool-call` chunk, so they wait here instead of being emitted as a synthetic `{}` call.\n   */\n  #pendingToolCalls: Record<\n    string,\n    {\n      meta: ToolCallStreamingMeta;\n      args: Record<string, unknown>;\n      streamed: boolean;\n      runId: string;\n      from: ToolCallChunk['from'];\n    }\n  > = Object.create(null);\n  #toolCalls: LLMStepResult<OUTPUT>['toolCalls'] = [];\n  #toolResults: LLMStepResult<OUTPUT>['toolResults'] = [];\n  #warnings: LLMStepResult<OUTPUT>['warnings'] = [];\n  #finishReason: LLMStepResult<OUTPUT>['finishReason'] = undefined;\n  /**\n   * Provider-specific metadata captured from the most recent step `finish`\n   * chunk (e.g. AWS Bedrock guardrail trace under\n   * `providerMetadata.bedrock.trace`). Exposed via {@link _getImmediateProviderMetadata}\n   * so output-step processors can attribute content-filter blocks, for which\n   * the completed-steps array is empty.\n   */\n  #stepProviderMetadata: ProviderMetadata | undefined = undefined;\n  #request: LLMStepResult<OUTPUT>['request'] = {};\n  #usageCount: LLMStepResult<OUTPUT>['usage'] = {\n    inputTokens: undefined,\n    outputTokens: undefined,\n    totalTokens: undefined,\n  };\n  #usageCountMissing = new Set<(typeof primaryUsageCountKeys)[number]>();\n  /**\n   * Usage of the most recently completed step. Kept apart from `#bufferedSteps`\n   * because goal truncation clears that buffer while usage keeps accumulating.\n   */\n  #lastStepUsage: LLMStepResult<OUTPUT>['usage'] | undefined = undefined;\n  /**\n   * Usage of the step that suspended on a tool call. That step never emits `step-finish`, so\n   * its usage arrives on the suspension chunk and is reported without entering `#usageCount`:\n   * the serialized `usageCount` excludes it, and the resumed run accumulates it when it replays\n   * the step's `step-finish`, keeping resumed totals cumulative for the whole run. It is\n   * serialized so a resumed tool that suspends again still reports it, and cleared on step-finish.\n   */\n  #suspendedStepUsage: LanguageModelUsage | undefined = undefined;\n  #suspendedUsageIsProvisional = false;\n  /**\n   * Cumulative usage the MODEL_GENERATION spans of earlier suspended legs of this run already\n   * recorded. Resumed legs report cumulative totals, so their generation span subtracts this to\n   * keep token metrics counted once. Serialized with the run state.\n   */\n  #generationReportedUsage: LanguageModelUsage | undefined = undefined;\n  /**\n   * How many `#bufferedSteps` entries the MODEL_GENERATION spans of earlier suspended legs\n   * already reported provider cost for. It counts the suspended step, which a resumed leg\n   * replays into `#bufferedSteps`. Serialized with the run state.\n   */\n  #generationReportedStepCount = 0;\n  #finishUsageIsTotal = false;\n  #tripwire: StepTripwireData | undefined = undefined;\n  #wasSuspended = false;\n  #resumedPriorText = '';\n  #transportRef: MastraModelOutputOptions<OUTPUT>['transportRef'] | undefined;\n  #transportClosed = false;\n\n  #delayedPromises: DelayedPromises<OUTPUT> = {\n    suspendPayload: new DelayedPromise<PromiseResults<OUTPUT>['suspendPayload']>(),\n    resumeSchema: new DelayedPromise<PromiseResults<OUTPUT>['resumeSchema']>(),\n    object: new DelayedPromise<PromiseResults<OUTPUT>['object']>(),\n    finishReason: new DelayedPromise<PromiseResults<OUTPUT>['finishReason']>(),\n    usage: new DelayedPromise<PromiseResults<OUTPUT>['usage']>(),\n    warnings: new DelayedPromise<PromiseResults<OUTPUT>['warnings']>(),\n    providerMetadata: new DelayedPromise<PromiseResults<OUTPUT>['providerMetadata']>(),\n    response: new DelayedPromise<PromiseResults<OUTPUT>['response']>(),\n    request: new DelayedPromise<PromiseResults<OUTPUT>['request']>(),\n    text: new DelayedPromise<PromiseResults<OUTPUT>['text']>(),\n    reasoning: new DelayedPromise<PromiseResults<OUTPUT>['reasoning']>(),\n    reasoningText: new DelayedPromise<string | undefined>(),\n    sources: new DelayedPromise<PromiseResults<OUTPUT>['sources']>(),\n    files: new DelayedPromise<PromiseResults<OUTPUT>['files']>(),\n    toolCalls: new DelayedPromise<PromiseResults<OUTPUT>['toolCalls']>(),\n    toolResults: new DelayedPromise<PromiseResults<OUTPUT>['toolResults']>(),\n    steps: new DelayedPromise<PromiseResults<OUTPUT>['steps']>(),\n    totalUsage: new DelayedPromise<PromiseResults<OUTPUT>['usage']>(),\n    content: new DelayedPromise<PromiseResults<OUTPUT>['content']>(),\n  };\n\n  #consumptionStarted = false;\n  #consumeStreamPromise: Promise<void> | undefined;\n  #consumeStreamErrored = false;\n  #consumeStreamError: unknown;\n  #returnScorerData = false;\n  #structuredOutputMode: 'direct' | 'processor' | undefined = undefined;\n\n  #model: {\n    modelId: string | undefined;\n    provider: string | undefined;\n    version: 'v2' | 'v3' | 'v4';\n  };\n\n  /**\n   * Unique identifier for this execution run.\n   */\n  public runId: string;\n  #options: MastraModelOutputOptions<OUTPUT>;\n  /**\n   * The processor runner for this stream.\n   */\n  public processorRunner?: ProcessorRunner;\n  /**\n   * The message list for this stream.\n   */\n  public messageList: MessageList;\n  /**\n   * Trace ID for this execution.\n   */\n  public traceId?: string;\n  /**\n   * Root span ID for this execution, identifying the top-level span in the trace.\n   */\n  public spanId?: string;\n  public messageId: string;\n\n  constructor({\n    model: _model,\n    stream,\n    messageList,\n    options,\n    messageId,\n    initialState,\n    initialToolCalls,\n    resumedText,\n    finishUsageIsTotal,\n    onFinishComplete,\n    getTerminalRequest,\n    onTracingTripwire,\n  }: {\n    model: {\n      modelId: string | undefined;\n      provider: string | undefined;\n      version: 'v2' | 'v3' | 'v4';\n    };\n    stream: ReadableStream<ChunkType<OUTPUT>>;\n    messageList: MessageList;\n    options: MastraModelOutputOptions<OUTPUT>;\n    messageId: string;\n    initialState?: any;\n    initialToolCalls?: ToolCallChunk[];\n    /**\n     * Text a resumed stream segment inherits from before its suspension: the run's text so far\n     * and the suspended step's part of it. Used when no serialized `initialState` is available.\n     */\n    resumedText?: { priorText: string; stepText: string };\n    finishUsageIsTotal?: boolean;\n    /** @internal Successful loop cleanup, after the agent's awaited final memory save. */\n    onFinishComplete?: () => Promise<void>;\n    /** @internal Caller-local terminal metadata, taking precedence over queued step chunks. */\n    getTerminalRequest?: () => LLMStepResult<OUTPUT>['request'] | undefined;\n    /** Internal tracing state, never serialized into finish chunks. */\n    onTracingTripwire?: import('../../loop/types').LoopOptions['onTracingTripwire'];\n  }) {\n    super({ component: 'LLM', name: 'MastraModelOutput' });\n    if (options.logger) {\n      this.__setLogger(options.logger);\n    }\n    this.#options = options;\n    this.#finishUsageIsTotal = finishUsageIsTotal ?? false;\n    this.#transportRef = options.transportRef;\n    this.#returnScorerData = !!options.returnScorerData;\n    this.runId = options.runId;\n    const resultSpan = getRootExportSpan(options.tracingContext?.currentSpan);\n    this.traceId = resultSpan?.externalTraceId;\n    this.spanId = resultSpan?.id;\n\n    this.#model = _model;\n\n    this.messageId = messageId;\n\n    // Determine structured output mode:\n    // - 'direct': LLM generates JSON directly (no model provided), object transformers run in this stream\n    // - 'processor': StructuredOutputProcessor uses internal agent with provided model\n    // - undefined: No structured output\n    if (options.structuredOutput?.schema) {\n      this.#structuredOutputMode = options.structuredOutput.model ? 'processor' : 'direct';\n    }\n\n    // Create processor runner if outputProcessors are provided\n    if (options.outputProcessors?.length) {\n      this.processorRunner = new ProcessorRunner({\n        inputProcessors: [],\n        outputProcessors: options.outputProcessors,\n        logger: this.logger,\n        agentName: 'MastraModelOutput',\n        agent: options.agent,\n        processorStates: options.processorStates,\n      });\n    }\n\n    this.messageList = messageList;\n\n    const self = this;\n\n    // Apply output processors if they exist\n    let processedStream = stream;\n    const processorRunner = this.processorRunner;\n    if (processorRunner && options.isLLMExecutionStep) {\n      // Use shared processor states if provided, otherwise create new ones\n      const processorStates = (options.processorStates || new Map<string, ProcessorState>()) as Map<\n        string,\n        ProcessorState<OUTPUT>\n      >;\n\n      // `options` never changes for the lifetime of this stream, so the\n      // resolved context is the same for every chunk. Deriving it eagerly\n      // per chunk clones the span metadata for logger + metrics contexts\n      // on every part, even when no stream processor consumes it.\n      let observabilityContext: ObservabilityContext | undefined;\n      const getObservabilityContext = () => (observabilityContext ??= resolveObservabilityContext(options));\n      // Set once the model stream errors or aborts; held parts are then dropped\n      // rather than released, since they belong to a failed (maybe retried) call.\n      let streamFailed = false;\n\n      processedStream = stream.pipeThrough(\n        new TransformStream<ChunkType<OUTPUT>, ChunkType<OUTPUT>>({\n          async transform(chunk, controller) {\n            if (isFailedStreamChunk(chunk)) streamFailed = true;\n            // Filter out intermediate finish chunks with 'tool-calls' reason\n            // These are internal signals that shouldn't reach output processors\n            //\n            // Error-shaped chunks are filtered out the same way when the caller\n            // opted into `deferErrorChunks`: they describe one model call that\n            // may still be retried or served by a fallback model, so processors\n            // must not react to them here. The caller runs processors on the\n            // error once it has ruled out recovery.\n            //\n            // Chunks marked output-processed already ran through the\n            // processors upstream, so they pass through too.\n            const isDeferredErrorChunk =\n              options.deferErrorChunks &&\n              (chunk.type === 'error' || (chunk.type === 'finish' && chunk.payload?.stepResult?.reason === 'error'));\n\n            if (\n              (chunk.type === 'finish' && chunk.payload?.stepResult?.reason === 'tool-calls') ||\n              isDeferredErrorChunk ||\n              isChunkOutputProcessed(chunk)\n            ) {\n              controller.enqueue(chunk);\n            } else {\n              /**\n               * Add/update base stream controller to structured output processor state\n               * so it can be used to enqueue chunks into the main stream from the structuring agent stream.\n               * Need to update controller on each new LLM execution step since each step has its own TransformStream.\n               */\n              if (!processorStates.has(STRUCTURED_OUTPUT_PROCESSOR_NAME)) {\n                const processorIndex = processorRunner.outputProcessors.findIndex(\n                  p => p.id === STRUCTURED_OUTPUT_PROCESSOR_NAME,\n                );\n                // Only create the state if the processor actually exists in the list\n                if (processorIndex !== -1) {\n                  const structuredOutputProcessor = processorRunner.outputProcessors[processorIndex];\n                  const structuredOutputProcessorState = new ProcessorState<OUTPUT>({\n                    processorName: structuredOutputProcessor?.name ?? STRUCTURED_OUTPUT_PROCESSOR_NAME,\n                    tracingContext: options.tracingContext,\n                    processorIndex,\n                    createSpan: true,\n                    processor: structuredOutputProcessor,\n                  });\n                  structuredOutputProcessorState.customState = { controller };\n                  processorStates.set(STRUCTURED_OUTPUT_PROCESSOR_NAME, structuredOutputProcessorState);\n                }\n              } else {\n                // Update controller for new LLM execution step\n                const structuredOutputProcessorState = processorStates.get(STRUCTURED_OUTPUT_PROCESSOR_NAME);\n                if (structuredOutputProcessorState) {\n                  structuredOutputProcessorState.customState.controller = controller;\n                }\n              }\n\n              // Create a ProcessorStreamWriter from the controller so processOutputStream can emit custom chunks\n              const streamWriter = {\n                custom: async (\n                  data: { type: string; data?: unknown; transient?: boolean },\n                  writerOptions?: { messageId?: string },\n                ) => {\n                  persistProcessorDataChunk(\n                    self.messageList,\n                    resolveProcessorWriterMessageId(self.messageList, self.messageId, writerOptions?.messageId),\n                    data,\n                  );\n                  controller.enqueue(data as ChunkType<OUTPUT>);\n                },\n              };\n\n              const {\n                part: processed,\n                blocked,\n                reason,\n                tripwireOptions,\n                processorId,\n              } = await processorRunner.processPart(\n                chunk,\n                processorStates,\n                getObservabilityContext(),\n                options.requestContext,\n                self.messageList,\n                0,\n                streamWriter,\n                options.abortSignal,\n              );\n              const enqueueTripwire = (r?: string, opts?: { retry?: boolean; metadata?: unknown }, pid?: string) => {\n                controller.enqueue({\n                  type: 'tripwire',\n                  payload: {\n                    reason: r || 'Output processor blocked content',\n                    retry: opts?.retry,\n                    metadata: opts?.metadata,\n                    processorId: pid,\n                  },\n                } as ChunkType<OUTPUT>);\n              };\n\n              if (blocked) {\n                // Emit a tripwire chunk so downstream knows about the abort\n                enqueueTripwire(reason, tripwireOptions, processorId);\n                return;\n              }\n              if (processed) {\n                controller.enqueue(processed as ChunkType<OUTPUT>);\n              }\n\n              // Emit any parts a processor stashed for reprocessing (e.g. the\n              // non-text part that triggered a BatchPartsProcessor flush),\n              // pushing each back through the whole chain for downstream\n              // processing.\n              const reprocessed = await processorRunner.drainReprocessParts(\n                processorStates,\n                getObservabilityContext(),\n                options.requestContext,\n                self.messageList,\n                0,\n                streamWriter,\n                options.abortSignal,\n              );\n              for (const r of reprocessed) {\n                if (r.blocked) {\n                  enqueueTripwire(r.reason, r.tripwireOptions, r.processorId);\n                  return;\n                }\n                if (r.part != null) {\n                  controller.enqueue(r.part as ChunkType<OUTPUT>);\n                }\n              }\n            }\n          },\n          async flush(controller) {\n            // Release parts processors still hold (e.g. a partial BatchPartsProcessor\n            // batch) so a model stream that ends mid-batch doesn't drop its tail.\n            // A failed or aborted stream drops them instead: a retry would duplicate\n            // them, and an abort must not emit content after cancellation.\n            if (streamFailed || options.abortSignal?.aborted) {\n              for (const part of await processorRunner.discardHeldParts(processorStates)) {\n                controller.enqueue(part as ChunkType<OUTPUT>);\n              }\n              processorRunner.endStreamProcessorSpans(processorStates, { keepStepScopedSpans: true });\n              return;\n            }\n            const released = await processorRunner.flushHeldParts(\n              processorStates,\n              getObservabilityContext(),\n              options.requestContext,\n              self.messageList,\n              0,\n              {\n                custom: async (data, writerOptions) => {\n                  persistProcessorDataChunk(\n                    self.messageList,\n                    resolveProcessorWriterMessageId(self.messageList, self.messageId, writerOptions?.messageId),\n                    data,\n                  );\n                  controller.enqueue(data as ChunkType<OUTPUT>);\n                },\n              },\n              options.abortSignal,\n            );\n            for (const r of released) {\n              if (r.blocked) {\n                controller.enqueue({\n                  type: 'tripwire',\n                  payload: {\n                    reason: r.reason || 'Output processor blocked content',\n                    retry: r.tripwireOptions?.retry,\n                    metadata: r.tripwireOptions?.metadata,\n                    processorId: r.processorId,\n                  },\n                } as ChunkType<OUTPUT>);\n                break;\n              }\n              if (r.part != null) {\n                controller.enqueue(r.part as ChunkType<OUTPUT>);\n              }\n            }\n            // Only this step's model stream ended; the step's tool results are still to come.\n            processorRunner.endStreamProcessorSpans(processorStates, { keepStepScopedSpans: true });\n          },\n          async cancel() {\n            // The model call was torn down (e.g. a mid-stream disconnect being\n            // retried). What processors hold belongs to it and must not be\n            // released with the next call's parts.\n            await processorRunner.discardHeldParts(processorStates);\n            processorRunner.endStreamProcessorSpans(processorStates);\n          },\n        }),\n      );\n    }\n\n    // Only apply object transformer in 'direct' mode (LLM generates JSON directly)\n    // In 'processor' mode, the StructuredOutputProcessor handles object transformation\n    if (self.#structuredOutputMode === 'direct' && self.#options.isLLMExecutionStep) {\n      processedStream = processedStream.pipeThrough(\n        createObjectStreamTransformer({\n          structuredOutput: self.#options.structuredOutput,\n          logger: self.logger,\n        }),\n      );\n    }\n\n    const emitSyntheticToolCall = (\n      controller: TransformStreamDefaultController<ChunkType<OUTPUT>>,\n      toolCallId: string,\n      meta: ToolCallStreamingMeta,\n      args: Record<string, unknown>,\n      runId: string,\n      from: ToolCallChunk['from'],\n    ) => {\n      const synthetic: ToolCallChunk = {\n        type: 'tool-call',\n        runId,\n        from,\n        payload: {\n          toolCallId,\n          toolName: meta.toolName,\n          args,\n          providerExecuted: meta.providerExecuted,\n          providerMetadata: meta.providerMetadata,\n          dynamic: meta.dynamic,\n          ...(meta.title ? { title: meta.title } : {}),\n          ...(meta.observability ? { observability: meta.observability } : {}),\n        },\n      };\n      self.#toolCalls.push(synthetic);\n      self.#bufferedByStep.toolCalls.push(synthetic);\n      self.#attemptToolCallIds.add(synthetic.payload.toolCallId);\n      self.#emitChunk(synthetic);\n      controller.enqueue(synthetic);\n    };\n\n    // A provider that ended a tool input stream without deltas and never sent the final\n    // tool-call still gets a (no-args) tool call recorded before the step closes.\n    const flushPendingToolCall = (\n      controller: TransformStreamDefaultController<ChunkType<OUTPUT>>,\n      toolCallId: string,\n    ) => {\n      const pending = self.#pendingToolCalls[toolCallId];\n      if (!pending) return;\n      delete self.#pendingToolCalls[toolCallId];\n      emitSyntheticToolCall(controller, toolCallId, pending.meta, pending.args, pending.runId, pending.from);\n    };\n    const flushPendingToolCalls = (\n      controller: TransformStreamDefaultController<ChunkType<OUTPUT>>,\n      { onlyStreamed = false }: { onlyStreamed?: boolean } = {},\n    ) => {\n      for (const [toolCallId, pending] of Object.entries(self.#pendingToolCalls)) {\n        if (!onlyStreamed || pending.streamed) flushPendingToolCall(controller, toolCallId);\n      }\n    };\n\n    let structuredOutputErrored = false;\n\n    this.#baseStream = processedStream.pipeThrough(\n      new TransformStream<ChunkType<OUTPUT>, ChunkType<OUTPUT>>({\n        transform: async (chunk, controller) => {\n          // A stream that fails after a tool input finished but before its final tool-call\n          // still records the call built from the streamed args. Calls with no streamed args\n          // stay pending: the error may be retried, and the retry delivers the real tool-call.\n          if (chunk.type === 'error') {\n            // A structured-output error fails the step: its pending calls, streamed or not, must\n            // not be recorded (a half-streamed input would otherwise run as `{}`/partial args).\n            if (isStructuredOutputError(chunk.payload.error)) {\n              structuredOutputErrored = true;\n              self.#pendingToolCalls = Object.create(null);\n            } else {\n              flushPendingToolCalls(controller, { onlyStreamed: true });\n            }\n          }\n          // A call's outcome must not precede the call itself.\n          if (chunk.type === 'tool-result' || chunk.type === 'tool-error') {\n            flushPendingToolCall(controller, chunk.payload.toolCallId);\n          }\n          switch (chunk.type) {\n            case 'tool-call-suspended':\n            case 'tool-call-approval':\n              self.#status = 'suspended';\n              self.#wasSuspended = true;\n              // Parallel suspended calls of one step share its usage; only the first chunk carries it.\n              self.#suspendedStepUsage ??= chunk.payload.usage;\n              self.#delayedPromises.suspendPayload.resolve(chunk.payload);\n              self.#delayedPromises.resumeSchema.resolve(chunk.payload.resumeSchema);\n              if (!self.#finishCallbackSent) {\n                self.#finishCallbackSent = true;\n                await options?.onFinish?.(self.#createSuspendedOnFinishPayload(chunk));\n              }\n              // A plain stream ends here, so flush settles usage. A durable stream stays open\n              // across the suspension, so settle the same numbers now. The next finish replaces them.\n              self.#settleSuspendedUsage();\n              break;\n            case 'abort':\n              self.#status = 'canceled';\n              if (!self.#finishCallbackSent) {\n                self.#finishCallbackSent = true;\n                await options?.onFinish?.(self.#createAbortedOnFinishPayload());\n              }\n              self.#closeTransportIfNeeded();\n              break;\n            case 'step-start':\n              // A step reports the reasoning of the model request that completed it. A request\n              // cancelled by a queued signal ends without step-finish, so drop what it streamed.\n              self.#bufferedByStep.reasoning = [];\n              self.#bufferedByStepReasoningDetails = {};\n              // Text works the same way: a request that streamed text and then failed into an\n              // API-error retry (the durable agent starts each attempt with a new step-start)\n              // must not leave its partial text in front of the next request's answer (#26081).\n              if (self.#bufferedByStep.text) {\n                self.#bufferedByStep.text = '';\n                self.#bufferedText.length = Math.min(self.#bufferedText.length, self.#bufferedTextAtStepStart);\n              }\n              // So does whatever else the unfinished request streamed: it belongs to no step. Its\n              // sources and files leave the run too. Its tool calls stay, since an eager tool may\n              // already have run and been carried into the next request, but a call the next\n              // request makes under the same id replaces the recorded one.\n              if (self.#runOutputAtStepStart) {\n                self.#bufferedSources.length = self.#runOutputAtStepStart.sources;\n                self.#bufferedFiles.length = self.#runOutputAtStepStart.files;\n                for (const call of self.#toolCalls.slice(self.#runOutputAtStepStart.toolCalls)) {\n                  self.#replaceableToolCallIds.add(call.payload.toolCallId);\n                }\n              }\n              self.#runOutputAtStepStart = {\n                sources: self.#bufferedSources.length,\n                files: self.#bufferedFiles.length,\n                toolCalls: self.#toolCalls.length,\n              };\n              Object.assign(self.#bufferedByStep, { sources: [], files: [], toolCalls: [], toolResults: [] });\n              if (self.#reasoningAtStepStart) {\n                self.#bufferedReasoning.length = self.#reasoningAtStepStart.length;\n                self.#bufferedReasoningDetails = self.#reasoningAtStepStart.details;\n              }\n              self.#reasoningAtStepStart = {\n                length: self.#bufferedReasoning.length,\n                details: { ...self.#bufferedReasoningDetails },\n              };\n              break;\n            case 'raw':\n              if (!self.#options.includeRawChunks) {\n                return;\n              }\n              break;\n            case 'object-result':\n              self.#bufferedObject = chunk.object;\n              self.#usedFallbackValue = chunk.metadata?.fallback === true;\n              // An output processor can still reject this attempt and ask for a retry,\n              // which would make this object stale. A settled promise cannot be\n              // un-settled, so when processors are in play the object is only buffered\n              // here and settled once the attempt survives `step-finish` (or at\n              // stream end, whichever comes first). Without processors no retry is\n              // possible, so resolve immediately and keep the existing timing.\n              // Only resolve if not already rejected by validation error\n              if (!self.processorRunner && self.#delayedPromises.object.status.type === 'pending') {\n                self.#delayedPromises.object.resolve(chunk.object);\n              }\n              break;\n            case 'source':\n              self.#bufferedSources.push(chunk);\n              self.#bufferedByStep.sources.push(chunk);\n              break;\n            case 'text-delta':\n              self.#bufferedText.push(chunk.payload.text);\n              self.#bufferedByStep.text += chunk.payload.text;\n              if (chunk.payload.id) {\n                const ary = self.#bufferedTextChunks[chunk.payload.id] ?? [];\n                ary.push(chunk.payload.text);\n                self.#bufferedTextChunks[chunk.payload.id] = ary;\n              }\n              break;\n            case 'tool-call-input-streaming-start':\n              // A call recorded in this step whose input streams again comes from a failed attempt being\n              // retried (the failure itself may never reach this stream), so the retry's call replaces it.\n              // Ids reused by a later step are separate calls.\n              if (self.#attemptToolCallIds.has(chunk.payload.toolCallId)) {\n                self.#replaceableToolCallIds.add(chunk.payload.toolCallId);\n              }\n              self.#toolCallDeltaIdNameMap[chunk.payload.toolCallId] = chunk.payload.toolName;\n              self.#toolCallStreamingMeta[chunk.payload.toolCallId] = {\n                toolName: chunk.payload.toolName,\n                providerExecuted: chunk.payload.providerExecuted,\n                providerMetadata: chunk.payload.providerMetadata,\n                dynamic: chunk.payload.dynamic,\n                ...(chunk.payload.title ? { title: chunk.payload.title } : {}),\n                ...(chunk.payload.observability ? { observability: chunk.payload.observability } : {}),\n              };\n              break;\n            case 'tool-call-input-streaming-end': {\n              const toolCallId = chunk.payload.toolCallId;\n              const meta = self.#toolCallStreamingMeta[toolCallId];\n              const deltaParts = self.#toolCallArgsDeltas[toolCallId];\n              let args: Record<string, unknown> = {};\n              if (deltaParts?.length) {\n                try {\n                  const merged = deltaParts.join('');\n                  args = typeof merged === 'string' && merged.length > 0 ? JSON.parse(merged) : {};\n                } catch {\n                  args = {};\n                }\n              }\n              delete self.#toolCallStreamingMeta[toolCallId];\n              delete self.#toolCallArgsDeltas[toolCallId];\n              delete self.#toolCallDeltaIdNameMap[toolCallId];\n              if (meta) {\n                // Let the real tool-call drive emission: it carries the final args (OpenAI Responses\n                // and Anthropic PTC stream none) and the tool payload transform metadata stamped\n                // upstream. A synthetic call from the deltas is only emitted if it never arrives.\n                self.#pendingToolCalls[toolCallId] = {\n                  meta,\n                  args,\n                  streamed: Boolean(deltaParts?.length),\n                  runId: chunk.runId,\n                  from: chunk.from,\n                };\n              }\n              break;\n            }\n            case 'tool-call-delta':\n              if (!self.#toolCallArgsDeltas[chunk.payload.toolCallId]) {\n                self.#toolCallArgsDeltas[chunk.payload.toolCallId] = [];\n              }\n              self.#toolCallArgsDeltas?.[chunk.payload.toolCallId]?.push(chunk.payload.argsTextDelta);\n              // mutate chunk to add toolname, we need it later to look up tools by their name\n              chunk.payload.toolName ||= self.#toolCallDeltaIdNameMap[chunk.payload.toolCallId];\n              break;\n            case 'file':\n              self.#bufferedFiles.push(chunk);\n              self.#bufferedByStep.files.push(chunk);\n              break;\n            case 'reasoning-start': {\n              const makeReasoningDetail = () => ({\n                type: 'reasoning' as const,\n                runId: chunk.runId,\n                from: chunk.from,\n                payload: {\n                  id: chunk.payload.id,\n                  providerMetadata: chunk.payload.providerMetadata,\n                  text: '',\n                },\n              });\n              // Two independent objects: the run-level entry keeps accumulating\n              // across steps while the per-step entry is dropped at step-finish.\n              self.#bufferedReasoningDetails[chunk.payload.id] = makeReasoningDetail();\n              self.#bufferedByStepReasoningDetails[chunk.payload.id] = makeReasoningDetail();\n              break;\n            }\n            case 'reasoning-delta': {\n              self.#bufferedReasoning.push({\n                type: 'reasoning',\n                runId: chunk.runId,\n                from: chunk.from,\n                payload: chunk.payload,\n              });\n              self.#bufferedByStep.reasoning.push({\n                type: 'reasoning',\n                runId: chunk.runId,\n                from: chunk.from,\n                payload: chunk.payload,\n              });\n\n              for (const bufferedReasoning of [\n                self.#bufferedReasoningDetails[chunk.payload.id],\n                self.#bufferedByStepReasoningDetails[chunk.payload.id],\n              ]) {\n                if (!bufferedReasoning) continue;\n                bufferedReasoning.payload.text += chunk.payload.text;\n                if (chunk.payload.providerMetadata) {\n                  bufferedReasoning.payload.providerMetadata = chunk.payload.providerMetadata;\n                }\n              }\n              break;\n            }\n\n            case 'reasoning-end': {\n              if (chunk.payload.providerMetadata) {\n                for (const bufferedReasoning of [\n                  self.#bufferedReasoningDetails[chunk.payload.id],\n                  self.#bufferedByStepReasoningDetails[chunk.payload.id],\n                ]) {\n                  if (!bufferedReasoning) continue;\n                  bufferedReasoning.payload.providerMetadata = chunk.payload.providerMetadata;\n                }\n              }\n              break;\n            }\n            case 'tool-call': {\n              const pending = self.#pendingToolCalls[chunk.payload.toolCallId];\n              if (pending) {\n                delete self.#pendingToolCalls[chunk.payload.toolCallId];\n                const { meta } = pending;\n                chunk.payload.providerExecuted ??= meta.providerExecuted;\n                chunk.payload.providerMetadata ??= meta.providerMetadata;\n                chunk.payload.dynamic ??= meta.dynamic;\n                if (meta.title && !chunk.payload.title) chunk.payload.title = meta.title;\n                if (meta.observability && !chunk.payload.observability) {\n                  chunk.payload.observability = meta.observability;\n                }\n              }\n              // The retry's real call replaces the one recorded from the failed attempt.\n              if (self.#replaceableToolCallIds.delete(chunk.payload.toolCallId)) {\n                self.#attemptToolCallIds.delete(chunk.payload.toolCallId);\n                for (const calls of [self.#toolCalls, self.#bufferedByStep.toolCalls]) {\n                  const index = calls.findLastIndex(tc => tc.payload.toolCallId === chunk.payload.toolCallId);\n                  if (index === -1) continue;\n                  calls.splice(index, 1);\n                  // Keep the step-start boundary on the same call, so a later retry can still replace this one.\n                  if (\n                    calls === self.#toolCalls &&\n                    self.#runOutputAtStepStart &&\n                    index < self.#runOutputAtStepStart.toolCalls\n                  ) {\n                    self.#runOutputAtStepStart.toolCalls--;\n                  }\n                }\n              }\n              // A call already recorded under this id in this step (a repeated tool-call) is not emitted twice.\n              if (self.#attemptToolCallIds.has(chunk.payload.toolCallId)) {\n                return;\n              }\n              self.#toolCalls.push(chunk);\n              self.#bufferedByStep.toolCalls.push(chunk);\n              self.#attemptToolCallIds.add(chunk.payload.toolCallId);\n              const toolCallPayload = chunk.payload;\n              // @ts-expect-error TODO: What does this mean??? Why is there a nested output, what is the type supposed to be\n              if (toolCallPayload?.output?.from === 'AGENT' && toolCallPayload?.output?.type === 'finish') {\n                // @ts-expect-error TODO: What does this mean??? Why is there a nested output, what is the type supposed to be\n                const finishPayload = toolCallPayload.output.payload;\n                if (finishPayload?.usage) {\n                  self.updateUsageCount(finishPayload.usage);\n                }\n              }\n              break;\n            }\n            case 'tool-result':\n              // Partial provider results are streamed only; the final result follows.\n              if (chunk.payload.preliminary) break;\n              self.#toolResults.push(chunk);\n              self.#bufferedByStep.toolResults.push(chunk);\n              break;\n            case 'step-finish': {\n              // A failed or retried step keeps its no-args calls pending, like an error chunk does.\n              const stepReason = chunk.payload.stepResult.reason as string;\n              const attemptFailed = stepReason === 'retry' || stepReason === 'error';\n              flushPendingToolCalls(controller, { onlyStreamed: attemptFailed });\n              if (!attemptFailed) {\n                self.#attemptToolCallIds.clear();\n                self.#replaceableToolCallIds.clear();\n              }\n              self.updateUsageCount(chunk.payload.output.usage);\n              // A resumed suspended step reaches its step-finish here; its usage is now in #usageCount.\n              self.#suspendedStepUsage = undefined;\n              // chunk.payload.totalUsage = self.totalUsage;\n              self.#warnings = chunk.payload.stepResult.warnings || [];\n\n              if (chunk.payload.metadata.request) {\n                self.#request = chunk.payload.metadata.request;\n              }\n\n              const { providerMetadata, request, ...otherMetadata } = chunk.payload.metadata;\n\n              // Check if this step has tripwire data (from DefaultStepResult in llm-execution-step)\n              // The current step is the last one in the steps array (MastraStepResult with tripwire field)\n              const payloadSteps = chunk.payload.output?.steps || [];\n              const currentPayloadStep = payloadSteps[payloadSteps.length - 1];\n              const stepTripwire = currentPayloadStep?.tripwire;\n\n              // Rejected and retried attempts contribute no text to the step or run,\n              // including onFinish. Preserve text from earlier accepted steps (#26081, COR-1464).\n              const isRetriedStep = (chunk.payload.stepResult.reason as string) === 'retry';\n              if (stepTripwire || isRetriedStep) {\n                self.#bufferedText.length = Math.min(self.#bufferedText.length, self.#bufferedTextAtStepStart);\n              }\n\n              // If step has tripwire, text should be empty (rejected response)\n              const stepText = stepTripwire || isRetriedStep ? '' : self.#bufferedByStep.text;\n\n              const stepResult: LLMStepResult<OUTPUT> = {\n                stepType: self.#bufferedSteps.length === 0 ? 'initial' : 'tool-result',\n                sources: self.#bufferedByStep.sources,\n                files: self.#bufferedByStep.files,\n                toolCalls: self.#bufferedByStep.toolCalls,\n                toolResults: self.#bufferedByStep.toolResults,\n\n                // Durable agents attach pre-computed step content on the\n                // step-finish chunk because the stream adapter's messageList\n                // may be a stale reference (each workflow step deserializes\n                // a fresh instance).  Fall back to the live messageList for\n                // non-durable agents.\n                // A retried attempt was rolled back, so the last response content belongs to an earlier step.\n                content: isRetriedStep\n                  ? []\n                  : ((chunk.payload as any)?._durableStepContent ??\n                    messageList.get.response.aiV5.modelContent(\n                      -1,\n                      self.#bufferedByStep.toolCalls.map(call => call.payload.toolCallId),\n                    )),\n                text: stepText,\n                // Include tripwire data if present\n                tripwire: stepTripwire,\n                // Scoped to this step (like `text` above); the run-level\n                // reasoning still spans every step.\n                reasoningText: self.#bufferedByStep.reasoning.map(reasoningPart => reasoningPart.payload.text).join(''),\n                reasoning: Object.values(self.#bufferedByStepReasoningDetails),\n                get staticToolCalls() {\n                  return self.#bufferedByStep.toolCalls.filter(\n                    part => part.type === 'tool-call' && part.payload?.dynamic === false,\n                  );\n                },\n                get dynamicToolCalls() {\n                  return self.#bufferedByStep.toolCalls.filter(\n                    part => part.type === 'tool-call' && part.payload?.dynamic === true,\n                  );\n                },\n                get staticToolResults() {\n                  return self.#bufferedByStep.toolResults.filter(\n                    part => part.type === 'tool-result' && part.payload?.dynamic === false,\n                  );\n                },\n                get dynamicToolResults() {\n                  return self.#bufferedByStep.toolResults.filter(\n                    part => part.type === 'tool-result' && part.payload?.dynamic === true,\n                  );\n                },\n                finishReason: chunk.payload.stepResult.reason,\n                usage: chunk.payload.output.usage,\n                warnings: self.#warnings,\n                request: request || {},\n                response: {\n                  id: chunk.payload.id || '',\n                  timestamp: (chunk.payload.metadata?.timestamp as Date) || new Date(),\n                  ...otherMetadata,\n                  modelId:\n                    (chunk.payload.metadata?.modelId as string) || (chunk.payload.metadata?.model as string) || '',\n                  messages: (chunk.payload as any)?._durableResponseMessages ?? chunk.payload.messages?.nonUser ?? [],\n                  dbMessages: self.messageList.get.response.db(),\n                  // We have to cast this until messageList can take generics also and type metadata, it was too\n                  // complicated to do this in this PR, it will require a much bigger change.\n                  uiMessages: messageList.get.response.aiV5.ui() as LLMStepResult<OUTPUT>['response']['uiMessages'],\n                },\n                providerMetadata: providerMetadata ?? chunk.payload.providerMetadata,\n              };\n\n              await options?.onStepFinish?.({\n                ...(self.#model.modelId && self.#model.provider && self.#model.version ? { model: self.#model } : {}),\n                ...stepResult,\n              });\n\n              self.#bufferedSteps.push(stepResult);\n              self.#lastStepUsage = stepResult.usage;\n\n              // `text` is excluded from a rejected attempt via the empty `stepText`\n              // above; the structured object needs the same treatment. Drop the\n              // buffered object when this attempt is being retried, otherwise settle\n              // the object promise now that the attempt has been accepted.\n              if (stepTripwire?.retry) {\n                self.#bufferedObject = undefined;\n                self.#usedFallbackValue = false;\n              } else if (self.#bufferedObject !== undefined && self.#delayedPromises.object.status.type === 'pending') {\n                self.#delayedPromises.object.resolve(self.#bufferedObject);\n              }\n\n              self.#bufferedByStep = {\n                text: '',\n                reasoning: [],\n                sources: [],\n                files: [],\n                toolCalls: [],\n                toolResults: [],\n                dynamicToolCalls: [],\n                dynamicToolResults: [],\n                staticToolCalls: [],\n                staticToolResults: [],\n                content: [],\n                usage: { inputTokens: undefined, outputTokens: undefined, totalTokens: undefined },\n                warnings: [],\n                request: {},\n                response: {\n                  id: '',\n                  timestamp: new Date(),\n                  modelId: '',\n                  messages: [],\n                  uiMessages: [],\n                },\n                reasoningText: '',\n                providerMetadata: undefined,\n                finishReason: undefined,\n              };\n              self.#bufferedByStepReasoningDetails = {};\n              self.#reasoningAtStepStart = undefined;\n              self.#runOutputAtStepStart = undefined;\n              self.#bufferedTextAtStepStart = self.#bufferedText.length;\n\n              // A continuing goal evaluation arrived while this step was still\n              // in flight (in-process chunk ordering): this step-finish belongs\n              // to the judged turn, so drop its buffers now that its stepResult\n              // and usage have been recorded.\n              if (self.#truncateAtNextStepFinish) {\n                self.#truncateAtNextStepFinish = false;\n                self.#truncateRunBuffers();\n              }\n\n              break;\n            }\n            case 'tripwire':\n              // Handle tripwire chunks from processors\n              self.#tripwire = {\n                reason: chunk.payload?.reason || 'Content blocked',\n                retry: chunk.payload?.retry,\n                metadata: chunk.payload?.metadata,\n                processorId: chunk.payload?.processorId,\n              };\n              // Tracing must not change how the stream settles.\n              try {\n                onTracingTripwire?.(self.#tripwire, self.#usageCount, self.#bufferedText.join(''));\n              } catch (error) {\n                self.logger?.warn('Error recording tripwire tracing', error);\n              }\n              self.#finishReason = 'other';\n              // The tripwire terminates the stream without a `finish` chunk, so settle the\n              // status here; otherwise the run stays 'running' forever.\n              if (self.#status !== 'failed' && self.#status !== 'canceled') {\n                self.#status = 'tripwire';\n              }\n              // Mark stream as finished for EventEmitter\n              self.#streamFinished = true;\n\n              // Resolve all delayed promises before terminating\n              self.resolvePromises({\n                text: self.#bufferedText.join(''),\n                finishReason: 'other',\n                object: undefined,\n                usage: self.#usageCount,\n                warnings: self.#warnings,\n                providerMetadata: undefined,\n                response: {\n                  // Durable runs end on this chunk when processOutputResult trips, so no finish\n                  // chunk builds the response messages; keep the rejected draft visible (#27562).\n                  ...(self.#options.resolveFinalPromises && {\n                    messages: self.messageList.get.response.aiV5.model(),\n                    uiMessages:\n                      self.messageList.get.response.aiV5.ui() as LLMStepResult<OUTPUT>['response']['uiMessages'],\n                  }),\n                  dbMessages: self.messageList.get.response.db(),\n                },\n                request: {},\n                reasoning: [],\n                reasoningText: undefined,\n                sources: [],\n                files: [],\n                toolCalls: [],\n                toolResults: [],\n                steps: self.#bufferedSteps,\n                totalUsage: self.#usageCount,\n                content: [],\n                suspendPayload: undefined, // Tripwire doesn't suspend, so resolve to undefined\n                resumeSchema: undefined,\n              });\n\n              self.#closeTransportIfNeeded();\n\n              // Emit the tripwire chunk for listeners\n              self.#emitChunk(chunk);\n              // Pass the tripwire chunk through\n              controller.enqueue(chunk);\n\n              // The flush that normally runs onFinish never runs after terminate(), so run it here.\n              // Do it after the tripwire chunk is out: #streamFinished is already set, so a\n              // subscriber that attaches while onFinish is pending only sees buffered chunks.\n              if (!self.#finishCallbackSent) {\n                self.#finishCallbackSent = true;\n                await options?.onFinish?.(self.#createTripwireOnFinishPayload());\n              }\n              // Emit finish event for EventEmitter streams (since flush won't be called on terminate)\n              self.#emitter.emit('finish');\n              // Terminate the stream\n              controller.terminate();\n              return;\n            case 'finish':\n              // A tripwire/abort bail ends the run without the final tool-call; don't record a\n              // placeholder no-args call for it.\n              // The same holds after a structured-output error: that step is failing, and a\n              // pending call whose input never arrived would run with empty args.\n              if ((chunk.payload.stepResult.reason as string) === 'tripwire' || structuredOutputErrored) {\n                self.#pendingToolCalls = Object.create(null);\n              } else {\n                flushPendingToolCalls(controller);\n              }\n              // 'suspended' is not terminal: a resume leg rehydrates the persisted 'suspended'\n              // status and must be able to finish as 'success'. Only 'failed' and 'canceled'\n              // block the success transition.\n              if (self.#status !== 'failed' && self.#status !== 'canceled') {\n                self.#status = 'success';\n              }\n              // A caller `abortSignal` cancellation bails through the same path processor\n              // tripwires use, so the bail's `finish` chunk carries `reason: 'tripwire'`. The\n              // preceding `abort` chunk already set the status to 'canceled'; preserve the\n              // 'aborted' finish reason instead of overwriting it with the synthetic tripwire.\n              if (self.#status === 'canceled') {\n                self.#finishReason = 'aborted';\n              } else if (chunk.payload.stepResult.reason) {\n                self.#finishReason = chunk.payload.stepResult.reason;\n              }\n\n              // We can preserve finish metadata from whichever shape the upstream SDK emitted,\n              // but we cannot reconstruct providerMetadata if the provider omitted it entirely.\n              const finalProviderMetadata = chunk.payload.metadata?.providerMetadata ?? chunk.payload.providerMetadata;\n\n              // Retain the step providerMetadata so output-step processors can\n              // read it (e.g. to attribute a Bedrock guardrail content-filter\n              // block to the responsible policy). The completed-steps array is\n              // empty on such blocks, so this is the only carrier of the trace.\n              if (finalProviderMetadata) {\n                self.#stepProviderMetadata = finalProviderMetadata;\n              }\n\n              // Check if this is a tripwire case - set tripwire data\n              // This can happen when max retries is exceeded or a processor triggers a tripwire\n              if ((chunk.payload.stepResult.reason as string) === 'tripwire') {\n                // Try to get the tripwire data from the last step (MastraStepResult)\n                const outputSteps = chunk.payload.output?.steps;\n                const lastStep = outputSteps?.[outputSteps?.length - 1];\n                const stepTripwire = lastStep?.tripwire;\n                // Don't synthesize a tripwire for a caller cancellation: aborts bail through this\n                // same 'tripwire' reason but carry no real step tripwire. Only surface a tripwire\n                // when an actual processor produced one (or when the run wasn't aborted).\n                if (self.#status !== 'canceled' || stepTripwire) {\n                  self.#tripwire = {\n                    reason: stepTripwire?.reason || 'Processor tripwire triggered',\n                    retry: stepTripwire?.retry,\n                    metadata: stepTripwire?.metadata,\n                    processorId: stepTripwire?.processorId,\n                  };\n                }\n              }\n\n              // Add structured output to the latest assistant message metadata\n              if (self.#bufferedObject !== undefined) {\n                const responseMessages = messageList.get.response.db();\n                const lastAssistantMessage = [...responseMessages].reverse().find(m => m.role === 'assistant');\n                if (lastAssistantMessage) {\n                  if (!lastAssistantMessage.content.metadata) {\n                    lastAssistantMessage.content.metadata = {};\n                  }\n                  lastAssistantMessage.content.metadata.structuredOutput = self.#bufferedObject;\n                }\n              }\n\n              let response: LLMStepResult<OUTPUT>['response'] = {};\n              if (chunk.payload.metadata) {\n                const { providerMetadata, request, ...otherMetadata } = chunk.payload.metadata;\n\n                response = {\n                  ...otherMetadata,\n                  messages: messageList.get.response.aiV5.model(),\n                  uiMessages: messageList.get.response.aiV5.ui() as LLMStepResult<OUTPUT>['response']['uiMessages'],\n                };\n              } else if (self.#bufferedSteps.length > 0) {\n                // Durable finish chunks carry no model metadata; the last step's response\n                // already holds the run's response messages and model id (#26780).\n                response = { ...self.#bufferedSteps[self.#bufferedSteps.length - 1]!.response };\n              }\n\n              if (self.#finishUsageIsTotal) {\n                self.#usageCount.inputTokens = undefined;\n                self.#usageCount.outputTokens = undefined;\n                self.#usageCount.totalTokens = undefined;\n                delete self.#usageCount.reasoningTokens;\n                delete self.#usageCount.cachedInputTokens;\n                delete self.#usageCount.cacheCreationInputTokens;\n                delete self.#usageCount.cacheCreationInputTokens5m;\n                delete self.#usageCount.cacheCreationInputTokens1h;\n                self.#usageCountMissing.clear();\n              }\n              this.populateUsageCount(chunk.payload.output.usage as Partial<LanguageModelUsage>);\n\n              chunk.payload.output.usage = {\n                inputTokens: self.#usageCount.inputTokens,\n                outputTokens: self.#usageCount.outputTokens,\n                totalTokens: self.#getTotalUsage().totalTokens,\n                ...(self.#usageCount.reasoningTokens !== undefined && {\n                  reasoningTokens: self.#usageCount.reasoningTokens,\n                }),\n                ...(self.#usageCount.cachedInputTokens !== undefined && {\n                  cachedInputTokens: self.#usageCount.cachedInputTokens,\n                }),\n                ...(self.#usageCount.cacheCreationInputTokens !== undefined && {\n                  cacheCreationInputTokens: self.#usageCount.cacheCreationInputTokens,\n                }),\n                ...(self.#usageCount.cacheCreationInputTokens5m !== undefined && {\n                  cacheCreationInputTokens5m: self.#usageCount.cacheCreationInputTokens5m,\n                }),\n                ...(self.#usageCount.cacheCreationInputTokens1h !== undefined && {\n                  cacheCreationInputTokens1h: self.#usageCount.cacheCreationInputTokens1h,\n                }),\n                ...(self.#usageCount.raw !== undefined && {\n                  raw: self.#usageCount.raw,\n                }),\n              };\n\n              // Create a writer from the controller so processOutputResult can emit custom chunks.\n              // Must use both #emitChunk (for fullStream/EventEmitter consumers) and\n              // controller.enqueue (for raw stream consumers) to ensure visibility.\n              // Also passed to onFinish so chunks written while `finish` is being assembled\n              // (e.g. a generated thread title) are delivered before the `finish` chunk.\n              const outputResultWriter = {\n                custom: async (\n                  data: { type: string; data?: unknown; transient?: boolean },\n                  writerOptions?: { messageId?: string },\n                ) => {\n                  persistProcessorDataChunk(\n                    self.messageList,\n                    resolveProcessorWriterMessageId(self.messageList, self.messageId, writerOptions?.messageId),\n                    data,\n                  );\n                  self.#emitChunk(data as ChunkType<OUTPUT>);\n                  controller.enqueue(data as ChunkType<OUTPUT>);\n                },\n              };\n\n              let outputResultTripwire: StepTripwireData | undefined;\n              let outputResultError: Error | undefined;\n              try {\n                if (self.processorRunner && !self.#options.isLLMExecutionStep) {\n                  // Run output processors when NOT in LLM execution step context\n                  // (i.e., when this is the final MastraModelOutput for the agent)\n\n                  const lastStep = self.#bufferedSteps[self.#bufferedSteps.length - 1];\n                  const lastStepText = lastStep?.text || '';\n\n                  const outputResult: OutputResult = {\n                    text: self.#bufferedText.join(''),\n                    usage: chunk.payload.output.usage as LanguageModelUsage,\n                    finishReason: self.#status === 'failed' ? 'error' : self.#finishReason || 'unknown',\n                    steps: [...self.#bufferedSteps] as LLMStepResult[],\n                  };\n\n                  // Canceled output bypasses the normal LLM-step response assembly. Add its\n                  // nonblank in-flight text to MessageList so every output processor receives\n                  // the same terminal transcript shape; persistence remains processor-owned.\n                  if (self.#status === 'canceled' && self.#bufferedByStep.text.trim().length > 0) {\n                    self.messageList.add(\n                      {\n                        role: 'assistant',\n                        content: [{ type: 'text', text: self.#bufferedByStep.text }],\n                      },\n                      'response',\n                      { merge: false },\n                    );\n                  }\n\n                  const outputTextBeforeProcessing = resolveOutputTextSkippingCompletionChecks(self.messageList);\n                  const stepMessage = resolveOutputMessageSkippingCompletionChecks(self.messageList);\n                  const iterationPartOffset = stepMessage\n                    ? findIterationPartOffset(self.messageList, stepMessage, lastStepText)\n                    : undefined;\n                  const separatedIteration =\n                    stepMessage && iterationPartOffset !== undefined\n                      ? self.messageList.splitResponseMessageAtPartOffset(stepMessage.id, iterationPartOffset)\n                      : undefined;\n                  const earlierStepMessage = separatedIteration\n                    ? self.messageList.get.response\n                        .db()\n                        .find(message => message.id === separatedIteration.earlierMessageId)\n                    : undefined;\n                  const earlierStepPartBoundaries = separatedIteration\n                    ? findStepPartBoundaries(earlierStepMessage, self.#bufferedSteps.slice(0, -1))\n                    : undefined;\n                  const earlierTextBeforeProcessing = earlierStepMessage\n                    ? resolveMessageText(earlierStepMessage)\n                    : undefined;\n                  const processorStepMessageId = separatedIteration?.currentMessageId ?? stepMessage?.id;\n                  const processorStepMessage = processorStepMessageId\n                    ? self.messageList.get.response.db().find(message => message.id === processorStepMessageId)\n                    : undefined;\n                  const processorStepMessageParts = processorStepMessage?.content?.parts;\n                  const originalProcessorStepMessageParts = processorStepMessageParts\n                    ? [...processorStepMessageParts]\n                    : undefined;\n\n                  let outputText: string | undefined;\n                  let stepText: string | undefined;\n                  let processedEarlierText: string | undefined;\n                  let processedEarlierMessage: MastraDBMessage | undefined;\n                  try {\n                    self.messageList = await self.processorRunner.runOutputProcessors(\n                      self.messageList,\n                      resolveObservabilityContext(options),\n                      self.#options.requestContext,\n                      0,\n                      outputResultWriter,\n                      outputResult,\n                    );\n\n                    const responseMessages = self.messageList.get.response.db();\n                    const resolvedProcessedStepMessage = resolveOutputMessageSkippingCompletionChecks(self.messageList);\n                    const idMatchedProcessedStepMessage = processorStepMessageId\n                      ? responseMessages.find(message => message.id === processorStepMessageId)\n                      : undefined;\n                    const processedStepMessage =\n                      resolvedProcessedStepMessage?.id === separatedIteration?.earlierMessageId\n                        ? idMatchedProcessedStepMessage\n                        : (resolvedProcessedStepMessage ?? idMatchedProcessedStepMessage);\n                    processedEarlierMessage = separatedIteration\n                      ? responseMessages.find(message => message.id === separatedIteration.earlierMessageId)\n                      : undefined;\n                    processedEarlierText = separatedIteration\n                      ? processedEarlierMessage\n                        ? resolveMessageText(processedEarlierMessage)\n                        : ''\n                      : undefined;\n                    const processedOutputText = resolveOutputTextSkippingCompletionChecks(self.messageList);\n                    const processedStepParts = processedStepMessage?.content?.parts;\n                    stepText =\n                      separatedIteration || processedOutputText !== outputTextBeforeProcessing\n                        ? resolveProcessedStepText({\n                            processedStepMessage,\n                            processedStepParts,\n                            originalMessageId: processorStepMessage?.id,\n                            originalIterationPartOffset: separatedIteration ? 0 : iterationPartOffset,\n                            originalPartCount: processorStepMessageParts?.length,\n                            originalParts: originalProcessorStepMessageParts,\n                            originalStepText: lastStepText,\n                            outputText: processedOutputText,\n                          })\n                        : undefined;\n                    const stepMessageWasReplaced =\n                      separatedIteration &&\n                      processedStepMessage &&\n                      processedStepMessage.id !== processorStepMessage?.id;\n                    if (stepMessageWasReplaced && resolveMessageText(processedStepMessage) === processedEarlierText) {\n                      stepText = '';\n                    }\n                    outputText = separatedIteration\n                      ? stepMessageWasReplaced\n                        ? processedOutputText\n                        : `${processedEarlierText}${stepText ?? ''}`\n                      : processedOutputText;\n\n                    if (processedEarlierText !== undefined) {\n                      reconcileBufferedStepTexts(\n                        self.#bufferedSteps.slice(0, -1),\n                        processedEarlierText,\n                        processedEarlierMessage,\n                        earlierStepPartBoundaries,\n                        earlierTextBeforeProcessing,\n                      );\n                    }\n                  } finally {\n                    clearStepPartIndexes(self.messageList.get.response.db());\n                    if (separatedIteration) {\n                      self.messageList.coalesceSplitResponseMessages(\n                        separatedIteration.earlierMessageId,\n                        separatedIteration.currentMessageId,\n                      );\n                    }\n                  }\n\n                  // When multiple iterations share one response message, separate the current iteration before result\n                  // processing so both the earlier buffered steps and the current step are reconciled from processor\n                  // output. Compare against undefined, not truthiness, so clearing to '' applies when the processor\n                  // removes an iteration's response.\n                  if (self.#status !== 'canceled' && lastStep && stepText !== undefined && stepText !== lastStepText) {\n                    lastStep.text = stepText;\n                  }\n\n                  // Use the processed text when a response message exists, even if the\n                  // processor intentionally emptied it. Only fall back to the raw model\n                  // text when there is no processed message at all.\n                  this.resolvePromises({\n                    text: outputText ?? (stepMessage ? '' : lastStepText),\n                    finishReason: self.#finishReason,\n                  });\n\n                  // Update response with processed messages after output processors have run\n                  if (chunk.payload.metadata) {\n                    const { providerMetadata, request, ...otherMetadata } = chunk.payload.metadata;\n                    response = {\n                      ...otherMetadata,\n                      messages: self.messageList.get.response.aiV5.model(),\n                      uiMessages:\n                        self.messageList.get.response.aiV5.ui() as LLMStepResult<OUTPUT>['response']['uiMessages'],\n                    };\n                  }\n\n                  // Cast needed because chunk.payload.response is typed with default OUTPUT=undefined\n                  (chunk.payload as { response?: LLMStepResult<OUTPUT>['response'] }).response = response;\n                } else if (!self.#options.isLLMExecutionStep || self.#options.resolveFinalPromises) {\n                  // No processor runner, not in LLM execution step - resolve ordinary\n                  // tool-driven multi-step runs with the last step's text so narration before\n                  // tool calls is excluded. Suspended/resumed tool approval flows keep the\n                  // aggregate stream text because pre-approval text is part of the resumed run.\n                  // Durable agents set resolveFinalPromises to force resolution even when\n                  // isLLMExecutionStep is true (single MastraModelOutput for the entire run).\n                  // A step rejected by a tripwire keeps its empty text, so durable runs don't\n                  // return a rejected reply (#26048).\n                  let rewrittenText: string | undefined;\n                  if (chunk.payload.textRewritten === true && self.#status !== 'canceled') {\n                    // Durable producers run processOutputResult after the last step-finish was\n                    // streamed. When it changed the reply, they write the result onto the run's\n                    // last step; otherwise the buffered text stands (a failed step's record is\n                    // empty while the stream already delivered its partial text). Like the\n                    // processed path above, the rewritten reply is the run's text, also after\n                    // a resume, where the buffered aggregate still holds pre-approval text.\n                    const finalizedText = chunk.payload.output?.steps?.at(-1)?.text;\n                    const lastStep = self.#bufferedSteps.at(-1);\n                    if (lastStep && typeof finalizedText === 'string') {\n                      lastStep.text = finalizedText;\n                      rewrittenText = finalizedText;\n                    }\n                  }\n                  this.resolvePromises({\n                    text: rewrittenText ?? self.#producedText(),\n                    finishReason: self.#finishReason,\n                  });\n                }\n                // If isLLMExecutionStep is true (without resolveFinalPromises), don't resolve\n                // text here - let the outer MastraModelOutput handle it\n              } catch (error) {\n                if (error instanceof TripWire) {\n                  self.#tripwire = {\n                    reason: error.message,\n                    retry: error.options?.retry,\n                    metadata: error.options?.metadata,\n                    processorId: error.processorId,\n                  };\n                  outputResultTripwire = self.#tripwire;\n                  // A tripwire rejects the output without erasing it; keep `text` in sync with\n                  // steps/response messages and report the rejection via `tripwire`.\n                  self.resolvePromises({\n                    finishReason: 'other',\n                    text: self.#producedText(),\n                  });\n                } else {\n                  self.#error = getErrorFromUnknown(error, {\n                    fallbackMessage: 'Unknown error in stream',\n                  });\n                  outputResultError = self.#error;\n                  self.resolvePromises({\n                    finishReason: 'error',\n                    text: '',\n                  });\n                }\n                if (self.#delayedPromises.object.status.type !== 'resolved') {\n                  self.#delayedPromises.object.resolve(self.#bufferedObject as OUTPUT);\n                }\n              }\n\n              const reasoningText =\n                self.#bufferedReasoning.length > 0\n                  ? self.#bufferedReasoning.map(reasoningPart => reasoningPart.payload.text).join('')\n                  : undefined;\n\n              const baseFinishStep = self.#bufferedSteps[self.#bufferedSteps.length - 1];\n              if (\n                baseFinishStep &&\n                baseFinishStep.providerMetadata === undefined &&\n                finalProviderMetadata !== undefined\n              ) {\n                baseFinishStep.providerMetadata = finalProviderMetadata;\n              }\n\n              // Resolve the private terminal override after all queued step-finish chunks.\n              self.#request = getTerminalRequest?.() ?? self.#request;\n\n              // Resolve all delayed promises with final values\n              this.resolvePromises({\n                usage: self.#usageCount,\n                warnings: self.#warnings,\n                providerMetadata: finalProviderMetadata,\n                response: { ...response, dbMessages: self.messageList.get.response.db() },\n                request: self.#request || {},\n                reasoningText,\n                reasoning: Object.values(self.#bufferedReasoningDetails || {}),\n                sources: self.#bufferedSources,\n                files: self.#bufferedFiles,\n                toolCalls: self.#toolCalls,\n                toolResults: self.#toolResults,\n                steps: self.#bufferedSteps,\n                totalUsage: self.#getTotalUsage(),\n                content: messageList.get.response.aiV5.stepContent(),\n                suspendPayload: undefined,\n                resumeSchema: undefined,\n              });\n\n              if (baseFinishStep) {\n                const onFinishPayload: MastraOnFinishCallbackArgs<OUTPUT> = {\n                  // StepResult properties from baseFinishStep\n                  providerMetadata: baseFinishStep.providerMetadata ?? finalProviderMetadata,\n                  text: self.#bufferedText.join(''),\n                  warnings: baseFinishStep.warnings ?? [],\n                  finishReason:\n                    outputResultError || self.#status === 'failed' ? 'error' : chunk.payload.stepResult.reason,\n                  content: messageList.get.response.aiV5.stepContent(),\n                  // A preceding error may have rejected result promises already accessed by callers.\n                  // Finish bookkeeping uses the final buffers, independently of those promises.\n                  request: self.#request || {},\n                  error: self.error,\n                  reasoning: Object.values(self.#bufferedReasoningDetails || {}),\n                  reasoningText,\n                  sources: self.#bufferedSources,\n                  files: self.#bufferedFiles,\n                  steps: self.#bufferedSteps,\n                  response: {\n                    ...response,\n                    ...baseFinishStep.response,\n                    messages: messageList.get.response.aiV5.model(),\n                    dbMessages: self.messageList.get.response.db(),\n                  },\n                  usage: chunk.payload.output.usage,\n                  totalUsage: self.#getTotalUsage(),\n                  ...(self.#generationReportedUsage && { generationReportedUsage: self.#generationReportedUsage }),\n                  ...(self.#generationReportedStepCount > 0 && {\n                    generationStepProviderMetadata: self.#bufferedSteps\n                      .slice(self.#generationReportedStepCount)\n                      .map(step => step.providerMetadata),\n                  }),\n                  toolCalls: self.#toolCalls,\n                  toolResults: self.#toolResults,\n                  staticToolCalls: self.#toolCalls.filter(toolCall => toolCall?.payload?.dynamic === false),\n                  staticToolResults: self.#toolResults.filter(toolResult => toolResult?.payload?.dynamic === false),\n                  dynamicToolCalls: self.#toolCalls.filter(toolCall => toolCall?.payload?.dynamic === true),\n                  dynamicToolResults: self.#toolResults.filter(toolResult => toolResult?.payload?.dynamic === true),\n                  // Custom properties (not part of standard callback)\n                  ...(self.#model.modelId && self.#model.provider && self.#model.version ? { model: self.#model } : {}),\n                  usedFallbackValue: self.#usedFallbackValue,\n                  object:\n                    self.#delayedPromises.object.status.type === 'rejected'\n                      ? undefined\n                      : self.#delayedPromises.object.status.type === 'resolved'\n                        ? self.#delayedPromises.object.status.value\n                        : self.#bufferedObject !== undefined\n                          ? self.#bufferedObject\n                          : self.#structuredOutputMode === 'direct' && baseFinishStep.text\n                            ? (() => {\n                                try {\n                                  return JSON.parse(baseFinishStep.text);\n                                } catch {\n                                  return undefined;\n                                }\n                              })()\n                            : undefined,\n                };\n\n                if (!self.#finishCallbackSent) {\n                  self.#finishCallbackSent = true;\n                  await options?.onFinish?.(onFinishPayload, {\n                    writer: outputResultWriter,\n                    ...(outputResultTripwire && { outputResultTripwire }),\n                  });\n                }\n              }\n\n              // Output processors may perform the final memory write. A rejected write\n              // must not turn into a clean finish or trigger successful snapshot cleanup.\n              if (outputResultError) throw outputResultError;\n              await onFinishComplete?.();\n              self.#closeTransportIfNeeded();\n\n              // A `processOutputResult` tripwire rejects the run: end the stream with a\n              // `tripwire` chunk instead of the `finish` chunk, matching every other tripwire.\n              if (outputResultTripwire) {\n                if (self.#status !== 'failed' && self.#status !== 'canceled') {\n                  self.#status = 'tripwire';\n                }\n                const tripwireChunk = {\n                  type: 'tripwire',\n                  runId: chunk.runId,\n                  from: chunk.from,\n                  payload: { ...outputResultTripwire },\n                } as ChunkType<OUTPUT>;\n                self.#emitChunk(tripwireChunk);\n                controller.enqueue(tripwireChunk);\n                return;\n              }\n              break;\n\n            case 'goal':\n              // A continuing goal evaluation marks a safe truncation point for\n              // run-lifetime buffers: the turn's messages are already persisted\n              // to the MessageList by this point, and goal runs chain many agent\n              // turns inside one stream — retaining every chunk, step, and tool\n              // result grows memory unboundedly over long goal runs (and bloats\n              // suspend snapshots via `serializeState`). `shouldContinue` is the\n              // goal gate's explicit continuation decision: only truncate when\n              // another judged iteration follows, so terminal evaluations\n              // (completion, waiting, judge failure, budget exhaustion) keep the\n              // final turn intact for run-end results like `getFullOutput()`.\n              if (chunk.payload.shouldContinue === true) {\n                self.#truncateRunBuffers();\n                // In-process engines emit the goal chunk BEFORE the judged\n                // turn's step-finish (the gate decides `isContinued` first);\n                // durable engines emit it after. If the judged step is still in\n                // flight, its step-finish lands after this boundary — drop that\n                // step's buffers too when it arrives.\n                const byStep = self.#bufferedByStep;\n                if (\n                  byStep.text.length > 0 ||\n                  byStep.toolCalls.length > 0 ||\n                  byStep.reasoning.length > 0 ||\n                  byStep.sources.length > 0 ||\n                  byStep.files.length > 0\n                ) {\n                  self.#truncateAtNextStepFinish = true;\n                }\n              }\n              break;\n\n            case 'error':\n              const error = getErrorFromUnknown(chunk.payload.error, {\n                fallbackMessage: 'Unknown error chunk in stream',\n              });\n              self.#error = error;\n              self.#status = 'failed';\n              // A total deadline closes the stream without a finish chunk, so the output processors\n              // (and with them memory) get their one pass here, over the steps that completed in time.\n              // The pass writes memory, so it only runs for callers that supply the write check.\n              const beforeDeadlineSave = self.#options.beforeDeadlineSave;\n              if (\n                isMastraTimeoutError(error) &&\n                error.timeoutType === 'total' &&\n                self.processorRunner &&\n                !self.#options.isLLMExecutionStep &&\n                beforeDeadlineSave\n              ) {\n                let streamOpen = true;\n                // Taken before the write check: a slow check must not stamp the cut-off reply with a\n                // time after a retry the deadline error already let the caller start.\n                // Like a cancel, the text the unfinished step already streamed is part of the turn.\n                const { turn, inFlightMessageId } = self.messageList.cloneWithCompletedSteps(self.#bufferedByStep.text);\n                const cutOffStep = self.#bufferedByStep;\n                const deadlinePass = (async () => {\n                  try {\n                    if ((await beforeDeadlineSave()) === false) return;\n                  } catch (authError) {\n                    self.logger?.warn('Memory write denied at the total deadline, the turn is not saved', {\n                      error: authError,\n                    });\n                    return;\n                  }\n                  // Data parts a step processor writes for the cut-off text, whether it names that message or\n                  // not, are held until the message is written back: the write-back replaces it, and would\n                  // drop parts merged into it.\n                  let heldDataChunks:\n                    | { data: { type: string; data?: unknown; transient?: boolean }; messageId?: string }[]\n                    | undefined;\n                  const writer = {\n                    custom: async (\n                      data: { type: string; data?: unknown; transient?: boolean },\n                      writerOptions?: { messageId?: string },\n                    ) => {\n                      if (\n                        heldDataChunks &&\n                        (!writerOptions?.messageId || writerOptions.messageId === inFlightMessageId)\n                      )\n                        heldDataChunks.push({ data, messageId: writerOptions?.messageId });\n                      else\n                        persistProcessorDataChunk(\n                          turn,\n                          resolveProcessorWriterMessageId(turn, self.messageId, writerOptions?.messageId),\n                          data,\n                        );\n                      if (!streamOpen) return;\n                      self.#emitChunk(data as ChunkType<OUTPUT>);\n                      controller.enqueue(data as ChunkType<OUTPUT>);\n                    },\n                  };\n                  let cutOffTextDropped = false;\n                  if (inFlightMessageId) {\n                    heldDataChunks = [];\n                    // The cut-off text never reached the step processors (redaction, refusal handling...).\n                    // Run them over that message alone: the rest of the turn already went through them.\n                    try {\n                      const stepList = turn.clone();\n                      stepList.removeByIds(\n                        stepList.get.all\n                          .db()\n                          .map(message => message.id)\n                          .filter(id => id !== inFlightMessageId),\n                      );\n                      await self.processorRunner!.runProcessOutputStep({\n                        // The loop hands step processors these same step results, typed as AI SDK steps.\n                        steps: [...self.#bufferedSteps] as unknown as StepResult<any>[],\n                        messages: stepList.get.all.db(),\n                        messageList: stepList,\n                        stepNumber: self.#bufferedSteps.length,\n                        finishReason: 'error',\n                        toolCalls: cutOffStep.toolCalls.length\n                          ? cutOffStep.toolCalls.map(({ payload }) => ({\n                              toolName: payload.toolName,\n                              toolCallId: payload.toolCallId,\n                              args: payload.args,\n                            }))\n                          : undefined,\n                        text: cutOffStep.text,\n                        usage: self.#usageCount,\n                        ...resolveObservabilityContext(options),\n                        requestContext: self.#options.requestContext,\n                        writer,\n                      });\n                      turn.removeByIds([inFlightMessageId]);\n                      for (const message of stepList.get.all.db()) turn.add(message, 'response', { merge: false });\n                    } catch (stepError) {\n                      // Fail closed: keep the completed steps rather than save unprocessed text.\n                      turn.removeByIds([inFlightMessageId]);\n                      cutOffTextDropped = true;\n                      self.logger?.warn('Output step processors failed on the text cut off at the total deadline', {\n                        error: stepError,\n                      });\n                    }\n                    for (const { data, messageId } of heldDataChunks) {\n                      // A part aimed at the cut-off message lands on it if it survived the write-back,\n                      // otherwise on the message an untargeted write would reach.\n                      const target =\n                        messageId && turn.get.all.db().some(message => message.id === messageId)\n                          ? messageId\n                          : resolveProcessorWriterMessageId(turn, self.messageId);\n                      persistProcessorDataChunk(turn, target, data);\n                    }\n                    heldDataChunks = undefined;\n                  }\n                  try {\n                    await self.processorRunner!.runOutputProcessors(\n                      turn,\n                      resolveObservabilityContext(options),\n                      self.#options.requestContext,\n                      0,\n                      writer,\n                      {\n                        // Text the step processors blocked must not reach the result processors either.\n                        text: cutOffTextDropped\n                          ? self.#bufferedSteps.map(step => step.text).join('')\n                          : self.#bufferedText.join(''),\n                        usage: self.#usageCount,\n                        finishReason: 'error',\n                        steps: [...self.#bufferedSteps] as LLMStepResult[],\n                      },\n                    );\n                  } catch (processorError) {\n                    if (processorError instanceof TripWire) await self.#options.onDeadlineTripwire?.(turn);\n                    throw processorError;\n                  }\n                })().catch(processorError => {\n                  self.logger?.error('Output processors failed at the total deadline', { error: processorError });\n                });\n                // Saved before the stream ends, unless the store hangs: the deadline must still surface.\n                await settledOrElapsed(deadlinePass, DEADLINE_SAVE_WAIT_MS);\n                streamOpen = false;\n              }\n              self.#streamFinished = true; // Mark stream as finished for EventEmitter\n\n              Object.values(self.#delayedPromises).forEach(promise => {\n                if (promise.status.type === 'pending') {\n                  promise.reject(self.#error);\n                }\n              });\n\n              self.#closeTransportIfNeeded();\n              // Deliver the error chunk downstream first, then settle waiters.\n              // An errored stream never reaches flush(), so without this,\n              // _waitUntilFinished() callers that subscribed before the error\n              // hang forever while later callers resolve immediately via the\n              // #streamFinished flag. Deliberately NOT 'finish': observer\n              // streams close on 'finish', and durable fallback/error-processor\n              // recovery keeps consuming chunks after an error chunk.\n              self.#emitChunk(chunk);\n              controller.enqueue(chunk);\n              self.#emitter.emit('settled');\n              return;\n          }\n          self.#emitChunk(chunk);\n          controller.enqueue(chunk);\n        },\n        flush: () => {\n          if (self.#delayedPromises.object.status.type === 'pending') {\n            // always resolve a pending object promise in flush (with the buffered object\n            // if the stream produced one, otherwise undefined) if it hasn't been rejected\n            // by a validation error\n            self.#delayedPromises.object.resolve(self.#bufferedObject as OUTPUT);\n          }\n\n          // If stream ends in suspended state (e.g., tool-call-approval), resolve promises with partial results\n          // This allows consumers to access data that was produced before the suspension\n          if (self.#status === 'suspended') {\n            self.#resolveSuspendedPromises();\n          }\n\n          // If stream ends without proper finish/error chunks, reject unresolved promises\n          // This must be in the final transformer flush to ensure\n          // all of the delayed promises had a chance to resolve or reject already\n          // Avoids promises hanging forever\n          Object.entries(self.#delayedPromises).forEach(([key, promise]) => {\n            if (promise.status.type === 'pending') {\n              promise.reject(new Error(`promise '${key}' was not resolved or rejected when stream finished`));\n            }\n          });\n\n          self.#closeTransportIfNeeded();\n\n          // Emit finish event for EventEmitter streams\n          self.#streamFinished = true;\n          self.#emitter.emit('finish');\n        },\n      }),\n    );\n\n    if (initialState) {\n      this.deserializeState(initialState);\n    } else {\n      if (initialToolCalls) this.#toolCalls = initialToolCalls;\n      if (resumedText) {\n        const { priorText, stepText } = resumedText;\n        this.#resumedPriorText = priorText;\n        this.#bufferedText = [priorText, stepText].filter(Boolean);\n        this.#bufferedTextAtStepStart = priorText ? 1 : 0;\n        this.#bufferedByStep.text = stepText;\n        this.#wasSuspended = true;\n      }\n    }\n  }\n\n  private resolvePromise<KEY extends keyof PromiseResults<OUTPUT>>(key: KEY, value: PromiseResults<OUTPUT>[KEY]) {\n    if (this.#suspendedUsageIsProvisional && (key === 'usage' || key === 'totalUsage' || key === 'finishReason')) {\n      this.#suspendedUsageIsProvisional = false;\n    }\n    if (!(key in this.#delayedPromises)) {\n      throw new MastraError({\n        id: 'MASTRA_MODEL_OUTPUT_INVALID_PROMISE_KEY',\n        domain: ErrorDomain.LLM,\n        category: ErrorCategory.SYSTEM,\n        text: `Attempted to resolve invalid promise key '${key}' with value '${typeof value === 'object' ? JSON.stringify(value, null, 2) : value}'`,\n      });\n    }\n    this.#delayedPromises[key].resolve(value);\n  }\n\n  private resolvePromises(data: Partial<PromiseResults<OUTPUT>>) {\n    for (const keyString in data) {\n      const key = keyString as keyof PromiseResults<OUTPUT>;\n      this.resolvePromise(key, data[key]);\n    }\n  }\n\n  // Same numbers flush would settle when a plain stream ends on suspension. A durable\n  // stream stays open, so callers waiting on usage would otherwise hang until resume.\n  #settleSuspendedUsage() {\n    const usage = this.#getUsageCountWithSuspendedStep();\n    this.#delayedPromises.usage.resolve(usage);\n    this.#delayedPromises.totalUsage.resolve(this.#getTotalUsage(usage));\n    this.#delayedPromises.finishReason.resolve('suspended');\n    this.#suspendedUsageIsProvisional = true;\n  }\n\n  #closeTransportIfNeeded() {\n    const transport = this.#transportRef?.current as StreamTransport | undefined;\n    if (!transport || !transport.closeOnFinish || this.#transportClosed) {\n      return;\n    }\n\n    this.#transportClosed = true;\n    try {\n      transport.close();\n    } catch {\n      // best-effort close\n    }\n  }\n\n  #getDelayedPromise<T>(promise: DelayedPromise<T>): Promise<T> {\n    if (!this.#consumptionStarted) {\n      this.consumeStream().catch(error => {\n        this.logger?.error('Error consuming stream', error);\n      });\n    }\n    return promise.promise;\n  }\n\n  /**\n   * Resolves to the complete text response after streaming completes.\n   */\n  get text() {\n    return this.#getDelayedPromise(this.#delayedPromises.text);\n  }\n\n  /**\n   * Resolves to reasoning parts array for models that support reasoning.\n   */\n  get reasoning() {\n    return this.#getDelayedPromise(this.#delayedPromises.reasoning);\n  }\n\n  /**\n   * Resolves to complete reasoning text for models that support reasoning.\n   */\n  get reasoningText() {\n    return this.#getDelayedPromise(this.#delayedPromises.reasoningText);\n  }\n\n  get sources() {\n    return this.#getDelayedPromise(this.#delayedPromises.sources);\n  }\n\n  get files() {\n    return this.#getDelayedPromise(this.#delayedPromises.files);\n  }\n\n  get steps() {\n    return this.#getDelayedPromise(this.#delayedPromises.steps);\n  }\n\n  get suspendPayload() {\n    return this.#getDelayedPromise(this.#delayedPromises.suspendPayload);\n  }\n\n  get resumeSchema() {\n    return this.#getDelayedPromise(this.#delayedPromises.resumeSchema);\n  }\n\n  /**\n   * Stream of all chunks. Provides complete control over stream processing.\n   */\n  get fullStream() {\n    const stream = this.__getUnfilteredFullStream();\n    const hideSignals = this.#options.hideSignals;\n    if (!hideSignals || (Array.isArray(hideSignals) && hideSignals.length === 0)) return stream;\n    return stream.pipeThrough(\n      new TransformStream<ChunkType<OUTPUT>, ChunkType<OUTPUT>>({\n        transform(chunk, controller) {\n          if (!isSignalChunkExcluded(chunk, hideSignals)) controller.enqueue(chunk);\n        },\n      }),\n    );\n  }\n\n  /** @internal Shared fanout must retain signal chunks, with the existing transforms applied. */\n  __getUnfilteredFullStream() {\n    const configuredTransforms = this.#options.experimentalTransform;\n    if (!configuredTransforms) {\n      return this.#createEventedStream();\n    }\n\n    const transforms = typeof configuredTransforms === 'function' ? [configuredTransforms] : configuredTransforms;\n    let stream = this.#createEventedStream();\n    for (const transform of transforms) {\n      stream = stream.pipeThrough(transform());\n    }\n    return stream;\n  }\n\n  /**\n   * Resolves to the reason generation finished.\n   */\n  get finishReason() {\n    return this.#getDelayedPromise(this.#delayedPromises.finishReason);\n  }\n\n  /**\n   * Resolves to array of all tool calls made during execution.\n   */\n  get toolCalls() {\n    return this.#getDelayedPromise(this.#delayedPromises.toolCalls);\n  }\n\n  /**\n   * Resolves to array of all tool execution results.\n   */\n  get toolResults() {\n    return this.#getDelayedPromise(this.#delayedPromises.toolResults);\n  }\n\n  /**\n   * Resolves to token usage statistics including inputTokens, outputTokens, and totalTokens.\n   */\n  get usage() {\n    return this.#getDelayedPromise(this.#delayedPromises.usage);\n  }\n\n  /**\n   * Resolves to array of all warnings generated during execution.\n   */\n  get warnings() {\n    return this.#getDelayedPromise(this.#delayedPromises.warnings);\n  }\n\n  /**\n   * Resolves to provider metadata generated during execution.\n   */\n  get providerMetadata() {\n    return this.#getDelayedPromise(this.#delayedPromises.providerMetadata);\n  }\n\n  /**\n   * Resolves to the complete response from the model.\n   */\n  get response() {\n    return this.#getDelayedPromise(this.#delayedPromises.response);\n  }\n\n  /**\n   * Resolves to the complete request sent to the model.\n   */\n  get request() {\n    return this.#getDelayedPromise(this.#delayedPromises.request);\n  }\n\n  /**\n   * Transport handle for the current stream (when available).\n   */\n  get transport(): StreamTransport | undefined {\n    return this.#transportRef?.current as StreamTransport | undefined;\n  }\n\n  /**\n   * Resolves to an error if an error occurred during streaming.\n   */\n  get error(): Error | undefined {\n    return this.#error;\n  }\n\n  updateUsageCount(usage: Partial<LanguageModelUsage>) {\n    if (!usage) {\n      return;\n    }\n    accumulateUsage(this.#usageCount, this.#usageCountMissing, usage);\n  }\n\n  populateUsageCount(usage: Partial<LanguageModelUsage>) {\n    if (!usage) {\n      return;\n    }\n\n    // Finish metadata can fill untouched counters, but cannot repair a primary\n    // counter already known to be incomplete from an earlier contributing step.\n    for (const key of primaryUsageCountKeys) {\n      const value = usage[key];\n      if (value !== undefined && this.#usageCount[key] === undefined && !this.#usageCountMissing.has(key)) {\n        this.#usageCount[key] = value;\n      }\n    }\n    for (const key of detailUsageCountKeys) {\n      const value = usage[key];\n      if (value !== undefined && this.#usageCount[key] === undefined) {\n        this.#usageCount[key] = value;\n      }\n    }\n    if (usage.raw !== undefined && this.#usageCount.raw === undefined) {\n      this.#usageCount.raw = usage.raw;\n    }\n  }\n\n  async consumeStream(options?: ConsumeStreamOptions): Promise<void> {\n    // Drain #baseStream exactly once but let every caller await full consumption,\n    // so `await consumeStream()` holds regardless of who started it. Capture any\n    // drain error once (don't bind a caller's onError to the drain), then fire each\n    // caller's own onError after the shared promise settles.\n    if (!this.#consumeStreamPromise) {\n      this.#consumptionStarted = true;\n      this.#consumeStreamPromise = consumeStream({\n        stream: this.#baseStream as globalThis.ReadableStream<any>,\n        onError: error => {\n          const streamError = getErrorFromUnknown(error, { fallbackMessage: 'Unknown error consuming stream' });\n          this.#consumeStreamErrored = true;\n          this.#consumeStreamError = streamError;\n          this.#error = streamError;\n          this.#status = 'failed';\n          this.#streamFinished = true;\n          Object.values(this.#delayedPromises).forEach(promise => {\n            if (promise.status.type === 'pending') {\n              promise.reject(streamError);\n            }\n          });\n          this.#closeTransportIfNeeded();\n          this.#emitter.emit('stream-error', streamError);\n          this.#emitter.emit('settled');\n        },\n        logger: this.logger,\n      });\n    }\n\n    await this.#consumeStreamPromise;\n\n    if (this.#consumeStreamErrored) {\n      options?.onError?.(this.#consumeStreamError);\n    }\n  }\n\n  /**\n   * Returns complete output including text, usage, tool calls, and all metadata.\n   */\n  async getFullOutput(): Promise<FullOutput<OUTPUT>> {\n    await this.consumeStream({\n      onError: (error: unknown) => {\n        this.logger.error('Error consuming stream', error);\n        throw error;\n      },\n    });\n\n    let scoringData:\n      | {\n          input: Omit<ScorerRunInputForAgent, 'runId'>;\n          output: ScorerRunOutputForAgent;\n        }\n      | undefined;\n\n    if (this.#returnScorerData) {\n      try {\n        scoringData = {\n          input: {\n            inputMessages: this.messageList.getPersisted.input.db(),\n            rememberedMessages: this.messageList.getPersisted.remembered.db(),\n            systemMessages: this.messageList.getSystemMessages(),\n            taggedSystemMessages: this.messageList.getPersisted.taggedSystemMessages,\n          },\n          output: await this.messageList.getRunResponseMessages(this.#options.loadStoredMessages),\n        };\n      } catch (error) {\n        this.logger.warn('Failed to load run response messages for scoring data', { error });\n      }\n    }\n\n    const steps = await this.steps;\n\n    // Calculate text from steps, which respects tripwire (rejected steps return empty text)\n    // This ensures rejected responses are excluded from the final text output\n    // A run that suspends mid-step (e.g. awaiting tool approval) has streamed text the step results\n    // don't hold yet. The per-step buffer is reset on every step-finish, so this text is never in `steps`.\n    const textFromSteps =\n      steps.map((step: any) => step.text || '').join('') +\n      (this.#status === 'suspended' ? this.#bufferedByStep.text : '');\n\n    const fullOutput: FullOutput<OUTPUT> = {\n      // After a tripwire, `text` already holds the resolved output (and a processOutputStream\n      // tripwire can end the run before any step completes), so reuse it to stay in sync.\n      text: this.tripwire || steps.length === 0 ? await this.text : this.#resumedPriorText + textFromSteps,\n      usage: await this.usage,\n      steps,\n      finishReason: await this.finishReason,\n      warnings: await this.warnings,\n      providerMetadata: await this.providerMetadata,\n      request: await this.request,\n      reasoning: await this.reasoning,\n      reasoningText: await this.reasoningText,\n      toolCalls: await this.toolCalls,\n      toolResults: await this.toolResults,\n      sources: await this.sources,\n      files: await this.files,\n      response: await this.response,\n      totalUsage: await this.totalUsage,\n      object: await this.object,\n      usedFallbackValue: this.#usedFallbackValue,\n      error: this.error,\n      tripwire: this.#tripwire,\n      ...(scoringData ? { scoringData } : {}),\n      traceId: this.traceId,\n      spanId: this.spanId,\n      runId: this.runId,\n      suspendPayload: await this.suspendPayload,\n      resumeSchema: await this.resumeSchema,\n      // All messages from this execution (input + memory history + response)\n      messages: this.messageList.get.all.db(),\n      // Only messages loaded from memory (conversation history)\n      rememberedMessages: this.messageList.get.remembered.db(),\n    };\n\n    return fullOutput;\n  }\n\n  /**\n   * Tripwire data if the stream was aborted due to an output processor blocking the content.\n   * Returns undefined if no tripwire was triggered.\n   */\n  get tripwire(): StepTripwireData | undefined {\n    return this.#tripwire;\n  }\n\n  /**\n   * The total usage of the stream.\n   */\n  get totalUsage() {\n    return this.#getDelayedPromise(this.#delayedPromises.totalUsage);\n  }\n\n  get content(): Promise<LLMStepResult['content']> {\n    return this.#getDelayedPromise(this.#delayedPromises.content);\n  }\n\n  /**\n   * Stream of valid JSON chunks. The final JSON result is validated against the output schema when the stream ends.\n   *\n   * @example\n   * ```typescript\n   * const stream = await agent.stream(\"Extract data\", {\n   *   structuredOutput: {\n   *     schema: z.object({ name: z.string(), age: z.number() }),\n   *     model: 'gpt-4o-mini' // optional to use a model for structuring json output\n   *   }\n   * });\n   * // partial json chunks\n   * for await (const data of stream.objectStream) {\n   *   console.log(data); // { name: 'John' }, { name: 'John', age: 30 }\n   * }\n   * ```\n   */\n  get objectStream() {\n    return this.#createEventedStream().pipeThrough(\n      new TransformStream<ChunkType<OUTPUT>, Partial<OUTPUT>>({\n        transform(chunk, controller) {\n          if (chunk.type === 'object') {\n            controller.enqueue(chunk.object);\n          }\n        },\n      }),\n    );\n  }\n\n  /**\n   * Stream of individual array elements when output schema is an array type.\n   */\n  get elementStream(): ReadableStream<OUTPUT extends Array<infer T> ? T : never> {\n    let publishedElements = 0;\n    let latestArray: unknown[] = [];\n\n    return this.#createEventedStream().pipeThrough(\n      new TransformStream<ChunkType<OUTPUT>, OUTPUT extends Array<infer T> ? T : never>({\n        transform(chunk, controller) {\n          if (chunk.type === 'object') {\n            if (Array.isArray(chunk.object)) {\n              latestArray = chunk.object;\n              // The trailing element may still be partial (a later chunk can\n              // complete it in place), so only publish elements followed by another.\n              for (; publishedElements < chunk.object.length - 1; publishedElements++) {\n                controller.enqueue(chunk.object[publishedElements]);\n              }\n            }\n          }\n        },\n        flush(controller) {\n          for (; publishedElements < latestArray.length; publishedElements++) {\n            controller.enqueue(latestArray[publishedElements] as OUTPUT extends Array<infer T> ? T : never);\n          }\n        },\n      }),\n    );\n  }\n\n  /**\n   * Stream of only text content, filtering out metadata and other chunk types.\n   */\n  get textStream() {\n    if (this.#structuredOutputMode === 'direct') {\n      const outputSchema = getTransformedSchema(this.#options.structuredOutput?.schema);\n      if (outputSchema?.outputFormat === 'array') {\n        return this.#createEventedStream().pipeThrough(\n          createJsonTextStreamTransformer(this.#options.structuredOutput?.schema),\n        );\n      }\n    }\n\n    return this.#createEventedStream().pipeThrough(\n      new TransformStream<ChunkType<OUTPUT>, string>({\n        transform(chunk, controller) {\n          if (chunk.type === 'text-delta') {\n            controller.enqueue(chunk.payload.text);\n          }\n        },\n      }),\n    );\n  }\n\n  /**\n   * Resolves to the complete object response from the model. Validated against the 'output' schema when the stream ends.\n   *\n   * @example\n   * ```typescript\n   * const stream = await agent.stream(\"Extract data\", {\n   *   structuredOutput: {\n   *     schema: z.object({ name: z.string(), age: z.number() }),\n   *     model: 'gpt-4o-mini' // optionally use a model for structuring json output\n   *   }\n   * });\n   * // final validated json\n   * const data = await stream.object // { name: 'John', age: 30 }\n   * ```\n   */\n  get object() {\n    if (\n      !this.processorRunner &&\n      !this.#options.structuredOutput?.schema &&\n      this.#delayedPromises.object.status.type === 'pending'\n    ) {\n      this.#delayedPromises.object.resolve(undefined as OUTPUT);\n    }\n\n    return this.#getDelayedPromise(this.#delayedPromises.object);\n  }\n\n  // Internal methods for immediate values - used internally by Mastra (llm-execution.ts bailing on errors/abort signals with current state)\n  // These are not part of the public API\n  /** @internal */\n  _getImmediateToolCalls() {\n    return this.#toolCalls;\n  }\n  /** @internal */\n  _getImmediateToolResults() {\n    return this.#toolResults;\n  }\n  /** @internal */\n  _getImmediateText() {\n    return this.#bufferedText.join('');\n  }\n\n  /** @internal */\n  _getImmediateObject() {\n    return this.#bufferedObject;\n  }\n\n  /**\n   * Whether the structured object is the configured `fallbackValue`, substituted because\n   * the model output failed schema validation — or the separate structuring model failed —\n   * under `errorStrategy: 'fallback'`.\n   *\n   * Starts `false` and reflects the most recently processed object. On a live stream, await\n   * `stream.object` or `stream.getFullOutput()` before reading it.\n   */\n  get usedFallbackValue(): boolean {\n    return this.#usedFallbackValue;\n  }\n  /** @internal */\n  _getImmediateUsage() {\n    return this.#usageCount;\n  }\n  /** @internal */\n  _getImmediateWarnings() {\n    return this.#warnings;\n  }\n  /** @internal */\n  _getImmediateFinishReason() {\n    return this.#finishReason;\n  }\n  /** @internal */\n  _getImmediateProviderMetadata() {\n    return this.#stepProviderMetadata;\n  }\n  /** @internal  */\n  _getBaseStream() {\n    // The caller now owns the base stream's reader; delayed-promise getters must\n    // not try to drain it a second time (that would throw \"ReadableStream is locked\").\n    this.#consumptionStarted = true;\n    return this.#baseStream;\n  }\n\n  /** @internal */\n  _waitUntilFinished() {\n    if (this.#streamFinished) {\n      return Promise.resolve();\n    }\n\n    return new Promise<void>(resolve => {\n      const done = () => {\n        this.#emitter.off('finish', done);\n        this.#emitter.off('settled', done);\n        resolve();\n      };\n      // 'finish' fires when the stream flushes cleanly; 'settled' fires when an\n      // error chunk marks the stream finished without closing it (observer\n      // streams must survive an error chunk for fallback recovery, so the\n      // error path cannot emit 'finish').\n      this.#emitter.once('finish', done);\n      this.#emitter.once('settled', done);\n    });\n  }\n\n  #getTotalUsage(usageCount: LLMStepResult<OUTPUT>['usage'] = this.#usageCount): LanguageModelUsage {\n    let total = usageCount.totalTokens;\n\n    if (total === undefined && usageCount.inputTokens !== undefined && usageCount.outputTokens !== undefined) {\n      total = usageCount.inputTokens + usageCount.outputTokens;\n    }\n\n    return {\n      inputTokens: usageCount.inputTokens,\n      outputTokens: usageCount.outputTokens,\n      totalTokens: total,\n      reasoningTokens: usageCount.reasoningTokens,\n      cachedInputTokens: usageCount.cachedInputTokens,\n      cacheCreationInputTokens: usageCount.cacheCreationInputTokens,\n      cacheCreationInputTokens5m: usageCount.cacheCreationInputTokens5m,\n      cacheCreationInputTokens1h: usageCount.cacheCreationInputTokens1h,\n      ...(usageCount.raw !== undefined && { raw: usageCount.raw }),\n    };\n  }\n\n  /** `#usageCount` plus the suspended step's usage, following the same missing-key rules. */\n  #getUsageCountWithSuspendedStep(\n    suspendedStepUsage: LanguageModelUsage | undefined = this.#suspendedStepUsage,\n  ): LLMStepResult<OUTPUT>['usage'] {\n    if (!suspendedStepUsage) return this.#usageCount;\n    const usageCount = { ...this.#usageCount };\n    accumulateUsage(usageCount, new Set(this.#usageCountMissing), suspendedStepUsage);\n    return usageCount;\n  }\n\n  #createAbortedOnFinishPayload(): MastraOnFinishCallbackArgs<OUTPUT> {\n    // Capture only text buffered before the abort event. Providers may continue producing\n    // chunks after cancellation, but those chunks cannot extend this terminal snapshot.\n    const emptyUsage = { inputTokens: undefined, outputTokens: undefined, totalTokens: undefined };\n    // Steps that completed before the abort were already billed by the provider, so keep their usage.\n    return {\n      finishReason: 'aborted',\n      text: this.#bufferedText.join(''),\n      reasoning: [],\n      reasoningText: undefined,\n      sources: [],\n      files: [],\n      toolCalls: [],\n      toolResults: [],\n      staticToolCalls: [],\n      staticToolResults: [],\n      dynamicToolCalls: [],\n      dynamicToolResults: [],\n      content: [],\n      usage: this.#lastStepUsage ?? emptyUsage,\n      warnings: [],\n      providerMetadata: undefined,\n      request: {},\n      response: {},\n      steps: [],\n      totalUsage: this.#lastStepUsage ? this.#getTotalUsage() : emptyUsage,\n      ...(this.#generationReportedUsage && { generationReportedUsage: this.#generationReportedUsage }),\n      object: undefined as OUTPUT,\n    };\n  }\n\n  #createTripwireOnFinishPayload(): MastraOnFinishCallbackArgs<OUTPUT> {\n    return {\n      ...this.#createAbortedOnFinishPayload(),\n      finishReason: 'other',\n      steps: this.#bufferedSteps,\n      tripwire: this.#tripwire,\n    } as MastraOnFinishCallbackArgs<OUTPUT>;\n  }\n\n  #createSuspendedOnFinishPayload(\n    chunk: Extract<ChunkType<OUTPUT>, { type: 'tool-call-approval' | 'tool-call-suspended' }>,\n  ): MastraOnFinishCallbackArgs<OUTPUT> & {\n    suspendReason: 'tool-call-approval' | 'tool-call-suspended';\n    toolName: string;\n    toolCallId: string;\n  } {\n    // Suspend flow invokes options?.onFinish so map-results-step.ts can close the AGENT_RUN span\n    // and the MODEL_GENERATION span (which records the usage below). The remaining\n    // LLMStepResult fields are empty defaults to satisfy the MastraOnFinishCallback shape without\n    // reconstructing partial buffered text/tool/message state from a half-finished stream.\n    const totalUsage = this.#getTotalUsage(this.#getUsageCountWithSuspendedStep());\n    const generationReportedUsage = this.#generationReportedUsage;\n    this.#generationReportedUsage = totalUsage;\n    // A leg that records no token counts leaves them to a later leg. Its provider cost moves\n    // with them.\n    const generationStepProviderMetadata: (ProviderMetadata | undefined)[] = [];\n    if (hasTokenCounts(totalUsage)) {\n      for (const step of this.#bufferedSteps.slice(this.#generationReportedStepCount)) {\n        generationStepProviderMetadata.push(step.providerMetadata);\n      }\n      generationStepProviderMetadata.push(chunk.payload.providerMetadata);\n      this.#generationReportedStepCount = this.#bufferedSteps.length + 1;\n    }\n    return {\n      finishReason: 'suspended',\n      suspendReason: chunk.type,\n      toolName: chunk.payload.toolName,\n      toolCallId: chunk.payload.toolCallId,\n      // Empty defaults for the LLMStepResult/MastraOnFinishCallback shape.\n      text: '',\n      reasoning: [],\n      reasoningText: undefined,\n      sources: [],\n      files: [],\n      toolCalls: [],\n      toolResults: [],\n      staticToolCalls: [],\n      staticToolResults: [],\n      dynamicToolCalls: [],\n      dynamicToolResults: [],\n      content: [],\n      usage: this.#getUsageCountWithSuspendedStep(),\n      warnings: [],\n      providerMetadata: undefined,\n      request: {},\n      response: {},\n      steps: [],\n      totalUsage,\n      ...(generationReportedUsage && { generationReportedUsage }),\n      generationStepProviderMetadata,\n      object: undefined as OUTPUT,\n    };\n  }\n\n  /** Resolves the result promises with what the run produced before it suspended. */\n  #resolveSuspendedPromises() {\n    const reasoningText =\n      this.#bufferedReasoning.length > 0\n        ? this.#bufferedReasoning.map(reasoningPart => reasoningPart.payload.text).join('')\n        : undefined;\n\n    this.resolvePromises({\n      toolResults: this.#toolResults,\n      toolCalls: this.#toolCalls,\n      text: this.#bufferedText.join(''),\n      reasoning: Object.values(this.#bufferedReasoningDetails || {}),\n      reasoningText,\n      sources: this.#bufferedSources,\n      files: this.#bufferedFiles,\n      steps: this.#bufferedSteps,\n      usage: this.#getUsageCountWithSuspendedStep(),\n      totalUsage: this.#getTotalUsage(this.#getUsageCountWithSuspendedStep()),\n      warnings: this.#warnings,\n      finishReason: 'suspended',\n      content: this.messageList.get.response.aiV5.stepContent(),\n      object: undefined,\n      request: this.#request,\n      response: {\n        dbMessages: this.messageList.get.response.db(),\n      },\n      providerMetadata: undefined,\n    });\n  }\n\n  #emitChunk(chunk: ChunkType<OUTPUT>) {\n    if (getChunkProducedAt(chunk) === undefined) stampChunkProducedAt(chunk, Date.now());\n    // Carry the traceId on every chunk Mastra produces so stream consumers can link chunks to their\n    // trace. Custom data-* chunks are left as written: their shape belongs to the user, and AI SDK\n    // UI streams forward them as-is.\n    if (this.traceId && !isDataChunk(chunk) && !chunk.traceId) {\n      chunk.traceId = this.traceId;\n    }\n    this.#bufferedChunks.push(chunk); // add to bufferedChunks for replay in new streams\n    this.#emitter.emit('chunk', chunk); // emit chunk for existing listener streams\n  }\n\n  /**\n   * Text produced by the run: the last step's text for tool-driven multi-step runs (excluding\n   * pre-tool narration), otherwise the aggregate stream text. Suspended/resumed runs keep the\n   * aggregate because pre-approval text is part of the resumed run.\n   */\n  #producedText(): string {\n    const lastStep = this.#bufferedSteps[this.#bufferedSteps.length - 1];\n    const hasToolStep = this.#bufferedSteps.some(step => step.toolCalls.length > 0 || step.toolResults.length > 0);\n    // Durable reads its final text from the steps, where a retried attempt's text is empty,\n    // plus the text of a step that never finished (an aborted run).\n    if (!hasToolStep && !this.#wasSuspended && this.#options.resolveFinalPromises) {\n      return this.#bufferedSteps.map(step => step.text).join('') + this.#bufferedByStep.text;\n    }\n    return hasToolStep && !this.#wasSuspended && lastStep ? lastStep.text : this.#bufferedText.join('');\n  }\n\n  /**\n   * Drops all run-lifetime accumulators. Called at goal-evaluation boundaries,\n   * where every completed step has already been persisted to the MessageList.\n   * After truncation, run-end results (`text`, `steps`, `toolCalls`, …,\n   * `getFullOutput()`) cover only the segment after the last evaluation —\n   * for goal runs that segment is the completion answer. Token usage\n   * (`#usageCount`), in-flight per-step state (`#bufferedByStep`), structured\n   * output, and the MessageList are intentionally untouched.\n   */\n  #truncateRunBuffers() {\n    this.#bufferedChunks.length = 0;\n    this.#bufferedSteps.length = 0;\n    this.#generationReportedStepCount = 0;\n    this.#bufferedText.length = 0;\n    this.#resumedPriorText = '';\n    this.#bufferedTextAtStepStart = 0;\n    this.#bufferedTextChunks = {};\n    this.#bufferedSources.length = 0;\n    this.#bufferedReasoning.length = 0;\n    this.#bufferedReasoningDetails = {};\n    this.#reasoningAtStepStart = undefined;\n    this.#runOutputAtStepStart = undefined;\n    this.#bufferedFiles.length = 0;\n    this.#toolCalls.length = 0;\n    this.#toolResults.length = 0;\n    this.#toolCallArgsDeltas = Object.create(null);\n    this.#toolCallDeltaIdNameMap = Object.create(null);\n    this.#toolCallStreamingMeta = Object.create(null);\n    this.#pendingToolCalls = Object.create(null);\n    this.#replaceableToolCallIds.clear();\n    this.#attemptToolCallIds.clear();\n  }\n\n  #createEventedStream() {\n    const self = this;\n    // Holds this subscriber's own detach function once start() registers its\n    // listeners. cancel() must only remove this subscriber's handlers — the\n    // emitter is shared across every concurrent consumer of this output, so\n    // removeAllListeners() here would silently kill every other subscriber\n    // (see #19743).\n    let detach: (() => void) | undefined;\n    // Erroring a ReadableStream discards the chunks still queued for its reader, so a failure that\n    // arrives while this subscriber is behind waits in `pendingError` until `pull` sees the queue empty.\n    let pendingError: { error: unknown } | undefined;\n    const fail = (controller: ReadableStreamDefaultController<ChunkType<OUTPUT>>, error: unknown) => {\n      if ((controller.desiredSize ?? 0) > 0) {\n        controller.error(error);\n      } else {\n        pendingError = { error };\n      }\n    };\n\n    return new ReadableStream<ChunkType<OUTPUT>>({\n      start(controller) {\n        // Replay existing buffered chunks\n        self.#bufferedChunks.forEach(chunk => {\n          controller.enqueue(chunk);\n        });\n\n        // If stream already finished, close immediately\n        if (self.#streamFinished) {\n          if (self.#consumeStreamErrored) {\n            fail(controller, self.#consumeStreamError);\n          } else {\n            controller.close();\n          }\n          return;\n        }\n\n        // Listen for new chunks and stream finish\n        const chunkHandler = (chunk: ChunkType<OUTPUT>) => {\n          safeEnqueue(controller, chunk);\n        };\n\n        const detachListeners = () => {\n          self.#emitter.off('chunk', chunkHandler);\n          self.#emitter.off('finish', finishHandler);\n          self.#emitter.off('stream-error', errorHandler);\n        };\n        const finishHandler = () => {\n          detachListeners();\n          safeClose(controller);\n        };\n        const errorHandler = (error: unknown) => {\n          detachListeners();\n          fail(controller, error);\n        };\n\n        self.#emitter.on('chunk', chunkHandler);\n        self.#emitter.on('finish', finishHandler);\n        self.#emitter.on('stream-error', errorHandler);\n\n        detach = detachListeners;\n      },\n\n      pull(controller) {\n        if (pendingError) {\n          controller.error(pendingError.error);\n          return;\n        }\n        // Only start consumption when someone is actively reading the stream\n        if (!self.#consumptionStarted) {\n          self.consumeStream().catch(error => {\n            self.logger?.error('Error consuming stream', error);\n          });\n        }\n      },\n\n      cancel() {\n        // Only detach this subscriber's own listeners — never the whole emitter.\n        detach?.();\n      },\n    });\n  }\n\n  get status() {\n    return this.#status;\n  }\n\n  /**\n   * @param pendingSuspension A suspension chunk the step has emitted but this output may not have\n   * processed yet. Tool suspension snapshots the stream state right after emitting the chunk, so\n   * the state is serialized as if the chunk was processed; otherwise a resumed run would not know\n   * which usage its suspended leg already reported.\n   */\n  serializeState(pendingSuspension?: { usage?: LanguageModelUsage }) {\n    const { steps, requests } = dedupeStepRequests(packStepMessageMirrors(this.#bufferedSteps));\n    // A restored run keeps status 'suspended' until it finishes, and its resumed step-finish clears\n    // the suspended step usage, so either one missing means the pending suspension is new.\n    const recordSuspension =\n      pendingSuspension !== undefined && (this.#status !== 'suspended' || this.#suspendedStepUsage === undefined);\n    const suspendedStepUsage = recordSuspension\n      ? (this.#suspendedStepUsage ?? pendingSuspension.usage)\n      : this.#suspendedStepUsage;\n    const generationReportedUsage = recordSuspension\n      ? this.#getTotalUsage(this.#getUsageCountWithSuspendedStep(suspendedStepUsage))\n      : this.#generationReportedUsage;\n    const generationReportedStepCount =\n      recordSuspension && hasTokenCounts(generationReportedUsage)\n        ? this.#bufferedSteps.length + 1\n        : this.#generationReportedStepCount;\n    return {\n      status: recordSuspension ? 'suspended' : this.#status,\n      bufferedSteps: steps,\n      bufferedStepRequests: requests,\n      bufferedReasoningDetails: this.#bufferedReasoningDetails,\n      bufferedByStepReasoningDetails: this.#bufferedByStepReasoningDetails,\n      bufferedByStep: this.#bufferedByStep,\n      bufferedText: this.#bufferedText,\n      bufferedTextAtStepStart: this.#bufferedTextAtStepStart,\n      bufferedTextChunks: this.#bufferedTextChunks,\n      bufferedSources: this.#bufferedSources,\n      bufferedReasoning: this.#bufferedReasoning,\n      bufferedFiles: this.#bufferedFiles,\n      toolCallArgsDeltas: this.#toolCallArgsDeltas,\n      toolCallDeltaIdNameMap: this.#toolCallDeltaIdNameMap,\n      toolCallStreamingMeta: this.#toolCallStreamingMeta,\n      pendingToolCalls: this.#pendingToolCalls,\n      replaceableToolCallIds: [...this.#replaceableToolCallIds],\n      attemptToolCallIds: [...this.#attemptToolCallIds],\n      toolCalls: this.#toolCalls,\n      toolResults: this.#toolResults,\n      warnings: this.#warnings,\n      finishReason: this.#finishReason,\n      request: this.#request,\n      usageCount: this.#usageCount,\n      usageCountMissing: [...this.#usageCountMissing],\n      lastStepUsage: this.#lastStepUsage,\n      suspendedStepUsage,\n      generationReportedUsage,\n      generationReportedStepCount,\n      tripwire: this.#tripwire,\n      wasSuspended: this.#wasSuspended || recordSuspension,\n      messageList: this.messageList.serialize(),\n    };\n  }\n\n  deserializeState(state: any) {\n    this.#status = state.status;\n    this.#bufferedReasoningDetails = state.bufferedReasoningDetails;\n    this.#bufferedByStepReasoningDetails = state.bufferedByStepReasoningDetails ?? {};\n    this.#bufferedByStep = state.bufferedByStep;\n    this.#bufferedText = state.bufferedText;\n    this.#bufferedTextAtStepStart = state.bufferedTextAtStepStart ?? state.bufferedText.length;\n    this.#bufferedTextChunks = state.bufferedTextChunks;\n    this.#bufferedSources = state.bufferedSources;\n    this.#bufferedReasoning = state.bufferedReasoning;\n    this.#bufferedFiles = state.bufferedFiles;\n    this.#toolCallArgsDeltas = Object.assign(Object.create(null), state.toolCallArgsDeltas);\n    this.#toolCallDeltaIdNameMap = Object.assign(Object.create(null), state.toolCallDeltaIdNameMap);\n    this.#toolCallStreamingMeta = Object.assign(Object.create(null), state.toolCallStreamingMeta);\n    this.#pendingToolCalls = Object.assign(Object.create(null), state.pendingToolCalls);\n    this.#replaceableToolCallIds = new Set(state.replaceableToolCallIds ?? []);\n    this.#attemptToolCallIds = new Set(state.attemptToolCallIds ?? []);\n    this.#toolCalls = state.toolCalls;\n    this.#toolResults = state.toolResults;\n    this.#warnings = state.warnings;\n    this.#finishReason = state.finishReason;\n    this.#request = state.request;\n    this.#usageCount = state.usageCount;\n\n    if (state.usageCountMissing === undefined) {\n      const hasPriorUsage =\n        (Array.isArray(state.bufferedSteps) && state.bufferedSteps.length > 0) ||\n        primaryUsageCountKeys.some(key => state.usageCount?.[key] !== undefined);\n\n      // Legacy snapshots do not record which completed steps omitted primary\n      // usage counters, so existing primary aggregates must fail closed. An\n      // empty snapshot taken before the first step can still accumulate them.\n      this.#usageCountMissing = hasPriorUsage ? new Set(primaryUsageCountKeys) : new Set();\n      if (hasPriorUsage) {\n        for (const key of primaryUsageCountKeys) {\n          this.#usageCount[key] = undefined;\n        }\n      }\n    } else {\n      this.#usageCountMissing = new Set(state.usageCountMissing);\n    }\n\n    this.#tripwire = state.tripwire;\n    this.#lastStepUsage = state.lastStepUsage ?? state.bufferedSteps?.at(-1)?.usage;\n    this.#suspendedStepUsage = state.suspendedStepUsage;\n    this.#generationReportedUsage = state.generationReportedUsage;\n    this.#generationReportedStepCount = state.generationReportedStepCount ?? 0;\n    this.#wasSuspended = state.wasSuspended ?? state.status === 'suspended';\n    this.messageList = this.messageList.deserialize(state.messageList);\n    // Buffered steps hold only the IDs of the response messages they had seen;\n    // rebuilding their lazy mirrors needs the restored message list, so this has\n    // to come last.\n    this.#bufferedSteps = unpackStepMessageMirrors(\n      rehydrateStepRequests(state.bufferedSteps, state.bufferedStepRequests),\n      this.messageList,\n    );\n  }\n}\n","import { ReadableStream } from 'node:stream/web';\nimport type { MastraLanguageModel } from '../llm/model/shared.types';\nimport type { ObservabilityContext } from '../observability';\nimport { resolveObservabilityContext } from '../observability';\nimport { MastraModelOutput } from '../stream/base/output';\nimport { ChunkFrom } from '../stream/types';\nimport type { ChunkType } from '../stream/types';\nimport type { InnerAgentExecutionOptions } from './agent.types';\nimport type { MessageList } from './message-list';\n\n/**\n * Options for TripWire that control how the tripwire should be handled\n */\nexport interface TripWireOptions<TMetadata = unknown> {\n  /**\n   * If true, the agent should retry with the tripwire reason as feedback.\n   * The failed response will be added to message history along with the reason.\n   */\n  retry?: boolean;\n  /**\n   * Strongly typed metadata from the processor.\n   * This allows processors to pass structured information about what triggered the tripwire.\n   */\n  metadata?: TMetadata;\n}\n\n/**\n * TripWire is a custom Error class for aborting processing with optional retry and metadata.\n *\n * When thrown from a processor, it signals that processing should stop.\n * The `options` field controls how the tripwire should be handled:\n * - `retry: true` - The agent will retry with the reason as feedback\n * - `metadata` - Strongly typed data about what triggered the tripwire\n */\nexport class TripWire<TMetadata = unknown> extends Error {\n  public readonly options: TripWireOptions<TMetadata>;\n  public readonly processorId?: string;\n\n  constructor(reason: string, options: TripWireOptions<TMetadata> = {}, processorId?: string) {\n    super(reason);\n    this.name = 'TripWire';\n    this.options = options;\n    this.processorId = processorId;\n    Object.setPrototypeOf(this, new.target.prototype);\n  }\n}\n\n/**\n * Tripwire data passed to getModelOutputForTripwire\n */\nexport interface TripwireData<TMetadata = unknown> {\n  reason: string;\n  retry?: boolean;\n  metadata?: TMetadata;\n  processorId?: string;\n}\n\nexport const getModelOutputForTripwire = async <OUTPUT = undefined, TMetadata = unknown>({\n  tripwire,\n  runId,\n  options,\n  model,\n  messageList,\n  ...rest\n}: {\n  tripwire: TripwireData<TMetadata>;\n  runId: string;\n  options: InnerAgentExecutionOptions<OUTPUT>;\n  model: MastraLanguageModel;\n  messageList: MessageList;\n} & ObservabilityContext) => {\n  const observabilityContext = resolveObservabilityContext(rest);\n  const tripwireStream = new ReadableStream<ChunkType<OUTPUT>>({\n    start(controller) {\n      controller.enqueue({\n        type: 'tripwire',\n        runId,\n        from: ChunkFrom.AGENT,\n        payload: {\n          reason: tripwire.reason || '',\n          retry: tripwire.retry,\n          metadata: tripwire.metadata,\n          processorId: tripwire.processorId,\n        },\n      });\n      controller.close();\n    },\n  });\n\n  const modelOutput = new MastraModelOutput<OUTPUT>({\n    model: {\n      modelId: model.modelId,\n      provider: model.provider,\n      version: model.specificationVersion,\n    },\n    stream: tripwireStream,\n    messageList,\n    options: {\n      runId,\n      structuredOutput: options.structuredOutput,\n      ...observabilityContext,\n      onFinish: options.onFinish as any, // Fix these types after the types PR is merged\n      onStepFinish: options.onStepFinish as any,\n      returnScorerData: options.returnScorerData,\n      requestContext: options.requestContext,\n    },\n    messageId: globalThis.crypto.randomUUID(),\n  });\n\n  return modelOutput;\n};\n","export async function consumeStream({\n  stream,\n  onError,\n}: {\n  stream: ReadableStream;\n  onError?: (error: unknown) => void;\n}) {\n  let reader: ReadableStreamDefaultReader | undefined;\n  try {\n    reader = stream.getReader();\n    while (true) {\n      const { done } = await reader.read();\n      if (done) break;\n    }\n  } catch (error) {\n    onError?.(error);\n  } finally {\n    reader?.releaseLock();\n  }\n}\n","import EventEmitter from 'node:events';\nimport { ReadableStream, WritableStream } from 'node:stream/web';\nimport type { ReadableStreamGetReaderOptions, ReadableWritablePair, StreamPipeOptions } from 'node:stream/web';\nimport type { LanguageModelUsage } from '@internal/ai-sdk-v5';\nimport type { WorkflowResult, WorkflowRunStatus } from '../workflows';\nimport { DelayedPromise } from './aisdk/v5/compat';\nimport type { MastraBaseStream } from './base/base';\nimport { consumeStream } from './base/consume-stream';\nimport { ChunkFrom } from './types';\nimport type { StepTripwireData, WorkflowStreamEvent } from './types';\n\ntype AggregatedLanguageModelUsage = Omit<LanguageModelUsage, 'inputTokens' | 'outputTokens' | 'totalTokens'> & {\n  inputTokens: number | undefined;\n  outputTokens: number | undefined;\n  totalTokens: number | undefined;\n  reasoningTokens?: number;\n  cachedInputTokens?: number;\n  cacheCreationInputTokens?: number;\n};\n\nconst primaryUsageKeys = ['inputTokens', 'outputTokens', 'totalTokens'] as const;\n\nexport class WorkflowRunOutput<\n  TResult extends WorkflowResult<any, any, any, any, 1 | 2> = WorkflowResult<any, any, any, any>,\n> implements MastraBaseStream<WorkflowStreamEvent> {\n  #status: WorkflowRunStatus = 'running';\n  #tripwireData: StepTripwireData | undefined;\n  #usageCount: AggregatedLanguageModelUsage = {\n    inputTokens: undefined,\n    outputTokens: undefined,\n    totalTokens: undefined,\n  };\n  #usageCountMissing = new Set<(typeof primaryUsageKeys)[number]>();\n  #consumptionStarted = false;\n  #baseStream: ReadableStream<WorkflowStreamEvent>;\n  #emitter = new EventEmitter();\n  #bufferedChunks: WorkflowStreamEvent[] = [];\n\n  #streamFinished = false;\n\n  #streamError: Error | undefined;\n\n  #finalWorkflowResult: unknown;\n\n  #delayedPromises = {\n    usage: new DelayedPromise<LanguageModelUsage>(),\n    result: new DelayedPromise<TResult>(),\n  };\n\n  /**\n   * Unique identifier for this workflow run\n   */\n  public runId: string;\n  /**\n   * Unique identifier for this workflow\n   */\n  public workflowId: string;\n\n  constructor({\n    runId,\n    workflowId,\n    stream,\n  }: {\n    runId: string;\n    workflowId: string;\n    stream: ReadableStream<WorkflowStreamEvent>;\n  }) {\n    const self = this;\n    this.runId = runId;\n    this.workflowId = workflowId;\n\n    this.#baseStream = stream;\n    stream\n      .pipeTo(\n        new WritableStream({\n          start() {\n            const chunk: WorkflowStreamEvent = {\n              type: 'workflow-start',\n              runId: self.runId,\n              from: ChunkFrom.WORKFLOW,\n              payload: {\n                workflowId: self.workflowId,\n              },\n            } as WorkflowStreamEvent;\n\n            self.#bufferedChunks.push(chunk);\n            self.#emitter.emit('chunk', chunk);\n          },\n          write(chunk) {\n            if (chunk.type !== 'workflow-step-finish') {\n              self.#bufferedChunks.push(chunk);\n              self.#emitter.emit('chunk', chunk);\n            }\n\n            if (chunk.type === 'workflow-step-output') {\n              if ('output' in chunk.payload && chunk.payload.output) {\n                const output = chunk.payload.output;\n                if (output.type === 'finish') {\n                  if (output.payload && 'usage' in output.payload && output.payload.usage) {\n                    self.#updateUsageCount(output.payload.usage);\n                  } else if (output.payload && 'output' in output.payload && output.payload.output) {\n                    const outputPayload = output.payload.output;\n                    if ('usage' in outputPayload && outputPayload.usage) {\n                      self.#updateUsageCount(outputPayload.usage);\n                    }\n                  }\n                }\n              }\n            } else if (chunk.type === 'workflow-canceled') {\n              self.#status = 'canceled';\n            } else if (chunk.type === 'workflow-step-suspended') {\n              self.#status = 'suspended';\n            } else if (chunk.type === 'workflow-step-result' && chunk.payload.status === 'failed') {\n              // Check if the failure was due to a tripwire\n              if (chunk.payload.tripwire) {\n                self.#status = 'tripwire';\n                self.#tripwireData = chunk.payload.tripwire;\n              } else {\n                self.#status = 'failed';\n              }\n            } else if (chunk.type === 'workflow-paused') {\n              self.#status = 'paused';\n            }\n          },\n          close() {\n            if (self.#status === 'running') {\n              self.#status = 'success';\n            }\n\n            self.#emitter.emit('chunk', {\n              type: 'workflow-finish',\n              runId: self.runId,\n              from: ChunkFrom.WORKFLOW,\n              payload: {\n                workflowStatus: self.#status,\n                metadata: self.#streamError\n                  ? {\n                      error: self.#streamError,\n                      errorMessage: self.#streamError?.message,\n                    }\n                  : {},\n                output: {\n                  usage: self.#usageCount,\n                },\n                ...(self.#status === 'success' && self.#finalWorkflowResult !== undefined\n                  ? { finalWorkflowResult: self.#finalWorkflowResult }\n                  : {}),\n                // Include tripwire data when status is 'tripwire'\n                ...(self.#status === 'tripwire' && self.#tripwireData ? { tripwire: self.#tripwireData } : {}),\n              },\n            });\n\n            self.#delayedPromises.usage.resolve(self.#usageCount);\n\n            Object.entries(self.#delayedPromises).forEach(([key, promise]) => {\n              if (promise.status.type === 'pending') {\n                promise.reject(new Error(`promise '${key}' was not resolved or rejected when stream finished`));\n              }\n            });\n\n            self.#streamFinished = true;\n            self.#emitter.emit('finish');\n          },\n        }),\n      )\n      .catch(reason => {\n        self.#finalizeWithError(reason);\n      });\n  }\n\n  #getDelayedPromise<T>(promise: DelayedPromise<T>): Promise<T> {\n    if (!this.#consumptionStarted) {\n      void this.consumeStream();\n    }\n    return promise.promise;\n  }\n\n  #updateUsageCount(\n    usage:\n      | {\n          inputTokens?: `${number}` | number;\n          outputTokens?: `${number}` | number;\n          totalTokens?: `${number}` | number;\n          reasoningTokens?: `${number}` | number;\n          cachedInputTokens?: `${number}` | number;\n          cacheCreationInputTokens?: `${number}` | number;\n        }\n      | {\n          promptTokens?: `${number}` | number;\n          completionTokens?: `${number}` | number;\n          totalTokens?: `${number}` | number;\n          reasoningTokens?: `${number}` | number;\n          cachedInputTokens?: `${number}` | number;\n          cacheCreationInputTokens?: `${number}` | number;\n        },\n  ) {\n    const primaryUsage = {\n      inputTokens:\n        'inputTokens' in usage ? usage.inputTokens : 'promptTokens' in usage ? usage.promptTokens : undefined,\n      outputTokens:\n        'outputTokens' in usage ? usage.outputTokens : 'completionTokens' in usage ? usage.completionTokens : undefined,\n      totalTokens: usage.totalTokens,\n    };\n\n    for (const key of primaryUsageKeys) {\n      const value = primaryUsage[key] === undefined ? undefined : Number(primaryUsage[key]);\n      if (value === undefined) {\n        this.#usageCountMissing.add(key);\n        this.#usageCount[key] = undefined;\n      } else if (!this.#usageCountMissing.has(key)) {\n        this.#usageCount[key] = (this.#usageCount[key] ?? 0) + value;\n      }\n    }\n\n    for (const key of ['reasoningTokens', 'cachedInputTokens', 'cacheCreationInputTokens'] as const) {\n      const value = usage[key] === undefined ? undefined : Number(usage[key]);\n      if (value !== undefined) {\n        this.#usageCount[key] = (this.#usageCount[key] ?? 0) + value;\n      }\n    }\n  }\n\n  /**\n   * Finalize the run when the underlying stream pipeline rejects.\n   *\n   * When `pipeTo` rejects, the WritableStream's `close()` never runs, so without\n   * this the terminal `workflow-finish` event would never fire, the delayed\n   * `result`/`usage` promises would never settle, and every `fullStream` consumer\n   * would hang forever. Mirror the `close()` path but mark the run as failed.\n   */\n  #finalizeWithError(reason: unknown) {\n    // A clean close already finalized the run; nothing to do.\n    if (this.#streamFinished) {\n      return;\n    }\n\n    const error = reason instanceof Error ? reason : new Error(String(reason));\n    this.#streamError = error;\n    // The run terminated because the stream pipeline rejected, so it failed —\n    // overwrite any earlier non-terminal status (paused/suspended/canceled/tripwire)\n    // so downstream consumers always see a failed terminal status.\n    this.#status = 'failed';\n\n    // Emit a terminal finish so fullStream consumers stop waiting and close.\n    this.#emitter.emit('chunk', {\n      type: 'workflow-finish',\n      runId: this.runId,\n      from: ChunkFrom.WORKFLOW,\n      payload: {\n        workflowStatus: this.#status,\n        metadata: {\n          error: this.#streamError,\n          errorMessage: this.#streamError.message,\n        },\n        output: {\n          usage: this.#usageCount,\n        },\n      },\n    });\n\n    // Reject any still-pending delayed promises so result/usage callers see the\n    // error instead of awaiting forever.\n    Object.entries(this.#delayedPromises).forEach(([_key, promise]) => {\n      if (promise.status.type === 'pending') {\n        promise.reject(error);\n      }\n    });\n\n    this.#streamFinished = true;\n    this.#emitter.emit('finish');\n\n    console.error('[WorkflowRunOutput] workflow stream pipeline error', error);\n  }\n\n  /**\n   * @internal\n   */\n  updateResults(results: TResult) {\n    if (results.status === 'success') {\n      this.#finalWorkflowResult = results.result;\n    }\n    this.#delayedPromises.result.resolve(results);\n  }\n\n  /**\n   * @internal\n   */\n  rejectResults(error: Error) {\n    this.#delayedPromises.result.reject(error);\n    this.#status = 'failed';\n    this.#streamError = error;\n  }\n\n  /**\n   * @internal\n   */\n  resume(stream: ReadableStream<WorkflowStreamEvent>) {\n    this.#baseStream = stream;\n    this.#streamFinished = false;\n    this.#consumptionStarted = false;\n    this.#status = 'running';\n    this.#delayedPromises = {\n      usage: new DelayedPromise<LanguageModelUsage>(),\n      result: new DelayedPromise<TResult>(),\n    };\n\n    const self = this;\n    stream\n      .pipeTo(\n        new WritableStream({\n          start() {\n            const chunk: WorkflowStreamEvent = {\n              type: 'workflow-start',\n              runId: self.runId,\n              from: ChunkFrom.WORKFLOW,\n              payload: {\n                workflowId: self.workflowId,\n              },\n            } as WorkflowStreamEvent;\n\n            self.#bufferedChunks.push(chunk);\n            self.#emitter.emit('chunk', chunk);\n          },\n          write(chunk) {\n            if (chunk.type !== 'workflow-step-finish') {\n              self.#bufferedChunks.push(chunk);\n              self.#emitter.emit('chunk', chunk);\n            }\n\n            if (chunk.type === 'workflow-step-output') {\n              if ('output' in chunk.payload && chunk.payload.output) {\n                const output = chunk.payload.output;\n                if (output.type === 'finish') {\n                  if (output.payload && 'usage' in output.payload && output.payload.usage) {\n                    self.#updateUsageCount(output.payload.usage);\n                  } else if (output.payload && 'output' in output.payload && output.payload.output) {\n                    const outputPayload = output.payload.output;\n                    if ('usage' in outputPayload && outputPayload.usage) {\n                      self.#updateUsageCount(outputPayload.usage);\n                    }\n                  }\n                }\n              }\n            } else if (chunk.type === 'workflow-canceled') {\n              self.#status = 'canceled';\n            } else if (chunk.type === 'workflow-step-suspended') {\n              self.#status = 'suspended';\n            } else if (chunk.type === 'workflow-step-result' && chunk.payload.status === 'failed') {\n              // Check if the failure was due to a tripwire\n              if (chunk.payload.tripwire) {\n                self.#status = 'tripwire';\n                self.#tripwireData = chunk.payload.tripwire;\n              } else {\n                self.#status = 'failed';\n              }\n            } else if (chunk.type === 'workflow-paused') {\n              self.#status = 'paused';\n            }\n          },\n          close() {\n            if (self.#status === 'running') {\n              self.#status = 'success';\n            }\n\n            self.#emitter.emit('chunk', {\n              type: 'workflow-finish',\n              runId: self.runId,\n              from: ChunkFrom.WORKFLOW,\n              payload: {\n                workflowStatus: self.#status,\n                metadata: self.#streamError\n                  ? {\n                      error: self.#streamError,\n                      errorMessage: self.#streamError?.message,\n                    }\n                  : {},\n                output: {\n                  usage: self.#usageCount,\n                },\n                ...(self.#status === 'success' && self.#finalWorkflowResult !== undefined\n                  ? { finalWorkflowResult: self.#finalWorkflowResult }\n                  : {}),\n                // Include tripwire data when status is 'tripwire'\n                ...(self.#status === 'tripwire' && self.#tripwireData ? { tripwire: self.#tripwireData } : {}),\n              },\n            });\n\n            self.#streamFinished = true;\n            self.#emitter.emit('finish');\n          },\n        }),\n      )\n      .catch(reason => {\n        self.#finalizeWithError(reason);\n      });\n  }\n\n  async consumeStream(options?: Parameters<typeof consumeStream>[0]): Promise<void> {\n    if (this.#consumptionStarted) {\n      return;\n    }\n\n    this.#consumptionStarted = true;\n\n    try {\n      await consumeStream({\n        stream: this.#baseStream as globalThis.ReadableStream,\n        onError: options?.onError,\n      });\n    } catch (error) {\n      options?.onError?.(error);\n    }\n  }\n\n  get fullStream(): ReadableStream<WorkflowStreamEvent> {\n    const self = this;\n    // Holds this subscriber's own detach function once start() registers its\n    // listeners. cancel() must only remove this subscriber's handlers — the\n    // emitter is shared across every concurrent fullStream/observe consumer of\n    // the same run, so removeAllListeners() here would silently kill every\n    // other subscriber (see #19743).\n    let detach: (() => void) | undefined;\n    return new ReadableStream<WorkflowStreamEvent>({\n      start(controller) {\n        // Replay existing buffered chunks\n        self.#bufferedChunks.forEach(chunk => {\n          controller.enqueue(chunk);\n        });\n\n        // If stream already finished, close immediately\n        if (self.#streamFinished) {\n          controller.close();\n          return;\n        }\n\n        // Listen for new chunks and stream finish\n        const chunkHandler = (chunk: WorkflowStreamEvent) => {\n          controller.enqueue(chunk);\n        };\n\n        const finishHandler = () => {\n          self.#emitter.off('chunk', chunkHandler);\n          self.#emitter.off('finish', finishHandler);\n          controller.close();\n        };\n\n        self.#emitter.on('chunk', chunkHandler);\n        self.#emitter.on('finish', finishHandler);\n\n        detach = () => {\n          self.#emitter.off('chunk', chunkHandler);\n          self.#emitter.off('finish', finishHandler);\n        };\n      },\n\n      pull(_controller) {\n        // Only start consumption when someone is actively reading the stream\n        if (!self.#consumptionStarted) {\n          void self.consumeStream();\n        }\n      },\n\n      cancel() {\n        // Only detach this subscriber's own listeners — never the whole emitter.\n        detach?.();\n      },\n    });\n  }\n\n  get status() {\n    return this.#status;\n  }\n\n  get result() {\n    return this.#getDelayedPromise(this.#delayedPromises.result);\n  }\n\n  get usage() {\n    return this.#getDelayedPromise(this.#delayedPromises.usage);\n  }\n\n  /**\n   * @deprecated Use `fullStream.locked` instead\n   */\n  get locked(): boolean {\n    console.warn('WorkflowRunOutput.locked is deprecated. Use fullStream.locked instead.');\n    return this.fullStream.locked;\n  }\n\n  /**\n   * @deprecated Use `fullStream.cancel()` instead\n   */\n  cancel(reason?: any): Promise<void> {\n    console.warn('WorkflowRunOutput.cancel() is deprecated. Use fullStream.cancel() instead.');\n    return this.fullStream.cancel(reason);\n  }\n\n  /**\n   * @deprecated Use `fullStream.getReader()` instead\n   */\n  getReader(\n    options?: ReadableStreamGetReaderOptions,\n  ): ReadableStreamDefaultReader<WorkflowStreamEvent> | ReadableStreamBYOBReader {\n    console.warn('WorkflowRunOutput.getReader() is deprecated. Use fullStream.getReader() instead.');\n    return this.fullStream.getReader(options as any) as any;\n  }\n\n  /**\n   * @deprecated Use `fullStream.pipeThrough()` instead\n   */\n  pipeThrough<T>(\n    transform: ReadableWritablePair<T, WorkflowStreamEvent>,\n    options?: StreamPipeOptions,\n  ): ReadableStream<T> {\n    console.warn('WorkflowRunOutput.pipeThrough() is deprecated. Use fullStream.pipeThrough() instead.');\n    return this.fullStream.pipeThrough(transform as any, options) as ReadableStream<T>;\n  }\n\n  /**\n   * @deprecated Use `fullStream.pipeTo()` instead\n   */\n  pipeTo(destination: WritableStream<WorkflowStreamEvent>, options?: StreamPipeOptions): Promise<void> {\n    console.warn('WorkflowRunOutput.pipeTo() is deprecated. Use fullStream.pipeTo() instead.');\n    return this.fullStream.pipeTo(destination, options);\n  }\n\n  /**\n   * @deprecated Use `fullStream.tee()` instead\n   */\n  tee(): [ReadableStream<WorkflowStreamEvent>, ReadableStream<WorkflowStreamEvent>] {\n    console.warn('WorkflowRunOutput.tee() is deprecated. Use fullStream.tee() instead.');\n    return this.fullStream.tee();\n  }\n\n  /**\n   * @deprecated Use `fullStream[Symbol.asyncIterator]()` instead\n   */\n  [Symbol.asyncIterator](): AsyncIterableIterator<WorkflowStreamEvent> {\n    console.warn(\n      'WorkflowRunOutput[Symbol.asyncIterator]() is deprecated. Use fullStream[Symbol.asyncIterator]() instead.',\n    );\n    return this.fullStream[Symbol.asyncIterator]();\n  }\n\n  /**\n   * Helper method to treat this object as a ReadableStream\n   * @deprecated Use `fullStream` directly instead\n   */\n  toReadableStream(): ReadableStream<WorkflowStreamEvent> {\n    console.warn('WorkflowRunOutput.toReadableStream() is deprecated. Use fullStream directly instead.');\n    return this.fullStream;\n  }\n}\n","import { ReadableStream } from 'node:stream/web';\nimport type { DefaultEngineType, Run, Step } from '../workflows';\nimport type { ChunkType } from './types';\n\nconst primaryUsageKeys = ['inputTokens', 'outputTokens', 'totalTokens'] as const;\n\nexport class MastraAgentNetworkStream<OUTPUT = undefined> extends ReadableStream<ChunkType<OUTPUT>> {\n  #usageCount: {\n    inputTokens: number | undefined;\n    outputTokens: number | undefined;\n    totalTokens: number | undefined;\n    cachedInputTokens?: number;\n    cacheCreationInputTokens?: number;\n    reasoningTokens?: number;\n  } = {\n    inputTokens: undefined,\n    outputTokens: undefined,\n    totalTokens: undefined,\n  };\n  #usageCountMissing = new Set<(typeof primaryUsageKeys)[number]>();\n  #streamPromise: {\n    promise: Promise<void>;\n    resolve: (value: void) => void;\n    reject: (reason?: any) => void;\n  };\n  #objectPromise: {\n    promise: Promise<OUTPUT | undefined>;\n    resolve: (value: OUTPUT | undefined) => void;\n    reject: (reason?: any) => void;\n  };\n  #objectStreamController: ReadableStreamDefaultController<Partial<OUTPUT>> | null = null;\n  #objectStream: ReadableStream<Partial<OUTPUT>> | null = null;\n  #run: Run;\n  runId: string;\n\n  constructor({\n    createStream,\n    run,\n  }: {\n    createStream: (writer: WritableStream<ChunkType<OUTPUT>>) => Promise<ReadableStream<any>> | ReadableStream<any>;\n    run: Run<DefaultEngineType, Step<string, any, any, any, any, any, DefaultEngineType>[], any, any, any>;\n  }) {\n    const deferredPromise = {\n      promise: null,\n      resolve: null,\n      reject: null,\n    } as unknown as {\n      promise: Promise<void>;\n      resolve: (value: void) => void;\n      reject: (reason?: any) => void;\n    };\n    deferredPromise.promise = new Promise((resolve, reject) => {\n      deferredPromise.resolve = resolve;\n      deferredPromise.reject = reject;\n    });\n\n    // Object promise for structured output\n    const objectDeferredPromise = {\n      promise: null,\n      resolve: null,\n      reject: null,\n    } as unknown as {\n      promise: Promise<OUTPUT | undefined>;\n      resolve: (value: OUTPUT | undefined) => void;\n      reject: (reason?: any) => void;\n    };\n    objectDeferredPromise.promise = new Promise((resolve, reject) => {\n      objectDeferredPromise.resolve = resolve;\n      objectDeferredPromise.reject = reject;\n    });\n\n    // Object stream controller reference\n    let objectStreamController: ReadableStreamDefaultController<Partial<OUTPUT>> | null = null;\n\n    const updateUsageCount = (usage: {\n      inputTokens?: `${number}` | number;\n      outputTokens?: `${number}` | number;\n      totalTokens?: `${number}` | number;\n      reasoningTokens?: `${number}` | number;\n      cachedInputTokens?: `${number}` | number;\n      cacheCreationInputTokens?: `${number}` | number;\n    }) => {\n      for (const key of primaryUsageKeys) {\n        const value = usage[key] === undefined ? undefined : Number(usage[key]);\n        if (value === undefined) {\n          this.#usageCountMissing.add(key);\n          this.#usageCount[key] = undefined;\n        } else if (!this.#usageCountMissing.has(key)) {\n          this.#usageCount[key] = (this.#usageCount[key] ?? 0) + value;\n        }\n      }\n\n      for (const key of ['reasoningTokens', 'cachedInputTokens', 'cacheCreationInputTokens'] as const) {\n        const value = usage[key] === undefined ? undefined : Number(usage[key]);\n        if (value !== undefined) {\n          this.#usageCount[key] = (this.#usageCount[key] ?? 0) + value;\n        }\n      }\n    };\n\n    super({\n      start: async controller => {\n        try {\n          const writer = new WritableStream<ChunkType<OUTPUT>>({\n            write: chunk => {\n              if (\n                (chunk.type === 'step-output' &&\n                  chunk.payload?.output?.from === 'AGENT' &&\n                  chunk.payload?.output?.type === 'finish') ||\n                (chunk.type === 'step-output' &&\n                  chunk.payload?.output?.from === 'WORKFLOW' &&\n                  chunk.payload?.output?.type === 'finish')\n              ) {\n                const output = chunk.payload?.output;\n                if (output && 'payload' in output && output.payload) {\n                  const finishPayload = output.payload;\n                  if ('usage' in finishPayload && finishPayload.usage) {\n                    updateUsageCount(finishPayload.usage);\n                  } else if ('output' in finishPayload && finishPayload.output) {\n                    const outputPayload = finishPayload.output;\n                    if ('usage' in outputPayload && outputPayload.usage) {\n                      updateUsageCount(outputPayload.usage);\n                    }\n                  }\n                }\n              }\n\n              controller.enqueue(chunk);\n            },\n          });\n\n          const stream: ReadableStream<ChunkType<OUTPUT>> = await createStream(writer);\n\n          const getInnerChunk = (chunk: ChunkType<OUTPUT>) => {\n            if (chunk.type === 'workflow-step-output') {\n              return getInnerChunk(chunk.payload.output as any);\n            }\n            return chunk;\n          };\n\n          let objectResolved = false;\n\n          for await (const chunk of stream) {\n            if (chunk.type === 'workflow-step-output') {\n              const innerChunk = getInnerChunk(chunk);\n              if (\n                innerChunk.type === 'routing-agent-end' ||\n                innerChunk.type === 'agent-execution-end' ||\n                innerChunk.type === 'workflow-execution-end'\n              ) {\n                if (innerChunk.payload?.usage) {\n                  updateUsageCount(innerChunk.payload.usage);\n                }\n              }\n\n              // Handle network-object chunks (partial objects during streaming)\n              if (innerChunk.type === 'network-object') {\n                if (objectStreamController) {\n                  objectStreamController.enqueue((innerChunk as any).payload?.object);\n                }\n                controller.enqueue(innerChunk);\n              }\n              // Handle network-object-result chunks (final structured object)\n              else if (innerChunk.type === 'network-object-result') {\n                if (!objectResolved) {\n                  objectResolved = true;\n                  objectDeferredPromise.resolve((innerChunk as any).payload?.object);\n                  if (objectStreamController) {\n                    objectStreamController.close();\n                  }\n                }\n                controller.enqueue(innerChunk);\n              } else if (innerChunk.type === 'network-execution-event-finish') {\n                const finishPayload = {\n                  ...innerChunk.payload,\n                  usage: this.#usageCount,\n                };\n                controller.enqueue({ ...innerChunk, payload: finishPayload });\n              } else {\n                controller.enqueue(innerChunk);\n              }\n            }\n          }\n\n          // If no object was resolved, resolve with undefined\n          if (!objectResolved) {\n            objectDeferredPromise.resolve(undefined);\n            if (objectStreamController) {\n              objectStreamController.close();\n            }\n          }\n\n          controller.close();\n          deferredPromise.resolve();\n        } catch (error) {\n          controller.error(error);\n          deferredPromise.reject(error);\n          objectDeferredPromise.reject(error);\n          if (objectStreamController) {\n            objectStreamController.error(error);\n          }\n        }\n      },\n    });\n\n    this.#run = run;\n    this.#streamPromise = deferredPromise;\n\n    this.runId = run.runId;\n    this.#objectPromise = objectDeferredPromise;\n\n    // Create object stream\n    this.#objectStream = new ReadableStream<Partial<OUTPUT>>({\n      start: ctrl => {\n        objectStreamController = ctrl;\n        this.#objectStreamController = ctrl;\n      },\n    });\n  }\n\n  get status() {\n    return this.#streamPromise.promise.then(() => this.#run._getExecutionResults()).then(res => res!.status);\n  }\n\n  get result() {\n    return this.#streamPromise.promise.then(() => this.#run._getExecutionResults());\n  }\n\n  get usage() {\n    return this.#streamPromise.promise.then(() => this.#usageCount);\n  }\n\n  /**\n   * Returns a promise that resolves to the structured output object.\n   * Only available when structuredOutput option is provided to network().\n   * Resolves to undefined if no structuredOutput was requested.\n   */\n  get object(): Promise<OUTPUT | undefined> {\n    return this.#objectPromise.promise;\n  }\n\n  /**\n   * Returns a ReadableStream of partial objects during structured output generation.\n   * Useful for streaming partial results as they're being generated.\n   */\n  get objectStream(): ReadableStream<Partial<OUTPUT>> {\n    return this.#objectStream!;\n  }\n}\n","import type {\n  LanguageModelV2FinishReason,\n  LanguageModelV2StreamPart,\n  LanguageModelV2Usage,\n  SharedV2ProviderMetadata,\n} from '@ai-sdk/provider-v5';\nimport type { LanguageModelV3FinishReason, LanguageModelV3Usage } from '@ai-sdk/provider-v6';\nimport type { ModelMessage, ObjectStreamPart, TextStreamPart, ToolSet } from '@internal/ai-sdk-v5';\nimport type { AIV5ResponseMessage } from '../../../agent/message-list';\nimport type { ChunkType, LanguageModelUsage } from '../../types';\nimport { ChunkFrom } from '../../types';\nimport { isUrlString } from './compat/content';\nimport { DefaultGeneratedFile, DefaultGeneratedFileWithType } from './file';\n\n/**\n * Sanitizes tool-call input strings for safe JSON parsing.\n *\n * LLMs sometimes append internal tokens like `<|call|>`, `<|endoftext|>`, or `<|end|>`\n * to otherwise valid JSON in streamed tool-call arguments, causing JSON.parse to fail.\n *\n * This function first attempts JSON.parse on the original input. If parsing succeeds,\n * the original string is returned unchanged — this avoids corrupting valid JSON payloads\n * that legitimately contain `<|...|>` patterns inside string values.\n *\n * Only when the original input is not valid JSON does the function fall back to stripping\n * `<|...|>` token patterns and surrounding whitespace via regex.\n *\n * @see https://github.com/mastra-ai/mastra/issues/13261\n * @see https://github.com/mastra-ai/mastra/issues/13185\n */\nexport function sanitizeToolCallInput(input: string): string {\n  // Fast path: if input is already valid JSON, return unchanged to avoid\n  // corrupting <|...|> patterns that appear inside JSON string values.\n  try {\n    JSON.parse(input);\n    return input;\n  } catch {\n    // Input is not valid JSON — strip LLM-specific tokens and retry.\n    // The pattern starts at the literal `<|` (no leading `\\s*`) to keep\n    // matching linear on adversarial inputs (CodeQL js/polynomial-redos);\n    // leftover whitespace is harmless to JSON.parse and trimmed at the ends.\n    return input.replace(/<\\|[^|]*\\|>\\s*/g, '').trim();\n  }\n}\n\n/**\n * Attempts to repair common JSON malformations produced by LLM providers.\n *\n * Some LLM providers (e.g., Kimi/K2) occasionally generate malformed JSON for\n * tool call arguments. This function applies a sequence of targeted fixes for\n * the most common errors before giving up.\n *\n * Repairs applied (in order):\n * 1. Missing quote before property name: `{\"a\":\"b\",c\":\"d\"}` → `{\"a\":\"b\",\"c\":\"d\"}`\n * 2. Unquoted property names: `{command:\"value\"}` → `{\"command\":\"value\"}`\n * 3. Single quotes → double quotes (only outside already-double-quoted strings)\n * 4. Trailing commas: `{\"a\":1,}` → `{\"a\":1}`\n *\n * @returns The parsed object if repair succeeds, or null if the JSON is unrecoverable.\n * @see https://github.com/mastra-ai/mastra/issues/11078\n */\nexport function tryRepairJson(input: string): Record<string, any> | null {\n  let repaired = input.trim();\n\n  // Fix 1: Missing quote before property name after comma or opening brace\n  // e.g. {\"a\":\"b\",c\":\"d\"} → {\"a\":\"b\",\"c\":\"d\"}\n  // Matches: ,c\" or {c\" where c is a word character sequence followed by \"\n  // but NOT already preceded by a quote\n  repaired = repaired.replace(/([{,]\\s*)([a-zA-Z_$][a-zA-Z0-9_$]*)\"/g, (match, prefix, name) => {\n    // Check if the name is already quoted — if so, leave it alone\n    if (prefix.trimEnd().endsWith('\"')) {\n      return match;\n    }\n    return `${prefix}\"${name}\"`;\n  });\n\n  // Fix 2: Unquoted property names (must come after Fix 1 since Fix 1 handles the partial-quote case)\n  // e.g. {command:\"value\"} → {\"command\":\"value\"}\n  repaired = repaired.replace(/([{,]\\s*)([a-zA-Z_$][a-zA-Z0-9_$]*)\\s*:/g, '$1\"$2\":');\n\n  // Fix 3: Single quotes → double quotes\n  // Simple approach: replace single quotes that act as JSON delimiters\n  repaired = repaired.replace(/'/g, '\"');\n\n  // Fix 4: Trailing commas before closing braces/brackets\n  // e.g. {\"a\":1,} → {\"a\":1}\n  repaired = repaired.replace(/,(\\s*[}\\]])/g, '$1');\n\n  // Fix 5: Unquoted date/datetime values (issue #14230)\n  // e.g. {\"dueStart\": 2026-04-15} → {\"dueStart\": \"2026-04-15\"}\n  // e.g. {\"start\": 2026-04-15T09:00:00} → {\"start\": \"2026-04-15T09:00:00\"}\n  repaired = repaired.replace(/:\\s*(\\d{4}-\\d{2}-\\d{2}(?:T[\\d:]+)?)\\s*([,}])/g, ': \"$1\"$2');\n\n  try {\n    return JSON.parse(repaired);\n  } catch {\n    return null;\n  }\n}\n\nexport type StreamPart =\n  | Exclude<LanguageModelV2StreamPart, { type: 'finish' | 'tool-result' }>\n  // V3+ provider specs (AI SDK v6+) stream partial provider-executed results flagged `preliminary`.\n  | (Extract<LanguageModelV2StreamPart, { type: 'tool-result' }> & { preliminary?: boolean })\n  // Present on newer AI SDK provider specs (V4 / AI SDK v7) but absent from the V2 union.\n  | {\n      type: 'reasoning-file';\n      data: string | Uint8Array;\n      mediaType: string;\n      providerMetadata?: SharedV2ProviderMetadata;\n    }\n  | {\n      type: 'custom';\n      kind: string;\n      providerMetadata?: SharedV2ProviderMetadata;\n    }\n  | {\n      type: 'finish';\n      /** Includes 'tripwire' and 'retry' for processor scenarios */\n      finishReason: LanguageModelV2FinishReason | 'tripwire' | 'retry';\n      usage: LanguageModelV2Usage;\n      providerMetadata: SharedV2ProviderMetadata;\n      messages: {\n        all: ModelMessage[];\n        user: ModelMessage[];\n        nonUser: AIV5ResponseMessage[];\n      };\n    };\n\nexport function convertFullStreamChunkToMastra(value: StreamPart, ctx: { runId: string }): ChunkType | undefined {\n  switch (value.type) {\n    // Intentionally not converted: warnings are surfaced separately by the input stream.\n    case 'stream-start':\n      return;\n\n    case 'response-metadata':\n      return {\n        type: 'response-metadata',\n        runId: ctx.runId,\n        from: ChunkFrom.AGENT,\n        payload: { ...value },\n      };\n    case 'text-start':\n      return {\n        type: 'text-start',\n        runId: ctx.runId,\n        from: ChunkFrom.AGENT,\n        payload: {\n          id: value.id,\n          providerMetadata: value.providerMetadata,\n        },\n      };\n    case 'text-delta':\n      // Keep empty deltas that carry provider metadata (e.g. Gemini thought signatures),\n      // otherwise that metadata is dropped before it reaches the consumer.\n      if (value.delta || value.providerMetadata != null) {\n        return {\n          type: 'text-delta',\n          runId: ctx.runId,\n          from: ChunkFrom.AGENT,\n          payload: {\n            id: value.id,\n            providerMetadata: value.providerMetadata,\n            text: value.delta,\n          },\n        };\n      }\n      return;\n\n    case 'text-end':\n      return {\n        type: 'text-end',\n        runId: ctx.runId,\n        from: ChunkFrom.AGENT,\n        payload: value,\n      };\n\n    case 'reasoning-start':\n      return {\n        type: 'reasoning-start',\n        runId: ctx.runId,\n        from: ChunkFrom.AGENT,\n        payload: {\n          id: value.id,\n          providerMetadata: value.providerMetadata,\n        },\n      };\n\n    case 'reasoning-delta':\n      return {\n        type: 'reasoning-delta',\n        runId: ctx.runId,\n        from: ChunkFrom.AGENT,\n        payload: {\n          id: value.id,\n          providerMetadata: value.providerMetadata,\n          text: value.delta,\n        },\n      };\n\n    case 'reasoning-end':\n      return {\n        type: 'reasoning-end',\n        runId: ctx.runId,\n        from: ChunkFrom.AGENT,\n        payload: {\n          id: value.id,\n          providerMetadata: value.providerMetadata,\n        },\n      };\n\n    case 'source':\n      return {\n        type: 'source',\n        runId: ctx.runId,\n        from: ChunkFrom.AGENT,\n        payload: {\n          id: value.id,\n          sourceType: value.sourceType,\n          title: value.title || '',\n          mimeType: value.sourceType === 'document' ? value.mediaType : undefined,\n          filename: value.sourceType === 'document' ? value.filename : undefined,\n          url: value.sourceType === 'url' ? value.url : undefined,\n          providerMetadata: value.providerMetadata,\n        },\n      };\n\n    case 'file': {\n      const pm = (value as any).providerMetadata;\n      return {\n        type: 'file',\n        runId: ctx.runId,\n        from: ChunkFrom.AGENT,\n        payload: {\n          data: value.data,\n          // URL-backed generated files flatten to URL strings, which are not base64.\n          base64: typeof value.data === 'string' && !isUrlString(value.data) ? value.data : undefined,\n          mimeType: value.mediaType,\n          ...(pm != null ? { providerMetadata: pm } : {}),\n        },\n      };\n    }\n\n    case 'tool-call': {\n      let toolCallInput: Record<string, any> | undefined = undefined;\n\n      if (value.input) {\n        const sanitized = sanitizeToolCallInput(value.input);\n        if (sanitized) {\n          try {\n            toolCallInput = JSON.parse(sanitized);\n          } catch {\n            // JSON.parse failed — attempt to repair common LLM JSON errors\n            const repaired = tryRepairJson(sanitized);\n            if (repaired) {\n              toolCallInput = repaired;\n            } else {\n              // Log only metadata: raw tool inputs can carry credentials or PII.\n              console.error('Error converting tool call input to JSON', {\n                toolCallId: value.toolCallId,\n                toolName: value.toolName,\n                inputLength: value.input.length,\n              });\n              toolCallInput = undefined;\n            }\n          }\n        }\n      }\n\n      return {\n        type: 'tool-call',\n        runId: ctx.runId,\n        from: ChunkFrom.AGENT,\n        payload: {\n          toolCallId: value.toolCallId,\n          toolName: value.toolName,\n          args: toolCallInput,\n          providerExecuted: value.providerExecuted,\n          providerMetadata: value.providerMetadata,\n          ...((value as { observability?: unknown }).observability\n            ? { observability: (value as { observability?: unknown }).observability as any }\n            : {}),\n        },\n      };\n    }\n\n    case 'tool-result':\n      return {\n        type: 'tool-result',\n        runId: ctx.runId,\n        from: ChunkFrom.AGENT,\n        payload: {\n          toolCallId: value.toolCallId,\n          toolName: value.toolName,\n          result: value.result,\n          isError: value.isError,\n          providerExecuted: value.providerExecuted,\n          providerMetadata: value.providerMetadata,\n          ...(value.preliminary ? { preliminary: true } : {}),\n        },\n      };\n\n    case 'tool-input-start':\n      return {\n        type: 'tool-call-input-streaming-start',\n        runId: ctx.runId,\n        from: ChunkFrom.AGENT,\n        payload: {\n          toolCallId: value.id,\n          toolName: value.toolName,\n          providerExecuted: value.providerExecuted,\n          providerMetadata: value.providerMetadata,\n          dynamic: (value as { dynamic?: boolean }).dynamic,\n          ...((value as { observability?: unknown }).observability\n            ? { observability: (value as { observability?: unknown }).observability as any }\n            : {}),\n        },\n      };\n\n    case 'tool-input-delta':\n      if (value.delta) {\n        return {\n          type: 'tool-call-delta',\n          runId: ctx.runId,\n          from: ChunkFrom.AGENT,\n          payload: {\n            argsTextDelta: value.delta,\n            toolCallId: value.id,\n            providerMetadata: value.providerMetadata,\n          },\n        };\n      }\n      return;\n\n    case 'tool-input-end':\n      return {\n        type: 'tool-call-input-streaming-end',\n        runId: ctx.runId,\n        from: ChunkFrom.AGENT,\n        payload: {\n          toolCallId: value.id,\n          providerMetadata: value.providerMetadata,\n        },\n      };\n\n    case 'finish':\n      const { finishReason, usage, providerMetadata, messages, ...rest } = value;\n      const rawFinishReason = extractRawFinishReason(finishReason);\n      return {\n        type: 'finish',\n        runId: ctx.runId,\n        from: ChunkFrom.AGENT,\n        payload: {\n          providerMetadata: value.providerMetadata,\n          stepResult: {\n            reason: normalizeFinishReason(value.finishReason),\n            ...(rawFinishReason !== undefined && { rawReason: rawFinishReason }),\n          },\n          output: {\n            // Normalize usage to handle both V2 (flat) and V3 (nested) formats\n            usage: normalizeUsage(value.usage, value.providerMetadata),\n          },\n          metadata: {\n            providerMetadata: value.providerMetadata,\n          },\n          messages: messages ?? {\n            all: [],\n            user: [],\n            nonUser: [],\n          },\n          ...rest,\n        },\n      };\n    case 'error':\n      return {\n        type: 'error',\n        runId: ctx.runId,\n        from: ChunkFrom.AGENT,\n        payload: value,\n      };\n\n    case 'raw':\n      return {\n        type: 'raw',\n        runId: ctx.runId,\n        from: ChunkFrom.AGENT,\n        payload: value.rawValue as Record<string, unknown>,\n      };\n\n    case 'reasoning-file':\n      return {\n        type: 'reasoning-file',\n        runId: ctx.runId,\n        from: ChunkFrom.AGENT,\n        payload: {\n          data: value.data,\n          // URL-backed generated files flatten to URL strings, which are not base64.\n          base64: typeof value.data === 'string' && !isUrlString(value.data) ? value.data : undefined,\n          mimeType: value.mediaType,\n          ...(value.providerMetadata != null ? { providerMetadata: value.providerMetadata } : {}),\n        },\n      };\n\n    case 'custom':\n      return {\n        type: 'custom',\n        runId: ctx.runId,\n        from: ChunkFrom.AGENT,\n        payload: {\n          kind: value.kind,\n          ...(value.providerMetadata != null ? { providerMetadata: value.providerMetadata } : {}),\n        },\n      };\n\n    default:\n      // Unknown stream part types must not disappear silently: surface them as raw chunks\n      // so consumers opting into raw chunks still receive the provider data.\n      return {\n        type: 'raw',\n        runId: ctx.runId,\n        from: ChunkFrom.AGENT,\n        payload: value as Record<string, unknown>,\n      };\n  }\n}\n\nexport type OutputChunkType<OUTPUT = undefined> =\n  | TextStreamPart<ToolSet>\n  | ObjectStreamPart<Partial<OUTPUT>>\n  | undefined;\n\nexport function convertMastraChunkToAISDKv5<OUTPUT = undefined>({\n  chunk,\n  mode = 'stream',\n}: {\n  chunk: ChunkType<OUTPUT>;\n  mode?: 'generate' | 'stream';\n}): OutputChunkType<OUTPUT> {\n  switch (chunk.type) {\n    case 'start':\n      return {\n        type: 'start',\n      };\n    case 'step-start':\n      const { messageId: _messageId, ...rest } = chunk.payload;\n      return {\n        type: 'start-step',\n        request: rest.request,\n        warnings: rest.warnings || [],\n      };\n    case 'raw':\n      return {\n        type: 'raw',\n        rawValue: chunk.payload,\n      };\n\n    case 'finish': {\n      return {\n        type: 'finish',\n        // Cast needed: Mastra extends reason with 'tripwire' | 'retry' for processor scenarios\n        finishReason: chunk.payload.stepResult.reason as LanguageModelV2FinishReason,\n        // Cast needed: Mastra's LanguageModelUsage has optional properties, V2 has required-but-nullable\n        totalUsage: chunk.payload.output.usage as LanguageModelV2Usage,\n      };\n    }\n    case 'reasoning-start':\n      return {\n        type: 'reasoning-start',\n        id: chunk.payload.id,\n        providerMetadata: chunk.payload.providerMetadata,\n      };\n    case 'reasoning-delta':\n      return {\n        type: 'reasoning-delta',\n        id: chunk.payload.id,\n        text: chunk.payload.text,\n        providerMetadata: chunk.payload.providerMetadata,\n      };\n    case 'reasoning-signature':\n      throw new Error('AISDKv5 chunk type \"reasoning-signature\" not supported');\n    case 'redacted-reasoning':\n      throw new Error('AISDKv5 chunk type \"redacted-reasoning\" not supported');\n\n    case 'reasoning-end':\n      return {\n        type: 'reasoning-end',\n        id: chunk.payload.id,\n        providerMetadata: chunk.payload.providerMetadata,\n      };\n    case 'source':\n      if (chunk.payload.sourceType === 'url') {\n        return {\n          type: 'source',\n          sourceType: 'url',\n          id: chunk.payload.id,\n          url: chunk.payload.url!,\n          title: chunk.payload.title,\n          providerMetadata: chunk.payload.providerMetadata,\n        };\n      }\n      return {\n        type: 'source',\n        sourceType: 'document',\n        id: chunk.payload.id,\n        mediaType: chunk.payload.mimeType!,\n        title: chunk.payload.title,\n        filename: chunk.payload.filename,\n        providerMetadata: chunk.payload.providerMetadata,\n      };\n\n    case 'file': {\n      const filePart =\n        mode === 'generate'\n          ? {\n              type: 'file' as const,\n              file: new DefaultGeneratedFile({\n                data: chunk.payload.data,\n                mediaType: chunk.payload.mimeType,\n              }),\n            }\n          : {\n              type: 'file' as const,\n              file: new DefaultGeneratedFileWithType({\n                data: chunk.payload.data,\n                mediaType: chunk.payload.mimeType,\n              }),\n            };\n\n      if (chunk.payload.providerMetadata) {\n        (filePart as any).providerMetadata = chunk.payload.providerMetadata;\n      }\n\n      return filePart;\n    }\n    case 'tool-call': {\n      const toolCallPart = {\n        type: 'tool-call',\n        toolCallId: chunk.payload.toolCallId,\n        providerMetadata: chunk.payload.providerMetadata,\n        providerExecuted: chunk.payload.providerExecuted,\n        toolName: chunk.payload.toolName,\n        input: chunk.payload.args,\n      };\n      if (chunk.payload.observability) {\n        (toolCallPart as { observability?: unknown }).observability = chunk.payload.observability;\n      }\n      return toolCallPart as OutputChunkType<OUTPUT>;\n    }\n    case 'tool-call-input-streaming-start':\n      return {\n        type: 'tool-input-start',\n        id: chunk.payload.toolCallId,\n        toolName: chunk.payload.toolName,\n        dynamic: !!chunk.payload.dynamic,\n        providerMetadata: chunk.payload.providerMetadata,\n        providerExecuted: chunk.payload.providerExecuted,\n        ...(chunk.payload.observability ? { observability: chunk.payload.observability as any } : {}),\n      };\n    case 'tool-call-input-streaming-end':\n      return {\n        type: 'tool-input-end',\n        id: chunk.payload.toolCallId,\n        providerMetadata: chunk.payload.providerMetadata,\n      };\n    case 'tool-call-delta':\n      return {\n        type: 'tool-input-delta',\n        id: chunk.payload.toolCallId,\n        delta: chunk.payload.argsTextDelta,\n        providerMetadata: chunk.payload.providerMetadata,\n      };\n    case 'step-finish': {\n      const { request: _request, providerMetadata: metadataProviderMetadata, ...rest } = chunk.payload.metadata;\n      return {\n        type: 'finish-step',\n        response: {\n          id: chunk.payload.id || '',\n          timestamp: new Date(),\n          modelId: (rest.modelId as string) || '',\n          ...rest,\n        },\n        usage: chunk.payload.output.usage,\n        finishReason: chunk.payload.stepResult.reason,\n        providerMetadata: metadataProviderMetadata ?? chunk.payload.providerMetadata,\n      };\n    }\n    case 'text-delta':\n      return {\n        type: 'text-delta',\n        id: chunk.payload.id,\n        text: chunk.payload.text,\n        providerMetadata: chunk.payload.providerMetadata,\n      };\n    case 'text-end':\n      return {\n        type: 'text-end',\n        id: chunk.payload.id,\n        providerMetadata: chunk.payload.providerMetadata,\n      };\n    case 'text-start':\n      return {\n        type: 'text-start',\n        id: chunk.payload.id,\n        providerMetadata: chunk.payload.providerMetadata,\n      };\n    case 'tool-result':\n      return {\n        type: 'tool-result',\n        input: chunk.payload.args,\n        toolCallId: chunk.payload.toolCallId,\n        providerExecuted: chunk.payload.providerExecuted,\n        toolName: chunk.payload.toolName,\n        output: chunk.payload.result,\n        ...(chunk.payload.preliminary ? { preliminary: true } : {}),\n        // providerMetadata: chunk.payload.providerMetadata, // AI v5 types don't show this?\n      };\n    case 'tool-error':\n      return {\n        type: 'tool-error',\n        error: chunk.payload.error,\n        input: chunk.payload.args,\n        toolCallId: chunk.payload.toolCallId,\n        providerExecuted: chunk.payload.providerExecuted,\n        toolName: chunk.payload.toolName,\n        // providerMetadata: chunk.payload.providerMetadata, // AI v5 types don't show this?\n      };\n\n    case 'abort':\n      return {\n        type: 'abort',\n      };\n\n    case 'error':\n      return {\n        type: 'error',\n        error: chunk.payload.error,\n      };\n\n    case 'object':\n      return {\n        type: 'object',\n        object: chunk.object,\n      };\n\n    default:\n      if (chunk.type && 'payload' in chunk && chunk.payload) {\n        return {\n          type: chunk.type as string,\n          ...(chunk.payload || {}),\n        } as OutputChunkType<OUTPUT>;\n      }\n      return undefined;\n  }\n}\n\n/**\n * Type guard to check if usage is in V3 format (nested objects)\n */\nfunction isV3Usage(usage: unknown): usage is LanguageModelV3Usage {\n  if (!usage || typeof usage !== 'object') return false;\n  const u = usage as Record<string, unknown>;\n  return (\n    typeof u.inputTokens === 'object' &&\n    u.inputTokens !== null &&\n    'total' in u.inputTokens &&\n    typeof u.outputTokens === 'object' &&\n    u.outputTokens !== null &&\n    'total' in u.outputTokens\n  );\n}\n\n/**\n * Peel `{ total: { total: … } }` down to the innermost token-detail object.\n *\n * AI SDK v7 wraps any model that advertises `specificationVersion: 'v2'` in a\n * compatibility shim that nests flat usage as `{ total: usage.inputTokens }`.\n * Mastra's model router advertises 'v2' but forwards V3/V4 usage untouched, so\n * wrapping it with `wrapLanguageModel` nests the already-nested counts once more.\n * Only the innermost object carries the real counts and cache/reasoning details;\n * the wrapper's own detail fields are `undefined`.\n */\nfunction innermostTokens<T extends { total?: unknown }>(tokens: T): T {\n  let current = tokens;\n  while (typeof current.total === 'object' && current.total !== null) {\n    current = current.total as T;\n  }\n  return current;\n}\n\n/**\n * Normalizes usage from either V2 (flat) or V3 (nested) format to Mastra's flat format.\n * V2 format: { inputTokens: number, outputTokens: number, totalTokens?: number }\n * V3 format: { inputTokens: { total, noCache, cacheRead, cacheWrite }, outputTokens: { total, text, reasoning } }\n *\n * The original usage data is preserved in the `raw` field for advanced use cases.\n */\nfunction getAnthropicCacheCreationUsage(\n  usage: LanguageModelV2Usage | LanguageModelV3Usage | undefined,\n  providerMetadata?: SharedV2ProviderMetadata,\n): {\n  cacheCreationInputTokens5m?: number;\n  cacheCreationInputTokens1h?: number;\n} {\n  const anthropic = providerMetadata?.anthropic as Record<string, unknown> | undefined;\n  // @ai-sdk/anthropic never sets `cacheCreation`; the TTL split arrives untouched from the API\n  // as `cache_creation` on `providerMetadata.anthropic.usage` and on `usage.raw`.\n  const cacheCreation =\n    anthropic?.cacheCreation ??\n    (anthropic?.usage as Record<string, unknown> | undefined)?.cache_creation ??\n    ((usage as { raw?: Record<string, unknown> } | undefined)?.raw?.cache_creation as unknown);\n  if (typeof cacheCreation !== 'object' || cacheCreation === null) return {};\n\n  const details = cacheCreation as Record<string, unknown>;\n  const cacheCreationInputTokens5m = details.ephemeral_5m_input_tokens ?? details.ephemeral5mInputTokens;\n  const cacheCreationInputTokens1h = details.ephemeral_1h_input_tokens ?? details.ephemeral1hInputTokens;\n  return {\n    ...(typeof cacheCreationInputTokens5m === 'number' && { cacheCreationInputTokens5m }),\n    ...(typeof cacheCreationInputTokens1h === 'number' && { cacheCreationInputTokens1h }),\n  };\n}\n\nfunction normalizeUsage(\n  usage: LanguageModelV2Usage | LanguageModelV3Usage | undefined,\n  providerMetadata?: SharedV2ProviderMetadata,\n): LanguageModelUsage {\n  const cacheCreationUsage = getAnthropicCacheCreationUsage(usage, providerMetadata);\n  if (!usage) {\n    return {\n      inputTokens: undefined,\n      outputTokens: undefined,\n      totalTokens: undefined,\n      reasoningTokens: undefined,\n      cachedInputTokens: undefined,\n      cacheCreationInputTokens: undefined,\n      ...cacheCreationUsage,\n      raw: undefined,\n    };\n  }\n\n  if (isV3Usage(usage)) {\n    // V3 format - extract from nested structure\n    const input = innermostTokens(usage.inputTokens);\n    const output = innermostTokens(usage.outputTokens);\n    const inputTokens = input.total;\n    const outputTokens = output.total;\n    return {\n      inputTokens,\n      outputTokens,\n      totalTokens: inputTokens !== undefined && outputTokens !== undefined ? inputTokens + outputTokens : undefined,\n      reasoningTokens: output.reasoning,\n      cachedInputTokens: input.cacheRead,\n      cacheCreationInputTokens: input.cacheWrite,\n      ...cacheCreationUsage,\n      raw: usage,\n    };\n  }\n\n  // V2 format - already flat\n  const v2Usage = usage as LanguageModelV2Usage;\n  return {\n    inputTokens: v2Usage.inputTokens,\n    outputTokens: v2Usage.outputTokens,\n    totalTokens:\n      v2Usage.totalTokens ??\n      (v2Usage.inputTokens !== undefined && v2Usage.outputTokens !== undefined\n        ? v2Usage.inputTokens + v2Usage.outputTokens\n        : undefined),\n    reasoningTokens: (v2Usage as { reasoningTokens?: number }).reasoningTokens,\n    cachedInputTokens: (v2Usage as { cachedInputTokens?: number }).cachedInputTokens,\n    cacheCreationInputTokens: (v2Usage as { cacheCreationInputTokens?: number }).cacheCreationInputTokens,\n    ...cacheCreationUsage,\n    raw: usage,\n  };\n}\n\n/**\n * Type guard to check if a finish reason is V3 format (object with unified/raw properties)\n */\nfunction isV3FinishReason(\n  finishReason: LanguageModelV2FinishReason | LanguageModelV3FinishReason | 'tripwire' | 'retry' | undefined,\n): finishReason is LanguageModelV3FinishReason {\n  return typeof finishReason === 'object' && finishReason !== null && 'unified' in finishReason;\n}\n\n/**\n * Normalize finish reason from either V2/V5 (string) or V3/V6 (object) format to a string.\n *\n * V2/V5 format: 'stop' | 'length' | 'content-filter' | 'tool-calls' | 'error' | 'other' | 'unknown'\n * V3/V6 format: { unified: 'stop' | 'length' | 'content-filter' | 'tool-calls' | 'error' | 'other', raw: string | undefined }\n *\n * We normalize to the unified string value for internal Mastra use.\n * Note: V6 removed 'unknown' and merged it into 'other'.\n */\nfunction normalizeFinishReason(\n  finishReason: LanguageModelV2FinishReason | LanguageModelV3FinishReason | 'tripwire' | 'retry' | undefined,\n): LanguageModelV2FinishReason | 'tripwire' | 'retry' {\n  // V3/V6 format - extract unified value. Peel repeated envelopes: the AI SDK v7\n  // 'v2' compatibility shim re-wraps an already-nested reason (see innermostTokens).\n  let reason = finishReason;\n  while (isV3FinishReason(reason)) {\n    reason = reason.unified as typeof finishReason;\n  }\n\n  if (!reason) {\n    return 'other';\n  }\n\n  // Handle Mastra-specific finish reasons\n  if (reason === 'tripwire' || reason === 'retry') {\n    return reason;\n  }\n\n  // V2/V5 format - already a string, but normalize 'unknown' to 'other' for consistency with V6\n  return reason === 'unknown' ? 'other' : reason;\n}\n\n/**\n * Extract the provider's raw finish reason, when the provider supplies one.\n *\n * V3/V6 providers report both a unified reason and the provider's own string\n * (e.g. Google sends `raw: 'MALFORMED_FUNCTION_CALL'` alongside `unified: 'error'`).\n * The unified value alone collapses distinct provider outcomes into one bucket,\n * so we keep the raw value next to it — mirroring how `normalizeUsage` retains `raw`.\n *\n * V2/V5 providers only ever send a string, so there is no raw value to preserve.\n */\nfunction extractRawFinishReason(\n  finishReason: LanguageModelV2FinishReason | LanguageModelV3FinishReason | 'tripwire' | 'retry' | undefined,\n): string | undefined {\n  // Walk nested envelopes: an outer compatibility wrapper carries `raw: undefined`,\n  // the provider's own string sits on the innermost object.\n  let raw: string | undefined;\n  let reason = finishReason;\n  while (isV3FinishReason(reason)) {\n    raw = reason.raw ?? raw;\n    reason = reason.unified as typeof finishReason;\n  }\n  return raw;\n}\n","import type { MastraServerCache } from '../cache/base';\n\n/**\n * Options for creating a CachingTransformStream\n */\nexport interface CachingTransformStreamOptions<T> {\n  /**\n   * Cache instance for storing stream chunks\n   */\n  cache: MastraServerCache;\n\n  /**\n   * Unique key for this stream's cache entries\n   */\n  cacheKey: string;\n\n  /**\n   * Optional serializer for chunks before caching.\n   * Defaults to identity (chunks stored as-is).\n   */\n  serialize?: (chunk: T) => unknown;\n\n  /**\n   * Optional deserializer for chunks from cache.\n   * Defaults to identity (chunks returned as-is).\n   */\n  deserialize?: (cached: unknown) => T;\n}\n\n/**\n * Creates a TransformStream that caches all chunks passing through it.\n *\n * Use this for workflow streaming where you need resumable streams\n * without changing to a PubSub-based architecture.\n *\n * @example\n * ```typescript\n * const cache = mastra.getServerCache();\n * const { transform, getHistory } = createCachingTransformStream({\n *   cache,\n *   cacheKey: runId,\n * });\n *\n * // Use the transform stream\n * const cachedStream = sourceStream.pipeThrough(transform);\n *\n * // Later, get cached history for replay\n * const history = await getHistory();\n * ```\n */\nexport function createCachingTransformStream<T>(options: CachingTransformStreamOptions<T>): {\n  /**\n   * TransformStream that caches chunks as they pass through\n   */\n  transform: TransformStream<T, T>;\n\n  /**\n   * Get all cached chunks for this stream\n   */\n  getHistory: (offset?: number) => Promise<T[]>;\n\n  /**\n   * Clear cached chunks for this stream\n   */\n  clearCache: () => Promise<void>;\n} {\n  const { cache, cacheKey, serialize = (x: T) => x, deserialize = (x: unknown) => x as T } = options;\n\n  const transform = new TransformStream<T, T>({\n    transform(chunk, controller) {\n      // Cache the chunk (non-blocking)\n      const serialized = serialize(chunk);\n      cache.listPush(cacheKey, serialized).catch(() => {\n        // Silently ignore cache errors - streaming should continue\n      });\n\n      // Pass through the chunk\n      controller.enqueue(chunk);\n    },\n  });\n\n  const getHistory = async (offset = 0): Promise<T[]> => {\n    const cached = await cache.listFromTo(cacheKey, offset);\n    return cached.map(item => deserialize(item));\n  };\n\n  const clearCache = async (): Promise<void> => {\n    await cache.delete(cacheKey);\n  };\n\n  return { transform, getHistory, clearCache };\n}\n\n/**\n * Creates a ReadableStream that first emits cached history, then pipes from a live source.\n *\n * Use this when a client reconnects and needs to receive missed chunks\n * before continuing with the live stream.\n *\n * @example\n * ```typescript\n * const cache = mastra.getServerCache();\n *\n * // Get cached history\n * const history = await cache.listFromTo(runId, 0);\n *\n * // Create combined stream\n * const stream = createReplayStream({\n *   history: history as ChunkType[],\n *   liveSource: workflow.stream(),\n *   cache,\n *   cacheKey: runId,\n * });\n * ```\n */\nexport function createReplayStream<T>(options: {\n  /**\n   * Cached chunks to emit first\n   */\n  history: T[];\n\n  /**\n   * Live stream to continue from after history\n   */\n  liveSource: ReadableStream<T>;\n\n  /**\n   * Optional cache for continued caching of live chunks\n   */\n  cache?: MastraServerCache;\n\n  /**\n   * Cache key for continued caching\n   */\n  cacheKey?: string;\n\n  /**\n   * Optional serializer for caching\n   */\n  serialize?: (chunk: T) => unknown;\n}): ReadableStream<T> {\n  const { history, liveSource, cache, cacheKey, serialize = (x: T) => x } = options;\n\n  let historyIndex = 0;\n  let liveReader: ReadableStreamDefaultReader<T> | null = null;\n  let historyComplete = false;\n\n  return new ReadableStream<T>({\n    async pull(controller) {\n      // First, emit all history chunks\n      if (!historyComplete) {\n        if (historyIndex < history.length) {\n          controller.enqueue(history[historyIndex]!);\n          historyIndex++;\n          return;\n        }\n        historyComplete = true;\n        liveReader = liveSource.getReader();\n      }\n\n      // Then, read from live source\n      if (liveReader) {\n        try {\n          const { done, value } = await liveReader.read();\n\n          if (done) {\n            controller.close();\n            return;\n          }\n\n          // Cache the live chunk if caching is enabled\n          if (cache && cacheKey) {\n            const serialized = serialize(value);\n            cache.listPush(cacheKey, serialized).catch(() => {});\n          }\n\n          controller.enqueue(value);\n        } catch (error) {\n          controller.error(error);\n        }\n      }\n    },\n\n    cancel(reason) {\n      if (liveReader) {\n        return liveReader.cancel(reason);\n      }\n\n      return liveSource.cancel(reason);\n    },\n  });\n}\n\n/**\n * Helper to create a caching transform and get history in one call.\n *\n * This is the recommended way to add caching to workflow streams.\n *\n * @example\n * ```typescript\n * const { pipeThrough, getHistory, clearCache } = withStreamCaching({\n *   cache: mastra.getServerCache(),\n *   cacheKey: runId,\n * });\n *\n * // Apply caching to a stream\n * const cachedStream = workflow.fullStream.pipeThrough(pipeThrough());\n *\n * // On reconnect, get history and create replay stream\n * const history = await getHistory();\n * const replayStream = createReplayStream({\n *   history,\n *   liveSource: workflow.resumeStream(),\n * });\n * ```\n */\nexport function withStreamCaching<T>(options: CachingTransformStreamOptions<T>): {\n  /**\n   * Creates a new TransformStream that caches chunks.\n   * Call this each time you need a new caching transform.\n   */\n  pipeThrough: () => TransformStream<T, T>;\n\n  /**\n   * Get cached history for this stream\n   */\n  getHistory: (offset?: number) => Promise<T[]>;\n\n  /**\n   * Clear the cache for this stream\n   */\n  clearCache: () => Promise<void>;\n} {\n  const { cache, cacheKey, serialize, deserialize } = options;\n\n  return {\n    pipeThrough: () => {\n      const { transform } = createCachingTransformStream({ cache, cacheKey, serialize, deserialize });\n      return transform;\n    },\n\n    getHistory: async (offset = 0) => {\n      const deserializeFn = deserialize ?? ((x: unknown) => x as T);\n      const cached = await cache.listFromTo(cacheKey, offset);\n      return cached.map(item => deserializeFn(item));\n    },\n\n    clearCache: async () => {\n      await cache.delete(cacheKey);\n    },\n  };\n}\n","import { TransformStream } from 'node:stream/web';\nimport type { ChunkType } from './types';\n\nconst CHUNKING_PATTERNS = {\n  word: /\\S+\\s+/m,\n  line: /\\n+/m,\n} as const;\n\nconst wait = (delayInMs: number) => new Promise<void>(resolve => setTimeout(resolve, delayInMs));\n\n/**\n * Detects the next complete chunk at the start of a buffered string.\n *\n * @experimental This API may change in a future release.\n */\nexport type SmoothStreamChunkDetector = (buffer: string) => string | null | undefined;\n\n/**\n * Options for {@link smoothStream}.\n *\n * @experimental This API may change in a future release.\n */\nexport interface SmoothStreamOptions {\n  /**\n   * Delay between emitted chunks in milliseconds. Set to `null` to emit chunks\n   * without a delay.\n   *\n   * @default 10\n   */\n  delayInMs?: number | null;\n\n  /**\n   * How buffered text and reasoning are divided into chunks.\n   *\n   * @default 'word'\n   */\n  chunking?: 'word' | 'line' | RegExp | SmoothStreamChunkDetector | Intl.Segmenter;\n}\n\ntype SmoothableChunk<OUTPUT> = Extract<ChunkType<OUTPUT>, { type: 'text-delta' | 'reasoning-delta' }>;\n\nfunction createChunkDetector(chunking: NonNullable<SmoothStreamOptions['chunking']>): SmoothStreamChunkDetector {\n  if (typeof chunking === 'object' && 'segment' in chunking && typeof chunking.segment === 'function') {\n    return buffer => {\n      if (!buffer) {\n        return null;\n      }\n\n      const firstSegment = chunking.segment(buffer)[Symbol.iterator]().next().value;\n      return firstSegment?.segment || null;\n    };\n  }\n\n  if (typeof chunking === 'function') {\n    return buffer => {\n      const match = chunking(buffer);\n\n      if (match == null) {\n        return null;\n      }\n\n      if (!match.length) {\n        throw new TypeError('The chunking function must return a non-empty string.');\n      }\n\n      if (!buffer.startsWith(match)) {\n        throw new TypeError('The chunking function must return a prefix of the buffered text.');\n      }\n\n      return match;\n    };\n  }\n\n  const pattern = typeof chunking === 'string' ? CHUNKING_PATTERNS[chunking] : chunking;\n\n  if (!(pattern instanceof RegExp)) {\n    throw new TypeError('chunking must be \"word\", \"line\", a RegExp, an Intl.Segmenter, or a chunk detector function.');\n  }\n\n  return buffer => {\n    pattern.lastIndex = 0;\n    const match = pattern.exec(buffer);\n\n    if (!match) {\n      return null;\n    }\n\n    const detected = buffer.slice(0, match.index) + match[0];\n    if (!detected.length) {\n      throw new TypeError('The chunking RegExp must match a non-empty string.');\n    }\n\n    return detected;\n  };\n}\n\n/**\n * Creates a transform stream that buffers text and reasoning deltas and emits\n * them in consistent, delayed chunks. Other stream parts pass through without\n * modification after any buffered content has been emitted.\n *\n * @experimental This API may change in a future release.\n */\nexport function smoothStream<OUTPUT = undefined>({\n  delayInMs = 10,\n  chunking = 'word',\n}: SmoothStreamOptions = {}): TransformStream<ChunkType<OUTPUT>, ChunkType<OUTPUT>> {\n  const detectChunk = createChunkDetector(chunking);\n  let buffer = '';\n  let bufferedChunk: SmoothableChunk<OUTPUT> | undefined;\n  let bufferedMetadata: SmoothableChunk<OUTPUT>['metadata'];\n  let bufferedProviderMetadata: SmoothableChunk<OUTPUT>['payload']['providerMetadata'];\n\n  const enqueueBufferedText = (controller: TransformStreamDefaultController<ChunkType<OUTPUT>>, text: string) => {\n    // Emit even when the text is empty if metadata is still pending, so a\n    // trailing metadata-only delta (e.g. Gemini thought signatures, #20469)\n    // is not silently dropped on flush.\n    const hasPendingMetadata = bufferedMetadata !== undefined || bufferedProviderMetadata !== undefined;\n    if (!bufferedChunk || (!text && !hasPendingMetadata)) {\n      return;\n    }\n\n    const { metadata: _metadata, ...chunkWithoutMetadata } = bufferedChunk;\n    const { providerMetadata: _providerMetadata, ...payloadWithoutProviderMetadata } = bufferedChunk.payload;\n\n    controller.enqueue({\n      ...chunkWithoutMetadata,\n      ...(bufferedMetadata !== undefined ? { metadata: bufferedMetadata } : {}),\n      payload: {\n        ...payloadWithoutProviderMetadata,\n        ...(bufferedProviderMetadata !== undefined ? { providerMetadata: bufferedProviderMetadata } : {}),\n        text,\n      },\n    } as ChunkType<OUTPUT>);\n\n    bufferedMetadata = undefined;\n    bufferedProviderMetadata = undefined;\n  };\n\n  const flushBuffer = (controller: TransformStreamDefaultController<ChunkType<OUTPUT>>) => {\n    enqueueBufferedText(controller, buffer);\n    buffer = '';\n    bufferedChunk = undefined;\n    bufferedMetadata = undefined;\n    bufferedProviderMetadata = undefined;\n  };\n\n  return new TransformStream<ChunkType<OUTPUT>, ChunkType<OUTPUT>>({\n    async transform(chunk, controller) {\n      if (chunk.type !== 'text-delta' && chunk.type !== 'reasoning-delta') {\n        flushBuffer(controller);\n        controller.enqueue(chunk);\n        return;\n      }\n\n      if (bufferedChunk && (chunk.type !== bufferedChunk.type || chunk.payload.id !== bufferedChunk.payload.id)) {\n        flushBuffer(controller);\n      }\n\n      buffer += chunk.payload.text;\n      bufferedChunk = chunk as SmoothableChunk<OUTPUT>;\n      bufferedMetadata = chunk.metadata ?? bufferedMetadata;\n      bufferedProviderMetadata = chunk.payload.providerMetadata ?? bufferedProviderMetadata;\n\n      let match: string | null | undefined;\n      while ((match = detectChunk(buffer)) != null) {\n        enqueueBufferedText(controller, match);\n        buffer = buffer.slice(match.length);\n\n        if (delayInMs !== null) {\n          await wait(delayInMs);\n        }\n      }\n    },\n    flush(controller) {\n      flushBuffer(contro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