UNPKG

@mastra/core

Version:
10,219 lines • 403 kB
import { n as __exportAll } from "./rolldown-runtime-tIEjjQTE.js";
import { d as attachModelStreamTransport, f as isDataChunk, i as resolveModelConfig, p as readModelStreamTransport } from "./llm-vu4qB_Xw.js";
import { B as getResponseProviderItemIdFromPart, G as RESPONSE_ITEM_ID_PROVIDERS, K as RESPONSE_RESULT_ITEM_ID_KEY, f as coreContentToString, n as MessageList, p as messagesAreEqual, t as convertMessages } from "./message-list-MEvVLv9o.js";
import { S as resolveObservabilityContext, x as createObservabilityContext } from "./observability-D3dpuDDk.js";
import { t as MastraBase } from "./base-CKLWBhDo.js";
import { i as MastraError, n as ErrorDomain, o as getErrorFromUnknown, t as ErrorCategory } from "./error-oh2DLsP2.js";
import { s as getRootExportSpan, t as executeWithContext } from "./utils-DU_pU5SK.js";
import { l as mastraDBMessageToSignal, n as createSignal } from "./signals-CqR_iWkg.js";
import { c as parsePartialJson, d as JSONParseError, f as TypeValidationError, o as isDeepEqualData, t as NoObjectGeneratedError, u as APICallError } from "./dist-TPVqg8oV.js";
import { a as sanitizeToolName } from "./to-prompt-BsDtVXrf.js";
import { t as EntityType } from "./storage-Cc50aQAp.js";
import { i as isAgentWorkflowTool } from "./toolchecks-CI0TngFS.js";
import { s as isValidationError } from "./tool-CXFwLwlu.js";
import { u as RequestContext } from "./request-context-COnZHt2-.js";
import { MISSING, normalizePredicatePath } from "./predicate/index.js";
import { isStandardSchemaWithJSON, standardSchemaToJSONSchema, toStandardSchema } from "./schema/index.js";
import { n as DefaultGeneratedFileWithType, t as DefaultGeneratedFile } from "./file-DGZrR5f7.js";
import { n as isUrlString } from "./content-CFBIylxS.js";
import EventEmitter$1, { EventEmitter } from "events";
import { ReadableStream as ReadableStream$1, TransformStream as TransformStream$1, WritableStream as WritableStream$1 } from "stream/web";
import { AnthropicSchemaCompatLayer, applyCompatLayer, isZodType } from "@mastra/schema-compat";
// src/mastra/run-scope.ts
/**
* Create a new {@link RunScopeKey}. Each call produces a fresh `Symbol`, so two
* keys with the same label do not collide.
*/
function createRunScopeKey(label) {
	return Symbol(label);
}
var MapRunScope = class {
	#slots = /* @__PURE__ */ new Map();
	get(key) {
		return this.#slots.get(key);
	}
	getOrThrow(key) {
		const sym = key;
		if (!this.#slots.has(sym)) throw new Error(`RunScope: missing required slot ${sym.toString()}`);
		return this.#slots.get(sym);
	}
	set(key, value) {
		this.#slots.set(key, value);
	}
	delete(key) {
		this.#slots.delete(key);
	}
	has(key) {
		return this.#slots.has(key);
	}
	get size() {
		return this.#slots.size;
	}
};
function createRunScope() {
	return new MapRunScope();
}
// src/stream/base/input.ts
/**
* Safely enqueue a chunk into a ReadableStreamDefaultController.
* Returns true if the enqueue succeeded, false if the controller was already closed/errored.
*
* Prefer this over checking desiredSize before enqueue, because desiredSize === 0
* indicates backpressure (queue full, stream still open) — not closure.
* Guarding on desiredSize would silently drop chunks under normal backpressure.
*/
function safeEnqueue(controller, chunk) {
	try {
		controller.enqueue(chunk);
		return true;
	} catch {
		return false;
	}
}
/**
* Safely close a ReadableStreamDefaultController.
* Returns true if the close succeeded, false if the controller was already closed/errored.
*/
function safeClose(controller) {
	try {
		controller.close();
		return true;
	} catch {
		return false;
	}
}
/**
* Safely signal an error on a ReadableStreamDefaultController.
* Returns true if the error succeeded, false if the controller was already closed/errored.
*/
function safeError(controller, error) {
	try {
		controller.error(error);
		return true;
	} catch {
		return false;
	}
}
var MastraModelInput = class extends MastraBase {
	initialize({ runId, createStream, onResult }) {
		const self = this;
		let outputStream;
		outputStream = new ReadableStream({ async start(controller) {
			try {
				const stream = await createStream();
				attachModelStreamTransport(outputStream, readModelStreamTransport(stream));
				const initialChunks = onResult({
					warnings: stream.warnings,
					request: stream.request,
					rawResponse: stream.rawResponse || stream.response || {}
				});
				if (initialChunks) for (const chunk of Array.isArray(initialChunks) ? initialChunks : [initialChunks]) controller.enqueue(chunk);
				await self.transform({
					runId,
					stream: stream.stream,
					controller
				});
				safeClose(controller);
			} catch (error) {
				safeError(controller, error);
			}
		} });
		return outputStream;
	}
};
// src/stream/aisdk/v5/compat/ui-message.ts
function convertFullStreamChunkToUIMessageStream({ part, messageMetadataValue, sendReasoning, sendSources, onError, sendStart, sendFinish, responseMessageId }) {
	const partType = part.type;
	switch (partType) {
		case "text-start": return {
			type: "text-start",
			id: part.id,
			...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}
		};
		case "text-delta": return {
			type: "text-delta",
			id: part.id,
			delta: part.text,
			...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}
		};
		case "text-end": return {
			type: "text-end",
			id: part.id,
			...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}
		};
		case "reasoning-start": return {
			type: "reasoning-start",
			id: part.id,
			...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}
		};
		case "reasoning-delta":
			if (sendReasoning) return {
				type: "reasoning-delta",
				id: part.id,
				delta: part.text,
				...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}
			};
			return;
		case "reasoning-end": return {
			type: "reasoning-end",
			id: part.id,
			...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}
		};
		case "file": {
			const base64 = part.file.base64;
			return {
				type: "file",
				mediaType: part.file.mediaType,
				url: isUrlString(base64) ? base64 : `data:${part.file.mediaType};base64,${base64}`
			};
		}
		case "source":
			if (sendSources && part.sourceType === "url") return {
				type: "source-url",
				sourceId: part.id,
				url: part.url,
				title: part.title,
				...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}
			};
			if (sendSources && part.sourceType === "document") return {
				type: "source-document",
				sourceId: part.id,
				mediaType: part.mediaType,
				title: part.title,
				filename: part.filename,
				...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}
			};
			return;
		case "tool-input-start": return {
			type: "tool-input-start",
			toolCallId: part.id,
			toolName: part.toolName,
			...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {},
			...part.dynamic != null ? { dynamic: part.dynamic } : {}
		};
		case "tool-input-delta": return {
			type: "tool-input-delta",
			toolCallId: part.id,
			inputTextDelta: part.delta
		};
		case "tool-call": return {
			type: "tool-input-available",
			toolCallId: part.toolCallId,
			toolName: part.toolName,
			input: part.input,
			...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {},
			...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},
			...part.dynamic != null ? { dynamic: part.dynamic } : {}
		};
		case "tool-result": return {
			type: "tool-output-available",
			toolCallId: part.toolCallId,
			output: part.output,
			...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {},
			...part.dynamic != null ? { dynamic: part.dynamic } : {},
			...part.preliminary != null ? { preliminary: part.preliminary } : {}
		};
		case "tool-output": return { ...part.output };
		case "tool-error": return {
			type: "tool-output-error",
			toolCallId: part.toolCallId,
			errorText: onError(part.error),
			...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {},
			...part.dynamic != null ? { dynamic: part.dynamic } : {}
		};
		case "error": return {
			type: "error",
			errorText: onError(part.error)
		};
		case "start-step": return { type: "start-step" };
		case "finish-step": return { type: "finish-step" };
		case "start":
			if (sendStart) return {
				type: "start",
				...messageMetadataValue != null ? { messageMetadata: messageMetadataValue } : {},
				...responseMessageId != null ? { messageId: responseMessageId } : {}
			};
			return;
		case "finish":
			if (sendFinish) return {
				type: "finish",
				...part.finishReason != null ? { finishReason: part.finishReason } : {},
				...messageMetadataValue != null ? { messageMetadata: messageMetadataValue } : {}
			};
			return;
		case "abort": return part;
		case "tool-input-end": return;
		case "raw": return;
		default: throw new Error(`Unknown chunk type: ${partType}`);
	}
}
// src/stream/aisdk/v5/compat/delayed-promise.ts
/**
* Delayed promise. It is only constructed once the value is accessed.
* This is useful to avoid unhandled promise rejections when the promise is created
* but not accessed.
*/
var DelayedPromise = class {
	status = { type: "pending" };
	_promise;
	_resolve = void 0;
	_reject = void 0;
	get promise() {
		if (this._promise) return this._promise;
		this._promise = new Promise((resolve, reject) => {
			if (this.status.type === "resolved") {
				resolve(this.status.value);
				return;
			}
			if (this.status.type === "rejected") {
				reject(this.status.error);
				return;
			}
			this._resolve = resolve;
			this._reject = reject;
		});
		return this._promise;
	}
	resolve(value) {
		this.status = {
			type: "resolved",
			value
		};
		if (!this._promise) return;
		if (this._resolve) {
			const resolve = this._resolve;
			this._resolve = void 0;
			resolve(value);
			return;
		}
		this._promise = this._promise.then(() => value);
	}
	reject(error) {
		this.status = {
			type: "rejected",
			error
		};
		if (this._promise) this._reject?.(error);
	}
};
// src/stream/aisdk/v5/compat/consume-stream.ts
async function consumeStream$1({ stream, onError, logger }) {
	let reader;
	try {
		reader = stream.getReader();
		while (true) {
			const { done } = await reader.read();
			if (done) break;
		}
	} catch (error) {
		logger?.error("consumeStream error", error);
		onError?.(error);
	} finally {
		reader?.releaseLock();
	}
}
// src/loop/timeout.ts
var MastraTimeoutError = class extends Error {
	timeoutType;
	timeoutMs;
	constructor({ timeoutType, timeoutMs }) {
		super(timeoutType === "total" ? `Agent execution timed out after ${timeoutMs}ms (modelSettings.timeout.totalMs)` : timeoutType === "firstChunk" ? `Model call timed out before first content after ${timeoutMs}ms (modelSettings.timeout.firstChunkMs)` : `Model call timed out after ${timeoutMs}ms (modelSettings.timeout.stepMs)`);
		this.name = "MastraTimeoutError";
		this.timeoutType = timeoutType;
		this.timeoutMs = timeoutMs;
	}
};
/**
* How long a total deadline's memory save may hold back the deadline error. A save that takes longer
* (a hung store) finishes in the background; the caller still sees the deadline on time.
*/
const DEADLINE_SAVE_WAIT_MS = 1e3;
/** 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. */
const DEADLINE_SAVE_CLAIM_HOLD_MS = 3e4;
/** Resolves when `promise` settles or `ms` passes, whichever is first. Never rejects. */
function settledOrElapsed(promise, ms) {
	let timer;
	return Promise.race([promise.then(() => {}, () => {}), new Promise((resolve) => {
		timer = setTimeout(resolve, ms);
	})]).finally(() => clearTimeout(timer));
}
function isMastraTimeoutError(error) {
	return error instanceof MastraTimeoutError;
}
/**
* Returns the abort reason of a signal, if it has been aborted.
*/
function getAbortReason(signal) {
	return signal?.aborted ? signal.reason : void 0;
}
/**
* Composes a caller-supplied abort signal with a time budget.
*
* When `timeoutMs` is undefined this is a pass-through: the parent signal is returned
* unchanged and no timer is created.
*
* Set `detachParentOnCleanup: false` when the parent signal lives no longer than the
* derived signal and `cleanup` may run while consumers still hold the derived signal:
* cleanup then only clears the timer, so a later parent abort still propagates.
*/
function createTimeoutAbortSignal({ parentSignal, timeoutMs, timeoutType, detachParentOnCleanup = true }) {
	if (typeof timeoutMs !== "number" || !Number.isFinite(timeoutMs) || timeoutMs <= 0) return {
		signal: parentSignal,
		cleanup: () => {}
	};
	const controller = new AbortController();
	let rejectTimeout;
	const timeoutPromise = new Promise((_resolve, reject) => {
		rejectTimeout = reject;
	});
	timeoutPromise.catch(() => {});
	const timer = setTimeout(() => {
		const error = new MastraTimeoutError({
			timeoutType,
			timeoutMs
		});
		controller.abort(error);
		rejectTimeout?.(error);
	}, timeoutMs);
	timer.unref?.();
	const onParentAbort = () => {
		controller.abort(parentSignal?.reason);
	};
	if (parentSignal) {
		if (parentSignal.aborted) onParentAbort();
		else parentSignal.addEventListener("abort", onParentAbort, { once: true });
	}
	return {
		signal: controller.signal,
		timeoutPromise,
		cleanup: () => {
			clearTimeout(timer);
			if (detachParentOnCleanup) parentSignal?.removeEventListener("abort", onParentAbort);
		}
	};
}
/**
* Rejects as soon as `signal` aborts, otherwise resolves with `promise`.
*
* Guards against providers that ignore `abortSignal` and would otherwise hang past
* their budget.
*/
/**
* Keeps a budget in force while a stream is consumed.
*
* Establishing a stream is rarely the slow part — a provider can open one and then stall
* mid-emission — so the budget has to stay armed until the stream ends. Errors the stream
* with the abort reason if the signal fires before it completes, and cancels the upstream
* so the provider connection is not left dangling.
*
* `onSettled` runs exactly once, whether the stream completes, errors or aborts.
*/
function guardStreamWithAbort(stream, signal, onSettled) {
	if (!signal) {
		if (!onSettled) return stream;
		return stream.pipeThrough(new TransformStream({ flush: () => onSettled() }));
	}
	const reader = stream.getReader();
	let settled = false;
	const settle = () => {
		if (settled) return;
		settled = true;
		onSettled?.();
	};
	return new ReadableStream({
		async pull(controller) {
			try {
				const { done, value } = await raceAgainstAbort(reader.read(), signal);
				if (done) {
					settle();
					controller.close();
					return;
				}
				controller.enqueue(value);
			} catch (error) {
				settle();
				reader.cancel(error).catch(() => {});
				controller.error(error);
			}
		},
		cancel(reason) {
			settle();
			return reader.cancel(reason);
		}
	});
}
function guardStreamUntilMatch(stream, signal, matches, onMatchedOrSettled) {
	if (!signal) return stream;
	const reader = stream.getReader();
	let active = true;
	const settle = () => {
		if (!active) return;
		active = false;
		onMatchedOrSettled();
	};
	return new ReadableStream({
		async pull(controller) {
			try {
				const result = active ? await raceAgainstAbort(reader.read(), signal) : await reader.read();
				if (result.done) {
					settle();
					controller.close();
					return;
				}
				if (matches(result.value)) settle();
				controller.enqueue(result.value);
			} catch (error) {
				settle();
				reader.cancel(error).catch(() => {});
				controller.error(error);
			}
		},
		cancel(reason) {
			settle();
			return reader.cancel(reason);
		}
	});
}
function raceAgainstAbort(promise, signal) {
	if (!signal) return promise;
	if (signal.aborted) {
		promise.catch(() => {});
		return Promise.reject(signal.reason ?? /* @__PURE__ */ new Error("Aborted"));
	}
	return new Promise((resolve, reject) => {
		const onAbort = () => {
			reject(signal.reason ?? /* @__PURE__ */ new Error("Aborted"));
		};
		signal.addEventListener("abort", onAbort, { once: true });
		promise.then((value) => {
			signal.removeEventListener("abort", onAbort);
			resolve(value);
		}, (error) => {
			signal.removeEventListener("abort", onAbort);
			reject(error);
		});
	});
}
// src/agent/state-signals.ts
function isPlainObject$2(value) {
	return typeof value === "object" && value !== null && !Array.isArray(value);
}
function getStateSignalsMetadata(threadMetadata) {
	if (!threadMetadata) return {};
	const mastra = threadMetadata.mastra;
	if (!isPlainObject$2(mastra)) return {};
	const stateSignals = mastra.stateSignals;
	return isPlainObject$2(stateSignals) ? stateSignals : {};
}
function setStateSignalMetadata(threadMetadata, stateId, tracking) {
	const existing = threadMetadata ?? {};
	const existingMastra = isPlainObject$2(existing.mastra) ? existing.mastra : {};
	const existingStateSignals = isPlainObject$2(existingMastra.stateSignals) ? existingMastra.stateSignals : {};
	return {
		...existing,
		mastra: {
			...existingMastra,
			stateSignals: {
				...existingStateSignals,
				[stateId]: tracking
			}
		}
	};
}
function signalCreatedAt(signal) {
	const timestamp = (signal.createdAt instanceof Date ? signal.createdAt : new Date(signal.createdAt)).getTime();
	return Number.isNaN(timestamp) ? 0 : timestamp;
}
function sortStateSignals(signals) {
	return signals.map((signal, index) => ({
		signal,
		index
	})).sort((left, right) => signalCreatedAt(left.signal) - signalCreatedAt(right.signal) || left.index - right.index).map(({ signal }) => signal);
}
function dbMessagesToStateSignals(messages, stateId, threadId) {
	return sortStateSignals(messages.filter((message) => message.role === "signal").map((message) => {
		try {
			return mastraDBMessageToSignal(message);
		} catch {
			return;
		}
	}).filter((signal) => signal?.type === "state" && isPlainObject$2(signal.metadata?.state) && (!stateId || signal.metadata.state.id === stateId) && signal.metadata.state.threadId === threadId));
}
function getActiveStateSignals(messageList, stateId, threadId) {
	return dbMessagesToStateSignals(messageList.get.all.db(), stateId, threadId);
}
function mergeStateSignals(...signalGroups) {
	const signalsById = /* @__PURE__ */ new Map();
	for (const signal of signalGroups.flat()) signalsById.set(signal.id, signal);
	return sortStateSignals([...signalsById.values()]);
}
function deriveStateSignalHistory(activeStateSignals) {
	const sortedStateSignals = sortStateSignals(activeStateSignals);
	const lastSnapshotIndex = sortedStateSignals.findLastIndex((signal) => signal.metadata?.state?.mode === "snapshot");
	const lastSnapshot = lastSnapshotIndex >= 0 ? sortedStateSignals[lastSnapshotIndex] : void 0;
	const deltasSinceSnapshot = sortedStateSignals.slice(lastSnapshotIndex + 1).filter((signal) => signal.metadata?.state?.mode === "delta");
	return {
		activeStateSignals: sortedStateSignals,
		contextWindow: { hasSnapshot: Boolean(lastSnapshot) },
		lastSnapshot,
		deltasSinceSnapshot
	};
}
async function resolveStateSignalHistory({ messageList, memory, threadId, stateId, tracking }) {
	const localStateSignals = getActiveStateSignals(messageList, stateId, threadId);
	const localHistory = deriveStateSignalHistory(localStateSignals);
	const contextWindow = localHistory.contextWindow;
	if (localHistory.contextWindow.hasSnapshot || !tracking?.lastSnapshotSignalId) return {
		...localHistory,
		contextWindow
	};
	const memoryStore = await memory.storage.getStore("memory");
	if (!memoryStore) return {
		...localHistory,
		contextWindow
	};
	const trackedSignalIds = /* @__PURE__ */ new Set();
	for (const activeCopy of tracking.activeCopies ?? []) trackedSignalIds.add(activeCopy.id);
	trackedSignalIds.add(tracking.lastSnapshotSignalId);
	if (trackedSignalIds.size === 0 || typeof memoryStore.listMessagesById !== "function") return {
		...localHistory,
		contextWindow
	};
	const resolvedStateSignals = mergeStateSignals(dbMessagesToStateSignals((await memoryStore.listMessagesById({ messageIds: [...trackedSignalIds] })).messages, stateId, threadId), localStateSignals);
	return {
		...deriveStateSignalHistory(resolvedStateSignals.length > 0 ? resolvedStateSignals : localStateSignals),
		contextWindow
	};
}
function createStateSignalInput(input, options) {
	const stateId = input.id ?? options?.defaultId;
	if (!stateId) throw new Error("state signal id is required");
	if (!input.cacheKey) throw new Error("state signal cacheKey is required");
	const mode = input.mode ?? "snapshot";
	const { id: _stateId, cacheKey, mode: _mode, value, delta, metadata, ...signalInput } = input;
	return {
		stateId,
		signal: createSignal({
			...signalInput,
			type: "state",
			tagName: signalInput.tagName ?? "state",
			acceptedAt: options?.acceptedAt,
			metadata: {
				...metadata,
				state: {
					...isPlainObject$2(metadata?.state) ? metadata.state : {},
					id: stateId,
					cacheKey,
					mode
				},
				...value !== void 0 ? { value } : {},
				...delta !== void 0 ? { delta } : {}
			}
		}),
		mode,
		cacheKey
	};
}
async function applyStateSignal({ input, memory, thread, resourceId, threadId, memoryConfig, messageList, activeStateSignals, defaultId, acceptedAt, beforeAddSignal, writeSignal }) {
	const { stateId, signal, cacheKey, mode } = createStateSignalInput(input, {
		defaultId,
		acceptedAt
	});
	const activeSignals = activeStateSignals ?? (messageList ? getActiveStateSignals(messageList, stateId, threadId) : []);
	const tracking = getStateSignalsMetadata(thread.metadata)[stateId];
	const usesActiveWindow = Boolean(messageList || activeStateSignals);
	const hasActiveCopy = activeSignals.some((signal) => signal.metadata?.state?.cacheKey === cacheKey && signal.metadata?.state?.mode === mode);
	const matchesCurrentState = tracking?.currentCacheKey === cacheKey && (tracking.currentMode === mode || !tracking.currentMode && hasActiveCopy);
	if (matchesCurrentState && (!usesActiveWindow || hasActiveCopy)) return {
		skipped: true,
		reason: "unchanged",
		stateId,
		tracking
	};
	const previousVersion = typeof tracking?.version === "number" ? tracking.version : 0;
	const version = matchesCurrentState ? previousVersion || 1 : previousVersion + 1;
	const updatedSignal = createSignal({
		...signal,
		metadata: {
			...signal.metadata,
			state: {
				...isPlainObject$2(signal.metadata?.state) ? signal.metadata.state : {},
				id: stateId,
				threadId,
				cacheKey,
				version,
				mode
			}
		}
	});
	beforeAddSignal?.();
	if (messageList) messageList.addSignal(updatedSignal);
	await writeSignal?.(updatedSignal);
	const updatedAt = (/* @__PURE__ */ new Date()).toISOString();
	const updatedActiveSignals = [...activeSignals, updatedSignal];
	const nextTracking = {
		currentCacheKey: cacheKey,
		currentMode: mode,
		version,
		lastSignalId: updatedSignal.id,
		lastSnapshotSignalId: mode === "snapshot" ? updatedSignal.id : tracking?.lastSnapshotSignalId,
		updatedAt,
		activeCopies: updatedActiveSignals.map((activeSignal) => {
			const activeStateMetadata = isPlainObject$2(activeSignal.metadata?.state) ? activeSignal.metadata.state : {};
			return {
				id: activeSignal.id,
				...typeof activeStateMetadata.cacheKey === "string" ? { cacheKey: activeStateMetadata.cacheKey } : {},
				...activeStateMetadata.mode === "snapshot" || activeStateMetadata.mode === "delta" ? { mode: activeStateMetadata.mode } : {},
				...typeof activeStateMetadata.version === "number" ? { version: activeStateMetadata.version } : {}
			};
		})
	};
	await memory.saveThread({
		thread: {
			...thread,
			id: threadId,
			resourceId: thread.resourceId ?? resourceId,
			createdAt: thread.createdAt ?? /* @__PURE__ */ new Date(),
			updatedAt: new Date(updatedAt),
			metadata: setStateSignalMetadata(thread.metadata, stateId, nextTracking)
		},
		memoryConfig
	});
	return {
		skipped: false,
		signal: updatedSignal,
		stateId,
		version,
		tracking: nextTracking
	};
}
// src/agent/utils.ts
const supportedLanguageModelSpecifications = [
	"v2",
	"v3",
	"v4"
];
const isSupportedLanguageModel = (model) => {
	return supportedLanguageModelSpecifications.includes(model.specificationVersion);
};
function isStructuredOutputFormatError(error) {
	return JSONParseError.isInstance(error) || NoObjectGeneratedError.isInstance(error) || TypeValidationError.isInstance(error) || error instanceof MastraError && (error.id === "STRUCTURED_OUTPUT_OBJECT_UNDEFINED" || error.id === "STRUCTURED_OUTPUT_SCHEMA_VALIDATION_FAILED" || error.id === "STRUCTURED_OUTPUT_TRUNCATED");
}
async function tryGenerateWithJsonFallback(agent, prompt, options) {
	if (!options.structuredOutput?.schema) throw new MastraError({
		id: "STRUCTURED_OUTPUT_OPTIONS_REQUIRED",
		domain: ErrorDomain.AGENT,
		category: ErrorCategory.USER,
		text: "structuredOutput is required to use tryGenerateWithJsonFallback"
	});
	try {
		const result = await agent.generate(prompt, options);
		if (result.object === void 0) throw new MastraError({
			id: "STRUCTURED_OUTPUT_OBJECT_UNDEFINED",
			domain: ErrorDomain.AGENT,
			category: ErrorCategory.USER,
			text: "structuredOutput object is undefined"
		});
		return result;
	} catch (error) {
		if (!isStructuredOutputFormatError(error)) throw error;
		agent.__getLogger().warn("Error in tryGenerateWithJsonFallback. Attempting fallback.", error);
		const result = await agent.generate(prompt, {
			...options,
			structuredOutput: {
				...options.structuredOutput,
				jsonPromptInjection: options.structuredOutput.jsonPromptInjection === "inline" || options.structuredOutput.jsonPromptInjection === "system" ? options.structuredOutput.jsonPromptInjection : true
			}
		});
		if (result.object === void 0) throw new MastraError({
			id: "STRUCTURED_OUTPUT_OBJECT_UNDEFINED",
			domain: ErrorDomain.AGENT,
			category: ErrorCategory.USER,
			text: "structuredOutput object is undefined"
		});
		return result;
	}
}
async function tryStreamWithJsonFallback(agent, prompt, options) {
	if (!options.structuredOutput?.schema) throw new MastraError({
		id: "STRUCTURED_OUTPUT_OPTIONS_REQUIRED",
		domain: ErrorDomain.AGENT,
		category: ErrorCategory.USER,
		text: "structuredOutput is required to use tryStreamWithJsonFallback"
	});
	const { onStream, onStreamAttempt, onStreamFinish, fallbackJsonPromptInjection, ...streamOptions } = options;
	try {
		await onStreamAttempt?.();
		const result = await agent.stream(prompt, streamOptions);
		onStream?.(result);
		try {
			if (await result.object === void 0) throw new MastraError({
				id: "STRUCTURED_OUTPUT_OBJECT_UNDEFINED",
				domain: ErrorDomain.AGENT,
				category: ErrorCategory.USER,
				text: "structuredOutput object is undefined"
			});
			return result;
		} finally {
			await onStreamFinish?.(result);
		}
	} catch (error) {
		if (!isStructuredOutputFormatError(error)) throw error;
		agent.__getLogger().warn("Error in tryStreamWithJsonFallback. Attempting fallback.", error);
		await onStreamAttempt?.();
		const result = await agent.stream(prompt, {
			...streamOptions,
			structuredOutput: {
				...streamOptions.structuredOutput,
				jsonPromptInjection: fallbackJsonPromptInjection ?? (streamOptions.structuredOutput.jsonPromptInjection === "inline" || streamOptions.structuredOutput.jsonPromptInjection === "system" ? streamOptions.structuredOutput.jsonPromptInjection : true)
			}
		});
		onStream?.(result);
		try {
			if (await result.object === void 0) throw new MastraError({
				id: "STRUCTURED_OUTPUT_OBJECT_UNDEFINED",
				domain: ErrorDomain.AGENT,
				category: ErrorCategory.USER,
				text: "structuredOutput object is undefined"
			});
			return result;
		} finally {
			await onStreamFinish?.(result);
		}
	}
}
/**
* Sentinel strings some models emit for the optional `suspendedToolRunId` auto-resume
* field when they mean "no value". These are serialization artifacts, not run ids —
* treating them as real ids defeats every falsy-based guard downstream (#23739).
*/
const SUSPENDED_TOOL_RUN_ID_SENTINELS = /* @__PURE__ */ new Set([
	"null",
	"undefined",
	"none",
	"nil"
]);
/**
* Normalizes a model-supplied `suspendedToolRunId` at the LLM trust boundary.
* Returns `undefined` for non-strings, empty/whitespace-only strings, and known
* serialization sentinels (`"null"`, `"undefined"`, `"none"`, `"nil"`, case-insensitive)
* so callers can treat them exactly as if the model had omitted the field.
* Any other string is returned unchanged (it may be a framework-persisted or
* hook-supplied run id, which are not required to be UUIDs).
*/
function resolveSuspendedToolRunId(value) {
	if (typeof value !== "string") return void 0;
	const trimmed = value.trim();
	if (!trimmed) return void 0;
	if (SUSPENDED_TOOL_RUN_ID_SENTINELS.has(trimmed.toLowerCase())) return void 0;
	return value;
}
function resolveThreadIdFromArgs(args) {
	let resolved;
	if (args?.memory?.thread) {
		if (typeof args.memory.thread === "string") resolved = { id: args.memory.thread };
		else if (typeof args.memory.thread === "object" && args.memory.thread.id) resolved = args.memory.thread;
	}
	if (!resolved && args?.threadId) resolved = { id: args.threadId };
	if (args.overrideId) return {
		...resolved || {},
		id: args.overrideId
	};
	return resolved;
}
// src/processors/is-processor-workflow.ts
/**
* Type guard to check if an object is a Workflow that can be used as a processor.
*
* Extracted to its own module so that `runner.ts` (and by extension
* `stream/base/output.ts`) can use it without loading the full processors
* barrel — which re-exports every built-in processor, many of which import
* from the agent barrel and create ESM init-time cycles.
*/
function isProcessorWorkflow(obj) {
	return obj !== null && typeof obj === "object" && "id" in obj && typeof obj.id === "string" && "inputSchema" in obj && "outputSchema" in obj && "execute" in obj && typeof obj.execute === "function" && !("processInput" in obj) && !("processInputStep" in obj) && !("processOutputStream" in obj) && !("processOutputResult" in obj) && !("processOutputStep" in obj) && !("processToolResult" in obj) && !("processLLMRequest" in obj) && !("processAPIError" in obj);
}
// src/loop/shared/normalize-model-output.ts
/**
* Normalize modelOutput from toModelOutput() into the lossless V2-authored
* storage shape kept in `providerMetadata.mastra.modelOutput`.
*
* Base64 payloads (`image-data`/`file-data`, and `image-url` parts carrying a
* `data:` URI) are stored as the V2 `media` content type. Remote-URL parts
* (`image-url`/`file-url`) are kept as-is because `media.data` is Base64-only —
* the spec-boundary prompt converters (aiV5PromptToAIV6Prompt /
* aiV5PromptToAIV7Prompt) emit the correct URL-shaped part for the target
* model's specification version.
*
* `providerOptions` and any other author-supplied keys are preserved.
*/
function normalizeModelOutput(output) {
	if (output == null || typeof output !== "object") return output;
	const obj = output;
	if (obj.type !== "content" || !Array.isArray(obj.value)) return output;
	return {
		...obj,
		value: obj.value.map((item) => {
			if (item == null || typeof item !== "object") return item;
			const part = item;
			if (part.type === "image-url" && typeof part.url === "string") {
				if (!/^data:/i.test(part.url)) return part;
				const mediaType = typeof part.mediaType === "string" && part.mediaType ? part.mediaType : part.url.slice(5, part.url.indexOf(";")) || "image/jpeg";
				const rest = { ...part };
				delete rest.url;
				return {
					...rest,
					type: "media",
					data: part.url,
					mediaType
				};
			}
			if (part.type === "image-data" && typeof part.data === "string") return {
				...part,
				type: "media",
				mediaType: part.mediaType ?? "image/jpeg"
			};
			if (part.type === "file-data" && typeof part.data === "string") return {
				...part,
				type: "media",
				mediaType: part.mediaType ?? "application/octet-stream"
			};
			return part;
		})
	};
}
/**
* Model output for a tool that declares `toModelOutput` but resolved with a
* validation error that Mastra's own validation produced (input, request
* context, suspend data or output validation failed).
*
* The mapper is typed to receive only the tool's output, so it is skipped and
* the model receives the model-facing form of the error, which leaves out the
* raw values the full error quotes. Tagging it `error-json` keeps the
* provider-level error flag (for example Anthropic's `is_error`) so the model
* treats the call as failed and can retry.
*/
function validationErrorModelOutput(error) {
	return {
		type: "error-json",
		value: error
	};
}
// src/loop/shared/steps/tool-result-commit-core.ts
/**
* Shared `toModelOutput` computation for the tool-result commit.
*
* Runs the tool's `toModelOutput` mapper under a MAPPING child span, normalizes
* media parts into the AI SDK's LanguageModelV2ToolResultOutput shape, and
* merges the mapped output into `providerMetadata.mastra.modelOutput`.
*
* A validation error Mastra produced for this call (`validationError`) is not
* the tool's output, so it skips the mapper: `toModelOutput` is typed to
* receive only successful output, and the model must see the error to retry.
* Its model-facing form, without the raw values the full error quotes, is
* stored as an `error-json` model output instead. A result that merely has a
* validation error's fields is mapped like any other result.
*
* A nullish mapping result means "no special mapping needed" — the raw result
* is already what the model should see. The key is not written in that case,
* because MessageList keys off its presence and would otherwise override the
* real result with `undefined`, producing a tool message with no output.
*
* Mapping failures propagate so a broken `toModelOutput` fails the run.
*
* A result from a tool an agent built from its `workflows` also gets
* `mastra.workflowTool: true`. Workflow tools can't define `toModelOutput`, so
* this per-call marker is how tracing knows it may show their result in the
* next MODEL_STEP input (#30219). The tool output the model receives is unchanged.
*
* Deliberately NOT consolidated with the background-task path
* (`background-task-result-core.ts`), which always overwrites
* `mastra.modelOutput` (null included) to clear the placeholder-derived value
* and runs without a tracing span. The presence-keyed omit here vs the
* always-overwrite there are both load-bearing; see its docblock.
*/
async function computeModelOutputProviderMetadata(deps) {
	const { tool, result } = deps;
	let modelOutput;
	if (tool?.toModelOutput && deps.validationError) modelOutput = validationErrorModelOutput(deps.validationError);
	else if (tool?.toModelOutput && result != null) {
		const mappingSpan = deps.parentSpan?.createChildSpan({
			type: "mapping",
			name: `tool output mapping: '${deps.toolName}'`,
			entityType: EntityType.TOOL,
			entityId: deps.toolName,
			entityName: deps.toolName,
			input: result,
			attributes: {
				mappingType: "toModelOutput",
				toolCallId: deps.toolCallId
			}
		});
		try {
			modelOutput = await tool.toModelOutput(result);
			modelOutput = normalizeModelOutput(modelOutput);
			mappingSpan?.end({ output: modelOutput });
		} catch (err) {
			mappingSpan?.error({
				error: err,
				endSpan: true
			});
			throw err;
		}
	}
	const existingMastra = deps.existingProviderMetadata?.mastra;
	const providerMetadata = withAgentWorkflowToolMarker({
		...deps.existingProviderMetadata,
		...modelOutput != null ? { mastra: {
			...existingMastra,
			modelOutput
		} } : {}
	}, tool);
	return providerMetadata && Object.keys(providerMetadata).length > 0 ? providerMetadata : void 0;
}
/**
* Adds `mastra.workflowTool: true` to a result's provider metadata when `tool`
* is one an agent built from its `workflows`; otherwise returns it unchanged.
* Shared by every engine path that records a tool result (#30219). The stored
* tool-invocation part holds call and result together, so prompts carry the
* marker on both the tool-call and tool-result parts, under `providerOptions.mastra`,
* which provider adapters don't read.
*/
function withAgentWorkflowToolMarker(providerMetadata, tool) {
	if (!isAgentWorkflowTool(tool)) return providerMetadata;
	return {
		...providerMetadata,
		mastra: {
			...providerMetadata?.mastra,
			workflowTool: true
		}
	};
}
/** The mapped `toModelOutput` value carried in `providerMetadata.mastra.modelOutput`, if any. */
function readModelOutput(providerMetadata) {
	return providerMetadata?.mastra?.modelOutput;
}
/** Whether any output processor (or processor workflow) can run `processToolResult`. */
function hasToolResultProcessor(processors) {
	return processors?.some((processor) => isProcessorWorkflow(processor) || typeof processor?.processToolResult === "function") ?? false;
}
/**
* A content snapshot of a tool result taken before `processToolResult` runs, so a
* processor that edits the result in place (same object, new contents) is still
* seen as having changed it. Undefined when the result can't be serialized; then
* only a replaced object counts as a change.
*/
function snapshotToolResult(result) {
	try {
		return JSON.stringify(result);
	} catch {
		return;
	}
}
/**
* The mapped output the next `processToolResult` should see: the one an earlier
* processor committed in `providerMetadata.mastra.modelOutput` (undefined when it
* cleared it), otherwise `fallback`, the output mapped before the hook.
*/
function latestProcessedModelOutput(messageList, toolCallId, fallback) {
	const mastra = (findCommittedToolInvocationPart(messageList, toolCallId)?.providerMetadata)?.mastra;
	if (!mastra || !("modelOutput" in mastra)) return fallback;
	return normalizeModelOutput(mastra.modelOutput) ?? void 0;
}
/**
* Resolve the model output after `processToolResult` ran.
*
* Processors rewrite a tool result by committing a `result`-state part through
* `messageList.updateToolInvocation`. That part may carry a replacement
* `providerMetadata.mastra.modelOutput` (e.g. resized or removed images); it
* then replaces the mapped output. A processor that only replaces the raw
* `result` gets it re-mapped through `toModelOutput`, so the model never sees
* the mapping of the value the processor replaced. Without either, the output
* mapped before the hook stands and `toModelOutput` is not called again. A
* result edited in place counts as replaced when its contents differ from
* `resultSnapshotBeforeProcessors`.
*
* When the tool resolved with Mastra's own validation error (`validationError`),
* a rewrite that is still a validation error (say, a redaction pass over every
* result) skips the mapper and sends the model-facing error, as the mapping
* before the hook did. A processor that replaced the error with any other value
* made that value the tool's output, so it is mapped.
*/
async function resolveModelOutputAfterToolResultProcessors(deps) {
	const part = findCommittedToolInvocationPart(deps.messageList, deps.toolCallId);
	const processorMastra = (part?.providerMetadata)?.mastra;
	const { mastra: previousMastra, ...otherNamespaces } = deps.providerMetadata ?? {};
	const { modelOutput: _previous, ...mastraWithoutModelOutput } = previousMastra ?? {};
	const withoutModelOutput = Object.keys(mastraWithoutModelOutput).length ? {
		...otherNamespaces,
		mastra: mastraWithoutModelOutput
	} : otherNamespaces;
	if (processorMastra && "modelOutput" in processorMastra) {
		const modelOutput = normalizeModelOutput(processorMastra.modelOutput);
		if (modelOutput == null) {
			delete processorMastra.modelOutput;
			return Object.keys(withoutModelOutput).length ? withoutModelOutput : void 0;
		}
		return {
			...withoutModelOutput,
			mastra: {
				...mastraWithoutModelOutput,
				modelOutput
			}
		};
	}
	const resultAfterProcessors = part ? part.toolInvocation.result : deps.resultBeforeProcessors;
	if (!(resultAfterProcessors !== deps.resultBeforeProcessors || deps.resultSnapshotBeforeProcessors !== void 0 && snapshotToolResult(resultAfterProcessors) !== deps.resultSnapshotBeforeProcessors) || !deps.tool?.toModelOutput) return deps.providerMetadata;
	return computeModelOutputProviderMetadata({
		tool: deps.tool,
		toolName: deps.toolName,
		toolCallId: deps.toolCallId,
		result: resultAfterProcessors,
		validationError: isValidationError(resultAfterProcessors) ? deps.validationError : void 0,
		existingProviderMetadata: Object.keys(withoutModelOutput).length ? withoutModelOutput : void 0,
		parentSpan: deps.parentSpan
	});
}
function findCommittedToolInvocationPart(messageList, toolCallId) {
	const messages = messageList.get.all.db();
	for (let i = messages.length - 1; i >= 0; i--) {
		const msg = messages[i];
		if (!msg || msg.role !== "assistant" || !msg.content?.parts) continue;
		for (const part of msg.content.parts) if (part?.type === "tool-invocation" && part.toolInvocation?.toolCallId === toolCallId && part.toolInvocation.state === "result") return part;
	}
}
/**
* Shared per-result transcript commit: record one resolved
* tool call on the MessageList as `output-denied`, `output-error`, or
* `result`. Returns whether a matching invocation was found and updated.
*
* Adjudications:
* - `sanitizeToolName` on every commit: main-only since #13633 (Bedrock
*   rejects unsanitized hallucinated names on replay); dated drift — durable
*   adopts via this core.
* - `errorText` fallback to 'Tool execution failed': same drift class — an
*   empty error message otherwise persists a failure with no explanation.
* - `fallbackAppend` (durable true / main false): after a process hop the
*   merge step may operate on a MessageList rebuilt from serialized state
*   where the original call part is missing — losing a completed result is
*   worse than appending a standalone tool message. In main the list is the
*   same live object that recorded the call, so a miss indicates corruption
*   and appending would mask the real bug. C1-forced deliberate difference,
*   not drift.
*/
function commitToolResult(deps) {
	const { messageList, outcome } = deps;
	const toolName = sanitizeToolName(deps.toolName);
	if (outcome.kind === "denied") return messageList.updateToolInvocation({
		type: "tool-invocation",
		toolInvocation: {
			state: "output-denied",
			toolCallId: deps.toolCallId,
			toolName,
			args: deps.toolArgs,
			approval: outcome.approval
		}
	});
	const errorText = outcome.kind === "error" ? outcome.errorText ?? "Tool execution failed" : void 0;
	const updated = messageList.updateToolInvocation({
		type: "tool-invocation",
		toolInvocation: {
			...outcome.kind === "error" ? {
				state: "output-error",
				errorText,
				...outcome.result != null ? { result: outcome.result } : {}
			} : {
				state: "result",
				result: outcome.result
			},
			toolCallId: deps.toolCallId,
			toolName,
			args: deps.toolArgs,
			...deps.approval ? { approval: deps.approval } : {}
		},
		...deps.providerMetadata ? { providerMetadata: deps.providerMetadata } : {}
	});
	if (!updated && deps.fallbackAppend) messageList.add([{
		role: "tool",
		content: [{
			type: "tool-result",
			toolCallId: deps.toolCallId,
			toolName,
			result: outcome.kind === "error" ? errorText : outcome.result,
			isError: outcome.kind === "error"
		}]
	}], "response");
	return updated;
}
// src/memory/types.ts
function isPlainObject$1(value) {
	return typeof value === "object" && value !== null && !Array.isArray(value);
}
/**
* Thread metadata flag marking the title as user-pinned. Set by
* `session.thread.rename()` so Observational Memory's title extractor never
* overwrites a manual rename, and cleared (set to `false`) when the user
* explicitly regenerates the title via `generateThreadTitle()`.
*/
const TITLE_PINNED_THREAD_METADATA_KEY = "titlePinned";
/**
* Whether the thread's title is pinned against automatic updates.
*/
function isThreadTitlePinned(threadMetadata) {
	return threadMetadata?.[TITLE_PINNED_THREAD_METADATA_KEY] === true;
}
/**
* Helper to get OM metadata from a thread's metadata object.
* Returns undefined if not present or if the structure is invalid.
*/
function getThreadOMMetadata(threadMetadata) {
	if (!threadMetadata) return void 0;
	const mastra = threadMetadata.mastra;
	if (!isPlainObject$1(mastra)) return void 0;
	const om = mastra.om;
	if (!isPlainObject$1(om)) return void 0;
	return om;
}
/**
* Helper to set OM metadata on a thread's metadata object.
* Creates the nested structure if it doesn't exist.
* Returns a new metadata object (does not mutate the original).
* Safely handles cases where existing mastra/om values are not objects.
*/
function setThreadOMMetadata(threadMetadata, omMetadata) {
	const existing = threadMetadata ?? {};
	const existingMastra = isPlainObject$1(existing.mastra) ? existing.mastra : {};
	const existingOM = isPlainObject$1(existingMastra.om) ? existingMastra.om : {};
	return {
		...existing,
		mastra: {
			...existingMastra,
			om: {
				...existingOM,
				...omMetadata
			}
		}
	};
}
/**
* Parse and validate memory runtime context from RequestContext
* @param requestContext - The RequestContext to extract memory context from
* @returns The validated MemoryRequestContext or null if not available
* @throws Error if the context exists but is malformed
*/
function parseMemoryRequestContext(requestContext) {
	if (!requestContext) return null;
	const memoryContext = requestContext.get("MastraMemory");
	if (!memoryContext) return null;
	if (typeof memoryContext !== "object" || memoryContext === null) throw new Error(`Invalid MemoryRequestContext: expected object, got ${typeof memoryContext}`);
	const ctx = memoryContext;
	if (ctx.thread !== void 0) {
		if (typeof ctx.thread !== "object" || ctx.thread === null) throw new Error(`Invalid MemoryRequestContext.thread: expected object, got ${typeof ctx.thread}`);
		const thread = ctx.thread;
		if (typeof thread.id !== "string") throw new Error(`Invalid MemoryRequestContext.thread.id: expected string, got ${typeof thread.id}`);
	}
	if (ctx.resourceId !== void 0 && typeof ctx.resourceId !== "string") throw new Error(`Invalid MemoryRequestContext.resourceId: expected string, got ${typeof ctx.resourceId}`);
	return memoryContext;
}
/**
* Check if observational memory is enabled from a `boolean | ObservationalMemoryOptions` value.
*
* - `true` → enabled
* - `false` → disabled
* - `{ enabled: false }` → disabled
* - `{ ... }` (without `enabled: false`) → enabled
* - `undefined` → disabled
*/
function isObservationalMemoryEnabled(config) {
	if (config === true) return true;
	if (config === false || config === void 0) return false;
	return config.enabled !== false;
}
// src/storage/domains/workflows/state-patch.ts
function isObject(value) {
	return typeof value === "object" && value !== null && !Array.isArray(value);
}
/**
* The ops that turn `prev` into `next`. Both must be JSON values (no `undefined`, Dates or class
* instances). Unchanged values produce no ops.
* @experimental
*/
function diffState(prev, next) {
	const ops = [];
	diffValue(prev, next, [], ops);
	return ops;
}
function diffValue(prev, next, path, ops) {
	if (prev === next) return;
	if (Array.isArray(prev) && Array.isArray(next)) {
		if (next.length < prev.length) {
			ops.push({
				op: "set",
				path,
				value: next
			});
			return;
		}
		for (let i = 0; i < prev.length; i++) diffValue(prev[i], next[i], [...path, i], ops);
		for (let i = prev.length; i < next.length; i++) ops.push({
			op: "set",
			path: [...path, i],
			value: next[i]
		});
		return;
	}
	if (isObject(prev) && isObject(next)) {
		for (const key of Object.keys(prev)) if (!Object.hasOwn(next, key)) ops.push({
			op: "delete",
			path: [...path, key]
		});
		for (const key of Object.keys(next)) if (Object.hasOwn(prev, key)) diffValue(prev[key], next[key], [...path, key], ops);
		else ops.push({
			op: "set",
			path: [...path, key],
			value: next[key]
		});
		return;
	}
	ops.push({
		op: "set",
		path,
		value: next
	});
}
const OMITTED = Symbol("omitted");
/**
* `value`, the `key` property of its holder, one level deep as `JSON.stringify` serializes it:
* `toJSON` applied, boxed primitives unboxed, non-finite numbers as `null`, and `OMITTED` for
* what it leaves out. Objects and arrays are returned as they are.
*/
function jsonNode(value, key) {
	if (typeof value === "object" && value !== null || typeof value === "function" || typeof value === "bigint") {
		const toJSON = value.toJSON;
		if (typeof toJSON === "function") value = toJSON.call(value, key);
	}
	if (value instanceof Number) value = Number(value);
	else if (value instanceof String) value = String(value);
	else if (value instanceof Boolean) value = value.valueOf();
	switch (typeof value) {
		case "string":
		case "boolean":
		case "object": return value;
		case "number": return Number.isFinite(value) ? value + 0 : null;
		case "bigint": throw new TypeError("Do not know how to serialize a BigInt");
		default: return OMITTED;
	}
}
function arrayItem(array, i) {
	const item = jsonNode(array[i], String(i));
	return item === OMITTED ? null : item;
}
/** A JSON copy of a `jsonNode` result. Throws, as `JSON.stringify` does, on a cycle. */
function jsonCopy(node) {
	if (typeof node !== "object" || node === null) return node;
	if (typeof node.toJSON === "function") {
		if (Array.isArray(node)) node = node.slice();
		else {
			const { toJSON: _, ...rest } = node;
			node = rest;
		}
	}
	return JSON.parse(JSON.stringify(node));
}
/**
* `diffState(prev, JSON.parse(JSON.stringify(next)))` without copying `next`: `next` can be any
* JSON-serializable value and is compared as its JSON form, and only the values of `set` ops are
* copied. `prev` must be a JSON value. Throws a `TypeError`, as `JSON.stringify` does, when
* `next` has a cycle or a BigInt, or has no JSON form at all.
* @experimental
*/
function diffStateAsJson(prev, next) {
	const root = jsonNode(next, "");
	if (root === OMITTED) throw new TypeError(`A ${typeof next} has no JSON form`);
	const ops = [];
	diffJsonValue(prev, root, [], ops);
	return ops;
}
/**
* `diffValue` on `next`'s JSON form, which `jsonNode` gives one level at a time. Every part of
* `next` is either walked alongside `prev` or copied by `jsonCopy`, and `prev` is finite, so a
* cycle in `next` always reaches `jsonCopy`, which throws.
*/
function diffJsonValue(prev, next, path, ops) {
	if (typeof next !== "object" || next === null) {
		if (prev !== next) ops.push({
			op: "set",
			path,
			value: next
		});
		return;
	}
	if (Array.isArray(next)) {
		if (!Array.isArray(prev) || next.length < prev.length) {
			ops.push({
				op: "set",
				path,
				value: jsonCopy(next)
			});
			return;
		}
		for (let i = 0; i < prev.length; i++) diffJsonValue(prev[i], arrayItem(next, i), [...path, i], ops);
		for (let i = prev.length; i < next.length; i++) ops.push({
			op: "set",
			path: [...path, i],
			value: jsonCopy(arrayItem(next, i))
		});
		return;
	}
	if (!isObject(prev)) {
		ops.push({
			op: "set",
			path,
			value: jsonCopy(next)
		});
		return;
	}
	const kept = /* @__PURE__ */ new Map();
	for (const key of Object.keys(next)) {
		const value = jsonNode(next[key], key);
		if (value !== OMITTED) kept.set(key, value);
	}
	for (const key of Object.keys(prev)) if (!kept.has(key)) ops.push({
		op: "delete",
		path: [...path, key]
	});
	for (const [key, value] of kept) if (Object.hasOwn(prev, key)) diffJsonValue(prev[key], value, [...path, key], ops);
	else ops.push({
		op: "set",
		path: [...path, key],
		value: jsonCopy(value)
	});
}
function childOf(container, key) {
	return Object.hasOwn(container, key) ? container[key] : void 0;
}
function setChild(container, key, value) {
	Object.defineProperty(container, key, {
		value,
		writable: true,
		enumerable: true,
		configurable: true
	});
}
/**
* Apply `ops` to `root` in order and return the result: `root` itself, mutated, unless an op
* replaces the root. A `set` creates missing or non-container intermediates (`[]` before a number
* segment, `{}` before a string); a `delete` whose path doesn't exist does nothing. Set values are
* copied, so the result shares nothing with `ops`.
* @experimental
*/
function applyStatePatch(root, ops) {
	return applyOps(root, ops);
}
/**
* `applyStatePatch` that leaves `root` as it is: each object or array an op changes is copied
* (once) first, so the result shares only what the ops didn't change with `root`.
* @experimental
*/
function patchState(root, ops) {
	return applyOps(root, ops, /* @__PURE__ */ new Set());
}
/** With `copies`, the containers copied or created so far, which ops can change in place. */
function applyOps(root, ops, copies) {
	const own = (value) => {
		if (!copies || typeof value !== "object" || value === null || copies.has(value)) return value;
		const copy = Array.isArray(value) ? value.slice() : { ...value };
		copies.add(copy);
		return copy;
	};
	const copyOf = (value) => {
		const copy = structuredClone(value);
		if (typeof copy === "object" && copy !== null) copies?.add(copy);
		return copy;
	};
	let result = root;
	for (const op of ops) {
		if (op.path.length === 0) {
			if (op.op === "set") result = copyOf(op.value);
			continue;
		}
		result = own(result);
		let container = result;
		for (let i = 0; i < op.path.length - 1; i++) {
			const key = op.path[i];
			let child = childOf(container, key);
			if (typeof child !== "object" || child === null) {
				if (op.op === "delete") {
					container = void 0;
					break;
				}
				child = typeof op.path[i + 1] === "number" ? [] : {};
				copies?.add(child);
				setChild(container, key, child);
			} else if (copies && !copies.has(child)) {
				child = own(child);
				setChild(container, key, child);
			}
			container = child;
		}
		if (container === void 0) continue;
		const key = op.path[op.path.length - 1];
		if (op.op === "set") setChild(container, key, copyOf(op.value));
		else if (Object.hasOwn(container, key)) delete container[key];
	}
	return result;
}
// src/storage/domains/workflows/journal.ts
/**
* The fields of a successful step result that its summary keeps. Exported for adapters that
* summarize in their query rather than with `summarizeStepResult`.
* @experimental
*/
const STEP_RESULT_SUMMARY_FIELDS = [
	"status",
	"startedAt",
	"endedAt",
	"suspendedAt",
	"resumedAt",
	"metadata"
];
/**
* The summary of a successful step result. Shared so every adapter summarizes the same way.
* @experimental
*/
function summarizeStepResult(result) {
	const summary = {};
	for (const field of STEP_RESULT_SUMMARY_FIELDS) if (result[field] !== void 0) summary[field] = result[field];
	return summary;
}
/**
* Once a run's state has this many patches after its latest `state` or `state-base` entry, its
* next state write is a full state, so rebuilding the state applies at most this many patches.
* @experimental
*/
const STATE_CHECKPOINT_PATCHES = 100;
/**
* The `StateColumnsWrite` of a write's state fields, entered as `writeWorkflowRunCheckpoint` and
* `appendWorkflowRunEntries` do: the state or state base (a checkpoint with neither starts over at
* `{}`), then the patch unless a full state was given. Undefined when the write has no state entry.
* @experimental
*/
function stateColumnsWrite({ state, stateBase, statePatch }, checkpoint) {
	if (state !== void 0) return {
		reset: true,
		stateBytes: JSON.stringify(state).length,
		patchCount: 0,
		patchBytes: 0
	};
	const patchCount = statePatch === void 0 ? 0 : 1;
	const patchBytes = statePatch === void 0 ? 0 : JSON.stringify(statePatch).length;
	if (stateBase !== void 0) return {
		reset: true,
		stateBytes: null,
		patchCount,
		patchBytes
	};
	if (checkpoint) return {
		reset: true,
		stateBytes: 2,
		patchCount,
		patchBytes
	};
	if (statePatch !== void 0) return {
		reset: false,
		stateBytes: null,
		patchCount,
		patchBytes
	};
}
/**
* A run's state columns after a write whose last entry is `lastSeq` (a write's state entries come
* after its steps). `columns` are the run's before it, undefined for a new run.
* @experimental
*/
function applyStateColumnsWrite(columns, write, lastSeq) {
	const before = columns ?? {
		stateSeq: 0,
		statePatchCount: 0,
		statePatchBytes: 0,
		stateBytes: null
	};
	if (!write) return {
		stateSeq: before.stateSeq,
		statePatchCount: before.statePatchCount,
		statePatchBytes: before.statePatchBytes,
		stateBytes: before.stateBytes
	};
	if (write.reset) return {
		stateSeq: lastSeq,
		statePatchCount: write.patchCount,
		statePatchBytes: write.patchBytes,
		stateBytes: write.stateBytes
	};
	return {
		stateSeq: lastSeq,
		statePatchCount: before.statePatchCount + write.patchCount,
		statePatchBytes: before.statePatchBytes + write.patchBytes,
		stateBytes: before.stateBytes
	};
}
/**
* Whether a run's state is due a full state entry: `STATE_CHECKPOINT_PATCHES` patches, or patches
* larger than its latest full state.
* @experimental
*/
function isStateCheckpointDue(columns) {
	return columns.statePatchCount >= 100 || columns.stateBytes !== null && columns.statePatchBytes > columns.stateBytes;
}
/**
* `state` with only the given top-level keys (all of it without `keys`). Keys it doesn't have are left out.
* @experimental
*/
function pickStateKeys(state, keys) {
	if (!keys) return state;
	const picked = {};
	for (const key of keys) if (Object.prototype.hasOwnProperty.call(state, key)) picked[key] = state[key];
	return picked;
}
function stateChain(entries, at) {
	const drafts = [];
	let version = at;
	while (version?.draft) {
		const seq = version.seq;
		const draft = entries.find((entry) => entry.seq === seq);
		if (draft?.kind !== "state-draft") throw new Error(`Storage v2 state draft ${seq} is not stored`);
		if ("state" in draft) return {
			base: draft.state,
			baseIsRef: false,
			patches: drafts.reverse()
		};
		drafts.push(draft.ops);
		version = draft.on;
	}
	const upTo = version?.seq ?? Infinity;
	let base;
	let baseIsRef = false;
	let patches = [];
	for (const entry of entries) {
		if (entry.seq > upTo) break;
		if (entry.kind === "state" || entry.kind === "state-base") {
			base = entry.kind === "state" ? entry.state : entry.base;
			baseIsRef = entry.kind === "state-base";
			patches = [];
		} else if (entry.kind === "state-patch") patches.push(entry.ops);
	}
	return {
		base,
		baseIsRef,
		patches: [...patches, ...drafts.reverse()]
	};
}
/**
* The other run's state version that a run's state (as of `at`, or latest) builds on, if any.
* Stores resolve it (by this same rule) and pass it to `materializeState` as `base`.
* @experimental
*/
function stateBaseOf(entries, at) {
	const chain = stateChain(entries, at);
	return chain.baseIsRef ? chain.base : void 0;
}
/**
* Rebuild a run's state from its entries (in `seq` order).
*
* The latest state (no `at`), or the state as of a `seq`, is the latest `state` or `state-base`
* entry up to it, with every later `state-patch` up to it applied in order. Drafts are left out. A
* `state-base` entry's state is `base`, the state the store resolved for `stateBaseOf(entries, at)`.
* The state of a draft is the version it is `on`, with its patch applied (or its full `state`).
*
* Patches are applied copy-on-write: the result shares what they don't change with `entries` and
* `base`, which are left as they are.
* @experimental
*/
function materializeState(entries, { at, base } = {}) {
	const chain = stateChain(entries, at);
	return patchState((chain.baseIsRef ? base : chain.base) ?? {}, chain.patches.flat());
}
/**
* The latest result of each step (only of `stepIds` when given), from a run's entries (in `seq`
* order), keyed in the order each step was first written: its latest `step` entry, with every later
* `step-patch` entry for the step applied in order. A patch with no earlier `step` entry for its
* step is ignored. A patched result is a JSON copy; the others are the entries' own objects.
* Shared so every adapter rebuilds step results the same way.
* @experimental
*/
function latestStepResults(entries, stepIds) {
	const latest = /* @__PURE__ */ new Map();
	for (const entry of entries) if (entry.kind === "step") {
		if (!stepIds || stepIds.has(entry.stepId)) latest.set(entry.stepId, {
			result: entry.result,
			patches: []
		});
	} else if (entry.kind === "step-patch") latest.get(entry.stepId)?.patches.push(entry.ops);
	const results = /* @__PURE__ */ new Map();
	for (const [stepId, { result, patches }] of latest) {
		if (!patches.length) {
			results.set(stepId, result);
			continue;
		}
		let patched = JSON.parse(JSON.stringify(result));
		for (const ops of patches) patched = applyStatePatch(patched, ops);
		results.set(stepId, patched);
	}
	return results;
}
/**
* Rebuild a run's `WorkflowRunState` from its storage v2 header and entries (in `seq` order).
* `latestStepResults` rebuilds `context`, and `materializeState` rebuilds `value` (`base` as there).
* @experimental
*/
function materializeWorkflowRun(header, entries, base) {
	const context = Object.fromEntries(latestStepResults(entries));
	return {
		...header,
		context,
		value: materializeState(entries, { base })
	};
}
// src/storage/domains/workflows/snapshot-memory-info.ts
/**
* Extracts the memory info (threadId/resourceId) embedded in a workflow-run
* snapshot. This is the canonical extraction: any storage adapter that
* implements the best-effort `threadId` filter on `listWorkflowRuns` MUST
* mirror these exact JSON paths in its query predicate (see
* `StorageListWorkflowRunsInput['threadId']`).
*
* The snapshot stores memory info at one of two locations depending on which
* loop produced it:
*
* 1. `agentic-loop` (dynamic step key):
*    `context.<step where status === 'suspended'>.suspendPayload.__streamState.messageList.memoryInfo`
* 2. Durable agentic-loop (fixed path):
*    `context.input.messageListState.memoryInfo`
*
* If either path changes, update the SQL predicates in `@mastra/pg` and
* `@mastra/libsql` (`listWorkflowRuns`) to match — otherwise they will wrongly
* exclude rows that this extraction would match.
*/
function getSnapshotMemoryInfo(snapshot) {
	for (const key in snapshot?.context) {
		const step = snapshot?.context[key];
		if (step && step.status === "suspended" && step.suspendPayload?.__streamState) return step.suspendPayload?.__streamState?.messageList?.memoryInfo;
	}
	const durableMemoryInfo = (snapshot?.context)?.input?.messageListState?.memoryInfo;
	if (durableMemoryInfo && typeof durableMemoryInfo === "object") return durableMemoryInfo;
}
// src/workflows/step.ts
const getStepResult = (stepResults, step) => {
	let result;
	if (typeof step === "string") result = stepResults[step];
	else {
		if (!step?.id) return null;
		result = stepResults[step.id];
	}
	return result?.status === "success" ? result.output : null;
};
const getStepResultAsync = async (stepResults, step) => getStepResult(stepResults, step);
// src/workflows/mapping-template.ts
/**
* The `${scope.path}` mapping-template DSL used by `.map()` template sources.
*
* Definition-time syntax checks live in {@link validateTemplate}; run-time
* resolution (path lookup + value coercion) lives in {@link resolveTemplate}.
* This module has no knowledge of the step-entry union — it is a pure
* string-DSL interpreter over a step's execute context.
*/
/** Walks a dotted path on an object. `''` or `'.'` returns the root unchanged. */
function traverseMappingPath(root, path, errorLabel) {
	if (path === "" || path === ".") return root;
	const parts = path.split(".");
	let value = root;
	for (const part of parts) if (typeof value === "object" && value !== null) value = value[part];
	else throw new Error(`Invalid path ${path} in ${errorLabel}`);
	return value;
}
const TEMPLATE_PLACEHOLDER = /\$\{([^}]*)\}/g;
const TEMPLATE_NAMESPACES = [
	"inputData",
	"initData",
	"state",
	"requestContext",
	"stepResults"
];
/** Common error-message prefix so every template diagnostic points at the exact placeholder. */
function describeBadPlaceholder(template, idx, rawExpr) {
	return `Template placeholder #${idx} (\${${rawExpr}}) in '${template}'`;
}
/** Split a placeholder body `scope.path.with.dots` into its leading scope and the dotted remainder. */
function parseTemplatePlaceholder(rawExpr) {
	const dot = rawExpr.indexOf(".");
	return {
		scope: dot === -1 ? rawExpr : rawExpr.slice(0, dot),
		rest: dot === -1 ? "" : rawExpr.slice(dot + 1)
	};
}
/**
* Validates a `{ template }` source's syntax at workflow-definition time.
* Throws if any placeholder is empty, whitespace-padded, references an unknown
* namespace, or is a malformed `stepResults.<stepId>` / `stepResults.<stepId>.<path>` shape.
*
* Run-time concerns (does the step actually exist, does the path resolve, is
* the value a primitive) stay in {@link resolveTemplate}.
*/
function validateTemplate(template) {
	let idx = 0;
	for (const match of template.matchAll(TEMPLATE_PLACEHOLDER)) {
		idx++;
		const rawExpr = match[1] ?? "";
		if (rawExpr.length === 0 || rawExpr !== rawExpr.trim()) throw new Error(`${describeBadPlaceholder(template, idx, rawExpr)} has empty or whitespace-padded contents. Use \${<scope>.<path>} with no surrounding whitespace.`);
		const { scope, rest } = parseTemplatePlaceholder(rawExpr);
		if (scope === "stepResults") {
			const innerDot = rest.indexOf(".");
			if (!(innerDot === -1 ? rest : rest.slice(0, innerDot))) throw new Error(`${describeBadPlaceholder(template, idx, rawExpr)} must be of the form \${stepResults.<stepId>} or \${stepResults.<stepId>.<path>}.`);
			continue;
		}
		if (scope === "requestContext") {
			if (!rest) throw new Error(`${describeBadPlaceholder(template, idx, rawExpr)} requires a request-context key — use \${requestContext.<key>}.`);
			continue;
		}
		if (TEMPLATE_NAMESPACES.includes(scope)) continue;
		throw new Error(`${describeBadPlaceholder(template, idx, rawExpr)} references unknown namespace "${scope}". Use one of: ${TEMPLATE_NAMESPACES.join(", ")}.`);
	}
}
/**
* Collects the step ids referenced by `${stepResults.<stepId>}` /
* `${stepResults.<stepId>.<path>}` placeholders in a template. Assumes the
* template already passed {@link validateTemplate}; malformed placeholders are
* skipped. Used by validation to scope-check template references against the
* preceding workflow-local steps.
*/
function collectTemplateStepIds(template) {
	const ids = [];
	for (const match of template.matchAll(TEMPLATE_PLACEHOLDER)) {
		const { scope, rest } = parseTemplatePlaceholder(match[1] ?? "");
		if (scope !== "stepResults") continue;
		const innerDot = rest.indexOf(".");
		const stepId = innerDot === -1 ? rest : rest.slice(0, innerDot);
		if (stepId) ids.push(stepId);
	}
	return ids;
}
/** Whether a template reads the run's state through `${state...}` placeholders. */
function templateReadsState(template) {
	for (const match of template.matchAll(TEMPLATE_PLACEHOLDER)) if (parseTemplatePlaceholder(match[1] ?? "").scope === "state") return true;
	return false;
}
/**
* Coerces a resolved placeholder value to a string. Primitives are stringified
* the normal way; objects and arrays are JSON-encoded so downstream agents can
* consume complex step outputs (e.g. `foreach(agent)` returns `{ text }[]`)
* directly in a template. `null`/`undefined` render as empty. If JSON encoding
* fails (circular references, BigInt, etc.), throws with a hint pointing at
* the offending placeholder.
*/
function stringifyTemplateValue(v, template, idx, rawExpr) {
	if (v === null || v === void 0) return "";
	if (typeof v === "object") try {
		return JSON.stringify(v);
	} catch (err) {
		throw new Error(`${describeBadPlaceholder(template, idx, rawExpr)} resolved to a value that could not be JSON-stringified (${err.message}). Drill into a primitive path (e.g. \${${rawExpr}.someField}) or reshape the value in a preceding step.`);
	}
	return String(v);
}
/**
* Resolves `${<scope>.<path>}` placeholders against the implicit namespaces
* available in a step's execute context. See the `.map()` overload signature
* for the full list of accepted scopes (`inputData`, `initData`, `state`,
* `requestContext`, `stepResults.<stepId>`).
*
* `stepResults.<stepId>` placeholders read `stepOutputs`, which the caller
* resolves up front for every id from {@link collectTemplateStepIds}.
*/
function resolveTemplate(template, ctx, stepOutputs) {
	let idx = 0;
	return template.replace(TEMPLATE_PLACEHOLDER, (_match, rawExpr) => {
		idx++;
		return resolveTemplatePlaceholder(rawExpr, template, idx, ctx, stepOutputs);
	});
}
function resolveTemplatePlaceholder(rawExpr, template, idx, ctx, stepOutputs) {
	const { scope, rest } = parseTemplatePlaceholder(rawExpr);
	const label = describeBadPlaceholder(template, idx, rawExpr);
	switch (scope) {
		case "inputData": return stringifyTemplateValue(traverseMappingPath(ctx.inputData, rest, label), template, idx, rawExpr);
		case "initData": return stringifyTemplateValue(traverseMappingPath(ctx.getInitData(), rest, label), template, idx, rawExpr);
		case "state": return stringifyTemplateValue(traverseMappingPath(ctx.state, rest, label), template, idx, rawExpr);
		case "requestContext": return stringifyTemplateValue(ctx.requestContext.get(rest), template, idx, rawExpr);
		case "stepResults": {
			const innerDot = rest.indexOf(".");
			const stepId = innerDot === -1 ? rest : rest.slice(0, innerDot);
			const subPath = innerDot === -1 ? "" : rest.slice(innerDot + 1);
			const stepResult = stepOutputs.get(stepId);
			if (stepResult == null) throw new Error(`${label} references stepResults.${stepId} but step "${stepId}" has no successful output (not run yet, not registered, failed, or produced no output).`);
			return stringifyTemplateValue(traverseMappingPath(stepResult, subPath, label), template, idx, rawExpr);
		}
		default: throw new Error(`${label} references unknown namespace "${scope}". Use one of: ${TEMPLATE_NAMESPACES.join(", ")}.`);
	}
}
// src/workflows/step-refs.ts
/**
* Declarative readers (`.map()` configs, templates, predicates) list the steps
* they read up front, then resolve them with `getStepResultAsync` before
* evaluating anything. That keeps them off the sync `getStepResult`, which
* can't serve runs whose step results aren't all in memory.
*/
/** Id of a `{ step }` mapping source: a step id string or a step-like object. */
function stepRefId(step) {
	if (typeof step === "string") return step;
	const id = step?.id;
	return typeof id === "string" && id ? id : void 0;
}
/**
* Step ids an object mapping config reads: `{ step }` sources (including every
* arm of an array) and `${stepResults.<id>}` template placeholders. `value`,
* `fn`, `requestContextPath` and `initData` sources read no step results.
* Checks run in the same order `runMappingEntry` applies them.
*/
function collectMappingStepRefs(mapConfig) {
	const ids = /* @__PURE__ */ new Set();
	for (const mapping of Object.values(mapConfig)) {
		const m = mapping;
		if (m === null || typeof m !== "object") continue;
		if (m.value !== void 0 || m.fn !== void 0) continue;
		if (typeof m.template === "string") {
			collectTemplateStepIds(m.template).forEach((id) => ids.add(id));
			continue;
		}
		if (m.requestContextPath || m.initData) continue;
		for (const step of Array.isArray(m.step) ? m.step : [m.step]) {
			const id = stepRefId(step);
			if (id) ids.add(id);
		}
	}
	return [...ids];
}
/** The normalized paths a predicate reads. */
function predicatePaths(predicate) {
	const paths = [];
	const addPath = (rawPath) => {
		const path = normalizePredicatePath(rawPath);
		if (path !== MISSING) paths.push(path);
	};
	const addRef = (ref) => {
		if ("path" in ref) addPath(ref.path);
	};
	const visit = (p) => {
		switch (p.op) {
			case "and":
			case "or":
				p.args.forEach(visit);
				break;
			case "not":
				visit(p.arg);
				break;
			case "exists":
			case "notExists":
				addPath(p.path);
				break;
			case "truthy":
			case "falsy":
			case "in":
			case "notIn":
				addRef(p.value);
				break;
			default:
				addRef(p.left);
				addRef(p.right);
		}
	};
	visit(predicate);
	return paths;
}
/** Step ids a predicate reads through `stepResults.<id>` paths. */
function collectPredicateStepRefs(predicate) {
	const ids = /* @__PURE__ */ new Set();
	for (const path of predicatePaths(predicate)) {
		if (!path.startsWith("stepResults.")) continue;
		const rest = path.slice(12);
		const dot = rest.indexOf(".");
		const id = dot === -1 ? rest : rest.slice(0, dot);
		if (id) ids.add(id);
	}
	return [...ids];
}
/** Whether a predicate reads the run's state through `state` paths. */
function predicateReadsState(predicate) {
	return predicatePaths(predicate).some((path) => path === "state" || path.startsWith("state."));
}
/**
* Resolves step ids to their outputs in one batch. Values match
* `getStepResultAsync`: the output of a successful step, `null` otherwise.
*/
async function resolveStepOutputs(ids, getStepResultAsync) {
	const outputs = await Promise.all(ids.map((id) => getStepResultAsync(id)));
	return new Map(ids.map((id, i) => [id, outputs[i]]));
}
// src/workflows/run-journal.ts
const stubs = /* @__PURE__ */ new WeakSet();
/**
* A stand-in for a successful step result that is stored but no longer held in memory: the
* result's summary fields, without its data. `RunJournal.hydrate` swaps it back for the stored
* result.
*
* @internal
*/
function stubStepResult(result) {
	const stub = summarizeStepResult(result);
	stubs.add(stub);
	return stub;
}
/** @internal */
function isStepResultStub(value) {
	return typeof value === "object" && value !== null && stubs.has(value);
}
/**
* Tracks what a storage-v2 run has written, so each engine write sends only the
* step results that changed (and the state's changes) instead of the whole snapshot.
* It also lets the engine drop stored results from memory (`evict`) and read them back
* (`hydrate`, `getStepResultAsync`).
*
* Step results are replaced, never edited in place, so a step changed when its object
* differs from the one last written. State can be edited in place, so the journal keeps a
* JSON copy of the state it last wrote and diffs the live state against it. A change is written
* as a patch, unless the patches written since the latest full state would outgrow the state:
* then the full state is written again, so reading the state back never replays more than
* about twice its size. A step result that is rewritten before it succeeds (a running foreach
* recording its finished items) is written the same way, as a `step-patch` on the result last
* written, once it has been written twice.
*
* The start writes of a parallel or branch block's steps are in flight at the same time, and
* the store can commit them in any order. If two of them carried the same step, the older value
* could commit last while the journal believes storage holds the newer one, and it never resends
* what it believes is stored. So a write that can overlap others names its steps (`stepIds`) and
* sends only those, and overlapping writes name different steps. Everything else (other steps'
* changes, the state, the checkpoint) goes out with boundary writes, which the engine makes only
* when no other write of the run is in flight (an entry's end, a loop iteration's start, a
* finished parallel arm or foreach item, sleeps, the run stopping). `write` throws when a write
* breaks that.
*
* @internal
*/
var RunJournal = class {
	/** Undefined when Mastra has no storage: nothing is written, so nothing is evicted. */
	store;
	workflowName;
	runId;
	/** stepId -> the object last written for it (a stub once evicted) */
	#written;
	/**
	* stepId -> a JSON copy of the result last written for it, the JSON size of the patches stored
	* after it was last written in full, and the write of the step it came from (see `#stepWrites`).
	* Only for a result that a later non-success result can be written as a patch on (see `#stepWrite`).
	*/
	#writtenCopies = /* @__PURE__ */ new Map();
	/** stepId -> how many writes that send the step have started */
	#stepWrites = /* @__PURE__ */ new Map();
	/** A JSON copy of the stored state. Replaced on each write, never edited. */
	#writtenState;
	/**
	* The stored state version `#writtenState` is, when known. Before the checkpoint of a nested run
	* built on its parent's state, a version of the parent's state.
	*/
	#writtenRef;
	/** The version a nested run's checkpoint builds on (`inherited`). */
	#inheritedRef;
	/** JSON size of the patches stored after the latest full state. */
	#patchBytes;
	/** The patches stored after the latest full state or state base. */
	#patchCount;
	/** The latest draft of the live state written for nested runs to build on, since the last state write. */
	#draft;
	/** JSON size of the draft patches chained since the latest full draft or state write. */
	#draftBytes = 0;
	/** Serializes `baseFor`, so concurrent nested starts share one draft. */
	#drafting = Promise.resolve();
	#needsCheckpoint;
	/** A resumed drive's start state version, until an append has recorded it. */
	#startStateSeq;
	/** Store writes sent and not yet settled, and whether one of them is a boundary write. */
	#inFlight = 0;
	#boundaryInFlight = false;
	#closed = false;
	/** The highest `lastSeq` of the run known here: as loaded, or reported by a write or draft. */
	#lastSeq;
	#runToken;
	/** Store calls (writes and drafts) sent and not yet settled. */
	#pending = /* @__PURE__ */ new Set();
	#resolveSettledLastSeq;
	/**
	* The run's `lastSeq` once its execution has ended (`close`) and every write and draft sent has
	* settled: the version a read of its stored steps must still find to see what the execution left.
	* Undefined when the run wasn't loaded and nothing was stored.
	*/
	settledLastSeq;
	settledRunToken;
	/**
	* @param seed The step results already in storage (a resumed or restarted run's loaded snapshot
	* context). Without it, the first boundary write is a checkpoint that replaces whatever is stored.
	* @param state The state already in storage, with `seed`.
	* @param storedState What the store reported for `state`: its `lastSeq`, `statePatchBytes` and `statePatchCount`.
	* @param inherited For a nested run that starts from a version of its parent's state (the parent
	* journal's `baseFor`): the checkpoint stores that version as the base, and only the changes to it.
	* @param resumed Set for a resume: the run's new drive starts from `storedState`, which the first
	* append records as the run's `startStateSeq`.
	*/
	constructor({ store, workflowName, runId, seed, state, storedState, inherited, resumed }) {
		this.store = store;
		this.workflowName = workflowName;
		this.runId = runId;
		this.#needsCheckpoint = !seed;
		this.#written = new Map(seed ? Object.entries(seed) : []);
		if (inherited) {
			this.#writtenState = inherited.state;
			this.#writtenRef = inherited.ref;
			this.#inheritedRef = inherited.ref;
		} else if (seed && state !== void 0) {
			this.#writtenState = normalizeState(state).state;
			if (storedState) this.#writtenRef = {
				workflowName,
				runId,
				seq: storedState.seq
			};
		}
		this.#patchBytes = storedState?.patchBytes ?? 0;
		this.#patchCount = storedState?.patchCount ?? 0;
		if (resumed && seed) this.#startStateSeq = storedState?.seq;
		this.#lastSeq = storedState?.seq;
		this.#runToken = storedState?.runToken;
		this.settledLastSeq = new Promise((resolve) => {
			this.#resolveSettledLastSeq = resolve;
		});
		this.settledRunToken = this.settledLastSeq.then(() => this.#runToken);
	}
	/**
	* Sends a store call, keeping it in `#pending` until it settles and noting the run's `lastSeq` it
	* reports, so `settledLastSeq` cannot resolve before a settled call's seq is noted.
	*/
	#send(call, seqOf) {
		const tracked = call.then((result) => {
			const seq = seqOf(result);
			if (seq !== void 0 && (this.#lastSeq === void 0 || seq > this.#lastSeq)) this.#lastSeq = seq;
			return result;
		});
		this.#pending.add(tracked);
		const settle = () => this.#pending.delete(tracked);
		tracked.then(settle, settle);
		return tracked;
	}
	/**
	* A stored version of this run's state, for a nested run starting from `state` to build on: the
	* stored state or the latest draft when `state` matches it, else a new draft of `state` (a patch
	* on the latest version, or the full state once the draft patches would outgrow it). Undefined
	* when there is nothing to build on (no store, the run isn't stored, a state that isn't JSON).
	*
	* Drafts don't change the run's state, so a restart never reads them: they only hold the live
	* state that a block's earlier steps changed, so the nested runs of a foreach or a loop each store
	* only their own changes.
	*/
	baseFor(state) {
		const result = this.#drafting.then(() => this.#baseFor(state));
		this.#drafting = result.catch(() => void 0);
		return result;
	}
	async #baseFor(state) {
		const store = this.store;
		if (!store || this.#closed) return void 0;
		let next;
		try {
			next = normalizeState(state);
		} catch {
			return;
		}
		const current = this.#draft ?? (this.#writtenRef && this.#writtenState && {
			ref: this.#writtenRef,
			state: this.#writtenState
		});
		const ops = current && diffState(current.state, next.state);
		if (current && !ops.length) return current;
		const own = current && current.ref.workflowName === this.workflowName && current.ref.runId === this.runId;
		const opsBytes = ops ? JSON.stringify(ops).length : 0;
		const chained = own && this.#draftBytes + opsBytes <= next.bytes;
		let seq;
		try {
			({seq} = await this.#send(store.appendWorkflowRunStateDraft({
				workflowName: this.workflowName,
				runId: this.runId,
				...chained ? {
					on: {
						seq: current.ref.seq,
						draft: current.ref.draft
					},
					ops
				} : { state: next.state }
			}), (written) => written.seq));
		} catch {
			return;
		}
		this.#draftBytes = chained ? this.#draftBytes + opsBytes : 0;
		this.#draft = {
			ref: {
				workflowName: this.workflowName,
				runId: this.runId,
				seq,
				draft: true
			},
			state: next.state
		};
		return this.#draft;
	}
	/**
	* Called when the run's execution ends. A step of a parallel or branch block can still be
	* running then (the block's `Promise.all` rejects on the first failure), and its write is dropped.
	*/
	close() {
		if (this.#closed) return;
		this.#closed = true;
		Promise.allSettled(this.#pending).then(() => this.#resolveSettledLastSeq(this.#lastSeq));
	}
	/**
	* @param stepIds Set by a write that can be in flight together with other writes of the run (a
	* step's start write): only these steps are sent, never the state, and no other write in flight
	* may name them. Leave it unset for a boundary write, made when no other write of the run is in
	* flight (an entry's end, a loop iteration's start, a finished parallel arm or foreach item,
	* sleeps, the run stopping): it sends every step result that changed since it was last written,
	* the state's changes, and the checkpoint when that is still to do.
	* @param foreachItems Set by a running foreach's progress write: the foreach's result differs
	* from the one it last wrote only by these indices' `metadata.foreachProgress` entries. When the
	* last written result can be patched, only those entries are sent, so recording a finished item
	* costs that item rather than every item finished so far.
	* @param expectedStatus Sent with the write as the store's compare-and-set guard on the stored status.
	* @returns False when the store rejected the write because of `expectedStatus`. Nothing was
	* stored, as with a write that throws.
	*/
	async write({ resourceId, snapshot, stepIds, foreachItems, expectedStatus }) {
		const store = this.store;
		if (!store || this.#closed) return true;
		const boundary = stepIds === void 0;
		if (!boundary && this.#needsCheckpoint) return true;
		const { context, value, ...header } = snapshot;
		const results = context;
		const checkpoint = this.#needsCheckpoint;
		let sent;
		if (checkpoint) {
			sent = Object.keys(results);
			const stubbed = sent.filter((stepId) => isStepResultStub(results[stepId]));
			if (stubbed.length) throw new MastraError({
				id: "WORKFLOW_STORAGE_V2_CHECKPOINT_STUB",
				domain: ErrorDomain.MASTRA_WORKFLOW,
				category: ErrorCategory.SYSTEM,
				text: `Storage v2 run ${this.runId} can't write a checkpoint while step results are evicted (${stubbed.join(", ")}).`
			});
		} else sent = (stepIds ?? Object.keys(results)).filter((stepId) => stepId in results && results[stepId] !== this.#written.get(stepId) && !isStepResultStub(results[stepId]));
		const steps = {};
		const stepPatches = {};
		const sentWrites = sent.map((stepId) => {
			const result = results[stepId];
			const write = this.#stepWrite(stepId, result, !checkpoint, foreachItems?.stepId === stepId ? foreachItems.indices : void 0);
			if (write.ops) stepPatches[stepId] = write.ops;
			else if (!write.unchanged) steps[stepId] = result;
			return {
				stepId,
				result,
				copy: write.copy,
				unchanged: write.unchanged
			};
		});
		const patched = Object.keys(stepPatches).length > 0;
		if (!boundary && !patched && !Object.keys(steps).length) {
			this.#recordWritten(sentWrites);
			return true;
		}
		if (this.#boundaryInFlight || boundary && this.#inFlight > 0) throw new MastraError({
			id: "WORKFLOW_STORAGE_V2_OVERLAPPING_WRITE",
			domain: ErrorDomain.MASTRA_WORKFLOW,
			category: ErrorCategory.SYSTEM,
			text: `Storage v2 run ${this.runId} started a write while ${boundary ? "another write" : "a boundary write"} was in flight.`
		});
		for (const { stepId, unchanged } of sentWrites) if (!unchanged) this.#stepWrites.set(stepId, (this.#stepWrites.get(stepId) ?? 0) + 1);
		let writtenState = this.#writtenState;
		let patchBytes = this.#patchBytes;
		let patchCount = this.#patchCount;
		let state;
		let stateBase;
		let statePatch;
		if (boundary) {
			const next = normalizeState(value);
			if (writtenState === void 0 || checkpoint && !this.#inheritedRef) state = next.state;
			else {
				if (checkpoint) {
					stateBase = this.#inheritedRef;
					patchBytes = 0;
					patchCount = 0;
				}
				const ops = diffState(writtenState, next.state);
				if (ops.length) {
					const opsBytes = JSON.stringify(ops).length;
					if (patchBytes + opsBytes > next.bytes || patchCount >= 100) {
						state = next.state;
						stateBase = void 0;
					} else {
						statePatch = ops;
						patchBytes += opsBytes;
						patchCount++;
					}
				}
			}
			if (state) {
				patchBytes = 0;
				patchCount = 0;
			}
			if (state || statePatch) writtenState = next.state;
		}
		this.#needsCheckpoint = false;
		this.#inFlight++;
		if (boundary) this.#boundaryInFlight = true;
		let lastSeq;
		const startStateSeq = this.#startStateSeq;
		try {
			const threadId = getSnapshotMemoryInfo(snapshot)?.threadId;
			const run = {
				workflowName: this.workflowName,
				runId: this.runId,
				resourceId,
				threadId,
				header,
				steps,
				state,
				statePatch,
				...expectedStatus ? { expectedStatus } : {}
			};
			const written = await this.#send(checkpoint ? store.writeWorkflowRunCheckpoint({
				...run,
				stateBase
			}) : store.appendWorkflowRunEntries({
				...run,
				...patched ? { stepPatches } : {},
				startStateSeq
			}), (written) => {
				this.#runToken ??= written?.runToken;
				return written?.lastSeq;
			});
			if (written === null) {
				if (checkpoint) this.#needsCheckpoint = true;
				return false;
			}
			lastSeq = written?.lastSeq;
			this.#startStateSeq = void 0;
		} catch (error) {
			if (checkpoint) this.#needsCheckpoint = true;
			throw error;
		} finally {
			this.#inFlight--;
			if (boundary) this.#boundaryInFlight = false;
		}
		this.#recordWritten(sentWrites);
		if (checkpoint || state || statePatch) this.#writtenRef = lastSeq === void 0 ? void 0 : {
			workflowName: this.workflowName,
			runId: this.runId,
			seq: lastSeq
		};
		if (checkpoint) this.#inheritedRef = void 0;
		if (boundary) {
			this.#draft = void 0;
			this.#draftBytes = 0;
		}
		this.#writtenState = writtenState;
		this.#patchBytes = patchBytes;
		this.#patchCount = patchCount;
		return true;
	}
	/**
	* How a write sends a step's result: as a patch on the result last written (`ops`), not at all
	* when it holds the same JSON (`unchanged`), else in full. A patch needs both results to be
	* non-success (only a success is summarized, and a step's start and success writes never pay for
	* a copy), the new one to be plain JSON (what JSON keeps as it is), every earlier write of the
	* step to be stored (else the stored result the patch applies to isn't known), and the patches
	* since the last full write to stay within its size, as for the state. `copy` is what
	* `#writtenCopies` holds for the step once the write is stored.
	*
	* With `foreachItems` (see `write`), the patch is built from those entries alone, without
	* serializing the whole result.
	*/
	#stepWrite(stepId, result, mayPatch, foreachItems) {
		const previous = this.#written.get(stepId);
		const rewritten = previous !== void 0 && previous.status !== "success" && result?.status !== "success";
		const started = this.#stepWrites.get(stepId) ?? 0;
		const prior = this.#writtenCopies.get(stepId);
		if (foreachItems && rewritten && mayPatch && prior?.write === started) {
			const progressPatch = foreachProgressPatch(prior, result, foreachItems);
			if (progressPatch === "unchanged") return {
				unchanged: true,
				copy: prior
			};
			if (progressPatch) {
				const patchBytes = prior.patchBytes + JSON.stringify(progressPatch.ops).length;
				if (patchBytes <= progressPatch.bytes) {
					for (const { key, value } of progressPatch.entries) progressPatch.written[key] = value;
					return {
						ops: progressPatch.ops,
						copy: {
							json: prior.json,
							bytes: progressPatch.bytes,
							patchBytes,
							write: started + 1
						}
					};
				}
			}
		}
		const json = rewritten && isPlainJson(result, /* @__PURE__ */ new Set()) ? JSON.stringify(result) : void 0;
		if (json === void 0) return { copy: void 0 };
		const next = JSON.parse(json);
		if (mayPatch && prior?.write === started) {
			const ops = diffState(prior.json, next);
			if (!ops.length) return {
				unchanged: true,
				copy: prior
			};
			const patchBytes = prior.patchBytes + JSON.stringify(ops).length;
			if (patchBytes <= json.length) return {
				ops,
				copy: {
					json: next,
					bytes: json.length,
					patchBytes,
					write: started + 1
				}
			};
		}
		return { copy: {
			json: next,
			bytes: json.length,
			patchBytes: 0,
			write: started + 1
		} };
	}
	/**
	* Records what a stored write sent. A copy is kept only from the latest write of its step: an
	* earlier write that finishes later doesn't hold what the store has last.
	*/
	#recordWritten(writes) {
		for (const { stepId, result, copy } of writes) {
			this.#written.set(stepId, result);
			if (copy && copy.write !== (this.#stepWrites.get(stepId) ?? 0)) continue;
			if (copy) this.#writtenCopies.set(stepId, copy);
			else this.#writtenCopies.delete(stepId);
		}
	}
	/**
	* Replace stored successful results with stubs, except `input` and the steps in `keep`.
	* Only results that are exactly what was last written are replaced, so nothing the store
	* doesn't have is dropped.
	*/
	evict(stepResults, keep) {
		if (!this.store) return;
		const kept = new Set(keep);
		for (const [stepId, result] of Object.entries(stepResults)) {
			if (stepId === "input" || kept.has(stepId) || result?.status !== "success" || isStepResultStub(result) || this.#written.get(stepId) !== result) continue;
			const stub = stubStepResult(result);
			stepResults[stepId] = stub;
			this.#written.set(stepId, stub);
		}
	}
	/** Whether `result` is what the store holds for `stepId`, as of the writes that have settled. */
	isStored(stepId, result) {
		return this.#written.get(stepId) === result;
	}
	/** Swap the stubs among `stepIds` back for their stored results, with one read. */
	async hydrate(stepResults, stepIds = Object.keys(stepResults)) {
		const { store, workflowName, runId } = this;
		if (!store) return;
		const loadSteps = (ids) => store.loadWorkflowRunSteps({
			workflowName,
			runId,
			stepIds: ids
		});
		const hydrated = await hydrateStepResults({
			runId,
			loadSteps
		}, stepResults, stepIds);
		for (const [stepId, result] of hydrated) this.#written.set(stepId, result);
	}
	/** `getStepResultAsync` for step code: reads an evicted step from storage first. */
	getStepResultAsync(stepResults, step) {
		return getHydratedStepResult(stepResults, step, (stepIds) => this.hydrate(stepResults, stepIds));
	}
};
/**
* `getStepResult` over step results that may hold stubs: a stubbed step is read back with
* `hydrate` first. The result stays in `stepResults`, so later reads of it are free.
*
* @internal
*/
async function getHydratedStepResult(stepResults, step, hydrate) {
	const stepId = stepRefId(step);
	if (stepId !== void 0 && isStepResultStub(stepResults[stepId])) await hydrate([stepId]);
	return getStepResult(stepResults, step);
}
/**
* The `getStepResult` / `getStepResultAsync` pair handed to step code. On storage v2
* runs, sync `getStepResult` throws: their step results won't always be in memory.
*
* @internal
*/
function buildStepResultAccessors(engine, runId, stepResults) {
	const journal = engine.getRunJournal(runId);
	if (!journal) return {
		getStepResult: getStepResult.bind(null, stepResults),
		getStepResultAsync: getStepResultAsync.bind(null, stepResults)
	};
	return storageV2StepResultAccessors((step) => journal.getStepResultAsync(stepResults, step));
}
/**
* The accessor pair for step code in a storage v2 run: sync `getStepResult` throws, as the run's
* step results won't always be in memory, and points to `getStepResultAsync`.
*
* @internal
*/
function storageV2StepResultAccessors(getStepResultAsync) {
	return {
		getStepResult: (step) => {
			const stepId = stepRefId(step) ?? String(step);
			throw new MastraError({
				id: "WORKFLOW_STORAGE_V2_SYNC_GET_STEP_RESULT",
				domain: ErrorDomain.MASTRA_WORKFLOW,
				category: ErrorCategory.USER,
				text: `getStepResult("${stepId}") isn't available in workflows with storageVersion: 2. Use \`await getStepResultAsync("${stepId}")\` instead.`
			});
		},
		getStepResultAsync
	};
}
/**
* Swaps the stubs among `stepIds` back for the run's stored results, with one read.
*
* @returns The stored results put in, by step id.
* @internal
*/
async function hydrateStepResults(run, stepResults, stepIds = Object.keys(stepResults)) {
	const hydrated = /* @__PURE__ */ new Map();
	const stubbed = /* @__PURE__ */ new Map();
	for (const stepId of stepIds) if (isStepResultStub(stepResults[stepId])) stubbed.set(stepId, stepResults[stepId]);
	if (!stubbed.size) return hydrated;
	const loaded = await run.loadSteps([...stubbed.keys()]);
	for (const [stepId, stub] of stubbed) {
		if (stepResults[stepId] !== stub) continue;
		const result = loaded?.[stepId];
		if (!result) throw new MastraError({
			id: "WORKFLOW_STORAGE_V2_STEP_RESULT_MISSING",
			domain: ErrorDomain.MASTRA_WORKFLOW,
			category: ErrorCategory.SYSTEM,
			text: `The stored result of step "${stepId}" in run ${run.runId} is missing. The run was deleted or overwritten while it ran.`
		});
		stepResults[stepId] = result;
		hydrated.set(stepId, result);
	}
	return hydrated;
}
/**
* The state as a JSON store keeps it (a `Date` becomes its ISO string, `undefined` keys drop), and
* its JSON size.
*/
function normalizeState(state) {
	const json = JSON.stringify(state ?? {});
	return {
		state: JSON.parse(json),
		bytes: json.length
	};
}
/**
* Whether JSON keeps `value` as it is: only strings, finite numbers, booleans, null, arrays and
* plain objects (no `Date`, `Error` or other class instance, and no `undefined` array item). An
* `undefined` object value is allowed: JSON drops the key, which reads back the same.
*/
/**
* The ops that add a running foreach's newly finished items to the copy of its last written result,
* and the copy's JSON size with them. `'unchanged'` when every item is in the copy already.
* Undefined when the copy holds no progress or an item isn't plain JSON: the result is then
* written the general way.
*/
function foreachProgressPatch(prior, result, indices) {
	const written = prior.json?.metadata?.foreachProgress;
	const live = result.metadata?.foreachProgress;
	if (typeof written !== "object" || written === null || !live) return void 0;
	const progress = written;
	const ops = [];
	const entries = [];
	let bytes = prior.bytes;
	for (const index of indices) {
		const key = String(index);
		if (Object.hasOwn(progress, key) || !Object.hasOwn(live, key)) continue;
		if (!isPlainJson(live[key], /* @__PURE__ */ new Set())) return void 0;
		const json = JSON.stringify(live[key]);
		const value = JSON.parse(json);
		ops.push({
			op: "set",
			path: [
				"metadata",
				"foreachProgress",
				key
			],
			value
		});
		entries.push({
			key,
			value
		});
		bytes += key.length + json.length + 4;
	}
	return ops.length ? {
		ops,
		entries,
		written: progress,
		bytes
	} : "unchanged";
}
function isPlainJson(value, ancestors) {
	switch (typeof value) {
		case "string":
		case "boolean": return true;
		case "number": return Number.isFinite(value);
		case "object": {
			if (value === null) return true;
			if (ancestors.has(value)) return false;
			const proto = Object.getPrototypeOf(value);
			if (!Array.isArray(value) && proto !== Object.prototype && proto !== null) return false;
			ancestors.add(value);
			let plain = true;
			if (Array.isArray(value)) for (let i = 0; plain && i < value.length; i++) plain = isPlainJson(value[i], ancestors);
			else for (const item of Object.values(value)) if (item !== void 0 && !isPlainJson(item, ancestors)) {
				plain = false;
				break;
			}
			ancestors.delete(value);
			return plain;
		}
		default: return false;
	}
}
/** The `steps` loader of a storage v2 result -> the step results it was built from (see `residentStepResults`). */
const residentResults = /* @__PURE__ */ new WeakMap();
/**
* The `steps()` of a storage v2 run's result: its step results as the execution left them, formatted
* by `format`. The successful results the journal evicted are read from storage on the first call,
* with one read shared by concurrent calls; the read fails if the run was written to since its
* execution ended (e.g. resumed or restarted), since storage then no longer holds what the result
* describes. A failed read isn't cached, so a later call retries.
*
* Holds the stubs and the results that weren't evicted until the run's writes settle; then the
* stored successful results are evicted too, so it holds only stubs, `input` and the results a
* reader needs without loading (suspended, failed, running). Call it after the run's last write is
* sent, and close the journal before anything awaits the loader.
*
* @internal
*/
function lazyStepResults(journal, stepResults, format) {
	const results = { ...stepResults };
	evictOnceStored(journal, results);
	const { store, workflowName, runId, settledLastSeq, settledRunToken } = journal;
	return storedStepResults({
		store,
		workflowName,
		runId,
		lastSeq: settledLastSeq,
		runToken: settledRunToken
	}, results, format);
}
function evictOnceStored(journal, results) {
	journal.settledLastSeq.then(() => {
		for (const [stepId, result] of Object.entries(results)) if (stepId !== "input" && result?.status === "success" && !isStepResultStub(result) && journal.isStored(stepId, result)) results[stepId] = stubStepResult(result);
	});
}
/**
* The `steps()` of a storage v2 result reconstructed from stored state. Holds successful-step
* stubs and hydrates them on the first call while the stored run identity and `lastSeq` still match.
*
* @internal
*/
function loadedStepResults({ store, workflowName, runId, lastSeq, runToken }, stepResults, format) {
	const results = {};
	for (const [stepId, result] of Object.entries(stepResults)) results[stepId] = stepId !== "input" && result?.status === "success" && !isStepResultStub(result) ? stubStepResult(result) : result;
	return storedStepResults({
		store,
		workflowName,
		runId,
		lastSeq: Promise.resolve(lastSeq),
		runToken: Promise.resolve(runToken)
	}, results, format);
}
/**
* The `steps()` of a storage v2 result that already holds every step result, so it reads none
* from storage: an evented run's, whose finish event carries them all.
*
* @internal
*/
function residentStepResultsLoader(stepResults) {
	const steps = () => Promise.resolve(stepResults);
	residentResults.set(steps, stepResults);
	return steps;
}
function storedStepResults({ store, workflowName, runId, lastSeq, runToken }, results, format) {
	let loaded;
	const load = async () => {
		const expectedLastSeq = await lastSeq;
		const expectedRunToken = await runToken;
		const stubbed = Object.keys(results).filter((stepId) => isStepResultStub(results[stepId]));
		if (!stubbed.length && expectedLastSeq === void 0) return format(results);
		const stored = await store.loadWorkflowRunSteps({
			workflowName,
			runId,
			stepIds: stubbed,
			expectedLastSeq,
			expectedRunToken
		});
		if (!stored) throw new MastraError({
			id: "WORKFLOW_STORAGE_V2_STEPS_STALE",
			domain: ErrorDomain.MASTRA_WORKFLOW,
			category: ErrorCategory.USER,
			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.`
		});
		const full = { ...results };
		for (const stepId of stubbed) {
			const result = stored[stepId];
			if (!result) throw new MastraError({
				id: "WORKFLOW_STORAGE_V2_STEP_RESULT_MISSING",
				domain: ErrorDomain.MASTRA_WORKFLOW,
				category: ErrorCategory.SYSTEM,
				text: `The stored result of step "${stepId}" in run ${runId} is missing.`
			});
			full[stepId] = result;
		}
		return format(full);
	};
	const steps = () => {
		loaded ??= load().catch((error) => {
			loaded = void 0;
			throw error;
		});
		return loaded;
	};
	residentResults.set(steps, results);
	return steps;
}
/**
* The step results a storage v2 result's `steps` loader holds without reading storage: every result
* but the successful ones that were evicted, which are stubs. Undefined for anything else (a v1
* result's `steps` record). For the engine's own reads of a nested run's suspended and failed steps.
*
* @internal
*/
function residentStepResults(steps) {
	return typeof steps === "function" ? residentResults.get(steps) : void 0;
}
/**
* Every step result of a run's result: a storage v2 result's `steps` loader is called, a v1
* result's record returned as is. For the framework's readers that hand all of them on.
*
* @internal
*/
async function loadStepResults(steps) {
	return typeof steps === "function" ? steps() : steps;
}
// src/processors/send-signal.ts
const PROCESSOR_LATE_SIGNAL_SINK = createRunScopeKey("processor-late-signal-sink");
function createProcessorSendSignal(args) {
	return async (signalInput) => {
		if (args.lateSink?.isClosed()) return args.lateSink.send(signalInput);
		const signal = createSignal(signalInput);
		if (args.rotateResponseMessageId) {
			args.messageList.markResponseMessageBoundary();
			args.rotateResponseMessageId();
		}
		const signalForTranscript = args.messageList.addSignal(signal);
		await args.writer?.custom(signalForTranscript.toDataPart());
		return signalForTranscript;
	};
}
// src/processors/span-declaration.ts
/**
* Phase names used by the processor-workflow executor, mapped onto
* `ProcessorSpanPhase`. The executor distinguishes `outputStream` from
* `outputResult`; both are the output phase as far as a declaration is
* concerned, matching how they share one entity type.
*/
const WORKFLOW_PHASE_TO_SPAN_PHASE = {
	input: "input",
	inputStep: "inputStep",
	llmRequest: "llmRequest",
	llmResponse: "llmResponse",
	outputStream: "output",
	outputResult: "output",
	outputStep: "outputStep",
	toolResult: "toolResult",
	requestError: "requestError"
};
/** Map a processor-workflow phase string onto the declaration phase. */
function toProcessorSpanPhase(phase) {
	return WORKFLOW_PHASE_TO_SPAN_PHASE[phase] ?? "output";
}
/**
* Resolve a processor's declared span name for the phase the span is being
* created in, falling back to the caller's default label.
*/
function resolveProcessorSpanName(processor, phase, fallback) {
	const declared = processor.spanName;
	if (typeof declared === "function") return declared(phase);
	return declared ?? fallback;
}
/**
* Resolve a processor's declared span attributes for this phase, with the phase
* itself recorded alongside them.
*
* The phase is applied last so a declaration cannot misreport which phase ran:
* readers narrow a processor span's payloads on this attribute, and a processor
* naming itself into another phase would hand them the wrong shape.
*/
function resolveProcessorSpanAttributes(processor, phase) {
	const declared = processor?.spanAttributes;
	const declarationPhase = toProcessorSpanPhase(phase);
	return {
		...typeof declared === "function" ? declared(declarationPhase) : declared,
		processorPhase: phase
	};
}
// src/processors/span-payload.ts
function isPlainObject(value) {
	if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
	const prototype = Object.getPrototypeOf(value);
	return prototype === Object.prototype || prototype === null;
}
function readString(value) {
	return typeof value === "string" ? value : void 0;
}
function summarizeProcessorToolEntry(key, value) {
	if (!isPlainObject(value)) return {
		id: key,
		name: key
	};
	const id = readString(value.id) ?? key;
	const name = readString(value.name) ?? id;
	const description = readString(value.description);
	return {
		id,
		name,
		...description !== void 0 ? { description } : {}
	};
}
function summarizeProcessorModelForSpan(value) {
	if (!isPlainObject(value)) return;
	const modelId = readString(value.modelId) ?? readString(value.id);
	const provider = readString(value.provider);
	const specificationVersion = readString(value.specificationVersion);
	if (modelId === void 0 && provider === void 0 && specificationVersion === void 0) return;
	return {
		...modelId !== void 0 ? { modelId } : {},
		...provider !== void 0 ? { provider } : {},
		...specificationVersion !== void 0 ? { specificationVersion } : {}
	};
}
function summarizeProcessorToolsForSpan(tools) {
	if (!isPlainObject(tools)) return;
	return Object.entries(tools).map(([key, value]) => summarizeProcessorToolEntry(key, value));
}
function summarizeProcessorToolRegistry(tools) {
	if (!isPlainObject(tools)) return;
	const summaries = summarizeProcessorToolsForSpan(tools);
	if (!summaries) return;
	return Object.keys(tools).map((registryKey, index) => ({
		registryKey,
		summary: summaries[index]
	}));
}
function resolveToolInRegistry(toolRegistry, toolKey) {
	return toolRegistry.find((candidate) => candidate.summary.id === toolKey || candidate.summary.name === toolKey || candidate.registryKey === toolKey);
}
function summarizeActiveToolsForSpan(activeTools, tools) {
	if (!Array.isArray(activeTools)) return;
	const toolRegistry = summarizeProcessorToolRegistry(tools) ?? [];
	return activeTools.map((tool) => {
		const toolKey = readString(tool);
		if (toolKey === void 0) return;
		const match = resolveToolInRegistry(toolRegistry, toolKey);
		return {
			id: match?.summary.id ?? toolKey,
			name: match?.summary.name ?? toolKey
		};
	}).filter((tool) => tool !== void 0);
}
function summarizeToolChoiceForSpan(toolChoice, tools) {
	if (typeof toolChoice === "string") return { type: toolChoice };
	if (!isPlainObject(toolChoice)) return;
	const type = readString(toolChoice.type);
	if (type === void 0) return;
	if (type !== "tool") return { type };
	const toolKey = readString(toolChoice.toolName) ?? readString(toolChoice.toolId);
	if (toolKey === void 0) return { type };
	const match = resolveToolInRegistry(summarizeProcessorToolRegistry(tools) ?? [], toolKey);
	const fallbackToolId = readString(toolChoice.toolId) ?? toolKey;
	const fallbackToolName = readString(toolChoice.toolName) ?? toolKey;
	return {
		type,
		tool: match ? {
			id: match.summary.id,
			name: match.summary.name
		} : {
			id: fallbackToolId,
			name: fallbackToolName
		}
	};
}
function summarizeProcessorResultForSpan(value) {
	if (!isPlainObject(value)) return;
	const projected = {};
	for (const key of [
		"text",
		"object",
		"finishReason",
		"toolCalls",
		"toolResults",
		"warnings",
		"files",
		"sources",
		"reasoning",
		"reasoningText",
		"tripwire"
	]) if (value[key] !== void 0) projected[key] = value[key];
	if (Array.isArray(value.steps)) projected.stepCount = value.steps.length;
	return Object.keys(projected).length > 0 ? projected : void 0;
}
// src/processors/stream-reprocess.ts
/**
* Well-known key a stream output processor can set on its `state` to ask the
* ProcessorRunner to re-drive an additional part through the full output
* processor chain after the current part has been emitted.
*
* `processOutputStream` can only return a single part, but some processors
* (e.g. `BatchPartsProcessor`) need to emit two parts for one input: a flushed
* batch of buffered text plus the non-text part that triggered the flush. The
* processor returns the flushed batch (so it flows through downstream
* processors normally) and stashes the non-text part under this key. The runner
* then re-feeds the stashed part through the whole chain so it also receives
* downstream processing and is emitted in order — instead of being deferred to
* a "next" call that may never happen (which dropped the part when a `stopWhen`
* condition stopped the agent on that part — issue #17094).
*/
const REPROCESS_PART_KEY = "__mastraReprocessPart";
/**
* Well-known key a stream output processor sets on its `state` when it holds
* parts back until a later part arrives (a batch, a sentence buffer). The value
* is a function that releases every held part, already processed by the
* holding processor, and clears the hold.
*
* When the stream ends, the runner calls it and pushes the released parts
* through the processors after the holder, so held text is not dropped when
* nothing follows the last held part (issue #27523).
*/
const FLUSH_HELD_PARTS_KEY = "__mastraFlushHeldParts";
/** Whether a part marks its model stream as errored or aborted (held parts are then discarded). */
function isFailedStreamChunk(part) {
	if (part.type === "error" || part.type === "abort") return true;
	if (part.type !== "finish") return false;
	const reason = part.payload?.stepResult?.reason;
	return reason === "error" || reason === "abort";
}
/** Drops content parts from a discarded hold, keeping control parts (start, error, finish, ...). */
function withoutHeldContent(parts) {
	return parts.filter((part) => part.type !== "text-delta" && part.type !== "reasoning-delta");
}
/** Releases the parts a processor is holding, or none if it holds nothing. */
async function takeHeldParts(state, options) {
	const flush = state?.[FLUSH_HELD_PARTS_KEY];
	return flush ? await flush(options) : [];
}
// src/processors/provider-history-compat.ts
function getErrorCandidates(error) {
	const candidates = [error.message];
	if (APICallError.isInstance(error) && typeof error.responseBody === "string") candidates.push(error.responseBody);
	return candidates.filter(Boolean);
}
function matchesRule(error, rule) {
	if (!rule.errorPatterns?.length) return false;
	const matches = (text) => rule.errorPatterns.some((p) => p.test(text));
	if (APICallError.isInstance(error)) return getErrorCandidates(error).some(matches);
	if (error instanceof Error) return getErrorCandidates(error).some(matches);
	return false;
}
const VALID_TOOL_ID_PATTERN = /^[a-zA-Z0-9_-]+$/;
function sanitizeToolId(id) {
	return id.replace(/[^a-zA-Z0-9_-]/g, "_");
}
function buildToolIdMap(messages) {
	const idMap = /* @__PURE__ */ new Map();
	for (const msg of messages) {
		if (!msg.content?.parts) continue;
		for (const part of msg.content.parts) if (part.type === "tool-invocation") {
			const id = part.toolInvocation.toolCallId;
			if (id && !VALID_TOOL_ID_PATTERN.test(id) && !idMap.has(id)) idMap.set(id, sanitizeToolId(id));
		}
		if (msg.content.toolInvocations) for (const inv of msg.content.toolInvocations) {
			const id = inv.toolCallId;
			if (id && !VALID_TOOL_ID_PATTERN.test(id) && !idMap.has(id)) idMap.set(id, sanitizeToolId(id));
		}
	}
	return idMap;
}
function rewriteToolIds(messages, idMap) {
	for (const msg of messages) {
		if (msg.content?.parts) for (let i = 0; i < msg.content.parts.length; i++) {
			const part = msg.content.parts[i];
			if (part.type === "tool-invocation") {
				const oldId = part.toolInvocation.toolCallId;
				const newId = idMap.get(oldId);
				if (newId) part.toolInvocation = {
					...part.toolInvocation,
					toolCallId: newId
				};
			}
		}
		if (msg.content?.toolInvocations) for (const inv of msg.content.toolInvocations) {
			const newId = idMap.get(inv.toolCallId);
			if (newId) inv.toolCallId = newId;
		}
	}
}
/**
* Rewrites invalid tool-call IDs in the outbound prompt, keeping call↔result
* pairing intact. Nothing is persisted — the prompt is rebuilt, and the
* original ids stay in the message list.
*
* Replacements are assigned per call, in encounter order, and never collide
* with an id the prompt already carries: a sanitized id that is already
* claimed — by another original id or by a valid id elsewhere in the prompt —
* gets `_2`, `_3`, … appended until it is unique. Anthropic rejects duplicate
* `tool_use.id` values, so uniqueness is what keeps call/result pairing
* resolvable. Two calls that share one invalid original id still receive
* distinct replacements; the nth result carrying that id pairs with the nth
* call, which is the only resolvable reading of an already-degenerate prompt.
*/
function rewritePromptToolIds(prompt) {
	const replacements = /* @__PURE__ */ new Map();
	const claimed = /* @__PURE__ */ new Set();
	for (const message of prompt) {
		if (message.role === "assistant" && Array.isArray(message.content)) {
			for (const part of message.content) if (part.type === "tool-call") claimed.add(part.toolCallId);
			continue;
		}
		if (message.role === "tool") for (const part of message.content) claimed.add(part.toolCallId);
	}
	let assigned = 0;
	for (const message of prompt) {
		if (message.role !== "assistant" || !Array.isArray(message.content)) continue;
		for (const part of message.content) {
			if (part.type !== "tool-call") continue;
			const id = part.toolCallId;
			if (VALID_TOOL_ID_PATTERN.test(id)) continue;
			const sanitized = sanitizeToolId(id);
			let candidate = sanitized;
			for (let suffix = 2; claimed.has(candidate); suffix++) candidate = `${sanitized}_${suffix}`;
			claimed.add(candidate);
			const queue = replacements.get(id);
			if (queue) queue.push(candidate);
			else replacements.set(id, [candidate]);
			assigned++;
		}
	}
	if (assigned === 0) return void 0;
	const callIndex = /* @__PURE__ */ new Map();
	const resultIndex = /* @__PURE__ */ new Map();
	const takeAt = (index, id) => {
		const queue = replacements.get(id);
		if (!queue) return void 0;
		const i = index.get(id) ?? 0;
		index.set(id, i + 1);
		return i < queue.length ? queue[i] : void 0;
	};
	const takeCall = (id) => takeAt(callIndex, id);
	const takeResult = (id) => takeAt(resultIndex, id);
	return prompt.map((message) => {
		if (message.role === "assistant" && Array.isArray(message.content)) {
			let changed = false;
			const content = message.content.map((part) => {
				if (part.type !== "tool-call") return part;
				const replacement = takeCall(part.toolCallId);
				if (!replacement) return part;
				changed = true;
				return {
					...part,
					toolCallId: replacement
				};
			});
			return changed ? {
				...message,
				content
			} : message;
		}
		if (message.role === "tool") {
			let changed = false;
			const content = message.content.map((part) => {
				const replacement = takeResult(part.toolCallId);
				if (!replacement) return part;
				changed = true;
				return {
					...part,
					toolCallId: replacement
				};
			});
			return changed ? {
				...message,
				content
			} : message;
		}
		return message;
	});
}
/**
* Anthropic enforces `^[a-zA-Z0-9_-]+$` on tool_use.id values.
* Tool-call IDs from other providers (e.g. containing `.`, `:`) will be
* rejected. This rule rewrites offending characters to `_` in the outbound
* prompt, so the rejection never happens and persisted history keeps its
* original IDs.
*/
const anthropicToolIdFormat = {
	name: "anthropic-tool-id-format",
	/**
	* Matches Anthropic's tool_use.id rejection. The preemptive
	* `applyToPrompt` hook repairs the outbound prompt first, so this pattern
	* only fires when that hook cannot see the request: Anthropic served
	* through a provider `isMaybeAnthropic` does not recognize (for example
	* Vertex- or Bedrock-hosted Claude), or compat configured outside the
	* agent's prompt path.
	*/
	errorPatterns: [/tool_use\.id:.*should match pattern/i, /tool_call_id.*invalid/i],
	/**
	* Rewrites invalid tool-call ids in place after a provider rejection.
	* This is the fallback repair for Anthropic served through a provider the
	* preemptive `applyToPrompt` check does not recognize (for example Vertex-
	* or Bedrock-hosted Claude), and the only repair available once an API
	* call has already been rejected.
	*/
	fix(messages) {
		const idMap = buildToolIdMap(messages);
		if (idMap.size === 0) return false;
		rewriteToolIds(messages, idMap);
		return true;
	},
	applyToPrompt({ prompt, model }) {
		if (!isMaybeAnthropic(model)) return void 0;
		return rewritePromptToolIds(prompt);
	}
};
/**
* Detects whether a model is (or might be) routed through Cerebras.
*
* Cerebras's API rejects assistant messages carrying `reasoning_content`
* (the field `@ai-sdk/openai-compatible@>=1.0.32` adds when serializing
* reasoning parts). A flexible matcher is used here because the model arg
* passed to processors may be a resolved language model, an unresolved
* model id string, a dynamic function, or a fallback array.
*/
function matchesProviderPrefix(model, providerPrefix) {
	if (model == null) return false;
	if (typeof model === "function") return false;
	if (Array.isArray(model)) return model.some((m) => matchesProviderPrefix(m.model ?? m, providerPrefix));
	const gatewayPattern = new RegExp(`^${providerPrefix}[/:]`, "i");
	const providerPattern = new RegExp(`^${providerPrefix}($|[.\\-])`, "i");
	if (typeof model === "string") return gatewayPattern.test(model);
	if (typeof model === "object") {
		const { provider, modelId } = model;
		if (typeof provider === "string" && providerPattern.test(provider)) return true;
		if (typeof modelId === "string") return gatewayPattern.test(modelId);
	}
	return false;
}
/**
* Extract the exact provider id from a resolved model — the same value
* `buildResponseModelMetadata` stamps onto each persisted assistant turn.
* Returns `undefined` for unresolved string ids and dynamic functions, where
* no reliable provider identity exists.
*/
function getModelProviderId(model) {
	if (model == null || typeof model === "function" || typeof model === "string") return void 0;
	if (Array.isArray(model)) {
		for (const entry of model) {
			const provider = getModelProviderId(entry.model ?? entry);
			if (provider) return provider;
		}
		return;
	}
	if (typeof model === "object") {
		const provider = model.provider;
		return typeof provider === "string" && provider.length > 0 ? provider : void 0;
	}
}
function isMaybeCerebras(model) {
	return matchesProviderPrefix(model, "cerebras");
}
function isMaybeAnthropic(model) {
	return matchesProviderPrefix(model, "anthropic");
}
function getModelProviderFamily(model) {
	if (matchesProviderPrefix(model, "anthropic")) return "anthropic";
	if (matchesProviderPrefix(model, "openai") || matchesProviderPrefix(model, "azure")) return "openai";
	if (matchesProviderPrefix(model, "google") || matchesProviderPrefix(model, "vertex")) return "google";
}
function getPartProviderFamily(part) {
	if (!part.providerOptions || typeof part.providerOptions !== "object") return void 0;
	const providers = Object.keys(part.providerOptions);
	if (providers.some((provider) => provider === "anthropic")) return "anthropic";
	if (providers.some((provider) => provider === "openai" || provider === "azure")) return "openai";
	if (providers.some((provider) => provider === "google" || provider === "vertex")) return "google";
}
/**
* Provider-executed tools are provider-owned continuation state. A foreign
* provider cannot resolve their IDs, so remove the call and paired result from
* the outbound prompt while leaving persisted history untouched.
*/
const stripForeignProviderExecutedTools = {
	name: "strip-foreign-provider-executed-tools",
	applyToPrompt({ prompt, model }) {
		const destinationProvider = getModelProviderFamily(model);
		if (!destinationProvider) return void 0;
		const foreignToolCallIds = /* @__PURE__ */ new Set();
		for (const message of prompt) {
			if (message.role !== "assistant" || !Array.isArray(message.content)) continue;
			for (const part of message.content) {
				if (part.type !== "tool-call" || !part.providerExecuted) continue;
				const sourceProvider = getPartProviderFamily(part);
				if (sourceProvider && sourceProvider !== destinationProvider) foreignToolCallIds.add(part.toolCallId);
			}
		}
		if (foreignToolCallIds.size === 0) return void 0;
		const rewritten = [];
		for (const message of prompt) {
			if (message.role === "assistant") {
				const content = message.content.filter((part) => part.type !== "tool-call" && part.type !== "tool-result" || !foreignToolCallIds.has(part.toolCallId));
				if (content.length > 0) rewritten.push({
					...message,
					content
				});
				continue;
			}
			if (message.role === "tool") {
				const content = message.content.filter((part) => !foreignToolCallIds.has(part.toolCallId));
				if (content.length > 0) rewritten.push({
					...message,
					content
				});
				continue;
			}
			rewritten.push(message);
		}
		return rewritten;
	}
};
const CLAUDE_VERSION_PATTERN = /claude-(?:(?:opus|sonnet|haiku)-)?(\d+)(?:[.-](\d+))?/i;
function supportsAssistantPrefill(modelId) {
	const match = CLAUDE_VERSION_PATTERN.exec(modelId);
	if (!match) return void 0;
	const major = Number(match[1]);
	const minor = Number(match[2] ?? 0);
	return major < 4 || major === 4 && minor < 6;
}
const GEMINI_VERSION_PATTERN = /gemini-(\d+)/i;
function supportsTrailingModelTurn(modelId) {
	const match = GEMINI_VERSION_PATTERN.exec(modelId);
	if (!match) return void 0;
	return Number(match[1]) < 3;
}
/**
* Detects Anthropic models that removed assistant-message prefill support.
* Claude 4.6 and later reject assistant-prefill requests, while earlier
* models retain support. Unknown Anthropic model versions are matched
* conservatively so a new model cannot silently bypass compatibility guards.
*/
function isMaybeAnthropicWithoutAssistantPrefill(model) {
	if (typeof model === "function") return true;
	if (Array.isArray(model)) return model.some((entry) => isMaybeAnthropicWithoutAssistantPrefill(entry.model ?? entry));
	if (!isMaybeAnthropic(model)) return false;
	const modelId = typeof model === "string" ? model : model && typeof model === "object" && typeof model.modelId === "string" ? model.modelId : void 0;
	if (!modelId) return true;
	return supportsAssistantPrefill(modelId) !== true;
}
/**
* Detects Google models that reject a request ending on a model turn.
*
* Gemini 3 and later return 400 "Requests ending with a model turn are not
* supported"; Gemini 2.x accepted the same prompt, including under native
* structured output. Unknown Google model versions are matched conservatively
* so a new model cannot silently bypass compatibility guards.
*
* @see https://github.com/mastra-ai/mastra/issues/23320
*/
function isMaybeGoogleWithoutTrailingModelTurn(model) {
	if (typeof model === "function") return true;
	if (Array.isArray(model)) return model.some((entry) => isMaybeGoogleWithoutTrailingModelTurn(entry.model ?? entry));
	if (getModelProviderFamily(model) !== "google") return false;
	const modelId = typeof model === "string" ? model : model && typeof model === "object" && typeof model.modelId === "string" ? model.modelId : void 0;
	if (!modelId) return true;
	return supportsTrailingModelTurn(modelId) !== true;
}
function isMaybeAzure(model) {
	if (Array.isArray(model)) return model.some((entry) => isMaybeAzure(entry.model ?? entry));
	if (model && typeof model === "object") {
		const { provider, modelId } = model;
		if (typeof provider === "string" && /^(?:azure|azure-openai)(?:\.[a-z0-9_-]+)?$/i.test(provider)) return true;
		return typeof modelId === "string" && (matchesProviderPrefix(modelId, "azure") || matchesProviderPrefix(modelId, "azure-openai"));
	}
	return matchesProviderPrefix(model, "azure") || matchesProviderPrefix(model, "azure-openai");
}
/**
* Detects providers that reject a conversation whose first non-system turn is
* the assistant's: Amazon Bedrock ("A conversation must start with a user
* message") and Google/Vertex Gemini. OpenAI, Anthropic, Groq, Mistral,
* DeepSeek and Cerebras accept that shape, so they are left alone.
*
* @see https://github.com/mastra-ai/mastra/issues/5465
* @see https://github.com/mastra-ai/mastra/issues/8053
*/
function isMaybeRequiringUserFirstTurn(model) {
	return getModelProviderFamily(model) === "google" || matchesProviderPrefix(model, "amazon") || matchesProviderPrefix(model, "amazon-bedrock") || matchesProviderPrefix(model, "bedrock");
}
/**
* Inserts a minimal user turn ahead of a leading assistant turn for providers
* that require conversations to start with the user (see
* {@link isMaybeRequiringUserFirstTurn}). History windows commonly start on an
* assistant turn — agents that greet first, or `lastMessages` cutting into a
* thread — and those providers reject the whole request otherwise.
*/
const ensureUserFirstTurn = {
	name: "ensure-user-first-turn",
	applyToPrompt({ prompt, model }) {
		if (!isMaybeRequiringUserFirstTurn(model)) return void 0;
		const firstTurnIndex = prompt.findIndex((message) => message.role !== "system");
		if (firstTurnIndex === -1 || prompt[firstTurnIndex].role !== "assistant") return void 0;
		return [
			...prompt.slice(0, firstTurnIndex),
			{
				role: "user",
				content: [{
					type: "text",
					text: "."
				}]
			},
			...prompt.slice(firstTurnIndex)
		];
	}
};
/**
* Returns the index of the trailing assistant message whose thinking blocks
* Anthropic verifies byte-for-byte: the last message when it is an assistant
* message, or the assistant message that only has tool messages after it (an
* active tool-use continuation). Returns `-1` when no such message exists —
* e.g. when the prompt ends with a fresh user turn, in which case Anthropic
* ignores thinking blocks on earlier assistant messages.
*/
function getProtectedAssistantIndex(prompt) {
	for (let i = prompt.length - 1; i >= 0; i--) {
		const role = prompt[i].role;
		if (role === "assistant") return i;
		if (role !== "tool") return -1;
	}
	return -1;
}
/**
* Returns a copy of the prompt with selected `reasoning` parts stripped from
* assistant messages, dropping any assistant message left with no content.
* Returns `undefined` if no changes were necessary.
*
* `skipIndex` excludes one message from stripping — used to protect the
* trailing assistant message of an active tool-use continuation, which
* Anthropic requires to be replayed unmodified ("`thinking` or
* `redacted_thinking` blocks in the latest assistant message cannot be
* modified").
*/
function stripReasoningFromPrompt(prompt, shouldStrip = () => true, skipIndex = -1) {
	let mutated = false;
	const next = [];
	for (let index = 0; index < prompt.length; index++) {
		const message = prompt[index];
		if (index === skipIndex || message.role !== "assistant" || typeof message.content === "string" || !Array.isArray(message.content)) {
			next.push(message);
			continue;
		}
		const filtered = message.content.filter((part) => part.type !== "reasoning" || !shouldStrip(part));
		if (filtered.length === message.content.length) {
			next.push(message);
			continue;
		}
		mutated = true;
		if (filtered.length === 0) continue;
		next.push({
			...message,
			content: filtered
		});
	}
	return mutated ? next : void 0;
}
function isAnthropicReasoningPart(part) {
	const providerOptions = part.providerOptions;
	if (providerOptions && typeof providerOptions === "object" && "anthropic" in providerOptions) return true;
	const providerMetadata = part.providerMetadata;
	if (providerMetadata && typeof providerMetadata === "object" && "anthropic" in providerMetadata) return true;
	return false;
}
function getProtectedAnthropicAssistantIndex(prompt) {
	const index = getProtectedAssistantIndex(prompt);
	if (index === -1) return -1;
	const message = prompt[index];
	if (message.role !== "assistant" || !Array.isArray(message.content)) return -1;
	return message.content.some((part) => part.type === "reasoning" && isAnthropicReasoningPart(part)) ? index : -1;
}
function getProviderMetadataForProvider(metadata, provider) {
	if (!metadata || typeof metadata !== "object") return void 0;
	const value = metadata[provider];
	return value && typeof value === "object" ? value : void 0;
}
function isEmptySignedReasoning(part) {
	if (part.type !== "reasoning") return false;
	const signature = getProviderMetadataForProvider(part.providerMetadata, "anthropic")?.signature;
	if (typeof signature !== "string" || signature.length === 0) return false;
	return !(typeof part.reasoning === "string" && part.reasoning.length > 0 || (part.details ?? []).some((detail) => detail.type === "text" && detail.text.length > 0));
}
/**
* Cerebras's API rejects assistant messages carrying a `reasoning_content`
* field with HTTP 400 (`property '...reasoning_content' is unsupported`).
*
* Starting in `@ai-sdk/openai-compatible@1.0.32` (https://github.com/vercel/ai/pull/12049),
* which `@ai-sdk/cerebras` depends on, reasoning parts on assistant messages
* are unconditionally serialized as `reasoning_content` on outbound requests.
* That breaks multi-turn tool calls with reasoning enabled (e.g.
* `cerebras/zai-glm-4.7`) on the second-or-later assistant turn.
*
* This rule preemptively strips `reasoning` parts from assistant messages
* in the outbound prompt when the resolved model is Cerebras. The strip
* runs in `processLLMRequest` so it affects only what is sent to Cerebras —
* the persisted message list (memory, UI, observability) keeps the full
* reasoning trace, and other providers (e.g. Z.ai's coding-plan endpoint,
* which *requires* `reasoning_content` echoed back for its preserved-thinking
* feature) are unaffected because the rule is provider-scoped.
*
* It can't be reactive (`processAPIError`) because the model emits a fresh
* reasoning part on every turn — a reactive rule would cause one
* failed-and-retried request per turn.
*
* Once https://github.com/vercel/ai/pull/11278 lands a per-provider
* `sendReasoning` opt-out, this rule can be replaced with `sendReasoning: false`
* on the cerebras provider config.
*/
const cerebrasStripReasoningContent = {
	name: "cerebras-strip-reasoning-content",
	applyToPrompt({ prompt, model }) {
		if (!isMaybeCerebras(model)) return void 0;
		return stripReasoningFromPrompt(prompt);
	}
};
/**
* Legacy records could contain Anthropic signed thinking metadata with an
* empty reasoning text. Anthropic signs the exact thinking text, so replaying
* that mismatched pair is rejected with the "thinking blocks cannot be
* modified" 400.
*
* Reactive, because an empty text with a signature is not by itself a sign of
* corruption: Claude 5.x returns exactly that for every thinking block when
* `display` is left at its default (`omitted`). Stripping those up front would
* change the prompt prefix on every step and break prompt caching, so the
* blocks are only dropped, from earlier assistant messages, once Anthropic has
* actually rejected the history.
*
* @see https://github.com/mastra-ai/mastra/issues/28309
*/
const anthropicStripEmptySignedReasoningContent = {
	name: "anthropic-strip-empty-signed-reasoning-content",
	errorPatterns: [/thinking`? or `?redacted_thinking`? blocks in the latest assistant message cannot be modified/i],
	fix(messages) {
		let mutated = false;
		const protectedIndex = messages.at(-1)?.role === "assistant" ? messages.length - 1 : -1;
		messages.forEach((message, index) => {
			const parts = message.content?.parts;
			if (message.role !== "assistant" || index === protectedIndex || !parts?.length) return;
			const kept = parts.filter((part) => !isEmptySignedReasoning(part));
			if (kept.length === parts.length) return;
			parts.splice(0, parts.length, ...kept);
			mutated = true;
		});
		return mutated;
	}
};
/**
* Anthropic accepts its own thinking/reasoning history, but rejects reasoning
* parts emitted by other providers. Strip only foreign reasoning parts at the
* Anthropic provider boundary so persisted history remains intact and native
* Anthropic thinking can still round-trip.
*/
const anthropicStripForeignReasoningContent = {
	name: "anthropic-strip-foreign-reasoning-content",
	applyToPrompt({ prompt, model }) {
		if (!isMaybeAnthropic(model)) return void 0;
		return stripReasoningFromPrompt(prompt, (part) => !isAnthropicReasoningPart(part), getProtectedAnthropicAssistantIndex(prompt));
	}
};
/**
* Replays of signed `thinking`/`redacted_thinking` blocks to a provider other
* than the one that signed them are rejected — Anthropic returns
* `Invalid \`signature\` in \`thinking\` block`.
*
* Several providers are served through `@ai-sdk/anthropic` and therefore write
* their reasoning metadata under the same `anthropic` key — Kimi For Coding
* talks to `api.kimi.com` over the Anthropic wire format — so a signature's
* `anthropic` key alone cannot tell which provider signed it. The durable
* provenance is the `provider` each assistant turn was stamped with by
* `buildResponseModelMetadata`, which only the persisted message list carries.
*
* Reasoning parts whose signature came from a turn stamped with a provider
* different from the current target are dropped from the outbound prompt, so
* the rejection never happens. Unstamped history is left untouched — turns
* persisted before their provider had a distinct identity stay ambiguous and
* are forwarded as-is. Turns emptied of all content by the drop are removed
* from the prompt (Anthropic rejects empty assistant content).
*/
const anthropicStripForeignSignedReasoning = {
	name: "anthropic-strip-foreign-signed-reasoning",
	applyToPrompt({ prompt, model, messageList }) {
		if (!messageList) return void 0;
		const targetProvider = getModelProviderId(model);
		if (!targetProvider) return void 0;
		const foreign = /* @__PURE__ */ new Map();
		for (const dbMessage of messageList.get.all.db()) {
			if (dbMessage.role !== "assistant") continue;
			if (dbMessage.content?.format !== 2) continue;
			const origin = dbMessage.content.metadata?.provider;
			if (typeof origin !== "string" || origin === targetProvider) continue;
			for (const part of dbMessage.content.parts ?? []) {
				if (part.type !== "reasoning") continue;
				const anthropic = part.providerMetadata?.anthropic;
				for (const value of [anthropic?.signature, anthropic?.redactedData]) if (typeof value === "string" && value && !foreign.has(value)) foreign.set(value, origin);
			}
		}
		if (foreign.size === 0) return void 0;
		let dropped = 0;
		const next = [];
		for (const message of prompt) {
			if (message.role !== "assistant" || !Array.isArray(message.content)) {
				next.push(message);
				continue;
			}
			const content = message.content.filter((part) => {
				if (part.type !== "reasoning") return true;
				const anthropic = part.providerOptions?.anthropic;
				const signature = anthropic?.signature ?? anthropic?.redactedData;
				if (typeof signature === "string" && foreign.has(signature)) {
					dropped++;
					return false;
				}
				return true;
			});
			if (content.length === message.content.length) {
				next.push(message);
				continue;
			}
			if (content.length > 0) next.push({
				...message,
				content
			});
		}
		return dropped > 0 ? next : void 0;
	}
};
const SYSTEM_REMINDER_OPEN_TAG = /<system-reminder(?=\s|\/?>)([^>]*)>/g;
const SYSTEM_REMINDER_CLOSE_TAG = /<\/system-reminder>/g;
function rewriteSystemReminderTags(text) {
	return text.replace(SYSTEM_REMINDER_OPEN_TAG, "<memory-context$1>").replace(SYSTEM_REMINDER_CLOSE_TAG, "</memory-context>");
}
/**
* Azure OpenAI's content moderation can classify `<system-reminder>` wrappers
* in user messages as prompt injection. Rename the wrapper at the provider
* boundary while leaving persisted history and other providers unchanged.
*/
const azureSystemReminderTransform = {
	name: "azure-system-reminder-transform",
	applyToPrompt({ prompt, model }) {
		if (!isMaybeAzure(model)) return void 0;
		let mutated = false;
		const next = prompt.map((message) => {
			if (message.role === "system") {
				const content = rewriteSystemReminderTags(message.content);
				if (content === message.content) return message;
				mutated = true;
				return {
					...message,
					content
				};
			}
			if (message.role !== "user") return message;
			let messageMutated = false;
			const content = message.content.map((part) => {
				if (part.type !== "text") return part;
				const text = rewriteSystemReminderTags(part.text);
				if (text === part.text) return part;
				mutated = true;
				messageMutated = true;
				return {
					...part,
					text
				};
			});
			return messageMutated ? {
				...message,
				content
			} : message;
		});
		return mutated ? next : void 0;
	}
};
function hasReasoningPart(message) {
	return (message.content?.parts ?? []).some((p) => p.type === "reasoning");
}
/**
* True when `message` looks like the leading half of a turn that storage split across two
* assistant rows: it carries a reasoning item and has not yet produced text of its own. A
* following text row is then covered by that reasoning item.
*
* Deliberately not "has any reasoning part" — a previous row that already paired its own
* reasoning with its own text says nothing about the row after it, and treating it as cover
* would leave a genuine orphan unrepaired. The retry would then hit the same 400, and
* `processAPIError` stops after its second pass, turning a recoverable turn into a hard failure.
*/
function isUnpairedReasoningRow(message) {
	const parts = message.content?.parts ?? [];
	return parts.some((p) => p.type === "reasoning") && !parts.some((p) => p.type === "text");
}
/**
* Strips `itemId` and its result-side partner from every Responses namespace a
* part carries, in both metadata containers, leaving every other field (cache
* counts, reasoning-token counts, logprobs) intact. Mirrors the narrow
* destructure in `client-sdks/ai-sdk/src/helpers.ts` (PR #23323).
*
* {@link RESPONSE_RESULT_ITEM_ID_KEY} has to go with it: a merged tool part
* keeps the result half of the pair under that key, and
* `splitResponsesToolItemReferences` turns it back into an `itemId` on the
* tool-result part during conversion. Dropping only `itemId` would leave a
* live reference into the very response that was rejected.
*
* Both `providerMetadata` and `providerOptions` are cleared because
* {@link getResponseProviderItemIdFromPart} reads an id from either, so
* leaving one behind would report a part as still item-bearing — and would
* leave the unsatisfiable reference in the prompt, which is the whole failure.
*
* Returns true when it removed an id.
*/
function stripResponseItemIds(part) {
	const containers = [part.providerMetadata, part.providerOptions];
	let stripped = false;
	for (const container of containers) {
		if (!container) continue;
		for (const provider of RESPONSE_ITEM_ID_PROVIDERS) {
			const namespace = container[provider];
			if (!namespace) continue;
			if (!("itemId" in namespace) && !("resultItemId" in namespace)) continue;
			const { itemId: _itemId, [RESPONSE_RESULT_ITEM_ID_KEY]: _resultItemId, ...rest } = namespace;
			container[provider] = rest;
			stripped = true;
		}
	}
	return stripped;
}
/**
* OpenAI's Responses API replays a persisted assistant message by reference
* (`item_reference`) when the message carries an `itemId` (`msg_…`). If that
* message has no accompanying `reasoning` item, the request is rejected with a
* non-retryable 400:
*
* ```
* Item 'msg_…' of type 'message' was provided without its required 'reasoning' item: 'rs_…'
* ```
*
* Because the offending message is already persisted, that 400 repeats on every
* subsequent turn, and the thread stops working. This rule is a recovery
* seatbelt for histories that are *already* corrupted: dropping the `itemId`
* makes the message replay by value instead of by reference, which OpenAI
* accepts. The content the user sees is unchanged.
*
* The repair is in-memory for the current turn: a message sourced from storage
* is not re-drained, so a later turn on the same thread spends one rejected
* request before recovering again. Same property as `anthropicToolIdFormat`.
*
* Reactive by design — it fires only after OpenAI has actually rejected the
* request, so a legitimately reasoning-free message (e.g.
* `reasoning.effort: 'none'`, or a non-reasoning model) is untouched on any
* thread that has not already hit this 400. Once it has, see the collateral
* note below.
*
* Deliberately narrow:
* - Matches only the `of type 'message'` phrasing. The sibling `function_call`
*   (`fc_…`) variant is a different failure, addressed by PR #19408. Matching
*   narrowly is not the same as repairing narrowly, though: once a message is
*   established as an orphan, every item reference it carries is unsatisfiable
*   for the same reason, so the repair covers all of them. A message whose
*   `msg_…` id was dropped while its `fc_…` id stayed would simply fail on the
*   next item in the list, spending the one available retry to arrive at the
*   same error.
* - Strips only the item-reference keys (`itemId` and its result-side partner
*   `resultItemId`); all other fields in the namespace survive.
* - Reads and strips through the shared Responses helpers, so the `azure`
*   namespace is covered on the same footing as `openai` — the repo treats
*   them as one Responses family, and Azure raises this same 400.
* - Skips a message whose reasoning lives on the immediately preceding
*   assistant row, when that row has reasoning and no text of its own. Stored
*   history can split one turn across adjacent assistant rows (adjacent rows
*   are merged when streamed, but not when loaded from storage), and in that
*   case the reasoning item *is* present in the prompt — stripping the id
*   there would fix nothing and would discard a valid reference. A preceding
*   row that already paired its own reasoning with its own text is not cover
*   and does not suppress the repair.
*
* Not covered by that guard, deliberately: the `assistant[reasoning, tool-call]
* → tool[result] → assistant[text]` shape, where the preceding entry is a tool
* message. If OpenAI rejected the text item there, its reference is genuinely
* unsatisfiable and stripping is the right repair.
*
* The rule repairs every orphan-shaped message in the history rather than only
* the id named in the error, because `fix` does not receive the error and the
* error names only the first item OpenAI tripped over. Healing that one id
* would trade a permanent failure for N sequential ones, and there is a single
* retry available, not N.
*
* The cost of that breadth: in a thread that mixes a reasoning model with a
* non-reasoning Responses model, the non-reasoning turns are also orphan-shaped
* (an `itemId`, no reasoning) but are perfectly valid, and they lose their item
* references too. Ordinary text and tool parts still replay correctly — by
* value instead of by reference — so for them the effect is a lost item
* reference, not a failure.
*
* One part type pays more than a reference. A hosted `tool_search` call cannot
* be replayed by value at all, so `isUnreplayableHostedToolSearchPart`
* (`output-converter.ts`) drops it from the prompt once its ids are gone. On a
* genuinely orphaned message that is the right outcome — the ids pointed into
* the rejected response. On a swept-along valid message it costs the model that
* search result, and it would have to search again. That is accepted: the
* asymmetry is still deliberate, because under-stripping ends the turn outright
* while over-stripping costs a reference, or at worst one hosted search.
*
* Known limitation: the guard reasons about message *shape*, because the
* required `rs_…` id named in the error is not available to `fix`. A turn whose
* reasoning row belongs to a different turn could in principle be skipped
* when it should have been repaired. That case degrades to today's behavior — the turn
* fails as it already does — so the guard can cost a recovery, never cause a
* new failure.
*
* This is a seatbelt, not the cure: the path that produces these orphans is
* fixed separately in the processor-retry rollback (#22291).
*/
const openaiOrphanItemId = {
	name: "openai-orphan-item-id",
	errorPatterns: [/Item '[^']*' of type 'message' was provided without its required 'reasoning' item/i],
	fix(messages) {
		let mutated = false;
		messages.forEach((message, index) => {
			if (message.role !== "assistant") return;
			const parts = message.content?.parts;
			if (!parts?.length) return;
			if (hasReasoningPart(message)) return;
			const previous = messages[index - 1];
			if (previous?.role === "assistant" && isUnpairedReasoningRow(previous)) return;
			for (const part of parts) {
				if (!getResponseProviderItemIdFromPart(part)) continue;
				mutated = stripResponseItemIds(part) || mutated;
			}
		});
		return mutated;
	}
};
/**
* All built-in compat rules. Extend by passing additional rules to the
* `ProviderHistoryCompat` constructor.
*/
const DEFAULT_COMPAT_RULES = [
	stripForeignProviderExecutedTools,
	anthropicToolIdFormat,
	cerebrasStripReasoningContent,
	{
		name: "anthropic-orphaned-thinking-step",
		errorPatterns: [/thinking`? or `?redacted_thinking`? blocks in the latest assistant message cannot be modified/i],
		fix(messages) {
			let mutated = false;
			messages.forEach((message, index) => {
				const parts = message.content?.parts;
				if (message.role !== "assistant" || !parts?.length) return;
				const followedByAssistant = messages[index + 1]?.role === "assistant";
				const steps = [];
				parts.forEach((part, i) => {
					const previous = parts[i - 1];
					if (part.type === "step-start" || previous?.type === "tool-invocation" && part.type !== "tool-invocation" || steps.length === 0) steps.push([]);
					steps[steps.length - 1].push(part);
				});
				const kept = steps.filter((step, i) => {
					const content = step.filter((part) => part.type !== "step-start" && !(part.type === "text" && !part.text?.trim()));
					return !(content.length > 0 && content.every((part) => part.type === "reasoning")) || i === steps.length - 1 && !followedByAssistant;
				});
				if (kept.length === steps.length) return;
				parts.splice(0, parts.length, ...kept.flat());
				mutated = true;
			});
			return mutated;
		}
	},
	anthropicStripEmptySignedReasoningContent,
	anthropicStripForeignReasoningContent,
	anthropicStripForeignSignedReasoning,
	azureSystemReminderTransform,
	openaiOrphanItemId,
	{
		name: "chat-completions-single-system-message",
		applyToPrompt({ prompt, model, apiProviderId }) {
			if (!(apiProviderId ?? getModelProviderId(model))?.endsWith(".chat")) return void 0;
			let leading = 0;
			while (leading < prompt.length && prompt[leading].role === "system") leading++;
			if (leading < 2) return void 0;
			const leadingMessages = prompt.slice(0, leading);
			if (leadingMessages.slice(0, -1).some((m) => m.providerOptions)) return void 0;
			const content = leadingMessages.map((m) => m.content).filter((text) => text.length > 0).join("\n\n");
			const { providerOptions } = leadingMessages[leading - 1];
			return [{
				role: "system",
				content,
				...providerOptions ? { providerOptions } : {}
			}, ...prompt.slice(leading)];
		}
	},
	{
		name: "tool-call-empty-input",
		applyToPrompt({ prompt }) {
			const isEmpty = (part) => part.type === "tool-call" && (part.input === void 0 || part.input === null);
			if (!prompt.some((m) => m.role === "assistant" && Array.isArray(m.content) && m.content.some(isEmpty))) return;
			return prompt.map((message) => message.role === "assistant" && Array.isArray(message.content) ? {
				...message,
				content: message.content.map((part) => isEmpty(part) ? {
					...part,
					input: {}
				} : part)
			} : message);
		}
	},
	ensureUserFirstTurn
];
/**
* Handles provider-specific history incompatibilities by applying a registry
* of {@link CompatRule}s. Rules can rewrite the outbound prompt preemptively
* via `processLLMRequest`, or react to non-retryable API rejections via
* `processAPIError`.
*
* Built-in rules:
* - **anthropic-tool-id-format** — rewrites tool-call IDs that contain
*   characters outside `[a-zA-Z0-9_-]` (e.g. `.` or `:` from other
*   providers). Preemptive; runs in `processLLMRequest` so the persisted
*   message list keeps its original IDs. Both the call and its paired result
*   are rewritten together, and a sanitized ID that would collide with an ID
*   already in the prompt gets a `_2`/`_3`… suffix. The reactive fallback
*   (matching a 400 response body and retrying with sanitized IDs) covers
*   providers the preemptive check doesn't recognize, such as Vertex-hosted
*   Claude.
* - **cerebras-strip-reasoning-content** — strips `reasoning` parts from
*   assistant messages in the outbound prompt when the resolved model is
*   Cerebras, to avoid the `@ai-sdk/openai-compatible@>=1.0.32` regression
*   that serializes them as `reasoning_content` (a field Cerebras's API
*   rejects). Preemptive; runs in `processLLMRequest` so the persisted
*   message list keeps the reasoning trace.
* - **anthropic-strip-empty-signed-reasoning-content** — strips legacy
*   Anthropic signed reasoning blocks whose text was lost before replay.
*   Reactive (matches the "thinking blocks cannot be modified" 400), because
*   Claude 5.x returns empty-text signed blocks as normal output and they must
*   be replayed untouched to keep the prompt cache.
* - **anthropic-strip-foreign-reasoning-content** — strips non-Anthropic
*   `reasoning` parts from assistant messages in the outbound prompt when the
*   resolved model is Anthropic. Anthropic-native reasoning parts are kept.
* - **anthropic-strip-foreign-signed-reasoning** — drops signed thinking
*   blocks from the outbound prompt when their origin turn was stamped with a
*   provider different from the current target (preemptive). Turns emptied of
*   all content by the drop are removed from the prompt. Unstamped history is
*   left untouched.
* - **openai-orphan-item-id** — drops the Responses `itemId` (`openai` and
*   `azure` namespaces alike) from every item-bearing part of an assistant
*   message that carries one but has no `reasoning` part, so it replays by
*   value instead of as an unsatisfiable `item_reference`. Reactive (matches
*   the specific `of type 'message' … without its required 'reasoning' item`
*   400); a recovery seatbelt for already-corrupted history.
* - **anthropic-orphaned-thinking-step** — drops steps left with only signed
*   reasoning when more assistant content follows them, so Anthropic doesn't
*   see that thinking merged into the next step. Reactive (matches the
*   "thinking blocks ... cannot be modified" 400); a recovery seatbelt for
*   already-corrupted history.
* - **chat-completions-single-system-message** — merges the leading system
*   messages into one for Chat Completions providers (API provider id ending
*   in `.chat`), whose hosted chat templates often reject a second system
*   message. Skipped when an earlier one carries its own `providerOptions`.
*   Preemptive.
* - **tool-call-empty-input** — sends an assistant tool call whose input is
*   `undefined` or `null` as `{}`, keeping its paired result, so a stored
*   call with unparseable arguments can't make every later request fail.
*   Preemptive; the stored message keeps its shape.
* - **ensure-user-first-turn** — inserts a `.` user turn ahead of a leading
*   assistant turn for Amazon Bedrock and Google/Vertex, which reject
*   assistant-first conversations. Preemptive; the turn is never persisted.
*
* To add custom rules, pass them to the constructor:
* ```ts
* new ProviderHistoryCompat({
*   additionalRules: [myCustomRule],
* })
* ```
*/
var ProviderHistoryCompat = class {
	id = "provider-history-compat";
	name = "Provider History Compat";
	rules;
	constructor(opts) {
		this.rules = [...DEFAULT_COMPAT_RULES, ...opts?.additionalRules ?? []];
	}
	processLLMRequest({ prompt, model, apiProviderId, messageList }) {
		let current = prompt;
		let mutated = false;
		for (const rule of this.rules) {
			if (!rule.applyToPrompt) continue;
			const next = rule.applyToPrompt({
				prompt: current,
				model,
				apiProviderId,
				messageList
			});
			if (next) {
				current = next;
				mutated = true;
			}
		}
		return mutated ? { prompt: current } : void 0;
	}
	async processAPIError({ error, messageList, retryCount }) {
		if (retryCount > 1) return;
		const messages = messageList.get.all.db();
		for (const rule of this.rules) {
			if (!rule.fix) continue;
			if (matchesRule(error, rule)) {
				if (rule.fix(messages)) return { retry: true };
			}
		}
	}
};
// src/processors/trailing-assistant-guard.ts
const SETTLED_TOOL_STATES = /* @__PURE__ */ new Set(["result", "output-error"]);
/** Metadata key that marks the synthetic user turn appended by {@link TrailingAssistantGuard}. */
const TRAILING_ASSISTANT_GUARD_CONTINUATION_KEY = "trailingAssistantGuardContinuation";
/** Whether `message` is the synthetic user turn appended by {@link TrailingAssistantGuard}. */
function isTrailingAssistantGuardContinuation(message) {
	return message.content.metadata?.[TRAILING_ASSISTANT_GUARD_CONTINUATION_KEY] === true;
}
/**
* Drop the guard's synthetic user turn once the step's prompt has been built. It only has
* to reach the provider; left in the list it sits between the trailing assistant message
* and the reply, so the reply is saved as a separate assistant message (#27520).
*/
function removeTrailingAssistantGuardContinuations(messageList) {
	const ids = messageList.get.all.db().filter(isTrailingAssistantGuardContinuation).map((message) => message.id);
	if (ids.length > 0) messageList.removeByIds(ids);
}
/**
* Whether a step needs `TrailingAssistantGuard` attached.
*
* True when the model as configured rejects a prompt ending on a model turn
* (Anthropic 4.6+ assistant prefill, Gemini 3+), or when any input processors are
* configured, since a processor may swap `model` mid-step. In the latter case the
* attach is speculative: the runner asks {@link TrailingAssistantGuard.appliesTo}
* against the final step model before running the guard, and skips it entirely
* (no processor span) when the provider does not need it.
*
* Used both where the `ProcessorRunner` is created for a step and where the
* runner assembles its processor list, so an agent with no input processors
* still gets a runner and that runner still appends the guard.
*/
function needsTrailingAssistantGuard(model, inputProcessors) {
	return inputProcessors.length > 0 || isMaybeAnthropicWithoutAssistantPrefill(model) || isMaybeGoogleWithoutTrailingModelTurn(model);
}
/**
* Whether the guard can have any effect for `model`. Cheap provider/version
* check the runner uses to skip a speculatively attached guard without
* recording a processor span for it.
*/
function trailingAssistantGuardAppliesTo(model) {
	return isMaybeGoogleWithoutTrailingModelTurn(model) || isMaybeAnthropicWithoutAssistantPrefill(model);
}
/**
* Whether the prompt built from this message will end on a model turn.
*
* Mirrors prompt conversion: a settled tool invocation becomes an assistant
* tool-call turn followed by a tool-result turn, so the prompt already ends on a
* non-model turn and appending a user message would inject a spurious turn into
* every agentic-loop step after a tool call. A still-pending invocation is either
* dropped from the prompt (default `MessageList` behaviour) — in which case the
* preceding content decides — or paired with a placeholder result, which also
* ends on a tool turn. `step-start` parts are loop markers, not content.
*/
function endsOnModelTurn(message, pendingCallsDropped) {
	if (message.role !== "assistant") return false;
	for (let index = message.content.parts.length - 1; index >= 0; index--) {
		const part = message.content.parts[index];
		if (part.type === "step-start") continue;
		if (part.type !== "tool-invocation") return true;
		if (SETTLED_TOOL_STATES.has(part.toolInvocation.state) || !pendingCallsDropped) return false;
	}
	return false;
}
/**
* Guards against requests that would end on an assistant message for providers
* that reject that shape.
*
* - Anthropic reads a trailing assistant message as response prefill. That is a
*   legitimate feature outside structured output, so the guard only intervenes when
*   native structured output (`responseFormat`) is in play, where Anthropic rejects it.
* - Gemini 3 and later return 400 "Requests ending with a model turn are not
*   supported" for any request, structured output or not, so the guard always
*   intervenes for those models.
*
* In both cases a short user message is appended so the request ends on a user turn.
* Provider and version gating for *attaching* the processor lives at the attach
* sites; this class only decides when the appended turn is needed.
*
* @see https://github.com/mastra-ai/mastra/issues/12800
* @see https://github.com/mastra-ai/mastra/issues/23320
*/
var TrailingAssistantGuard = class {
	id = "trailing-assistant-guard";
	name = "Trailing Assistant Guard";
	appliesTo(model) {
		return trailingAssistantGuardAppliesTo(model);
	}
	processInputStep({ messages, messageList, structuredOutput, model }) {
		const willUseResponseFormat = Boolean(structuredOutput?.schema && !structuredOutput?.model && !structuredOutput?.jsonPromptInjection);
		if (!isMaybeGoogleWithoutTrailingModelTurn(model) && !(willUseResponseFormat && this.appliesTo(model))) return;
		const lastMessage = messages[messages.length - 1];
		if (!lastMessage || !endsOnModelTurn(lastMessage, messageList?.dropsIncompleteToolCalls ?? true)) return;
		const lastCreatedAt = new Date(lastMessage.createdAt).getTime();
		const createdAt = new Date(Math.max(Date.now(), (Number.isNaN(lastCreatedAt) ? 0 : lastCreatedAt) + 1));
		const continuation = {
			id: globalThis.crypto.randomUUID(),
			role: "user",
			content: {
				format: 2,
				parts: [{
					type: "text",
					text: willUseResponseFormat ? "Generate the structured response." : "Continue."
				}],
				metadata: { [TRAILING_ASSISTANT_GUARD_CONTINUATION_KEY]: true }
			},
			createdAt
		};
		if (messageList) {
			messageList.add(continuation, "context");
			return { messageList };
		}
		return { messages: [...messages, continuation] };
	}
};
// src/processors/runner.ts
var runner_exports = /* @__PURE__ */ __exportAll({ ProcessorRunner: () => ProcessorRunner });
/**
* Safely invoke a processor's onViolation callback when a TripWire is caught.
* Errors from the callback are silently caught.
*/
async function invokeOnViolation(processor, error) {
	if (!processor.onViolation) return;
	try {
		const violation = {
			processorId: error.processorId ?? processor.id,
			message: error.message,
			detail: error.options?.metadata
		};
		await processor.onViolation(violation);
	} catch {}
}
function getProcessableResponseMessages(messageList) {
	const liveMessages = messageList.get.response.db();
	const persistedMessages = messageList.getPersisted.response.db();
	if (persistedMessages.length === 0) return [...liveMessages];
	if (liveMessages.length === 0) return [...persistedMessages];
	const messagesById = new Map(persistedMessages.map((message) => [message.id, message]));
	for (const message of liveMessages) messagesById.set(message.id, message);
	return messageList.get.all.db().filter((message) => messagesById.has(message.id)).map((message) => messagesById.get(message.id));
}
/**
* Implementation of processor state management
*/
/**
* Tracks state for stream processing across chunks.
* Used by both legacy processors and workflow processors.
*/
var ProcessorState = class {
	inputAccumulatedText = "";
	outputAccumulatedText = "";
	outputChunkCount = 0;
	customState = {};
	streamParts = [];
	span;
	/**
	* Milliseconds spent inside `processOutputStream`, summed across every
	* chunk. The span itself lasts for the whole stream, so its duration is
	* dominated by the model's inter-chunk latency; this is the processor's own
	* share of that window.
	*/
	hookDurationMs = 0;
	constructor(options) {
		if (!options?.createSpan || !options.processorName) return;
		const processor = options.processor;
		const currentSpan = options.tracingContext?.currentSpan;
		const parentSpan = currentSpan?.findParent("agent_run") || currentSpan?.parent || currentSpan;
		this.span = parentSpan?.createChildSpan({
			type: processor?.spanType ?? "processor_run",
			name: processor ? resolveProcessorSpanName(processor, "output", `output stream processor: ${options.processorName}`) : `output stream processor: ${options.processorName}`,
			entityType: EntityType.OUTPUT_PROCESSOR,
			entityId: processor?.id,
			entityName: options.processorName,
			attributes: {
				...resolveProcessorSpanAttributes(processor, "outputStream"),
				processorExecutor: "legacy",
				processorIndex: options.processorIndex ?? 0
			},
			input: { totalChunks: 0 }
		});
	}
	/** Track incoming chunk (before processor transformation) */
	addInputPart(part) {
		if (part.type === "text-delta") this.inputAccumulatedText += part.payload.text;
		this.streamParts.push(part);
		if (this.span) this.span.input = {
			totalChunks: this.streamParts.length,
			accumulatedText: this.inputAccumulatedText
		};
	}
	/** Track outgoing chunk (after processor transformation) */
	addOutputPart(part) {
		if (!part) return;
		this.outputChunkCount++;
		if (part.type === "text-delta") this.outputAccumulatedText += part.payload.text;
	}
	/** Get final output for span */
	getFinalOutput() {
		return {
			totalChunks: this.outputChunkCount,
			accumulatedText: this.outputAccumulatedText
		};
	}
	/** Attributes attached on every end path of the span. */
	getFinalAttributes() {
		return { hookDurationMs: this.hookDurationMs };
	}
};
/**
* Key under which the workflow-processor stream path keeps its accumulated
* hook time on the shared processor state, next to `__outputStreamSpan_<id>`.
*/
const OUTPUT_STREAM_HOOK_DURATION_KEY_PREFIX = "__outputStreamHookDurationMs_";
/**
* The MODEL_STEP an output stream processor span belongs under: `span` itself
* (a step's stream passes its step span) or its nearest step ancestor. Stops at
* the first agent run, so a nested agent's stream never attaches to its
* caller's step.
*/
function findOwnModelStepSpan(span) {
	for (let current = span; current && current.type !== "agent_run"; current = current.parent) if (current.type === "model_step") return current;
}
/** Chunk types that end the model step an output stream processor span sits under. */
const STEP_END_CHUNK_TYPES = /* @__PURE__ */ new Set([
	"step-finish",
	"error",
	"abort"
]);
function endStoredOutputStreamSpan(state, processorId, totalChunks) {
	const spanKey = `__outputStreamSpan_${processorId}`;
	const hookDurationKey = `${OUTPUT_STREAM_HOOK_DURATION_KEY_PREFIX}${processorId}`;
	state[spanKey]?.end({
		output: { totalChunks },
		attributes: { hookDurationMs: state[hookDurationKey] ?? 0 }
	});
	delete state[spanKey];
	delete state[hookDurationKey];
}
/**
* When a step's stream starts, ends the stored output stream processor span if
* it was opened outside that step (e.g. by a tool result replayed on resume,
* before any step started), so it does not carry into the step.
*/
function endOutputStreamSpanOutsideStep(state, processorId, part, stepSpan, totalChunks) {
	const span = state[`__outputStreamSpan_${processorId}`];
	if (span && part.type === "step-start" && stepSpan?.type === "model_step" && span.parent?.id !== stepSpan.id) endStoredOutputStreamSpan(state, processorId, totalChunks);
}
/**
* Ends the stored output stream processor span when the model step it sits
* under ends. The span outlives the step's model stream so the step's tool
* results land in it too.
*/
function endOutputStreamSpanAtStepEnd(state, processorId, part, totalChunks) {
	if (state[`__outputStreamSpan_${processorId}`]?.parent?.type === "model_step" && STEP_END_CHUNK_TYPES.has(part.type)) endStoredOutputStreamSpan(state, processorId, totalChunks);
}
function areProcessorMessageArraysEqual(before, after) {
	if (before === after) return true;
	if (!before || !after) return before === after;
	return before.length === after.length && before.every((message, index) => messagesAreEqual(message, after[index]));
}
function buildProcessInputStepSpanInput(args) {
	const summarizedModel = summarizeProcessorModelForSpan(args.model);
	const summarizedTools = summarizeProcessorToolsForSpan(args.tools);
	const summarizedToolChoice = summarizeToolChoiceForSpan(args.toolChoice, args.tools);
	const summarizedActiveTools = summarizeActiveToolsForSpan(args.activeTools, args.tools);
	return {
		messages: args.messages,
		systemMessages: args.systemMessages,
		stepNumber: args.stepNumber,
		...args.messageId ? { messageId: args.messageId } : {},
		retryCount: args.retryCount,
		...summarizedModel ? { model: summarizedModel } : {},
		...summarizedTools ? { tools: summarizedTools } : {},
		...summarizedToolChoice ? { toolChoice: summarizedToolChoice } : {},
		...summarizedActiveTools ? { activeTools: summarizedActiveTools } : {}
	};
}
function buildProcessInputStepSpanOutput(args) {
	const output = {};
	if (!areProcessorMessageArraysEqual(args.beforeMessages, args.messages)) output.messages = args.messages;
	if (!areProcessorMessageArraysEqual(args.beforeSystemMessages, args.systemMessages)) output.systemMessages = args.systemMessages;
	if (args.afterStepInput.messageId !== args.beforeStepInput.messageId) output.messageId = args.afterStepInput.messageId;
	if (args.result.model !== void 0 || args.afterStepInput.model !== args.beforeStepInput.model) {
		const model = summarizeProcessorModelForSpan(args.afterStepInput.model);
		if (model) output.model = model;
	}
	if (args.result.tools !== void 0 || args.afterStepInput.tools !== args.beforeStepInput.tools) {
		const tools = summarizeProcessorToolsForSpan(args.afterStepInput.tools);
		if (tools) output.tools = tools;
	}
	if (args.result.toolChoice !== void 0 || args.afterStepInput.toolChoice !== args.beforeStepInput.toolChoice || args.afterStepInput.tools !== args.beforeStepInput.tools) {
		const toolChoice = summarizeToolChoiceForSpan(args.afterStepInput.toolChoice, args.afterStepInput.tools);
		if (toolChoice) output.toolChoice = toolChoice;
	}
	if (args.result.activeTools !== void 0 || args.afterStepInput.activeTools !== args.beforeStepInput.activeTools || args.afterStepInput.tools !== args.beforeStepInput.tools) {
		const activeTools = summarizeActiveToolsForSpan(args.afterStepInput.activeTools, args.afterStepInput.tools);
		if (activeTools) output.activeTools = activeTools;
	}
	if (args.result.retryCount !== void 0) output.retryCount = args.result.retryCount;
	return output;
}
var ProcessorRunner = class ProcessorRunner {
	inputProcessors;
	outputProcessors;
	errorProcessors;
	logger;
	agentName;
	agent;
	/**
	* Shared processor state that persists across loop iterations.
	* Used by all processor methods (input and output) to share state.
	* Keyed by processor ID.
	*/
	processorStates;
	lateSignalSink;
	constructor({ inputProcessors, outputProcessors, errorProcessors, logger, agentName, agent, processorStates, lateSignalSink }) {
		this.inputProcessors = inputProcessors ?? [];
		this.outputProcessors = outputProcessors ?? [];
		this.errorProcessors = errorProcessors ?? [];
		this.logger = logger;
		this.agentName = agentName;
		this.agent = agent;
		this.processorStates = processorStates ?? /* @__PURE__ */ new Map();
		this.lateSignalSink = lateSignalSink;
	}
	/**
	* Get or create ProcessorState for the given processor ID.
	* This state persists across loop iterations and is shared between
	* all processor methods (input and output).
	*/
	getProcessorState(processorId) {
		let state = this.processorStates.get(processorId);
		if (!state) {
			state = new ProcessorState();
			this.processorStates.set(processorId, state);
		}
		return state;
	}
	async runComputeStateSignal({ processor, messageList, stepNumber, steps, requestContext, writer, abort, processorState, memory, resourceId, threadId, abortSignal, retryCount, rotateResponseMessageId, observabilityContext }) {
		const computeStateSignal = processor.computeStateSignal?.bind(processor);
		if (!computeStateSignal) return;
		const memoryContext = parseMemoryRequestContext(requestContext);
		const resolvedMemory = memory;
		const resolvedThreadId = threadId ?? memoryContext?.thread?.id;
		const resolvedResourceId = resourceId ?? memoryContext?.resourceId;
		if (!resolvedMemory) throw new Error(`[Processor:${processor.id}] computeStateSignal requires Mastra memory with an active resourceId and threadId`);
		if (!resolvedThreadId || !resolvedResourceId) {
			this.logger.debug(`[Processor:${processor.id}] computeStateSignal skipped — no threadId/resourceId resolved for this invocation`);
			return;
		}
		const loadedThread = await resolvedMemory.getThreadById({ threadId: resolvedThreadId }) ?? memoryContext?.thread;
		if (!loadedThread) throw new Error(`[Processor:${processor.id}] computeStateSignal could not load thread ${resolvedThreadId}`);
		let thread = {
			...loadedThread,
			id: resolvedThreadId,
			resourceId: loadedThread.resourceId ?? resolvedResourceId,
			createdAt: loadedThread.createdAt ?? /* @__PURE__ */ new Date(),
			updatedAt: loadedThread.updatedAt ?? /* @__PURE__ */ new Date(),
			metadata: loadedThread.metadata
		};
		const stateId = processor.stateId ?? processor.id;
		const beforeAddStateSignal = rotateResponseMessageId;
		const tracking = getStateSignalsMetadata(thread.metadata)[stateId];
		const { activeStateSignals, contextWindow, lastSnapshot, deltasSinceSnapshot } = await resolveStateSignalHistory({
			messageList,
			memory: resolvedMemory,
			threadId: resolvedThreadId,
			stateId,
			tracking
		});
		const result = await computeStateSignal({
			...createObservabilityContext({ currentSpan: observabilityContext?.tracingContext?.currentSpan }),
			messages: messageList.get.all.db(),
			messageList,
			stepNumber,
			steps,
			state: processorState.customState,
			requestContext,
			writer,
			abortSignal,
			abort,
			retryCount,
			resourceId: resolvedResourceId,
			threadId: resolvedThreadId,
			activeStateSignals,
			contextWindow,
			lastSnapshot,
			deltasSinceSnapshot,
			tracking,
			sendStateSignal: async (stateSignal) => {
				const sendResult = await applyStateSignal({
					input: stateSignal,
					memory: resolvedMemory,
					thread,
					resourceId: resolvedResourceId,
					threadId: resolvedThreadId,
					memoryConfig: memoryContext?.memoryConfig,
					messageList,
					defaultId: stateId,
					beforeAddSignal: beforeAddStateSignal,
					writeSignal: (signal) => writer?.custom(signal.toDataPart())
				});
				if (!sendResult.skipped) {
					const updated = await resolvedMemory.getThreadById({ threadId: resolvedThreadId });
					if (updated) thread = {
						...thread,
						metadata: updated.metadata
					};
				}
				return sendResult.skipped ? sendResult : sendResult.signal;
			}
		});
		if (!result) return;
		await applyStateSignal({
			input: result,
			memory: resolvedMemory,
			thread,
			resourceId: resolvedResourceId,
			threadId: resolvedThreadId,
			memoryConfig: memoryContext?.memoryConfig,
			messageList,
			defaultId: stateId,
			beforeAddSignal: beforeAddStateSignal,
			writeSignal: (signal) => writer?.custom(signal.toDataPart())
		});
		observabilityContext?.tracingContext?.currentSpan?.createEventSpan({
			type: "agent_signal",
			name: `signal: ${result.id ?? stateId}`,
			attributes: {
				stateId: result.id ?? stateId,
				mode: result.mode,
				tagName: result.tagName,
				processorId: processor.id
			},
			output: {
				attributes: result.attributes,
				hasDelta: Boolean(result.delta)
			}
		});
	}
	async runWorkflowComputeStateSignals({ workflow, messageList, stepNumber, steps, requestContext, writer, memory, resourceId, threadId, abortSignal, retryCount, rotateResponseMessageId, observabilityContext }) {
		for (const processor of workflow.__stateSignalProcessors ?? []) {
			const abort = (reason, options) => {
				throw new TripWire(reason || `Tripwire triggered by ${processor.id}`, options, processor.id);
			};
			await this.runComputeStateSignal({
				processor,
				messageList,
				stepNumber,
				steps,
				requestContext,
				writer,
				abort,
				processorState: this.getProcessorState(processor.id),
				observabilityContext,
				memory,
				resourceId,
				threadId,
				abortSignal,
				retryCount,
				rotateResponseMessageId
			});
		}
	}
	/**
	* Execute a workflow as a processor and handle the result.
	* Returns the processed messages and any tripwire information.
	*/
	async executeWorkflowAsProcessor(workflow, input, observabilityContext, requestContext, writer, abortSignal) {
		const isPerChunkPhase = input.phase === "outputStream";
		const inputData = {
			...input,
			processorStates: this.processorStates,
			abortSignal,
			agent: this.agent,
			lateSignalSink: this.lateSignalSink
		};
		const outputWriter = writer ? (chunk, options) => writer.custom(chunk, options) : void 0;
		if (isPerChunkPhase && workflow.__executeOutputStream) {
			const execute = workflow.__executeOutputStream;
			return executeWithContext({
				span: observabilityContext?.tracingContext?.currentSpan,
				fn: () => execute({
					inputData,
					...observabilityContext,
					requestContext: requestContext ?? new RequestContext(),
					outputWriter
				})
			});
		}
		const run = await workflow.createRun(isPerChunkPhase ? {
			shouldPersistSnapshot: () => false,
			tracingPolicy: { internal: 1 }
		} : void 0);
		const scope = this.lateSignalSink ? workflow.mastra?.__createRunScope(run.runId) : void 0;
		if (this.lateSignalSink) scope?.set(PROCESSOR_LATE_SIGNAL_SINK, this.lateSignalSink);
		const result = await (async () => {
			try {
				return await run.start({
					inputData,
					...observabilityContext,
					requestContext,
					outputWriter
				});
			} finally {
				if (scope) workflow.mastra?.__releaseRunScope(run.runId);
			}
		})();
		if (result.status === "tripwire") {
			const tripwireData = result.tripwire;
			throw new TripWire(tripwireData?.reason || `Tripwire triggered in workflow ${workflow.id}`, {
				retry: tripwireData?.retry,
				metadata: tripwireData?.metadata
			}, tripwireData?.processorId || workflow.id);
		}
		if (result.status !== "success") {
			const details = [];
			const steps = residentStepResults(result.steps) ?? result.steps;
			if (result.status === "failed") {
				if (result.error) details.push(result.error.message || JSON.stringify(result.error));
				for (const [stepId, step] of Object.entries(steps)) if (step.status === "failed" && step.error?.message) details.push(`step ${stepId}: ${step.error.message}`);
			}
			const detailStr = details.length > 0 ? ` — ${details.join("; ")}` : "";
			let failedStepError;
			if (result.status === "failed") {
				for (const step of Object.values(steps)) if (step.status === "failed" && step.error) {
					failedStepError = step.error;
					break;
				}
			}
			throw new MastraError({
				category: "USER",
				domain: "AGENT",
				id: "PROCESSOR_WORKFLOW_FAILED",
				text: `Processor workflow ${workflow.id} failed with status: ${result.status}${detailStr}`
			}, result.status === "failed" ? failedStepError ?? result.error : void 0);
		}
		const output = result.result;
		if (!output || typeof output !== "object") return input;
		if (!("phase" in output) || !("messages" in output || "part" in output || "messageList" in output)) throw new MastraError({
			category: "USER",
			domain: "AGENT",
			id: "PROCESSOR_WORKFLOW_INVALID_OUTPUT",
			text: `Processor workflow ${workflow.id} returned invalid output format. Expected ProcessorStepOutput.`
		});
		return output;
	}
	async runOutputProcessors(messageList, observabilityContext, requestContext, retryCount = 0, writer, result) {
		for (const [index, processorOrWorkflow] of this.outputProcessors.entries()) {
			let processableMessages = getProcessableResponseMessages(messageList);
			const idsBeforeProcessing = processableMessages.map((m) => m.id);
			const check = messageList.makeMessageSourceChecker();
			if (isProcessorWorkflow(processorOrWorkflow)) {
				await this.executeWorkflowAsProcessor(processorOrWorkflow, {
					phase: "outputResult",
					messages: processableMessages,
					messageList,
					retryCount,
					result
				}, observabilityContext, requestContext, writer);
				continue;
			}
			const processor = processorOrWorkflow;
			const abort = (reason, options) => {
				throw new TripWire(reason || `Tripwire triggered by ${processor.id}`, options, processor.id);
			};
			const processMethod = processor.processOutputResult?.bind(processor);
			if (!processMethod) continue;
			const outputMessagesBefore = processableMessages;
			const outputSystemMessagesBefore = messageList.getAllSystemMessages();
			const defaultResult = {
				text: "",
				usage: {
					inputTokens: 0,
					outputTokens: 0,
					totalTokens: 0
				},
				finishReason: "unknown",
				steps: []
			};
			const summarizedResult = result ? summarizeProcessorResultForSpan(result) : void 0;
			const currentSpan = observabilityContext?.tracingContext?.currentSpan;
			const processorSpan = (currentSpan?.findParent("agent_run") || currentSpan?.parent || currentSpan)?.createChildSpan({
				type: processor.spanType ?? "processor_run",
				name: resolveProcessorSpanName(processor, "output", `output processor: ${processor.id}`),
				entityType: EntityType.OUTPUT_PROCESSOR,
				entityId: processor.id,
				entityName: processor.name,
				attributes: {
					...resolveProcessorSpanAttributes(processor, "outputResult"),
					processorExecutor: "legacy",
					processorIndex: index
				},
				input: {
					messages: processableMessages,
					...summarizedResult ? { result: summarizedResult } : {},
					retryCount
				}
			});
			messageList.startRecording();
			try {
				const processorState = this.getProcessorState(processor.id);
				const processResult = await processMethod({
					messages: processableMessages,
					messageList,
					state: processorState.customState,
					result: result ?? defaultResult,
					abort,
					agent: this.agent,
					...createObservabilityContext({ currentSpan: processorSpan }),
					requestContext,
					retryCount,
					writer,
					sendSignal: createProcessorSendSignal({
						messageList,
						writer,
						lateSink: this.lateSignalSink
					})
				});
				const mutations = messageList.stopRecording();
				if (processResult instanceof MessageList) {
					if (processResult !== messageList) throw new MastraError({
						category: "USER",
						domain: "AGENT",
						id: "PROCESSOR_RETURNED_EXTERNAL_MESSAGE_LIST",
						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.`
					});
					if (mutations.length > 0) processableMessages = getProcessableResponseMessages(processResult);
				} else if (processResult) {
					const deletedIds = idsBeforeProcessing.filter((i) => !processResult.some((m) => m.id === i));
					if (deletedIds.length) messageList.removeByIds(deletedIds);
					processableMessages = processResult || [];
					for (const message of processResult) {
						messageList.removeByIds([message.id]);
						messageList.add(message, check.getSource(message) || "response", { merge: false });
					}
				}
				processorSpan?.end({
					output: {
						...!areProcessorMessageArraysEqual(outputMessagesBefore, processableMessages) ? { messages: processableMessages } : {},
						...!areProcessorMessageArraysEqual(outputSystemMessagesBefore, messageList.getAllSystemMessages()) ? { systemMessages: messageList.getAllSystemMessages() } : {}
					},
					attributes: mutations.length > 0 ? { messageListMutations: mutations } : void 0
				});
			} catch (error) {
				messageList.stopRecording();
				if (error instanceof TripWire) {
					processorSpan?.error({
						error,
						endSpan: true,
						attributes: { tripwireAbort: {
							reason: error.message,
							retry: error.options?.retry,
							metadata: error.options?.metadata
						} }
					});
					await invokeOnViolation(processor, error);
					throw error;
				}
				processorSpan?.error({
					error,
					endSpan: true
				});
				throw error;
			}
		}
		return messageList;
	}
	/**
	* Process a stream part through all output processors with state management
	*/
	async processPart(part, processorStates, observabilityContext, requestContext, messageList, retryCount = 0, writer, abortSignal, startIndex = 0) {
		if (!this.outputProcessors.length) return {
			part,
			blocked: false
		};
		try {
			let processedPart = part;
			const isFinishChunk = part.type === "finish";
			for (const [index, processorOrWorkflow] of this.outputProcessors.entries()) {
				if (index < startIndex) continue;
				if (isProcessorWorkflow(processorOrWorkflow)) {
					if (!processedPart) continue;
					const workflowId = processorOrWorkflow.id;
					let state = processorStates.get(workflowId);
					if (!state) {
						state = new ProcessorState();
						processorStates.set(workflowId, state);
					}
					state.addInputPart(processedPart);
					if (processorOrWorkflow.__processOutputStream === false) {
						state.addOutputPart(processedPart);
						continue;
					}
					try {
						const result = await this.executeWorkflowAsProcessor(processorOrWorkflow, {
							phase: "outputStream",
							part: processedPart,
							streamParts: state.streamParts,
							state: state.customState,
							messageList,
							retryCount
						}, observabilityContext, requestContext, writer, abortSignal);
						if ("part" in result) processedPart = result.part;
						state.addOutputPart(processedPart);
					} catch (error) {
						if (error instanceof TripWire) return {
							part: null,
							blocked: true,
							reason: error.message,
							tripwireOptions: error.options,
							processorId: error.processorId || workflowId
						};
						throw error;
					}
					continue;
				}
				const processor = processorOrWorkflow;
				try {
					if (processor.processOutputStream && processedPart) {
						let state = processorStates.get(processor.id);
						if (!state) {
							state = new ProcessorState({
								processorName: processor.name ?? processor.id,
								...observabilityContext,
								processorIndex: index,
								createSpan: true,
								processor
							});
							processorStates.set(processor.id, state);
						}
						state.addInputPart(processedPart);
						const hookStart = performance.now();
						let result;
						try {
							result = await processor.processOutputStream({
								part: processedPart,
								streamParts: state.streamParts,
								state: state.customState,
								agent: this.agent,
								abort: (reason, options) => {
									throw new TripWire(reason || `Tripwire triggered by ${processor.id}`, options, processor.id);
								},
								...createObservabilityContext({ currentSpan: state.span }),
								requestContext,
								messageList,
								retryCount,
								writer,
								abortSignal
							});
						} finally {
							state.hookDurationMs += performance.now() - hookStart;
						}
						processedPart = result;
						state.addOutputPart(processedPart);
					}
				} catch (error) {
					if (error instanceof TripWire) {
						const state = processorStates.get(processor.id);
						state?.span?.error({
							error,
							endSpan: true,
							attributes: {
								...state.getFinalAttributes(),
								tripwireAbort: {
									reason: error.message,
									retry: error.options?.retry,
									metadata: error.options?.metadata
								}
							}
						});
						await invokeOnViolation(processor, error);
						return {
							part: null,
							blocked: true,
							reason: error.message,
							tripwireOptions: error.options,
							processorId: processor.id
						};
					}
					throw error;
				}
			}
			if (isFinishChunk) {
				for (const state of processorStates.values()) if (state.span) state.span.end({
					output: state.getFinalOutput(),
					attributes: state.getFinalAttributes()
				});
			}
			return {
				part: processedPart,
				blocked: false
			};
		} catch (error) {
			this.logger.error("Stream part processing failed", {
				agent: this.agentName,
				error
			});
			for (const state of processorStates.values()) state.span?.error({
				error,
				endSpan: true,
				attributes: state.getFinalAttributes()
			});
			throw error;
		}
	}
	endStreamProcessorSpans(processorStates, options) {
		for (const state of processorStates.values()) {
			state.span?.end({
				output: state.getFinalOutput(),
				attributes: state.getFinalAttributes()
			});
			for (const [key, value] of Object.entries(state.customState)) if (key.startsWith("__outputStreamSpan_")) {
				const span = value;
				if (options?.keepStepScopedSpans && span?.parent?.type === "model_step") continue;
				const durationKey = OUTPUT_STREAM_HOOK_DURATION_KEY_PREFIX + key.slice(19);
				const hookDurationMs = state.customState[durationKey];
				span?.end(typeof hookDurationMs === "number" ? { attributes: { hookDurationMs } } : void 0);
				delete state.customState[key];
				delete state.customState[durationKey];
			}
		}
	}
	/**
	* Re-drive any parts that stream processors stashed for reprocessing through
	* the full output processor chain.
	*
	* A stream processor can only return one part from `processOutputStream`, but
	* some processors (e.g. `BatchPartsProcessor`) need to emit a second part for
	* one input — it returns the first part and stashes the second under
	* `REPROCESS_PART_KEY` on its state. After the primary part has been emitted,
	* callers invoke this to push each stashed part back through the whole chain
	* (so it receives downstream processing) and emit the results in order.
	*
	* Returns the processed results in emission order. Reprocessing can itself
	* stash more parts, so this drains until none remain.
	*/
	async drainReprocessParts(processorStates, observabilityContext, requestContext, messageList, retryCount = 0, writer, abortSignal, minIndex) {
		const results = [];
		if (minIndex !== void 0) {
			const takeFrom = () => {
				for (let j = minIndex; j < this.outputProcessors.length; j++) {
					const processor = this.outputProcessors[j];
					if (isProcessorWorkflow(processor)) continue;
					const custom = processorStates.get(processor.id)?.customState;
					const stashed = custom?.[REPROCESS_PART_KEY];
					if (stashed) {
						delete custom[REPROCESS_PART_KEY];
						return [stashed, j];
					}
				}
			};
			let guard = 0;
			let next = takeFrom();
			while (next && guard++ < 1e3) {
				const result = await this.processPart(next[0], processorStates, observabilityContext, requestContext, messageList, retryCount, writer, abortSignal, next[1]);
				results.push(result);
				if (result.blocked) break;
				next = takeFrom();
			}
			return results;
		}
		const takeNext = () => {
			for (const state of processorStates.values()) {
				const custom = state.customState;
				const stashed = custom[REPROCESS_PART_KEY];
				if (stashed) {
					delete custom[REPROCESS_PART_KEY];
					return stashed;
				}
			}
		};
		let guard = 0;
		let next = takeNext();
		while (next && guard++ < 1e3) {
			const result = await this.processPart(next, processorStates, observabilityContext, requestContext, messageList, retryCount, writer, abortSignal);
			results.push(result);
			if (result.blocked) break;
			next = takeNext();
		}
		return results;
	}
	/**
	* Call when a stream ends. Processors that hold parts until a later part
	* arrives (`BatchPartsProcessor`, LLM-buffered checks) would otherwise drop
	* what they hold when nothing follows it. Each held part is released and
	* pushed through the processors after its holder, then any stashed parts are
	* drained. Returns the results in emission order, stopping at the first block.
	*/
	async flushHeldParts(processorStates, observabilityContext, requestContext, messageList, retryCount = 0, writer, abortSignal) {
		const results = [];
		for (const [index, processorOrWorkflow] of this.outputProcessors.entries()) {
			let held;
			try {
				if (isProcessorWorkflow(processorOrWorkflow)) {
					const flush = processorOrWorkflow.__flushOutputStream;
					if (!flush) continue;
					const outputWriter = writer ? (chunk, options) => writer.custom(chunk, options) : void 0;
					held = await executeWithContext({
						span: observabilityContext?.tracingContext?.currentSpan,
						fn: () => flush({
							inputData: {
								phase: "outputStream",
								streamParts: [],
								state: {},
								messageList,
								retryCount,
								processorStates: this.processorStates,
								abortSignal,
								agent: this.agent
							},
							...observabilityContext,
							requestContext: requestContext ?? new RequestContext(),
							outputWriter
						})
					});
				} else held = await takeHeldParts(processorStates.get(processorOrWorkflow.id)?.customState);
			} catch (error) {
				if (error instanceof TripWire) {
					results.push({
						part: null,
						blocked: true,
						reason: error.message,
						tripwireOptions: error.options,
						processorId: error.processorId || processorOrWorkflow.id
					});
					return results;
				}
				throw error;
			}
			for (const part of held) {
				const result = await this.processPart(part, processorStates, observabilityContext, requestContext, messageList, retryCount, writer, abortSignal, index + 1);
				results.push(result);
				if (result.blocked) return results;
				const reprocessed = await this.drainReprocessParts(processorStates, observabilityContext, requestContext, messageList, retryCount, writer, abortSignal, index + 1);
				results.push(...reprocessed);
				if (reprocessed.some((r) => r.blocked)) return results;
			}
		}
		return results;
	}
	/**
	* Call instead of {@link flushHeldParts} when a stream errored or was aborted:
	* clears what processors hold without emitting or checking it, so a retry
	* doesn't repeat it and nothing is emitted after cancellation.
	*/
	/**
	* Drops what output processors hold after a failed or aborted model stream, without running
	* any checks. Returns the held control parts (start, error, finish, ...), oldest first.
	*/
	async discardHeldParts(processorStates) {
		const kept = [];
		for (const processorOrWorkflow of [...this.outputProcessors].reverse()) {
			const parts = isProcessorWorkflow(processorOrWorkflow) ? await processorOrWorkflow.__discardOutputStream?.(this.processorStates) ?? [] : await takeHeldParts(processorStates.get(processorOrWorkflow.id)?.customState, { discard: true });
			kept.push(...parts);
		}
		return kept;
	}
	async runOutputProcessorsForStream(streamResult, observabilityContext, writer) {
		return new ReadableStream({ start: async (controller) => {
			const reader = streamResult.fullStream.getReader();
			const processorStates = /* @__PURE__ */ new Map();
			const streamWriter = writer ?? { custom: async (data) => controller.enqueue(data) };
			let streamFailed = false;
			try {
				while (true) {
					const { done, value } = await reader.read();
					if (done) {
						if (streamFailed) {
							for (const part of await this.discardHeldParts(processorStates)) controller.enqueue(part);
							controller.close();
							break;
						}
						for (const r of await this.flushHeldParts(processorStates, observabilityContext, void 0, void 0, 0, streamWriter)) {
							if (r.blocked) {
								controller.enqueue({
									type: "tripwire",
									payload: {
										reason: r.reason || "Output processor blocked content",
										retry: r.tripwireOptions?.retry,
										metadata: r.tripwireOptions?.metadata,
										processorId: r.processorId
									}
								});
								break;
							}
							if (r.part != null) controller.enqueue(r.part);
						}
						controller.close();
						break;
					}
					if (isFailedStreamChunk(value)) streamFailed = true;
					const { part: processedPart, blocked, reason, tripwireOptions, processorId } = await this.processPart(value, processorStates, observabilityContext, void 0, void 0, 0, streamWriter);
					const enqueueTripwire = (r, opts, pid) => {
						this.logger.debug("Stream part blocked by output processor", {
							agent: this.agentName,
							reason: r,
							originalPart: value
						});
						controller.enqueue({
							type: "tripwire",
							payload: {
								reason: r || "Output processor blocked content",
								retry: opts?.retry,
								metadata: opts?.metadata,
								processorId: pid
							}
						});
					};
					if (blocked) {
						enqueueTripwire(reason, tripwireOptions, processorId);
						controller.close();
						break;
					} else if (processedPart != null) controller.enqueue(processedPart);
					const reprocessed = await this.drainReprocessParts(processorStates, observabilityContext, void 0, void 0, 0, streamWriter);
					let aborted = false;
					for (const r of reprocessed) {
						if (r.blocked) {
							enqueueTripwire(r.reason, r.tripwireOptions, r.processorId);
							controller.close();
							aborted = true;
							break;
						}
						if (r.part != null) controller.enqueue(r.part);
					}
					if (aborted) break;
				}
			} catch (error) {
				controller.error(error);
				await reader.cancel(error).catch(() => {});
			}
		} });
	}
	async runInputProcessors(messageList, observabilityContext, requestContext, retryCount = 0) {
		for (const [index, processorOrWorkflow] of this.inputProcessors.entries()) {
			let processableMessages = messageList.get.input.db();
			const inputIds = processableMessages.map((m) => m.id);
			const check = messageList.makeMessageSourceChecker();
			if (isProcessorWorkflow(processorOrWorkflow)) {
				const currentSystemMessages = messageList.getSystemMessages();
				await this.executeWorkflowAsProcessor(processorOrWorkflow, {
					phase: "input",
					messages: processableMessages,
					messageList,
					systemMessages: currentSystemMessages,
					retryCount
				}, observabilityContext, requestContext);
				continue;
			}
			const processor = processorOrWorkflow;
			const abort = (reason, options) => {
				throw new TripWire(reason || `Tripwire triggered by ${processor.id}`, options, processor.id);
			};
			const processMethod = processor.processInput?.bind(processor);
			if (!processMethod) continue;
			const currentSystemMessages = messageList.getSystemMessages();
			const inputMessagesBefore = processableMessages;
			const inputSystemMessagesBefore = currentSystemMessages;
			const currentSpan = observabilityContext?.tracingContext?.currentSpan;
			const processorSpan = (currentSpan?.findParent("agent_run") || currentSpan?.parent || currentSpan)?.createChildSpan({
				type: processor.spanType ?? "processor_run",
				name: resolveProcessorSpanName(processor, "input", `input processor: ${processor.id}`),
				entityType: EntityType.INPUT_PROCESSOR,
				entityId: processor.id,
				entityName: processor.name,
				attributes: {
					...resolveProcessorSpanAttributes(processor, "input"),
					processorExecutor: "legacy",
					processorIndex: index
				},
				input: {
					messages: processableMessages,
					systemMessages: currentSystemMessages
				}
			});
			messageList.startRecording();
			try {
				const processorState = this.getProcessorState(processor.id);
				const result = await processMethod({
					messages: processableMessages,
					systemMessages: currentSystemMessages,
					state: processorState.customState,
					abort,
					agent: this.agent,
					...createObservabilityContext({ currentSpan: processorSpan }),
					messageList,
					requestContext,
					retryCount,
					sendSignal: createProcessorSendSignal({
						messageList,
						lateSink: this.lateSignalSink
					})
				});
				let mutations;
				if (result instanceof MessageList) {
					if (result !== messageList) throw new MastraError({
						category: "USER",
						domain: "AGENT",
						id: "PROCESSOR_RETURNED_EXTERNAL_MESSAGE_LIST",
						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.`
					});
					mutations = messageList.stopRecording();
					if (mutations.length > 0) processableMessages = messageList.get.input.db();
				} else if (this.isProcessInputResultWithSystemMessages(result)) {
					mutations = messageList.stopRecording();
					messageList.replaceAllSystemMessages(result.systemMessages);
					const regularMessages = result.messages;
					if (regularMessages) {
						const deletedIds = inputIds.filter((i) => !regularMessages.some((m) => m.id === i));
						if (deletedIds.length) messageList.removeByIds(deletedIds);
						const newSystemMessages = regularMessages.filter((m) => m.role === "system");
						const nonSystemMessages = regularMessages.filter((m) => m.role !== "system");
						for (const sysMsg of newSystemMessages) {
							const systemText = sysMsg.content.content ?? sysMsg.content.parts?.map((p) => p.type === "text" ? p.text : "").join("\n") ?? "";
							messageList.addSystem(systemText);
						}
						if (nonSystemMessages.length > 0) for (const message of nonSystemMessages) {
							messageList.removeByIds([message.id]);
							messageList.add(message, check.getSource(message) || "input", { merge: false });
						}
					}
					processableMessages = messageList.get.input.db();
				} else {
					mutations = messageList.stopRecording();
					if (result) {
						const deletedIds = inputIds.filter((i) => !result.some((m) => m.id === i));
						if (deletedIds.length) messageList.removeByIds(deletedIds);
						const systemMessages = result.filter((m) => m.role === "system");
						const nonSystemMessages = result.filter((m) => m.role !== "system");
						for (const sysMsg of systemMessages) {
							const systemText = sysMsg.content.content ?? sysMsg.content.parts?.map((p) => p.type === "text" ? p.text : "").join("\n") ?? "";
							messageList.addSystem(systemText);
						}
						if (nonSystemMessages.length > 0) for (const message of nonSystemMessages) {
							messageList.removeByIds([message.id]);
							messageList.add(message, check.getSource(message) || "input", { merge: false });
						}
						processableMessages = messageList.get.input.db();
					}
				}
				processorSpan?.end({
					output: {
						...!areProcessorMessageArraysEqual(inputMessagesBefore, processableMessages) ? { messages: processableMessages } : {},
						...!areProcessorMessageArraysEqual(inputSystemMessagesBefore, messageList.getSystemMessages()) ? { systemMessages: messageList.getSystemMessages() } : {}
					},
					attributes: mutations.length > 0 ? { messageListMutations: mutations } : void 0
				});
			} catch (error) {
				messageList.stopRecording();
				if (error instanceof TripWire) {
					processorSpan?.error({
						error,
						endSpan: true,
						attributes: { tripwireAbort: {
							reason: error.message,
							retry: error.options?.retry,
							metadata: error.options?.metadata
						} }
					});
					await invokeOnViolation(processor, error);
					throw error;
				}
				processorSpan?.error({
					error,
					endSpan: true
				});
				throw error;
			}
		}
		return messageList;
	}
	/**
	* Run processInputStep for all processors that implement it.
	* Called at each step of the agentic loop, before the LLM is invoked.
	*
	* Unlike processInput which runs once at the start, this runs at every step
	* (including tool call continuations). This is useful for:
	* - Transforming message types between steps (e.g., AI SDK 'reasoning' -> Anthropic 'thinking')
	* - Modifying messages based on step context
	* - Implementing per-step message transformations
	*
	* @param args.messages - The current messages to be sent to the LLM (MastraDBMessage format)
	* @param args.messageList - MessageList instance for managing message sources
	* @param args.stepNumber - The current step number (0-indexed)
	* @param args.tracingContext - Optional tracing context for observability
	* @param args.requestContext - Optional runtime context with execution metadata
	*
	* @returns The processed MessageList
	*/
	async runProcessInputStep(args) {
		const { messageList, stepNumber, steps, requestContext, writer } = args;
		const observabilityContext = resolveObservabilityContext(args);
		const stepInput = {
			messageId: args.messageId,
			tools: args.tools,
			toolChoice: args.toolChoice,
			model: args.model,
			activeTools: args.activeTools,
			providerOptions: args.providerOptions,
			modelSettings: args.modelSettings,
			structuredOutput: args.structuredOutput,
			retryCount: args.retryCount ?? 0
		};
		const processors = stepInput.model && needsTrailingAssistantGuard(stepInput.model, this.inputProcessors) ? [...this.inputProcessors, new TrailingAssistantGuard()] : this.inputProcessors;
		for (const [index, processorOrWorkflow] of processors.entries()) {
			const processableMessages = messageList.get.all.db();
			const idsBeforeProcessing = processableMessages.map((m) => m.id);
			const check = messageList.makeMessageSourceChecker();
			if (isProcessorWorkflow(processorOrWorkflow)) {
				const currentSystemMessages = messageList.getSystemMessages();
				const result = await this.executeWorkflowAsProcessor(processorOrWorkflow, {
					phase: "inputStep",
					messages: processableMessages,
					messageList,
					stepNumber,
					runId: args.runId,
					steps,
					systemMessages: currentSystemMessages,
					rotateResponseMessageId: args.rotateResponseMessageId ? () => {
						const nextMessageId = args.rotateResponseMessageId();
						stepInput.messageId = nextMessageId;
						return nextMessageId;
					} : void 0,
					llmRequestProcessorIds: args.llmRequestProcessorIds,
					...stepInput
				}, observabilityContext, requestContext, writer, args.abortSignal);
				Object.assign(stepInput, result);
				await this.runWorkflowComputeStateSignals({
					workflow: processorOrWorkflow,
					messageList,
					stepNumber,
					steps,
					requestContext,
					writer,
					observabilityContext,
					memory: args.memory,
					resourceId: args.resourceId,
					threadId: args.threadId,
					abortSignal: args.abortSignal,
					retryCount: args.retryCount ?? 0,
					rotateResponseMessageId: args.rotateResponseMessageId ? () => {
						const nextMessageId = args.rotateResponseMessageId();
						stepInput.messageId = nextMessageId;
						return nextMessageId;
					} : void 0
				});
				continue;
			}
			const processor = processorOrWorkflow;
			const processMethod = processor.processInputStep?.bind(processor);
			const computeStateSignal = processor.computeStateSignal?.bind(processor);
			if (!processMethod && !computeStateSignal) continue;
			if (processorOrWorkflow instanceof TrailingAssistantGuard && !processorOrWorkflow.appliesTo(stepInput.model)) continue;
			const abort = (reason, options) => {
				throw new TripWire(reason || `Tripwire triggered by ${processor.id}`, options, processor.id);
			};
			const currentSystemMessages = messageList.getSystemMessages();
			const inputData = {
				messages: processableMessages,
				runId: args.runId,
				stepNumber,
				steps,
				messageId: stepInput.messageId,
				systemMessages: currentSystemMessages,
				tools: stepInput.tools,
				toolChoice: stepInput.toolChoice,
				model: stepInput.model,
				activeTools: stepInput.activeTools,
				providerOptions: stepInput.providerOptions,
				modelSettings: stepInput.modelSettings,
				structuredOutput: stepInput.structuredOutput,
				requestContext,
				agent: this.agent
			};
			const processorSpan = (observabilityContext.tracingContext?.currentSpan)?.createChildSpan({
				type: processor.spanType ?? "processor_run",
				name: resolveProcessorSpanName(processor, "inputStep", `input step processor: ${processor.id}`),
				entityType: EntityType.INPUT_STEP_PROCESSOR,
				entityId: processor.id,
				entityName: processor.name,
				attributes: {
					...resolveProcessorSpanAttributes(processor, "inputStep"),
					processorExecutor: "legacy",
					processorIndex: index
				},
				input: buildProcessInputStepSpanInput({
					messages: inputData.messages,
					systemMessages: inputData.systemMessages,
					stepNumber: inputData.stepNumber,
					messageId: inputData.messageId,
					retryCount: args.retryCount ?? 0,
					model: inputData.model,
					tools: inputData.tools,
					toolChoice: inputData.toolChoice,
					activeTools: inputData.activeTools
				})
			});
			messageList.startRecording();
			try {
				const processorState = this.getProcessorState(processor.id);
				const beforeStepInput = {
					messageId: inputData.messageId,
					model: inputData.model,
					tools: inputData.tools,
					toolChoice: inputData.toolChoice,
					activeTools: inputData.activeTools
				};
				const rotateResponseMessageId = args.rotateResponseMessageId ? () => {
					const nextMessageId = args.rotateResponseMessageId();
					stepInput.messageId = nextMessageId;
					return nextMessageId;
				} : void 0;
				const processMethodArgs = {
					messageList,
					...inputData,
					state: processorState.customState,
					llmRequestStage: args.llmRequestProcessorIds?.has(processor.id) || void 0,
					abort,
					...rotateResponseMessageId ? { rotateResponseMessageId } : {},
					...createObservabilityContext({ currentSpan: processorSpan }),
					retryCount: args.retryCount ?? 0,
					writer,
					abortSignal: args.abortSignal,
					agent: this.agent,
					sendSignal: createProcessorSendSignal({
						messageList,
						writer,
						rotateResponseMessageId,
						lateSink: this.lateSignalSink
					}),
					sendStateSignal: async (stateSignal) => {
						const memoryContext = parseMemoryRequestContext(requestContext);
						const resolvedMemory = args.memory;
						const resolvedThreadId = args.threadId ?? memoryContext?.thread?.id;
						const resolvedResourceId = args.resourceId ?? memoryContext?.resourceId;
						if (!resolvedMemory || !resolvedThreadId || !resolvedResourceId) throw new Error(`[Processor:${processor.id}] sendStateSignal requires Mastra memory with an active resourceId and threadId`);
						const loadedThread = await resolvedMemory.getThreadById({ threadId: resolvedThreadId }) ?? memoryContext?.thread;
						if (!loadedThread) throw new Error(`[Processor:${processor.id}] sendStateSignal could not load thread ${resolvedThreadId}`);
						const result = await applyStateSignal({
							input: stateSignal,
							memory: resolvedMemory,
							thread: {
								...loadedThread,
								id: resolvedThreadId,
								resourceId: loadedThread.resourceId ?? resolvedResourceId,
								createdAt: loadedThread.createdAt ?? /* @__PURE__ */ new Date(),
								updatedAt: loadedThread.updatedAt ?? /* @__PURE__ */ new Date(),
								metadata: loadedThread.metadata
							},
							resourceId: resolvedResourceId,
							threadId: resolvedThreadId,
							memoryConfig: memoryContext?.memoryConfig,
							messageList,
							defaultId: processor.stateId ?? processor.id,
							beforeAddSignal: rotateResponseMessageId,
							writeSignal: (signal) => writer?.custom(signal.toDataPart())
						});
						return result.skipped ? result : result.signal;
					}
				};
				const result = processMethod ? await ProcessorRunner.validateAndFormatProcessInputStepResult(await processMethod(processMethodArgs), {
					messageList,
					processor,
					stepNumber
				}) : {};
				const { messages, systemMessages, ...rest } = result;
				if (messages) ProcessorRunner.applyMessagesToMessageList(messages, messageList, idsBeforeProcessing, check);
				if (systemMessages) messageList.replaceAllSystemMessages(systemMessages);
				Object.assign(stepInput, rest);
				await this.runComputeStateSignal({
					processor,
					messageList,
					stepNumber,
					steps,
					requestContext,
					writer,
					abort,
					processorState,
					observabilityContext: createObservabilityContext({ currentSpan: processorSpan }),
					memory: args.memory,
					resourceId: args.resourceId,
					threadId: args.threadId,
					abortSignal: args.abortSignal,
					retryCount: args.retryCount ?? 0,
					rotateResponseMessageId
				});
				const mutations = messageList.stopRecording();
				processorSpan?.end({
					output: buildProcessInputStepSpanOutput({
						result,
						beforeStepInput,
						afterStepInput: stepInput,
						beforeMessages: inputData.messages,
						beforeSystemMessages: inputData.systemMessages,
						messages: messageList.get.all.db(),
						systemMessages: messageList.getSystemMessages()
					}),
					attributes: mutations.length > 0 ? { messageListMutations: mutations } : void 0
				});
			} catch (error) {
				messageList.stopRecording();
				if (error instanceof TripWire) {
					processorSpan?.error({
						error,
						endSpan: true,
						attributes: { tripwireAbort: {
							reason: error.message,
							retry: error.options?.retry,
							metadata: error.options?.metadata
						} }
					});
					await invokeOnViolation(processor, error);
					throw error;
				}
				processorSpan?.error({
					error,
					endSpan: true
				});
				throw error;
			}
		}
		return stepInput;
	}
	/**
	* IDs of the processors that `runProcessLLMRequest` will call for these input processors.
	* Pass the result to `runProcessInputStep` as `llmRequestProcessorIds`.
	*/
	static getLLMRequestProcessorIds(processors) {
		const ids = /* @__PURE__ */ new Set();
		for (const processor of processors) if (!isProcessorWorkflow(processor) && processor.processLLMRequest) ids.add(processor.id);
		return ids;
	}
	/**
	* Run processLLMRequest for all processors that implement it.
	*
	* Called *after* `MessageList` has been converted to `LanguageModelV2Prompt`
	* and immediately *before* the prompt is forwarded to the provider.
	* Mutations are scoped to this single call — they do not affect the
	* persisted message list, memory, UI, or future model swaps.
	*/
	async runProcessLLMRequest(args) {
		const observabilityContext = resolveObservabilityContext({ tracingContext: args.tracingContext });
		let currentPrompt = args.prompt;
		let cachedResponse;
		for (const [index, processorOrWorkflow] of this.inputProcessors.entries()) {
			if (isProcessorWorkflow(processorOrWorkflow)) continue;
			const processor = processorOrWorkflow;
			const processMethod = processor.processLLMRequest?.bind(processor);
			if (!processMethod) continue;
			const abort = (reason, options) => {
				throw new TripWire(reason || `Tripwire triggered by ${processor.id}`, options, processor.id);
			};
			const processorSpan = (observabilityContext.tracingContext?.currentSpan)?.createChildSpan({
				type: processor.spanType ?? "processor_run",
				name: resolveProcessorSpanName(processor, "llmRequest", `llm request processor: ${processor.id}`),
				entityType: EntityType.INPUT_PROCESSOR,
				entityId: processor.id,
				entityName: processor.name,
				attributes: {
					...resolveProcessorSpanAttributes(processor, "llmRequest"),
					processorExecutor: "legacy",
					processorIndex: index
				},
				input: {
					prompt: currentPrompt,
					stepNumber: args.stepNumber,
					retryCount: args.retryCount ?? 0
				}
			});
			try {
				const processorState = this.getProcessorState(processor.id);
				const promptBefore = currentPrompt;
				const result = await processMethod({
					prompt: currentPrompt,
					model: args.model,
					apiProviderId: args.apiProviderId,
					messageList: args.messageList,
					workspace: args.workspace,
					stepNumber: args.stepNumber,
					steps: args.steps,
					state: processorState.customState,
					retryCount: args.retryCount ?? 0,
					requestContext: args.requestContext,
					agent: this.agent,
					abort,
					abortSignal: args.abortSignal,
					writer: args.writer,
					...createObservabilityContext({ currentSpan: processorSpan })
				});
				if (result && typeof result === "object") {
					if (Object.prototype.hasOwnProperty.call(result, "prompt")) currentPrompt = result.prompt;
					if (result.response && !cachedResponse) cachedResponse = result.response;
				}
				processorSpan?.end({ output: {
					...currentPrompt !== promptBefore ? { prompt: currentPrompt } : {},
					shortCircuited: Boolean(result && typeof result === "object" && result.response)
				} });
			} catch (error) {
				if (error instanceof TripWire) {
					processorSpan?.error({
						error,
						endSpan: true,
						attributes: { tripwireAbort: {
							reason: error.message,
							retry: error.options?.retry,
							metadata: error.options?.metadata
						} }
					});
					await invokeOnViolation(processor, error);
					throw error;
				}
				processorSpan?.error({
					error,
					endSpan: true
				});
				throw error;
			}
		}
		return {
			prompt: currentPrompt,
			response: cachedResponse
		};
	}
	/**
	* Run processLLMResponse for all processors that implement it.
	*
	* Called *after* the LLM step completes (or after a cached response is
	* replayed) and *after* output processors have collected the response
	* chunks. The shared `state` object is the same instance passed to
	* `processLLMRequest` for the same step, allowing processors to correlate
	* pre- and post-call work (e.g. cache key stash, then cache write).
	*/
	async runProcessLLMResponse(args) {
		const observabilityContext = resolveObservabilityContext({ tracingContext: args.tracingContext });
		for (const [index, processorOrWorkflow] of this.inputProcessors.entries()) {
			if (isProcessorWorkflow(processorOrWorkflow)) continue;
			const processor = processorOrWorkflow;
			const processMethod = processor.processLLMResponse?.bind(processor);
			if (!processMethod) continue;
			const abort = (reason, options) => {
				throw new TripWire(reason || `Tripwire triggered by ${processor.id}`, options, processor.id);
			};
			const processorSpan = (observabilityContext.tracingContext?.currentSpan)?.createChildSpan({
				type: processor.spanType ?? "processor_run",
				name: resolveProcessorSpanName(processor, "llmResponse", `llm response processor: ${processor.id}`),
				entityType: EntityType.INPUT_PROCESSOR,
				entityId: processor.id,
				entityName: processor.name,
				attributes: {
					...resolveProcessorSpanAttributes(processor, "llmResponse"),
					processorExecutor: "legacy",
					processorIndex: index
				},
				input: {
					stepNumber: args.stepNumber,
					retryCount: args.retryCount ?? 0,
					fromCache: args.fromCache,
					chunkCount: args.chunks.length
				}
			});
			try {
				const processorState = this.getProcessorState(processor.id);
				await processMethod({
					chunks: args.chunks,
					model: args.model,
					stepNumber: args.stepNumber,
					steps: args.steps,
					state: processorState.customState,
					warnings: args.warnings,
					request: args.request,
					rawResponse: args.rawResponse,
					fromCache: args.fromCache,
					retryCount: args.retryCount ?? 0,
					requestContext: args.requestContext,
					agent: this.agent,
					abort,
					abortSignal: args.abortSignal,
					writer: args.writer,
					...createObservabilityContext({ currentSpan: processorSpan })
				});
				processorSpan?.end({ output: {} });
			} catch (error) {
				if (error instanceof TripWire) {
					processorSpan?.error({
						error,
						endSpan: true,
						attributes: { tripwireAbort: {
							reason: error.message,
							retry: error.options?.retry,
							metadata: error.options?.metadata
						} }
					});
					await invokeOnViolation(processor, error);
					throw error;
				}
				processorSpan?.error({
					error,
					endSpan: true
				});
				throw error;
			}
		}
	}
	/**
	* Type guard to check if result is { messages, systemMessages }
	*/
	isProcessInputResultWithSystemMessages(result) {
		return result !== null && typeof result === "object" && "messages" in result && "systemMessages" in result && Array.isArray(result.messages) && Array.isArray(result.systemMessages);
	}
	/**
	* Run processOutputStep for all processors that implement it.
	* Called after each LLM response in the agentic loop, before tool execution.
	*
	* Unlike processOutputResult which runs once at the end, this runs at every step.
	* This is the ideal place to implement guardrails that can trigger retries.
	*
	* @param args.messages - The current messages including the LLM response
	* @param args.messageList - MessageList instance for managing message sources
	* @param args.stepNumber - The current step number (0-indexed)
	* @param args.finishReason - The finish reason from the LLM
	* @param args.toolCalls - Tool calls made in this step (if any)
	* @param args.text - Generated text from this step
	* @param args.tracingContext - Optional tracing context for observability
	* @param args.requestContext - Optional runtime context with execution metadata
	* @param args.retryCount - Number of times processors have triggered retry
	*
	* @returns The processed MessageList
	*/
	async runProcessOutputStep(args) {
		const { steps, messageList, stepNumber, finishReason, providerMetadata, toolCalls, text, usage, requestContext, retryCount = 0, writer } = args;
		const observabilityContext = resolveObservabilityContext(args);
		for (const [index, processorOrWorkflow] of this.outputProcessors.entries()) {
			const processableMessages = messageList.get.all.db();
			const idsBeforeProcessing = processableMessages.map((m) => m.id);
			const check = messageList.makeMessageSourceChecker();
			if (isProcessorWorkflow(processorOrWorkflow)) {
				const currentSystemMessages = messageList.getSystemMessages();
				await this.executeWorkflowAsProcessor(processorOrWorkflow, {
					phase: "outputStep",
					messages: processableMessages,
					messageList,
					stepNumber,
					finishReason,
					providerMetadata,
					toolCalls,
					text,
					usage,
					systemMessages: currentSystemMessages,
					steps,
					retryCount
				}, observabilityContext, requestContext, writer);
				continue;
			}
			const processor = processorOrWorkflow;
			const processMethod = processor.processOutputStep?.bind(processor);
			if (!processMethod) continue;
			const abort = (reason, options) => {
				throw new TripWire(reason || `Tripwire triggered by ${processor.id}`, options, processor.id);
			};
			const currentSystemMessages = messageList.getSystemMessages();
			const defaultUsage = {
				inputTokens: void 0,
				outputTokens: void 0,
				totalTokens: void 0
			};
			const currentSpan = observabilityContext.tracingContext?.currentSpan;
			const processorSpan = (currentSpan?.findParent("agent_run") || currentSpan?.parent || currentSpan)?.createChildSpan({
				type: processor.spanType ?? "processor_run",
				name: resolveProcessorSpanName(processor, "outputStep", `output step processor: ${processor.id}`),
				entityType: EntityType.OUTPUT_STEP_PROCESSOR,
				entityId: processor.id,
				entityName: processor.name,
				attributes: {
					...resolveProcessorSpanAttributes(processor, "outputStep"),
					processorExecutor: "legacy",
					processorIndex: index
				},
				input: {
					messages: processableMessages,
					systemMessages: currentSystemMessages,
					stepNumber,
					...finishReason !== void 0 ? { finishReason } : {},
					...toolCalls !== void 0 ? { toolCalls } : {},
					...text !== void 0 ? { text } : {}
				}
			});
			messageList.startRecording();
			const processorState = this.getProcessorState(processor.id);
			try {
				const result = await processMethod({
					messages: processableMessages,
					messageList,
					stepNumber,
					finishReason,
					providerMetadata,
					toolCalls,
					text,
					usage: usage ?? defaultUsage,
					systemMessages: currentSystemMessages,
					steps,
					state: processorState.customState,
					abort,
					...createObservabilityContext({ currentSpan: processorSpan }),
					requestContext,
					agent: this.agent,
					retryCount,
					writer,
					sendSignal: createProcessorSendSignal({
						messageList,
						writer,
						lateSink: this.lateSignalSink
					})
				});
				const mutations = messageList.stopRecording();
				if (result instanceof MessageList) {
					if (result !== messageList) throw new MastraError({
						category: "USER",
						domain: "AGENT",
						id: "PROCESSOR_RETURNED_EXTERNAL_MESSAGE_LIST",
						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.`
					});
				} else if (result) {
					const deletedIds = idsBeforeProcessing.filter((i) => !result.some((m) => m.id === i));
					if (deletedIds.length) messageList.removeByIds(deletedIds);
					for (const message of result) {
						messageList.removeByIds([message.id]);
						if (message.role === "system") {
							const systemText = message.content.content ?? message.content.parts?.map((p) => p.type === "text" ? p.text : "").join("\n") ?? "";
							messageList.addSystem(systemText);
						} else messageList.add(message, check.getSource(message) || "response", { merge: false });
					}
				}
				processorSpan?.end({
					output: {
						...!areProcessorMessageArraysEqual(processableMessages, messageList.get.all.db()) ? { messages: messageList.get.all.db() } : {},
						...!areProcessorMessageArraysEqual(currentSystemMessages, messageList.getSystemMessages()) ? { systemMessages: messageList.getSystemMessages() } : {}
					},
					attributes: mutations.length > 0 ? { messageListMutations: mutations } : void 0
				});
			} catch (error) {
				messageList.stopRecording();
				if (error instanceof TripWire) {
					processorSpan?.error({
						error,
						endSpan: true,
						attributes: { tripwireAbort: {
							reason: error.message,
							retry: error.options?.retry,
							metadata: error.options?.metadata
						} }
					});
					await invokeOnViolation(processor, error);
					throw error;
				}
				processorSpan?.error({
					error,
					endSpan: true
				});
				throw error;
			}
		}
		return messageList;
	}
	/**
	* Run processToolResult on all output processors that implement it.
	* Called after tool.execute() returns and before the result is appended to
	* the message list / fed to the next LLM call.
	*
	* Symmetric with runProcessOutputStep — same TripWire/abort/state plumbing.
	* Processors mutate via messageList.updateToolInvocation. The caller is
	* responsible for re-reading the post-mutation result and syncing it into
	* the downstream stream chunk so streaming clients see the processed value.
	*/
	async runProcessToolResult(args) {
		const { steps, messageList, stepNumber, toolName, toolCallId, toolArgs, result, modelOutput, providerExecuted, requestContext, retryCount = 0, writer, abortSignal } = args;
		const observabilityContext = resolveObservabilityContext(args);
		for (const [index, processorOrWorkflow] of this.outputProcessors.entries()) {
			const currentModelOutput = latestProcessedModelOutput(messageList, toolCallId, modelOutput);
			const processableMessages = messageList.get.all.db();
			const idsBeforeProcessing = processableMessages.map((m) => m.id);
			const check = messageList.makeMessageSourceChecker();
			if (isProcessorWorkflow(processorOrWorkflow)) {
				const currentSystemMessages = messageList.getAllSystemMessages();
				await this.executeWorkflowAsProcessor(processorOrWorkflow, {
					phase: "toolResult",
					messages: processableMessages,
					messageList,
					stepNumber,
					toolName,
					toolCallId,
					args: toolArgs,
					toolResultValue: result,
					modelOutput: currentModelOutput,
					providerExecuted,
					systemMessages: currentSystemMessages,
					steps,
					retryCount
				}, observabilityContext, requestContext, writer, abortSignal);
				continue;
			}
			const processor = processorOrWorkflow;
			const processMethod = processor.processToolResult?.bind(processor);
			if (!processMethod) continue;
			const abort = (reason, options) => {
				throw new TripWire(reason || `Tripwire triggered by ${processor.id}`, options, processor.id);
			};
			const currentSystemMessages = messageList.getAllSystemMessages();
			const currentSpan = observabilityContext.tracingContext?.currentSpan;
			const processorSpan = (currentSpan?.findParent("agent_run") || currentSpan?.parent || currentSpan)?.createChildSpan({
				type: processor.spanType ?? "processor_run",
				name: resolveProcessorSpanName(processor, "toolResult", `tool result processor: ${processor.id}`),
				entityType: EntityType.TOOL_RESULT_PROCESSOR,
				entityId: processor.id,
				entityName: processor.name,
				attributes: {
					...resolveProcessorSpanAttributes(processor, "toolResult"),
					processorExecutor: "legacy",
					processorIndex: index
				},
				input: {
					toolName,
					toolCallId,
					stepNumber,
					...providerExecuted !== void 0 ? { providerExecuted } : {}
				}
			});
			messageList.startRecording();
			const processorState = this.getProcessorState(processor.id);
			try {
				const processorResult = await processMethod({
					messages: processableMessages,
					messageList,
					stepNumber,
					toolName,
					toolCallId,
					args: toolArgs,
					result,
					modelOutput: currentModelOutput,
					providerExecuted,
					systemMessages: currentSystemMessages,
					steps,
					state: processorState.customState,
					abort,
					...createObservabilityContext({ currentSpan: processorSpan }),
					requestContext,
					retryCount,
					writer,
					abortSignal
				});
				const mutations = messageList.stopRecording();
				if (processorResult instanceof MessageList) {
					if (processorResult !== messageList) throw new MastraError({
						category: "USER",
						domain: "AGENT",
						id: "PROCESSOR_RETURNED_EXTERNAL_MESSAGE_LIST",
						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.`
					});
				} else if (processorResult) ProcessorRunner.applyMessagesToMessageList(processorResult, messageList, idsBeforeProcessing, check, "response");
				processorSpan?.end({
					output: {
						...!areProcessorMessageArraysEqual(processableMessages, messageList.get.all.db()) ? { messages: messageList.get.all.db() } : {},
						...!areProcessorMessageArraysEqual(currentSystemMessages, messageList.getAllSystemMessages()) ? { systemMessages: messageList.getAllSystemMessages() } : {}
					},
					attributes: mutations.length > 0 ? { messageListMutations: mutations } : void 0
				});
			} catch (error) {
				messageList.stopRecording();
				if (error instanceof TripWire) {
					processorSpan?.error({
						error,
						endSpan: true,
						attributes: { tripwireAbort: {
							reason: error.message,
							retry: error.options?.retry,
							metadata: error.options?.metadata
						} }
					});
					throw error;
				}
				processorSpan?.error({
					error,
					endSpan: true
				});
				throw error;
			}
		}
		return messageList;
	}
	/**
	* Run processAPIError on all processors that implement it.
	* Called when an LLM API call fails with a non-retryable error.
	* Iterates through both input and output processors.
	*
	* @returns { retry: boolean } indicating whether to retry the LLM call
	*/
	async runProcessAPIError(args) {
		const { error, messageList, stepNumber, steps, requestContext, retryCount = 0, writer, abortSignal } = args;
		const observabilityContext = resolveObservabilityContext(args);
		const allProcessors = [
			...this.inputProcessors,
			...this.outputProcessors,
			...this.errorProcessors
		];
		for (const [index, processorOrWorkflow] of allProcessors.entries()) {
			if (isProcessorWorkflow(processorOrWorkflow)) continue;
			const processor = processorOrWorkflow;
			const processMethod = processor.processAPIError?.bind(processor);
			if (!processMethod) continue;
			const abort = (reason, options) => {
				throw new TripWire(reason || `Tripwire triggered by ${processor.id}`, options, processor.id);
			};
			const processableMessages = messageList.get.all.db();
			const systemMessagesBefore = messageList.getAllSystemMessages();
			const messageIdBefore = args.messageId;
			let messageIdAfter = args.messageId;
			const currentSpan = observabilityContext.tracingContext?.currentSpan;
			const processorSpan = (findOwnModelStepSpan(currentSpan) ?? (currentSpan?.findParent("agent_run") || currentSpan?.parent || currentSpan))?.createChildSpan({
				type: processor.spanType ?? "processor_run",
				name: resolveProcessorSpanName(processor, "requestError", `request error processor: ${processor.id}`),
				entityType: EntityType.OUTPUT_STEP_PROCESSOR,
				entityId: processor.id,
				entityName: processor.name,
				attributes: {
					...resolveProcessorSpanAttributes(processor, "requestError"),
					processorExecutor: "legacy",
					processorIndex: index
				},
				input: {
					messages: processableMessages,
					error: error instanceof Error ? error.message : String(error),
					stepNumber,
					...args.messageId ? { messageId: args.messageId } : {},
					retryCount
				}
			});
			messageList.startRecording();
			const processorState = this.getProcessorState(processor.id);
			try {
				const rotateResponseMessageId = args.rotateResponseMessageId ? () => {
					const nextMessageId = args.rotateResponseMessageId();
					messageIdAfter = nextMessageId;
					return nextMessageId;
				} : void 0;
				const result = await processMethod({
					messages: processableMessages,
					messageList,
					stepNumber,
					steps,
					state: processorState.customState,
					error,
					abort,
					...createObservabilityContext({ currentSpan: processorSpan }),
					requestContext,
					agent: this.agent,
					retryCount,
					writer,
					abortSignal,
					messageId: args.messageId,
					...rotateResponseMessageId ? { rotateResponseMessageId } : {},
					sendSignal: createProcessorSendSignal({
						messageList,
						writer,
						rotateResponseMessageId,
						lateSink: this.lateSignalSink
					})
				});
				const mutations = messageList.stopRecording();
				const messagesAfter = messageList.get.all.db();
				const systemMessagesAfter = messageList.getAllSystemMessages();
				const output = { retry: result?.retry ?? false };
				if (!areProcessorMessageArraysEqual(processableMessages, messagesAfter)) output.messages = messagesAfter;
				if (!areProcessorMessageArraysEqual(systemMessagesBefore, systemMessagesAfter)) output.systemMessages = systemMessagesAfter;
				if (messageIdAfter !== messageIdBefore) output.messageId = messageIdAfter;
				processorSpan?.end({
					output,
					attributes: mutations.length > 0 ? { messageListMutations: mutations } : void 0
				});
				if (result?.retry) return { retry: true };
			} catch (processorError) {
				messageList.stopRecording();
				if (processorError instanceof TripWire) {
					processorSpan?.error({
						error: processorError,
						endSpan: true,
						attributes: { tripwireAbort: {
							reason: processorError.message,
							retry: processorError.options?.retry,
							metadata: processorError.options?.metadata
						} }
					});
					await invokeOnViolation(processor, processorError);
					throw processorError;
				}
				processorSpan?.error({
					error: processorError,
					endSpan: true
				});
				this.logger.error(`[Agent:${this.agentName}] - Request error processor ${processor.id} failed:`, processorError);
			}
		}
		return { retry: false };
	}
	static applyMessagesToMessageList(messages, messageList, idsBeforeProcessing, check, defaultSource = "input") {
		const deletedIds = idsBeforeProcessing.filter((i) => !messages.some((m) => m.id === i));
		if (deletedIds.length) messageList.removeByIds(deletedIds);
		const currentById = new Map(messageList.get.all.db().map((message) => [message.id, message]));
		for (const message of messages) {
			if (currentById.get(message.id) === message) continue;
			messageList.removeByIds([message.id]);
			if (message.role === "system") {
				const systemText = message.content.content ?? message.content.parts?.map((p) => p.type === "text" ? p.text : "").join("\n") ?? "";
				messageList.addSystem(systemText);
			} else messageList.add(message, check.getSource(message) || defaultSource, { merge: false });
		}
	}
	static async validateAndFormatProcessInputStepResult(result, { messageList, processor, stepNumber }) {
		if (result instanceof MessageList) {
			if (result !== messageList) throw new MastraError({
				category: "USER",
				domain: "AGENT",
				id: "PROCESSOR_RETURNED_EXTERNAL_MESSAGE_LIST",
				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.`
			});
			return { messageList: result };
		} else if (Array.isArray(result)) return { messages: result };
		else if (result) {
			if (result.messageList && result.messageList !== messageList) throw new MastraError({
				category: "USER",
				domain: "AGENT",
				id: "PROCESSOR_RETURNED_EXTERNAL_MESSAGE_LIST",
				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.`
			});
			if (result.messages && result.messageList) throw new MastraError({
				category: "USER",
				domain: "AGENT",
				id: "PROCESSOR_RETURNED_MESSAGES_AND_MESSAGE_LIST",
				text: `Processor ${processor.id} returned both messages and messageList. Only one of these is allowed.`
			});
			const { model: _model, ...rest } = result;
			if (result.model) {
				const resolvedModel = await resolveModelConfig(result.model);
				if (!isSupportedLanguageModel(resolvedModel)) throw new MastraError({
					category: "USER",
					domain: "AGENT",
					id: "PROCESSOR_RETURNED_UNSUPPORTED_MODEL",
					text: `Processor ${processor.id} returned an unsupported model version ${resolvedModel.specificationVersion} in step ${stepNumber}. Only ${supportedLanguageModelSpecifications.join(", ")} models are supported in processInputStep.`
				});
				return {
					model: resolvedModel,
					...rest
				};
			}
			return rest;
		}
		return {};
	}
};
// src/stream/signal-exclusions.ts
function canonicalSignalType(type) {
	switch (type) {
		case "system-reminder": return "reactive";
		case "user-message": return "user";
		case "user":
		case "state":
		case "reactive":
		case "notification": return type;
		default: return;
	}
}
/** @internal Caller-local policy; never apply to shared buffers or model messages. */
function isSignalChunkExcluded(chunk, hideSignals) {
	if (!hideSignals || !chunk || typeof chunk !== "object") return false;
	if (!("type" in chunk) || chunk.type !== "data-signal" && chunk.type !== "data-user-message" && chunk.type !== "data-user-message-pending") return false;
	if (!("data" in chunk) || !chunk.data || typeof chunk.data !== "object" || Array.isArray(chunk.data)) return false;
	if (!("type" in chunk.data)) return false;
	const type = canonicalSignalType(chunk.data.type);
	return type !== void 0 && (hideSignals === true || hideSignals.some((excluded) => canonicalSignalType(excluded) === type));
}
// src/stream/base/schema.ts
function asJsonSchema(schema) {
	if (!schema) return;
	if (isStandardSchemaWithJSON(schema)) return standardSchemaToJSONSchema(schema, {
		io: "input",
		target: "draft-07"
	});
	return schema;
}
function getTransformedSchema(schema, options) {
	if (!schema) return;
	const jsonSchema = options?.model ? applyCompatLayer({
		schema,
		compatLayers: [new AnthropicSchemaCompatLayer(options.model)],
		mode: "jsonSchema"
	}) : asJsonSchema(schema);
	if (!jsonSchema) return;
	const { $schema, ...itemSchema } = jsonSchema;
	if (itemSchema.type === "array") return {
		jsonSchema: {
			$schema,
			type: "object",
			properties: { elements: {
				type: "array",
				items: itemSchema.items
			} },
			required: ["elements"],
			additionalProperties: false
		},
		outputFormat: "array"
	};
	if (itemSchema.enum && Array.isArray(itemSchema.enum)) return {
		jsonSchema: {
			$schema,
			type: "object",
			properties: { result: {
				type: itemSchema.type || "string",
				enum: itemSchema.enum
			} },
			required: ["result"],
			additionalProperties: false
		},
		outputFormat: "enum"
	};
	return {
		jsonSchema,
		outputFormat: jsonSchema.type
	};
}
function getResponseFormat(schema, options) {
	if (schema) return {
		type: "json",
		schema: getTransformedSchema(schema, options)?.jsonSchema
	};
	return { type: "text" };
}
// src/stream/base/output-format-handlers.ts
/**
* Escapes unescaped newlines, carriage returns, and tabs within JSON string values.
*
* LLMs often output actual newline characters inside JSON strings instead of properly
* escaped \n sequences, which breaks JSON parsing. This function fixes that by:
* 1. Tracking whether we're inside a JSON string (after an unescaped quote)
* 2. Replacing literal newlines/tabs with their escape sequences only inside strings
* 3. Preserving already-escaped sequences like \\n
*
* @param text - Raw JSON text that may contain unescaped control characters in strings
* @returns JSON text with control characters properly escaped inside string values
*/
function escapeUnescapedControlCharsInJsonStrings(text) {
	let result = "";
	let inString = false;
	let i = 0;
	while (i < text.length) {
		const char = text[i];
		if (char === "\\" && i + 1 < text.length) {
			result += char + text[i + 1];
			i += 2;
			continue;
		}
		if (char === "\"") {
			inString = !inString;
			result += char;
			i++;
			continue;
		}
		if (inString) {
			if (char === "\n") {
				result += "\\n";
				i++;
				continue;
			}
			if (char === "\r") {
				result += "\\r";
				i++;
				continue;
			}
			if (char === "	") {
				result += "\\t";
				i++;
				continue;
			}
		}
		result += char;
		i++;
	}
	return result;
}
function extractBalancedJsonObject(text) {
	const trimmed = text.trim();
	if (trimmed.startsWith("{") || trimmed.startsWith("[")) return void 0;
	let start = -1;
	let depth = 0;
	let inString = false;
	let escaped = false;
	let lastBalanced;
	for (let i = 0; i < text.length; i++) {
		const char = text[i];
		if (escaped) {
			escaped = false;
			continue;
		}
		if (char === "\\") {
			escaped = true;
			continue;
		}
		if (char === "\"") {
			inString = !inString;
			continue;
		}
		if (inString) continue;
		if (char === "{") {
			if (depth === 0) start = i;
			depth++;
			continue;
		}
		if (char === "}" && depth > 0) {
			depth--;
			if (depth === 0 && start !== -1) lastBalanced = text.slice(start, i + 1);
		}
	}
	return lastBalanced;
}
/**
* Base class for all output format handlers.
* Each handler implements format-specific logic for processing partial chunks
* and validating final results.
*/
var BaseFormatHandler = class {
	/**
	* The original user-provided schema (Zod, JSON Schema, or AI SDK Schema).
	*/
	schema;
	/**
	* Validate partial chunks as they are streamed. @planned
	*/
	validatePartialChunks = false;
	partialSchema;
	constructor(schema, options = {}) {
		this.schema = schema;
		if (options.validatePartialChunks && this.isZodSchema(schema) && "partial" in schema && typeof schema.partial === "function") {
			this.partialSchema = schema.partial();
			this.validatePartialChunks = true;
		}
	}
	/**
	* Checks if the original schema is a Zod schema with safeParse method.
	*/
	isZodSchema(schema) {
		return isZodType(schema);
	}
	/**
	* Validates a value against the schema using StandardSchemaWithJSON's validate method.
	*/
	async validateValue(value, diagnosticValue = value) {
		if (!this.schema) return {
			success: true,
			value
		};
		if (this.isZodSchema(this.schema)) try {
			const ssResult = await this.schema["~standard"].validate(value);
			if (!ssResult.issues) return {
				success: true,
				value: ssResult.value
			};
			const errorMessages = ssResult.issues.map((e) => `- ${e.path?.join(".") || "root"}: ${e.message}`).join("\n");
			const zodResult = this.schema.safeParse(value);
			const zodError = !zodResult.success ? zodResult.error : void 0;
			return {
				success: false,
				error: new MastraError({
					domain: ErrorDomain.AGENT,
					category: ErrorCategory.SYSTEM,
					id: "STRUCTURED_OUTPUT_SCHEMA_VALIDATION_FAILED",
					text: `Structured output validation failed: ${errorMessages}`,
					details: { value: typeof diagnosticValue === "object" ? JSON.stringify(diagnosticValue) : String(diagnosticValue) }
				}, zodError)
			};
		} catch (error) {
			return {
				success: false,
				error: error instanceof Error ? error : new Error("Zod validation failed", { cause: error })
			};
		}
		try {
			const ssResult = await this.schema["~standard"].validate(value);
			if (!ssResult.issues) return {
				success: true,
				value: ssResult.value
			};
			const errorMessages = ssResult.issues.map((e) => `- ${e.path?.join(".") || "root"}: ${e.message}`).join("\n");
			return {
				success: false,
				error: new MastraError({
					domain: ErrorDomain.AGENT,
					category: ErrorCategory.SYSTEM,
					id: "STRUCTURED_OUTPUT_SCHEMA_VALIDATION_FAILED",
					text: `Structured output validation failed: ${errorMessages}`,
					details: { value: typeof diagnosticValue === "object" ? JSON.stringify(diagnosticValue) : String(diagnosticValue) }
				})
			};
		} catch (error) {
			return {
				success: false,
				error: error instanceof Error ? error : new Error("Validation failed", { cause: error })
			};
		}
	}
	/**
	* Preprocesses accumulated text to handle LLMs that wrap JSON in code blocks
	* and fix common JSON formatting issues like unescaped newlines in strings.
	* Extracts content from the first complete valid ```json...``` code block or removes opening ```json prefix if no complete code block is found (streaming chunks).
	* @param accumulatedText - Raw accumulated text from streaming
	* @returns Processed text ready for JSON parsing
	*/
	preprocessText(accumulatedText) {
		let processedText = accumulatedText;
		if (processedText.includes("<|message|>")) {
			const match = processedText.match(/<\|message\|>([\s\S]+)$/);
			if (match && match[1]) processedText = match[1];
		}
		const trimmedStart = processedText.trimStart();
		if (/^```json\b/.test(trimmedStart)) {
			const match = trimmedStart.match(/^```json\s*\n?([\s\S]*?)\n?\s*```\s*$/);
			if (match && match[1]) processedText = match[1].trim();
			else processedText = trimmedStart.replace(/^```json\s*\n?/, "");
		}
		const extractedObject = extractBalancedJsonObject(processedText);
		if (extractedObject) processedText = extractedObject;
		processedText = escapeUnescapedControlCharsInJsonStrings(processedText);
		return processedText;
	}
};
/**
* Handles object format streaming. Emits parsed objects when they change during streaming.
* This is the simplest format - objects are parsed and emitted directly without wrapping.
*/
var ObjectFormatHandler = class extends BaseFormatHandler {
	type = "object";
	async processPartialChunk({ accumulatedText, previousObject }) {
		const processedAccumulatedText = this.preprocessText(accumulatedText);
		const { value: currentObjectJson, state } = await parsePartialJson(processedAccumulatedText);
		if (this.validatePartialChunks && this.partialSchema) {
			const result = this.partialSchema?.safeParse(currentObjectJson);
			if (result.success && result.data && result.data !== void 0 && !isDeepEqualData(previousObject, result.data)) return {
				shouldEmit: true,
				emitValue: result.data,
				newPreviousResult: result.data
			};
			/**
			* TODO: emit error chunk if partial validation fails?
			* maybe we need to either not emit the object chunk,
			* emit our error chunk, or wait until final parse to emit the error chunk?
			*/
			return { shouldEmit: false };
		}
		if (currentObjectJson !== void 0 && currentObjectJson !== null && typeof currentObjectJson === "object" && !isDeepEqualData(previousObject, currentObjectJson)) return {
			shouldEmit: ["successful-parse", "repaired-parse"].includes(state),
			emitValue: currentObjectJson,
			newPreviousResult: currentObjectJson
		};
		return { shouldEmit: false };
	}
	async validateAndTransformFinal(finalRawValue) {
		if (!finalRawValue) return {
			success: false,
			error: /* @__PURE__ */ new Error("No object generated: could not parse the response.")
		};
		const rawValue = this.preprocessText(finalRawValue);
		const { value } = await parsePartialJson(rawValue);
		return this.validateValue(value, value === void 0 ? rawValue : value);
	}
};
/**
* Handles array format streaming. Arrays are wrapped in {elements: [...]} objects by the LLM
* for better generation reliability. This handler unwraps them and filters incomplete elements.
* Emits progressive array states as elements are completed.
*/
var ArrayFormatHandler = class extends BaseFormatHandler {
	type = "array";
	/** Previously filtered array to track changes */
	textPreviousFilteredArray = [];
	/** Whether we've emitted the initial empty array */
	hasEmittedInitialArray = false;
	async processPartialChunk({ accumulatedText, previousObject }) {
		const processedAccumulatedText = this.preprocessText(accumulatedText);
		const { value: currentObjectJson, state: parseState } = await parsePartialJson(processedAccumulatedText);
		if (currentObjectJson !== void 0 && !isDeepEqualData(previousObject, currentObjectJson)) {
			const rawElements = currentObjectJson && typeof currentObjectJson === "object" && "elements" in currentObjectJson && Array.isArray(currentObjectJson.elements) ? currentObjectJson.elements : [];
			const filteredElements = [];
			for (let i = 0; i < rawElements.length; i++) {
				const element = rawElements[i];
				if (i === rawElements.length - 1 && parseState !== "successful-parse") {
					if (element && typeof element === "object" && Object.keys(element).length > 0) filteredElements.push(element);
				} else if (element !== void 0) filteredElements.push(element);
			}
			if (!this.hasEmittedInitialArray) {
				this.hasEmittedInitialArray = true;
				if (filteredElements.length === 0) {
					this.textPreviousFilteredArray = [];
					return {
						shouldEmit: true,
						emitValue: [],
						newPreviousResult: currentObjectJson
					};
				}
			}
			if (!isDeepEqualData(this.textPreviousFilteredArray, filteredElements)) {
				this.textPreviousFilteredArray = [...filteredElements];
				return {
					shouldEmit: true,
					emitValue: filteredElements,
					newPreviousResult: currentObjectJson
				};
			}
		}
		return { shouldEmit: false };
	}
	async validateAndTransformFinal(finalRawValue) {
		if (!finalRawValue) return {
			success: false,
			error: /* @__PURE__ */ new Error("No object generated: could not parse the response.")
		};
		const { value } = await parsePartialJson(this.preprocessText(finalRawValue));
		const resultValue = value && typeof value === "object" && "elements" in value && Array.isArray(value.elements) ? value.elements : this.textPreviousFilteredArray;
		return this.validateValue(resultValue);
	}
};
/**
* Handles enum format streaming. Enums are wrapped in {result: ""} objects by the LLM
* for better generation reliability. This handler unwraps them and provides partial matching.
* Emits progressive enum states as they are completed.
* Validates the final result against the user-provided schema.
*/
var EnumFormatHandler = class extends BaseFormatHandler {
	type = "enum";
	/** Previously emitted enum result to avoid duplicate emissions */
	textPreviousEnumResult;
	/**
	* Finds the best matching enum value for a partial result string.
	* If multiple values match, returns the partial string. If only one matches, returns that value.
	* @param partialResult - Partial enum string from streaming
	* @returns Best matching enum value or undefined if no matches
	*/
	findBestEnumMatch(partialResult) {
		if (!this.schema) return;
		const enumValues = standardSchemaToJSONSchema(this.schema)?.enum;
		if (!enumValues) return;
		const possibleEnumValues = enumValues.filter((value) => typeof value === "string").filter((enumValue) => enumValue.startsWith(partialResult));
		if (possibleEnumValues.length === 0) return;
		const firstMatch = possibleEnumValues[0];
		return possibleEnumValues.length === 1 && firstMatch !== void 0 ? firstMatch : partialResult;
	}
	async processPartialChunk({ accumulatedText, previousObject }) {
		const processedAccumulatedText = this.preprocessText(accumulatedText);
		const { value: currentObjectJson } = await parsePartialJson(processedAccumulatedText);
		if (currentObjectJson !== void 0 && currentObjectJson !== null && typeof currentObjectJson === "object" && !Array.isArray(currentObjectJson) && "result" in currentObjectJson && typeof currentObjectJson.result === "string" && !isDeepEqualData(previousObject, currentObjectJson)) {
			const partialResult = currentObjectJson.result;
			const bestMatch = this.findBestEnumMatch(partialResult);
			if (partialResult.length > 0 && bestMatch && bestMatch !== this.textPreviousEnumResult) {
				this.textPreviousEnumResult = bestMatch;
				return {
					shouldEmit: true,
					emitValue: bestMatch,
					newPreviousResult: currentObjectJson
				};
			}
		}
		return { shouldEmit: false };
	}
	async validateAndTransformFinal(rawFinalValue) {
		const processedValue = this.preprocessText(rawFinalValue);
		const { value } = await parsePartialJson(processedValue);
		if (!(typeof value === "object" && value !== null && "result" in value)) return {
			success: false,
			error: /* @__PURE__ */ new Error("Invalid enum format: expected object with result property")
		};
		const finalValue = value;
		if (!finalValue || typeof finalValue !== "object" || typeof finalValue.result !== "string") return {
			success: false,
			error: /* @__PURE__ */ new Error("Invalid enum format: expected object with result property")
		};
		return this.validateValue(finalValue.result);
	}
};
/**
* Factory function to create the appropriate output format handler based on schema.
* Analyzes the transformed schema format and returns the corresponding handler instance.
* @param schema - Original user-provided schema (e.g., Zod schema from agent.stream({output: z.object({})}))
* @param transformedSchema - Wrapped/transformed schema used for LLM generation (arrays wrapped in {elements: []}, enums in {result: ""})
* @returns Handler instance for the detected format type
*/
function createOutputHandler({ schema }) {
	const normalizedSchema = schema ? toStandardSchema(schema) : void 0;
	switch (getTransformedSchema(normalizedSchema)?.outputFormat) {
		case "array": return new ArrayFormatHandler(normalizedSchema);
		case "enum": return new EnumFormatHandler(normalizedSchema);
		default: return new ObjectFormatHandler(normalizedSchema);
	}
}
/**
* Errors this transformer emits itself (validation, truncation, malformed enum), as opposed to
* errors the provider streamed. They are enqueued before the model's `finish` chunk.
*/
const structuredOutputErrors = /* @__PURE__ */ new WeakSet();
function isStructuredOutputError(error) {
	return typeof error === "object" && error !== null && structuredOutputErrors.has(error);
}
/**
* Transforms raw text-delta chunks into structured object chunks for JSON mode streaming.
*
* For JSON response formats, this transformer:
* - Accumulates text deltas and parses them as partial JSON
* - Emits 'object' chunks when the parsed structure changes
* - For arrays: filters incomplete elements and unwraps from {elements: [...]} wrapper
* - For objects: emits the parsed object directly
* - For enums: unwraps from {result: ""} wrapper and provides partial matching
* - Always passes through original chunks for downstream processing
*/
function createObjectStreamTransformer({ structuredOutput, logger }) {
	const handler = createOutputHandler({ schema: structuredOutput?.schema });
	let accumulatedText = "";
	let previousObject = void 0;
	let currentRunId;
	let finalResult;
	let finishReason;
	let hasPendingToolCalls = false;
	return new TransformStream$1({
		async transform(chunk, controller) {
			if (chunk.runId) currentRunId = chunk.runId;
			if (chunk.type === "step-start") {
				accumulatedText = "";
				previousObject = void 0;
				finalResult = void 0;
				finishReason = void 0;
				hasPendingToolCalls = false;
			}
			if (chunk.type === "tool-call" && !chunk.payload?.providerExecuted) hasPendingToolCalls = true;
			if (chunk.type === "text-delta" && typeof chunk.payload?.text === "string") {
				accumulatedText += chunk.payload.text;
				const result = await handler.processPartialChunk({
					accumulatedText,
					previousObject
				});
				if (result.shouldEmit) {
					previousObject = result.newPreviousResult ?? previousObject;
					const chunkData = {
						from: chunk.from,
						runId: chunk.runId,
						type: "object",
						object: result.emitValue
					};
					controller.enqueue(chunkData);
				}
			}
			if (chunk.type === "finish") {
				finishReason = chunk.payload.stepResult.reason;
				await finalize(controller);
			}
			controller.enqueue(chunk);
		},
		async flush(controller) {
			await finalize(controller);
		}
	});
	async function finalize(controller) {
		if (!accumulatedText?.trim() || finalResult || finishReason === "error") return;
		if (hasPendingToolCalls && finishReason !== "length" && finishReason !== "content-filter") return;
		if (finishReason === "length" || finishReason === "content-filter") finalResult = {
			success: false,
			error: new MastraError({
				domain: ErrorDomain.AGENT,
				category: ErrorCategory.SYSTEM,
				id: "STRUCTURED_OUTPUT_TRUNCATED",
				text: `Structured output was truncated because the model finished with reason "${finishReason}".`,
				details: {
					finishReason,
					value: accumulatedText
				}
			})
		};
		else finalResult = await handler.validateAndTransformFinal(accumulatedText);
		if (finalResult.success) controller.enqueue({
			from: "AGENT",
			runId: currentRunId ?? "",
			type: "object-result",
			object: finalResult.value
		});
		else handleValidationError(finalResult.error, controller);
	}
	/**
	* Handle validation errors based on error strategy
	*/
	function handleValidationError(error, controller) {
		if (structuredOutput?.errorStrategy === "warn") logger?.warn(error.message);
		else if (structuredOutput?.errorStrategy === "fallback") controller.enqueue({
			from: "AGENT",
			runId: currentRunId ?? "",
			type: "object-result",
			object: structuredOutput.fallbackValue,
			metadata: { fallback: true }
		});
		else {
			structuredOutputErrors.add(error);
			controller.enqueue({
				from: "AGENT",
				runId: currentRunId ?? "",
				type: "error",
				payload: { error }
			});
		}
	}
}
/**
* Transforms object chunks into JSON text chunks for streaming.
*
* This transformer:
* - For arrays: emits opening bracket, new elements, and closing bracket
* - For objects/no-schema: emits the object as JSON
*/
function createJsonTextStreamTransformer(schema) {
	let emittedCount = 0;
	let latestArray = [];
	let hasStartedArray = false;
	const emitElements = (controller, array, end) => {
		for (; emittedCount < end; emittedCount++) {
			const elementJson = JSON.stringify(array[emittedCount]);
			controller.enqueue(emittedCount > 0 ? "," + elementJson : elementJson);
		}
	};
	let pendingFirstArrayChunk;
	const outputSchema = getTransformedSchema(schema);
	return new TransformStream$1({
		transform(chunk, controller) {
			if (chunk.type !== "object" || !chunk.object) return;
			if (outputSchema?.outputFormat === "array" && Array.isArray(chunk.object)) {
				if (pendingFirstArrayChunk !== void 0) {
					controller.enqueue("[");
					hasStartedArray = true;
					pendingFirstArrayChunk = void 0;
				} else if (!hasStartedArray) {
					pendingFirstArrayChunk = chunk.object;
					return;
				}
				latestArray = chunk.object;
				emitElements(controller, chunk.object, chunk.object.length - 1);
			} else controller.enqueue(JSON.stringify(chunk.object));
		},
		flush(controller) {
			if (outputSchema?.outputFormat !== "array") return;
			if (pendingFirstArrayChunk !== void 0) {
				const firstChunk = pendingFirstArrayChunk;
				pendingFirstArrayChunk = void 0;
				controller.enqueue(firstChunk.length > 0 ? JSON.stringify(firstChunk) : "[]");
			} else if (hasStartedArray) {
				emitElements(controller, latestArray, latestArray.length);
				controller.enqueue("]");
			}
		}
	});
}
// src/stream/base/output-processed.ts
/**
* Chunks that already ran through the run's output processors before they
* reached this stream (durable tool chunks, processed in the tool-call step
* before publishing). MastraModelOutput passes them through without running
* the processors again.
*/
const outputProcessedChunks = /* @__PURE__ */ new WeakSet();
function markChunkOutputProcessed(chunk) {
	if (chunk && typeof chunk === "object") outputProcessedChunks.add(chunk);
}
function isChunkOutputProcessed(chunk) {
	return !!chunk && typeof chunk === "object" && outputProcessedChunks.has(chunk);
}
// src/stream/base/produced-at.ts
/**
* Epoch ms at which a model output produced each chunk. Recorded when the
* chunk is emitted, before any consumer can queue it, so thread history can
* compare it with storage stamps regardless of how long publishing took.
*/
const chunkProducedAt = /* @__PURE__ */ new WeakMap();
function stampChunkProducedAt(chunk, at) {
	if (chunk && typeof chunk === "object") chunkProducedAt.set(chunk, at);
}
function getChunkProducedAt(chunk) {
	return chunk && typeof chunk === "object" ? chunkProducedAt.get(chunk) : void 0;
}
// src/stream/base/step-message-mirrors.ts
const RESPONSE_MESSAGE_IDS = "__responseMessageIds";
function isRecord(value) {
	return !!value && typeof value === "object" && !Array.isArray(value);
}
function withoutMessageMirrors(response) {
	const rest = {};
	for (const key of Object.keys(response)) {
		if (key === "dbMessages" || key === "uiMessages" || key === "messages" || key === RESPONSE_MESSAGE_IDS) continue;
		rest[key] = response[key];
	}
	return rest;
}
function packStepMessageMirrors(steps) {
	if (!Array.isArray(steps)) return steps;
	return steps.map((step) => {
		if (!isRecord(step) || !isRecord(step.response) || !Array.isArray(step.response.dbMessages)) return step;
		const dbMessages = step.response.dbMessages;
		return {
			...step,
			response: {
				...withoutMessageMirrors(step.response),
				[RESPONSE_MESSAGE_IDS]: dbMessages.map((message) => message.id)
			}
		};
	});
}
function unpackStepMessageMirrors(steps, messageList) {
	if (!Array.isArray(steps)) return steps;
	if (!steps.some((step) => isRecord(step) && isRecord(step.response) && RESPONSE_MESSAGE_IDS in step.response)) return steps;
	let messagesById;
	return steps.map((step) => {
		if (!isRecord(step) || !isRecord(step.response) || !(RESPONSE_MESSAGE_IDS in step.response)) return step;
		const messageIds = step.response[RESPONSE_MESSAGE_IDS];
		const response = withoutMessageMirrors(step.response);
		let dbMessages;
		let uiMessages;
		let messages;
		const getDbMessages = () => {
			if (!dbMessages) {
				messagesById ??= new Map(messageList.get.all.db().map((message) => [message.id, message]));
				dbMessages = messageIds.flatMap((id) => {
					const message = messagesById.get(id);
					return message ? [message] : [];
				});
			}
			return dbMessages;
		};
		Object.defineProperties(response, {
			dbMessages: {
				enumerable: true,
				get: getDbMessages
			},
			uiMessages: {
				enumerable: true,
				get() {
					return uiMessages ??= convertMessages(getDbMessages()).to("AIV5.UI");
				}
			},
			messages: {
				enumerable: true,
				get() {
					return messages ??= convertMessages(getDbMessages()).to("AIV5.Model");
				}
			}
		});
		return {
			...step,
			response
		};
	});
}
// src/stream/base/step-request-dedupe.ts
/**
* Every buffered step of a run carries the request that produced it, and that
* request's `body` holds the tool schemas plus the system instruction — data
* that is invariant across the steps of a single run and, in practice,
* byte-identical. Persisting a full copy per step made a suspended snapshot
* grow linearly with step count, and a HITL agent that takes a dozen tool calls
* before its first approval could push a single document past MongoDB's hard
* 16 MB limit, failing the write and stranding the run.
*
* So the snapshot stores each distinct request once and has the steps point at
* it. This is purely a storage representation: callers still see a `request` on
* every step after rehydration.
*/
const REQUEST_REF = "__requestRef";
/**
* Whether a value's JSON text identifies it uniquely.
*
* Two steps are treated as sharing a request when their JSON text matches, so
* the text has to be injective over the values we compare. It is not, for the
* types JSON has no representation of: `Map`, `Set`, `Error` and class
* instances all render as `{}`, and a key whose value is `undefined` or a
* function disappears entirely — so two genuinely different requests would
* collide and one step would resume against the other's request.
*
* `Date` is allowed: it renders lossily, but distinct instants still render
* distinctly, so it cannot collide. Anything else falls back to storing the
* request inline, which is what every snapshot did before this change.
*/
function hasInjectiveJson(value, seen = /* @__PURE__ */ new Set()) {
	if (value === null) return true;
	const type = typeof value;
	if (type === "string" || type === "boolean") return true;
	if (type === "number") return Number.isFinite(value);
	if (type !== "object") return false;
	const object = value;
	if (seen.has(object)) return false;
	seen.add(object);
	try {
		if (object instanceof Date) return true;
		if (Array.isArray(object)) return object.every((element, index) => index in object && hasInjectiveJson(element, seen));
		const prototype = Object.getPrototypeOf(object);
		if (prototype !== Object.prototype && prototype !== null) return false;
		if ("toJSON" in object) return false;
		return Reflect.ownKeys(object).every((key) => {
			if (typeof key === "symbol") return false;
			return hasInjectiveJson(object[key], seen);
		});
	} finally {
		seen.delete(object);
	}
}
function dedupeStepRequests(steps) {
	if (!Array.isArray(steps) || steps.length < 2) return {
		steps,
		requests: void 0
	};
	const requests = [];
	const indexByKey = /* @__PURE__ */ new Map();
	let sharedAny = false;
	const rewritten = steps.map((step) => {
		if (!step || typeof step !== "object" || step.request === void 0) return step;
		if (!hasInjectiveJson(step.request)) return step;
		let key;
		try {
			key = JSON.stringify(step.request) ?? "undefined";
		} catch {
			return step;
		}
		let index = indexByKey.get(key);
		if (index === void 0) {
			index = requests.length;
			indexByKey.set(key, index);
			requests.push(step.request);
		} else sharedAny = true;
		const { request: _dropped, ...rest } = step;
		return {
			...rest,
			[REQUEST_REF]: index
		};
	});
	if (!sharedAny) return {
		steps,
		requests: void 0
	};
	return {
		steps: rewritten,
		requests
	};
}
function rehydrateStepRequests(steps, requests) {
	if (!Array.isArray(steps) || !Array.isArray(requests)) return steps;
	return steps.map((step) => {
		if (!step || typeof step !== "object" || !(REQUEST_REF in step)) return step;
		const { [REQUEST_REF]: index, ...rest } = step;
		return {
			...rest,
			request: requests[index]
		};
	});
}
// src/stream/base/output.ts
const STRUCTURED_OUTPUT_PROCESSOR_NAME = "structured-output";
const primaryUsageCountKeys = [
	"inputTokens",
	"outputTokens",
	"totalTokens"
];
const detailUsageCountKeys = [
	"reasoningTokens",
	"cachedInputTokens",
	"cacheCreationInputTokens",
	"cacheCreationInputTokens5m",
	"cacheCreationInputTokens1h"
];
[...primaryUsageCountKeys, ...detailUsageCountKeys];
function hasTokenCounts(usage) {
	return primaryUsageCountKeys.some((key) => usage?.[key] !== void 0);
}
function accumulateUsage(target, missing, usage) {
	for (const key of primaryUsageCountKeys) {
		const value = usage[key];
		if (value === void 0) {
			missing.add(key);
			target[key] = void 0;
		} else if (!missing.has(key)) target[key] = (target[key] ?? 0) + value;
	}
	for (const key of detailUsageCountKeys) {
		const value = usage[key];
		if (value !== void 0) target[key] = (target[key] ?? 0) + value;
	}
	if (usage.raw !== void 0) target.raw = usage.raw;
}
/**
* Helper function to create a destructurable version of MastraModelOutput.
* This wraps the output to ensure properties maintain their context when destructured.
*/
function createDestructurableOutput(output) {
	return new Proxy(output, { get(target, prop, _receiver) {
		const originalValue = Reflect.get(target, prop, target);
		if (typeof originalValue === "function") return originalValue.bind(target);
		return originalValue;
	} });
}
/**
* Persist a non-transient `data-*` chunk emitted by an output processor's
* `writer.custom()` onto the assistant message, so the chunk survives in
* thread history instead of being stream-only (#19375). Transient chunks
* and non-data chunks are left untouched.
*
* Exported for the durable engine, whose producer-side processor writers
* persist into the workflow-side MessageList (the one serialized into
* `messageListState` and flushed to memory at finalize).
*/
function persistProcessorDataChunk(messageList, messageId, chunk) {
	if (!isDataChunk(chunk) || chunk.transient) return;
	const message = {
		id: messageId,
		role: "assistant",
		content: {
			format: 2,
			parts: [{
				type: chunk.type,
				data: chunk.data,
				...chunk.id !== void 0 ? { id: chunk.id } : {}
			}]
		},
		createdAt: /* @__PURE__ */ new Date()
	};
	messageList.add(message, "response");
}
/**
* Resolve the output text from the latest response message, skipping internal
* completion-check feedback so it can't become the final text.
* The completionResult metadata only exists on DB-format messages, and the
* message is converted alone so adjacent assistant messages aren't merged.
*
* Converting to model messages splits an assistant message at every tool
* result, so when the current loop iteration called a tool the last converted
* message holds only the text after the call, or nothing if the step ended on
* it. In that case the text is read from the DB message's parts after the
* iteration's boundary instead. The last `step-start` is not that boundary:
* one is also inserted inside a single response whenever text follows a tool call.
*
* Returns `undefined` only when there is no response message to read text from,
* so callers can distinguish "no processed output exists" from an output
* processor deliberately clearing the text to `''`. Never collapse the two with
* a truthiness check: a redacting processor must be able to produce empty text.
*/
function resolveOutputMessageSkippingCompletionChecks(messageList) {
	const responseDbMessages = messageList.get.response.db();
	return responseDbMessages.some((m) => m.content?.metadata?.completionResult) ? responseDbMessages.findLast((m) => !m.content?.metadata?.completionResult) : responseDbMessages[responseDbMessages.length - 1];
}
/**
* A failed completion check moves the answer to a new message, but this output keeps the id it
* was built with. Resolve at write time so processor data lands on the answer that is returned.
*/
function resolveProcessorWriterMessageId(messageList, fallbackMessageId, explicitMessageId) {
	if (explicitMessageId) return explicitMessageId;
	if (!messageList.get.response.db().some((m) => m.content?.metadata?.completionResult)) return fallbackMessageId;
	return resolveOutputMessageSkippingCompletionChecks(messageList)?.id ?? fallbackMessageId;
}
function resolveOutputTextSkippingCompletionChecks(messageList) {
	const lastRealMessage = resolveOutputMessageSkippingCompletionChecks(messageList);
	if (!lastRealMessage) return void 0;
	if (lastRealMessage.role === "assistant" && lastRealMessage.content?.parts) {
		const stepParts = messageList.partsSinceStepBoundary(lastRealMessage);
		if (stepParts.some((p) => p.type === "tool-invocation")) return stepParts.map((p) => p.type === "text" ? p.text : "").join("");
	}
	const converted = messageList.get.response.db().some((m) => m.content?.metadata?.completionResult) ? convertMessages([lastRealMessage]).to("AIV4.Core") : messageList.get.response.aiV4.core();
	const lastConverted = converted[converted.length - 1];
	return lastConverted ? coreContentToString(lastConverted.content) : void 0;
}
/**
* Step text for the current iteration of the message that supplies the resolved output text.
*
* The iteration boundary is a property of a message's own part array, so the offset measured before
* processing must not be transplanted onto a message a processor produced. Resolve the boundary in
* this order:
*   1. the message's own `step-start` marker, when it has one;
*   2. for the same message, the pre-processing step text where it survives (an unchanged in-place
*      rewrite, or a split of the current iteration's text), the pre-processing offset while the
*      parts before it are unchanged, then the offset while the part count and part kinds are
*      unchanged (redaction or other rewrites that keep positions), then the unchanged prefix;
*   3. for a different message, the trailing text matching the pre-processing step text, which finds
*      the boundary when a processor replaced the id of the accumulated response;
*   4. otherwise the whole message, which then holds only this iteration.
*
* The rules below are heuristics over the processed parts, so a processor can defeat them. When it
* rewrites the current iteration's text (so the pre-processing step text no longer appears) *and*
* moves the boundary while keeping the part count and kinds (for example by merging an earlier
* iteration's parts and splitting the current one), the measured offset still matches by count and
* kind and the step text is taken from the wrong position. That information is gone from the parts —
* only a processor that preserves the boundary (a `step-start` part, or positions it does not move)
* can be resolved exactly.
*/
function resolveProcessedStepText({ processedStepMessage, processedStepParts, originalMessageId, originalIterationPartOffset, originalPartCount, originalParts, originalStepText, outputText }) {
	if (!processedStepMessage || !processedStepParts) return outputText ?? "";
	const textWithin = (parts) => parts.map((part) => part.type === "text" ? part.text : "").join("");
	const boundaryIndex = processedStepParts.findLastIndex((part) => part.type === "step-start");
	if (boundaryIndex !== -1) return textWithin(processedStepParts.slice(boundaryIndex + 1));
	if (processedStepMessage.id === originalMessageId && originalParts) {
		const sliceFrom = (index) => textWithin(processedStepParts.slice(index));
		const offset = originalIterationPartOffset;
		const textOffset = findIterationOffsetInParts(processedStepParts, originalStepText);
		if (textOffset !== void 0) return sliceFrom(textOffset);
		if (offset !== void 0 && offset > 0 && processedStepParts.length >= offset && originalParts.slice(0, offset).every((part, index) => partMatches(part, processedStepParts[index]))) return sliceFrom(offset);
		if (offset !== void 0 && originalPartCount !== void 0 && processedStepParts.length === originalPartCount && originalParts.slice(0, offset).every((part, index) => part?.type === processedStepParts[index]?.type)) return sliceFrom(offset);
		let common = 0;
		while (common < originalParts.length && common < processedStepParts.length && partMatches(originalParts[common], processedStepParts[common])) common++;
		if (common > 0) return sliceFrom(common);
		return textWithin(processedStepParts);
	}
	const offset = findIterationOffsetInParts(processedStepParts, originalStepText);
	return offset !== void 0 ? textWithin(processedStepParts.slice(offset)) : textWithin(processedStepParts);
}
function partMatches(a, b) {
	if (!a || !b || a.type !== b.type) return false;
	if (a.type === "text") return a.text === b.text;
	if (a.type === "reasoning") return a.reasoning === b.reasoning;
	if (a.type === "tool-invocation") return a.toolInvocation?.toolCallId === b.toolInvocation?.toolCallId;
	if (a.type === "step-start") return Number(a.createdAt) === Number(b.createdAt);
	return true;
}
function findIterationOffsetInParts(parts, stepText) {
	if (!stepText) return void 0;
	let suffixText = "";
	for (let index = parts.length - 1; index >= 0; index--) {
		const part = parts[index];
		if (part?.type === "text") suffixText = part.text + suffixText;
		if (suffixText === stepText) return index;
		if (!stepText.endsWith(suffixText)) return void 0;
	}
}
function findIterationPartOffset(messageList, message, stepText) {
	const parts = message.content?.parts;
	if (!parts) return void 0;
	const stepParts = messageList.partsSinceStepBoundary(message);
	if (stepParts.length < parts.length) return parts.length - stepParts.length;
	if (!stepText) return void 0;
	let suffixText = "";
	for (let index = parts.length - 1; index >= 0; index--) {
		const part = parts[index];
		if (part?.type === "text") suffixText = part.text + suffixText;
		if (suffixText === stepText) return index;
		if (!stepText.endsWith(suffixText)) return void 0;
	}
}
function resolveMessageText(message) {
	const converted = convertMessages([message]).to("AIV4.Core");
	const convertedMessage = converted[converted.length - 1];
	return convertedMessage ? coreContentToString(convertedMessage.content) : "";
}
const stepPartIndex = Symbol("stepPartIndex");
function findStepPartBoundaries(message, steps) {
	const parts = message?.content.parts;
	if (!parts) return void 0;
	const offsets = Array(steps.length + 1);
	offsets[steps.length] = parts.length;
	let partIndex = parts.length;
	for (let stepIndex = steps.length - 1; stepIndex >= 0; stepIndex--) {
		const stepText = steps[stepIndex].text;
		let text = "";
		while (partIndex > 0 && text !== stepText) {
			const part = parts[--partIndex];
			if (part.type === "text") text = `${part.text}${text}`;
		}
		if (text !== stepText) return void 0;
		offsets[stepIndex] = partIndex;
	}
	for (const [stepIndex] of steps.entries()) for (const part of parts.slice(offsets[stepIndex], offsets[stepIndex + 1])) if (part.type === "text") part[stepPartIndex] = stepIndex;
	return { offsets };
}
function clearStepPartIndexes(messages) {
	for (const message of messages) for (const part of message.content.parts) delete part[stepPartIndex];
}
function reconcileBufferedStepTexts(steps, processedText, processedMessage, stepPartBoundaries, originalText) {
	if (processedText === originalText) return;
	const processedParts = processedMessage?.content.parts;
	let processedOffsets;
	if (processedParts && stepPartBoundaries) {
		const processedStepTexts = steps.map(() => "");
		let lastStepIndex = 0;
		let hasUnknownPart = false;
		for (const part of processedParts) {
			if (part.type !== "text") continue;
			const stepIndex = part[stepPartIndex];
			if (stepIndex === void 0 || stepIndex < lastStepIndex) {
				hasUnknownPart = true;
				break;
			}
			processedStepTexts[stepIndex] += part.text;
			lastStepIndex = stepIndex;
		}
		if (!hasUnknownPart) {
			for (const [index, step] of steps.entries()) step.text = processedStepTexts[index];
			return;
		}
		if (stepPartBoundaries.offsets.at(-1) === processedParts.length) processedOffsets = stepPartBoundaries.offsets;
	}
	if (processedParts && processedOffsets) {
		for (const [index, step] of steps.entries()) step.text = processedParts.slice(processedOffsets[index], processedOffsets[index + 1]).map((part) => part.type === "text" ? part.text : "").join("");
		return;
	}
	let offset = 0;
	let index = 0;
	while (index < steps.length && processedText.startsWith(steps[index].text, offset)) {
		offset += steps[index].text.length;
		index++;
	}
	if (index === steps.length) return;
	steps[index].text = processedText.slice(offset);
	for (const step of steps.slice(index + 1)) step.text = "";
}
var MastraModelOutput = class extends MastraBase {
	#status = "running";
	#error;
	#baseStream;
	#bufferedChunks = [];
	/**
	* Set when a continuing goal evaluation arrives while a step is still in
	* flight (in-process engines emit the goal chunk before the judged turn's
	* step-finish): the next step-finish belongs to the judged turn and its
	* buffers are dropped once its stepResult and usage are recorded.
	*/
	#truncateAtNextStepFinish = false;
	#streamFinished = false;
	#finishCallbackSent = false;
	#emitter = new EventEmitter();
	#bufferedSteps = [];
	#bufferedReasoningDetails = {};
	/**
	* Per-step counterpart of `#bufferedReasoningDetails`. Reset on `step-finish`
	* alongside `#bufferedByStep` so a step result reports only its own reasoning.
	*/
	#bufferedByStepReasoningDetails = {};
	#bufferedByStep = {
		text: "",
		reasoning: [],
		sources: [],
		files: [],
		toolCalls: [],
		toolResults: [],
		dynamicToolCalls: [],
		dynamicToolResults: [],
		staticToolCalls: [],
		staticToolResults: [],
		content: [],
		usage: {
			inputTokens: void 0,
			outputTokens: void 0,
			totalTokens: void 0
		},
		warnings: [],
		request: {},
		response: {
			id: "",
			timestamp: /* @__PURE__ */ new Date(),
			modelId: "",
			messages: [],
			uiMessages: []
		},
		reasoningText: "",
		providerMetadata: void 0,
		finishReason: void 0
	};
	#bufferedText = [];
	/** Length of `#bufferedText` when the current step began; rejected or retried steps are cut back to it. */
	#bufferedTextAtStepStart = 0;
	#bufferedObject;
	#usedFallbackValue = false;
	#bufferedTextChunks = {};
	#bufferedSources = [];
	#bufferedReasoning = [];
	/** Run-level reasoning as of the last `step-start` that has no `step-finish` yet. */
	#reasoningAtStepStart;
	#bufferedFiles = [];
	/** Run-level sources, files and tool calls as of the last `step-start` that has no `step-finish` yet. */
	#runOutputAtStepStart;
	#toolCallArgsDeltas = Object.create(null);
	#toolCallDeltaIdNameMap = Object.create(null);
	#toolCallStreamingMeta = Object.create(null);
	/** Recorded calls whose input streams again in a retry; the retry's tool-call replaces them. */
	#replaceableToolCallIds = /* @__PURE__ */ new Set();
	/** Calls recorded since the last accepted step; only these can be replaced by a retry. */
	#attemptToolCallIds = /* @__PURE__ */ new Set();
	/**
	* Tool calls whose input stream ended without any deltas. Their args only arrive with the
	* final `tool-call` chunk, so they wait here instead of being emitted as a synthetic `{}` call.
	*/
	#pendingToolCalls = Object.create(null);
	#toolCalls = [];
	#toolResults = [];
	#warnings = [];
	#finishReason = void 0;
	/**
	* Provider-specific metadata captured from the most recent step `finish`
	* chunk (e.g. AWS Bedrock guardrail trace under
	* `providerMetadata.bedrock.trace`). Exposed via {@link _getImmediateProviderMetadata}
	* so output-step processors can attribute content-filter blocks, for which
	* the completed-steps array is empty.
	*/
	#stepProviderMetadata = void 0;
	#request = {};
	#usageCount = {
		inputTokens: void 0,
		outputTokens: void 0,
		totalTokens: void 0
	};
	#usageCountMissing = /* @__PURE__ */ new Set();
	/**
	* Usage of the most recently completed step. Kept apart from `#bufferedSteps`
	* because goal truncation clears that buffer while usage keeps accumulating.
	*/
	#lastStepUsage = void 0;
	/**
	* Usage of the step that suspended on a tool call. That step never emits `step-finish`, so
	* its usage arrives on the suspension chunk and is reported without entering `#usageCount`:
	* the serialized `usageCount` excludes it, and the resumed run accumulates it when it replays
	* the step's `step-finish`, keeping resumed totals cumulative for the whole run. It is
	* serialized so a resumed tool that suspends again still reports it, and cleared on step-finish.
	*/
	#suspendedStepUsage = void 0;
	#suspendedUsageIsProvisional = false;
	/**
	* Cumulative usage the MODEL_GENERATION spans of earlier suspended legs of this run already
	* recorded. Resumed legs report cumulative totals, so their generation span subtracts this to
	* keep token metrics counted once. Serialized with the run state.
	*/
	#generationReportedUsage = void 0;
	/**
	* How many `#bufferedSteps` entries the MODEL_GENERATION spans of earlier suspended legs
	* already reported provider cost for. It counts the suspended step, which a resumed leg
	* replays into `#bufferedSteps`. Serialized with the run state.
	*/
	#generationReportedStepCount = 0;
	#finishUsageIsTotal = false;
	#tripwire = void 0;
	#wasSuspended = false;
	#resumedPriorText = "";
	#transportRef;
	#transportClosed = false;
	#delayedPromises = {
		suspendPayload: new DelayedPromise(),
		resumeSchema: new DelayedPromise(),
		object: new DelayedPromise(),
		finishReason: new DelayedPromise(),
		usage: new DelayedPromise(),
		warnings: new DelayedPromise(),
		providerMetadata: new DelayedPromise(),
		response: new DelayedPromise(),
		request: new DelayedPromise(),
		text: new DelayedPromise(),
		reasoning: new DelayedPromise(),
		reasoningText: new DelayedPromise(),
		sources: new DelayedPromise(),
		files: new DelayedPromise(),
		toolCalls: new DelayedPromise(),
		toolResults: new DelayedPromise(),
		steps: new DelayedPromise(),
		totalUsage: new DelayedPromise(),
		content: new DelayedPromise()
	};
	#consumptionStarted = false;
	#consumeStreamPromise;
	#consumeStreamErrored = false;
	#consumeStreamError;
	#returnScorerData = false;
	#structuredOutputMode = void 0;
	#model;
	/**
	* Unique identifier for this execution run.
	*/
	runId;
	#options;
	/**
	* The processor runner for this stream.
	*/
	processorRunner;
	/**
	* The message list for this stream.
	*/
	messageList;
	/**
	* Trace ID for this execution.
	*/
	traceId;
	/**
	* Root span ID for this execution, identifying the top-level span in the trace.
	*/
	spanId;
	messageId;
	constructor({ model: _model, stream, messageList, options, messageId, initialState, initialToolCalls, resumedText, finishUsageIsTotal, onFinishComplete, getTerminalRequest, onTracingTripwire }) {
		super({
			component: "LLM",
			name: "MastraModelOutput"
		});
		if (options.logger) this.__setLogger(options.logger);
		this.#options = options;
		this.#finishUsageIsTotal = finishUsageIsTotal ?? false;
		this.#transportRef = options.transportRef;
		this.#returnScorerData = !!options.returnScorerData;
		this.runId = options.runId;
		const resultSpan = getRootExportSpan(options.tracingContext?.currentSpan);
		this.traceId = resultSpan?.externalTraceId;
		this.spanId = resultSpan?.id;
		this.#model = _model;
		this.messageId = messageId;
		if (options.structuredOutput?.schema) this.#structuredOutputMode = options.structuredOutput.model ? "processor" : "direct";
		if (options.outputProcessors?.length) this.processorRunner = new ProcessorRunner({
			inputProcessors: [],
			outputProcessors: options.outputProcessors,
			logger: this.logger,
			agentName: "MastraModelOutput",
			agent: options.agent,
			processorStates: options.processorStates
		});
		this.messageList = messageList;
		const self = this;
		let processedStream = stream;
		const processorRunner = this.processorRunner;
		if (processorRunner && options.isLLMExecutionStep) {
			const processorStates = options.processorStates || /* @__PURE__ */ new Map();
			let observabilityContext;
			const getObservabilityContext = () => observabilityContext ??= resolveObservabilityContext(options);
			let streamFailed = false;
			processedStream = stream.pipeThrough(new TransformStream$1({
				async transform(chunk, controller) {
					if (isFailedStreamChunk(chunk)) streamFailed = true;
					const isDeferredErrorChunk = options.deferErrorChunks && (chunk.type === "error" || chunk.type === "finish" && chunk.payload?.stepResult?.reason === "error");
					if (chunk.type === "finish" && chunk.payload?.stepResult?.reason === "tool-calls" || isDeferredErrorChunk || isChunkOutputProcessed(chunk)) controller.enqueue(chunk);
					else {
						/**
						* Add/update base stream controller to structured output processor state
						* so it can be used to enqueue chunks into the main stream from the structuring agent stream.
						* Need to update controller on each new LLM execution step since each step has its own TransformStream.
						*/
						if (!processorStates.has(STRUCTURED_OUTPUT_PROCESSOR_NAME)) {
							const processorIndex = processorRunner.outputProcessors.findIndex((p) => p.id === STRUCTURED_OUTPUT_PROCESSOR_NAME);
							if (processorIndex !== -1) {
								const structuredOutputProcessor = processorRunner.outputProcessors[processorIndex];
								const structuredOutputProcessorState = new ProcessorState({
									processorName: structuredOutputProcessor?.name ?? STRUCTURED_OUTPUT_PROCESSOR_NAME,
									tracingContext: options.tracingContext,
									processorIndex,
									createSpan: true,
									processor: structuredOutputProcessor
								});
								structuredOutputProcessorState.customState = { controller };
								processorStates.set(STRUCTURED_OUTPUT_PROCESSOR_NAME, structuredOutputProcessorState);
							}
						} else {
							const structuredOutputProcessorState = processorStates.get(STRUCTURED_OUTPUT_PROCESSOR_NAME);
							if (structuredOutputProcessorState) structuredOutputProcessorState.customState.controller = controller;
						}
						const streamWriter = { custom: async (data, writerOptions) => {
							persistProcessorDataChunk(self.messageList, resolveProcessorWriterMessageId(self.messageList, self.messageId, writerOptions?.messageId), data);
							controller.enqueue(data);
						} };
						const { part: processed, blocked, reason, tripwireOptions, processorId } = await processorRunner.processPart(chunk, processorStates, getObservabilityContext(), options.requestContext, self.messageList, 0, streamWriter, options.abortSignal);
						const enqueueTripwire = (r, opts, pid) => {
							controller.enqueue({
								type: "tripwire",
								payload: {
									reason: r || "Output processor blocked content",
									retry: opts?.retry,
									metadata: opts?.metadata,
									processorId: pid
								}
							});
						};
						if (blocked) {
							enqueueTripwire(reason, tripwireOptions, processorId);
							return;
						}
						if (processed) controller.enqueue(processed);
						const reprocessed = await processorRunner.drainReprocessParts(processorStates, getObservabilityContext(), options.requestContext, self.messageList, 0, streamWriter, options.abortSignal);
						for (const r of reprocessed) {
							if (r.blocked) {
								enqueueTripwire(r.reason, r.tripwireOptions, r.processorId);
								return;
							}
							if (r.part != null) controller.enqueue(r.part);
						}
					}
				},
				async flush(controller) {
					if (streamFailed || options.abortSignal?.aborted) {
						for (const part of await processorRunner.discardHeldParts(processorStates)) controller.enqueue(part);
						processorRunner.endStreamProcessorSpans(processorStates, { keepStepScopedSpans: true });
						return;
					}
					const released = await processorRunner.flushHeldParts(processorStates, getObservabilityContext(), options.requestContext, self.messageList, 0, { custom: async (data, writerOptions) => {
						persistProcessorDataChunk(self.messageList, resolveProcessorWriterMessageId(self.messageList, self.messageId, writerOptions?.messageId), data);
						controller.enqueue(data);
					} }, options.abortSignal);
					for (const r of released) {
						if (r.blocked) {
							controller.enqueue({
								type: "tripwire",
								payload: {
									reason: r.reason || "Output processor blocked content",
									retry: r.tripwireOptions?.retry,
									metadata: r.tripwireOptions?.metadata,
									processorId: r.processorId
								}
							});
							break;
						}
						if (r.part != null) controller.enqueue(r.part);
					}
					processorRunner.endStreamProcessorSpans(processorStates, { keepStepScopedSpans: true });
				},
				async cancel() {
					await processorRunner.discardHeldParts(processorStates);
					processorRunner.endStreamProcessorSpans(processorStates);
				}
			}));
		}
		if (self.#structuredOutputMode === "direct" && self.#options.isLLMExecutionStep) processedStream = processedStream.pipeThrough(createObjectStreamTransformer({
			structuredOutput: self.#options.structuredOutput,
			logger: self.logger
		}));
		const emitSyntheticToolCall = (controller, toolCallId, meta, args, runId, from) => {
			const synthetic = {
				type: "tool-call",
				runId,
				from,
				payload: {
					toolCallId,
					toolName: meta.toolName,
					args,
					providerExecuted: meta.providerExecuted,
					providerMetadata: meta.providerMetadata,
					dynamic: meta.dynamic,
					...meta.title ? { title: meta.title } : {},
					...meta.observability ? { observability: meta.observability } : {}
				}
			};
			self.#toolCalls.push(synthetic);
			self.#bufferedByStep.toolCalls.push(synthetic);
			self.#attemptToolCallIds.add(synthetic.payload.toolCallId);
			self.#emitChunk(synthetic);
			controller.enqueue(synthetic);
		};
		const flushPendingToolCall = (controller, toolCallId) => {
			const pending = self.#pendingToolCalls[toolCallId];
			if (!pending) return;
			delete self.#pendingToolCalls[toolCallId];
			emitSyntheticToolCall(controller, toolCallId, pending.meta, pending.args, pending.runId, pending.from);
		};
		const flushPendingToolCalls = (controller, { onlyStreamed = false } = {}) => {
			for (const [toolCallId, pending] of Object.entries(self.#pendingToolCalls)) if (!onlyStreamed || pending.streamed) flushPendingToolCall(controller, toolCallId);
		};
		let structuredOutputErrored = false;
		this.#baseStream = processedStream.pipeThrough(new TransformStream$1({
			transform: async (chunk, controller) => {
				if (chunk.type === "error") {
					if (isStructuredOutputError(chunk.payload.error)) {
						structuredOutputErrored = true;
						self.#pendingToolCalls = Object.create(null);
					} else flushPendingToolCalls(controller, { onlyStreamed: true });
				}
				if (chunk.type === "tool-result" || chunk.type === "tool-error") flushPendingToolCall(controller, chunk.payload.toolCallId);
				switch (chunk.type) {
					case "tool-call-suspended":
					case "tool-call-approval":
						self.#status = "suspended";
						self.#wasSuspended = true;
						self.#suspendedStepUsage ??= chunk.payload.usage;
						self.#delayedPromises.suspendPayload.resolve(chunk.payload);
						self.#delayedPromises.resumeSchema.resolve(chunk.payload.resumeSchema);
						if (!self.#finishCallbackSent) {
							self.#finishCallbackSent = true;
							await options?.onFinish?.(self.#createSuspendedOnFinishPayload(chunk));
						}
						self.#settleSuspendedUsage();
						break;
					case "abort":
						self.#status = "canceled";
						if (!self.#finishCallbackSent) {
							self.#finishCallbackSent = true;
							await options?.onFinish?.(self.#createAbortedOnFinishPayload());
						}
						self.#closeTransportIfNeeded();
						break;
					case "step-start":
						self.#bufferedByStep.reasoning = [];
						self.#bufferedByStepReasoningDetails = {};
						if (self.#bufferedByStep.text) {
							self.#bufferedByStep.text = "";
							self.#bufferedText.length = Math.min(self.#bufferedText.length, self.#bufferedTextAtStepStart);
						}
						if (self.#runOutputAtStepStart) {
							self.#bufferedSources.length = self.#runOutputAtStepStart.sources;
							self.#bufferedFiles.length = self.#runOutputAtStepStart.files;
							for (const call of self.#toolCalls.slice(self.#runOutputAtStepStart.toolCalls)) self.#replaceableToolCallIds.add(call.payload.toolCallId);
						}
						self.#runOutputAtStepStart = {
							sources: self.#bufferedSources.length,
							files: self.#bufferedFiles.length,
							toolCalls: self.#toolCalls.length
						};
						Object.assign(self.#bufferedByStep, {
							sources: [],
							files: [],
							toolCalls: [],
							toolResults: []
						});
						if (self.#reasoningAtStepStart) {
							self.#bufferedReasoning.length = self.#reasoningAtStepStart.length;
							self.#bufferedReasoningDetails = self.#reasoningAtStepStart.details;
						}
						self.#reasoningAtStepStart = {
							length: self.#bufferedReasoning.length,
							details: { ...self.#bufferedReasoningDetails }
						};
						break;
					case "raw":
						if (!self.#options.includeRawChunks) return;
						break;
					case "object-result":
						self.#bufferedObject = chunk.object;
						self.#usedFallbackValue = chunk.metadata?.fallback === true;
						if (!self.processorRunner && self.#delayedPromises.object.status.type === "pending") self.#delayedPromises.object.resolve(chunk.object);
						break;
					case "source":
						self.#bufferedSources.push(chunk);
						self.#bufferedByStep.sources.push(chunk);
						break;
					case "text-delta":
						self.#bufferedText.push(chunk.payload.text);
						self.#bufferedByStep.text += chunk.payload.text;
						if (chunk.payload.id) {
							const ary = self.#bufferedTextChunks[chunk.payload.id] ?? [];
							ary.push(chunk.payload.text);
							self.#bufferedTextChunks[chunk.payload.id] = ary;
						}
						break;
					case "tool-call-input-streaming-start":
						if (self.#attemptToolCallIds.has(chunk.payload.toolCallId)) self.#replaceableToolCallIds.add(chunk.payload.toolCallId);
						self.#toolCallDeltaIdNameMap[chunk.payload.toolCallId] = chunk.payload.toolName;
						self.#toolCallStreamingMeta[chunk.payload.toolCallId] = {
							toolName: chunk.payload.toolName,
							providerExecuted: chunk.payload.providerExecuted,
							providerMetadata: chunk.payload.providerMetadata,
							dynamic: chunk.payload.dynamic,
							...chunk.payload.title ? { title: chunk.payload.title } : {},
							...chunk.payload.observability ? { observability: chunk.payload.observability } : {}
						};
						break;
					case "tool-call-input-streaming-end": {
						const toolCallId = chunk.payload.toolCallId;
						const meta = self.#toolCallStreamingMeta[toolCallId];
						const deltaParts = self.#toolCallArgsDeltas[toolCallId];
						let args = {};
						if (deltaParts?.length) try {
							const merged = deltaParts.join("");
							args = typeof merged === "string" && merged.length > 0 ? JSON.parse(merged) : {};
						} catch {
							args = {};
						}
						delete self.#toolCallStreamingMeta[toolCallId];
						delete self.#toolCallArgsDeltas[toolCallId];
						delete self.#toolCallDeltaIdNameMap[toolCallId];
						if (meta) self.#pendingToolCalls[toolCallId] = {
							meta,
							args,
							streamed: Boolean(deltaParts?.length),
							runId: chunk.runId,
							from: chunk.from
						};
						break;
					}
					case "tool-call-delta":
						if (!self.#toolCallArgsDeltas[chunk.payload.toolCallId]) self.#toolCallArgsDeltas[chunk.payload.toolCallId] = [];
						self.#toolCallArgsDeltas?.[chunk.payload.toolCallId]?.push(chunk.payload.argsTextDelta);
						chunk.payload.toolName ||= self.#toolCallDeltaIdNameMap[chunk.payload.toolCallId];
						break;
					case "file":
						self.#bufferedFiles.push(chunk);
						self.#bufferedByStep.files.push(chunk);
						break;
					case "reasoning-start": {
						const makeReasoningDetail = () => ({
							type: "reasoning",
							runId: chunk.runId,
							from: chunk.from,
							payload: {
								id: chunk.payload.id,
								providerMetadata: chunk.payload.providerMetadata,
								text: ""
							}
						});
						self.#bufferedReasoningDetails[chunk.payload.id] = makeReasoningDetail();
						self.#bufferedByStepReasoningDetails[chunk.payload.id] = makeReasoningDetail();
						break;
					}
					case "reasoning-delta":
						self.#bufferedReasoning.push({
							type: "reasoning",
							runId: chunk.runId,
							from: chunk.from,
							payload: chunk.payload
						});
						self.#bufferedByStep.reasoning.push({
							type: "reasoning",
							runId: chunk.runId,
							from: chunk.from,
							payload: chunk.payload
						});
						for (const bufferedReasoning of [self.#bufferedReasoningDetails[chunk.payload.id], self.#bufferedByStepReasoningDetails[chunk.payload.id]]) {
							if (!bufferedReasoning) continue;
							bufferedReasoning.payload.text += chunk.payload.text;
							if (chunk.payload.providerMetadata) bufferedReasoning.payload.providerMetadata = chunk.payload.providerMetadata;
						}
						break;
					case "reasoning-end":
						if (chunk.payload.providerMetadata) for (const bufferedReasoning of [self.#bufferedReasoningDetails[chunk.payload.id], self.#bufferedByStepReasoningDetails[chunk.payload.id]]) {
							if (!bufferedReasoning) continue;
							bufferedReasoning.payload.providerMetadata = chunk.payload.providerMetadata;
						}
						break;
					case "tool-call": {
						const pending = self.#pendingToolCalls[chunk.payload.toolCallId];
						if (pending) {
							delete self.#pendingToolCalls[chunk.payload.toolCallId];
							const { meta } = pending;
							chunk.payload.providerExecuted ??= meta.providerExecuted;
							chunk.payload.providerMetadata ??= meta.providerMetadata;
							chunk.payload.dynamic ??= meta.dynamic;
							if (meta.title && !chunk.payload.title) chunk.payload.title = meta.title;
							if (meta.observability && !chunk.payload.observability) chunk.payload.observability = meta.observability;
						}
						if (self.#replaceableToolCallIds.delete(chunk.payload.toolCallId)) {
							self.#attemptToolCallIds.delete(chunk.payload.toolCallId);
							for (const calls of [self.#toolCalls, self.#bufferedByStep.toolCalls]) {
								const index = calls.findLastIndex((tc) => tc.payload.toolCallId === chunk.payload.toolCallId);
								if (index === -1) continue;
								calls.splice(index, 1);
								if (calls === self.#toolCalls && self.#runOutputAtStepStart && index < self.#runOutputAtStepStart.toolCalls) self.#runOutputAtStepStart.toolCalls--;
							}
						}
						if (self.#attemptToolCallIds.has(chunk.payload.toolCallId)) return;
						self.#toolCalls.push(chunk);
						self.#bufferedByStep.toolCalls.push(chunk);
						self.#attemptToolCallIds.add(chunk.payload.toolCallId);
						const toolCallPayload = chunk.payload;
						if (toolCallPayload?.output?.from === "AGENT" && toolCallPayload?.output?.type === "finish") {
							const finishPayload = toolCallPayload.output.payload;
							if (finishPayload?.usage) self.updateUsageCount(finishPayload.usage);
						}
						break;
					}
					case "tool-result":
						if (chunk.payload.preliminary) break;
						self.#toolResults.push(chunk);
						self.#bufferedByStep.toolResults.push(chunk);
						break;
					case "step-finish": {
						const stepReason = chunk.payload.stepResult.reason;
						const attemptFailed = stepReason === "retry" || stepReason === "error";
						flushPendingToolCalls(controller, { onlyStreamed: attemptFailed });
						if (!attemptFailed) {
							self.#attemptToolCallIds.clear();
							self.#replaceableToolCallIds.clear();
						}
						self.updateUsageCount(chunk.payload.output.usage);
						self.#suspendedStepUsage = void 0;
						self.#warnings = chunk.payload.stepResult.warnings || [];
						if (chunk.payload.metadata.request) self.#request = chunk.payload.metadata.request;
						const { providerMetadata, request, ...otherMetadata } = chunk.payload.metadata;
						const payloadSteps = chunk.payload.output?.steps || [];
						const stepTripwire = payloadSteps[payloadSteps.length - 1]?.tripwire;
						const isRetriedStep = chunk.payload.stepResult.reason === "retry";
						if (stepTripwire || isRetriedStep) self.#bufferedText.length = Math.min(self.#bufferedText.length, self.#bufferedTextAtStepStart);
						const stepText = stepTripwire || isRetriedStep ? "" : self.#bufferedByStep.text;
						const stepResult = {
							stepType: self.#bufferedSteps.length === 0 ? "initial" : "tool-result",
							sources: self.#bufferedByStep.sources,
							files: self.#bufferedByStep.files,
							toolCalls: self.#bufferedByStep.toolCalls,
							toolResults: self.#bufferedByStep.toolResults,
							content: isRetriedStep ? [] : chunk.payload?._durableStepContent ?? messageList.get.response.aiV5.modelContent(-1, self.#bufferedByStep.toolCalls.map((call) => call.payload.toolCallId)),
							text: stepText,
							tripwire: stepTripwire,
							reasoningText: self.#bufferedByStep.reasoning.map((reasoningPart) => reasoningPart.payload.text).join(""),
							reasoning: Object.values(self.#bufferedByStepReasoningDetails),
							get staticToolCalls() {
								return self.#bufferedByStep.toolCalls.filter((part) => part.type === "tool-call" && part.payload?.dynamic === false);
							},
							get dynamicToolCalls() {
								return self.#bufferedByStep.toolCalls.filter((part) => part.type === "tool-call" && part.payload?.dynamic === true);
							},
							get staticToolResults() {
								return self.#bufferedByStep.toolResults.filter((part) => part.type === "tool-result" && part.payload?.dynamic === false);
							},
							get dynamicToolResults() {
								return self.#bufferedByStep.toolResults.filter((part) => part.type === "tool-result" && part.payload?.dynamic === true);
							},
							finishReason: chunk.payload.stepResult.reason,
							usage: chunk.payload.output.usage,
							warnings: self.#warnings,
							request: request || {},
							response: {
								id: chunk.payload.id || "",
								timestamp: chunk.payload.metadata?.timestamp || /* @__PURE__ */ new Date(),
								...otherMetadata,
								modelId: chunk.payload.metadata?.modelId || chunk.payload.metadata?.model || "",
								messages: chunk.payload?._durableResponseMessages ?? chunk.payload.messages?.nonUser ?? [],
								dbMessages: self.messageList.get.response.db(),
								uiMessages: messageList.get.response.aiV5.ui()
							},
							providerMetadata: providerMetadata ?? chunk.payload.providerMetadata
						};
						await options?.onStepFinish?.({
							...self.#model.modelId && self.#model.provider && self.#model.version ? { model: self.#model } : {},
							...stepResult
						});
						self.#bufferedSteps.push(stepResult);
						self.#lastStepUsage = stepResult.usage;
						if (stepTripwire?.retry) {
							self.#bufferedObject = void 0;
							self.#usedFallbackValue = false;
						} else if (self.#bufferedObject !== void 0 && self.#delayedPromises.object.status.type === "pending") self.#delayedPromises.object.resolve(self.#bufferedObject);
						self.#bufferedByStep = {
							text: "",
							reasoning: [],
							sources: [],
							files: [],
							toolCalls: [],
							toolResults: [],
							dynamicToolCalls: [],
							dynamicToolResults: [],
							staticToolCalls: [],
							staticToolResults: [],
							content: [],
							usage: {
								inputTokens: void 0,
								outputTokens: void 0,
								totalTokens: void 0
							},
							warnings: [],
							request: {},
							response: {
								id: "",
								timestamp: /* @__PURE__ */ new Date(),
								modelId: "",
								messages: [],
								uiMessages: []
							},
							reasoningText: "",
							providerMetadata: void 0,
							finishReason: void 0
						};
						self.#bufferedByStepReasoningDetails = {};
						self.#reasoningAtStepStart = void 0;
						self.#runOutputAtStepStart = void 0;
						self.#bufferedTextAtStepStart = self.#bufferedText.length;
						if (self.#truncateAtNextStepFinish) {
							self.#truncateAtNextStepFinish = false;
							self.#truncateRunBuffers();
						}
						break;
					}
					case "tripwire":
						self.#tripwire = {
							reason: chunk.payload?.reason || "Content blocked",
							retry: chunk.payload?.retry,
							metadata: chunk.payload?.metadata,
							processorId: chunk.payload?.processorId
						};
						try {
							onTracingTripwire?.(self.#tripwire, self.#usageCount, self.#bufferedText.join(""));
						} catch (error) {
							self.logger?.warn("Error recording tripwire tracing", error);
						}
						self.#finishReason = "other";
						if (self.#status !== "failed" && self.#status !== "canceled") self.#status = "tripwire";
						self.#streamFinished = true;
						self.resolvePromises({
							text: self.#bufferedText.join(""),
							finishReason: "other",
							object: void 0,
							usage: self.#usageCount,
							warnings: self.#warnings,
							providerMetadata: void 0,
							response: {
								...self.#options.resolveFinalPromises && {
									messages: self.messageList.get.response.aiV5.model(),
									uiMessages: self.messageList.get.response.aiV5.ui()
								},
								dbMessages: self.messageList.get.response.db()
							},
							request: {},
							reasoning: [],
							reasoningText: void 0,
							sources: [],
							files: [],
							toolCalls: [],
							toolResults: [],
							steps: self.#bufferedSteps,
							totalUsage: self.#usageCount,
							content: [],
							suspendPayload: void 0,
							resumeSchema: void 0
						});
						self.#closeTransportIfNeeded();
						self.#emitChunk(chunk);
						controller.enqueue(chunk);
						if (!self.#finishCallbackSent) {
							self.#finishCallbackSent = true;
							await options?.onFinish?.(self.#createTripwireOnFinishPayload());
						}
						self.#emitter.emit("finish");
						controller.terminate();
						return;
					case "finish":
						if (chunk.payload.stepResult.reason === "tripwire" || structuredOutputErrored) self.#pendingToolCalls = Object.create(null);
						else flushPendingToolCalls(controller);
						if (self.#status !== "failed" && self.#status !== "canceled") self.#status = "success";
						if (self.#status === "canceled") self.#finishReason = "aborted";
						else if (chunk.payload.stepResult.reason) self.#finishReason = chunk.payload.stepResult.reason;
						const finalProviderMetadata = chunk.payload.metadata?.providerMetadata ?? chunk.payload.providerMetadata;
						if (finalProviderMetadata) self.#stepProviderMetadata = finalProviderMetadata;
						if (chunk.payload.stepResult.reason === "tripwire") {
							const outputSteps = chunk.payload.output?.steps;
							const stepTripwire = (outputSteps?.[outputSteps?.length - 1])?.tripwire;
							if (self.#status !== "canceled" || stepTripwire) self.#tripwire = {
								reason: stepTripwire?.reason || "Processor tripwire triggered",
								retry: stepTripwire?.retry,
								metadata: stepTripwire?.metadata,
								processorId: stepTripwire?.processorId
							};
						}
						if (self.#bufferedObject !== void 0) {
							const lastAssistantMessage = [...messageList.get.response.db()].reverse().find((m) => m.role === "assistant");
							if (lastAssistantMessage) {
								if (!lastAssistantMessage.content.metadata) lastAssistantMessage.content.metadata = {};
								lastAssistantMessage.content.metadata.structuredOutput = self.#bufferedObject;
							}
						}
						let response = {};
						if (chunk.payload.metadata) {
							const { providerMetadata, request, ...otherMetadata } = chunk.payload.metadata;
							response = {
								...otherMetadata,
								messages: messageList.get.response.aiV5.model(),
								uiMessages: messageList.get.response.aiV5.ui()
							};
						} else if (self.#bufferedSteps.length > 0) response = { ...self.#bufferedSteps[self.#bufferedSteps.length - 1].response };
						if (self.#finishUsageIsTotal) {
							self.#usageCount.inputTokens = void 0;
							self.#usageCount.outputTokens = void 0;
							self.#usageCount.totalTokens = void 0;
							delete self.#usageCount.reasoningTokens;
							delete self.#usageCount.cachedInputTokens;
							delete self.#usageCount.cacheCreationInputTokens;
							delete self.#usageCount.cacheCreationInputTokens5m;
							delete self.#usageCount.cacheCreationInputTokens1h;
							self.#usageCountMissing.clear();
						}
						this.populateUsageCount(chunk.payload.output.usage);
						chunk.payload.output.usage = {
							inputTokens: self.#usageCount.inputTokens,
							outputTokens: self.#usageCount.outputTokens,
							totalTokens: self.#getTotalUsage().totalTokens,
							...self.#usageCount.reasoningTokens !== void 0 && { reasoningTokens: self.#usageCount.reasoningTokens },
							...self.#usageCount.cachedInputTokens !== void 0 && { cachedInputTokens: self.#usageCount.cachedInputTokens },
							...self.#usageCount.cacheCreationInputTokens !== void 0 && { cacheCreationInputTokens: self.#usageCount.cacheCreationInputTokens },
							...self.#usageCount.cacheCreationInputTokens5m !== void 0 && { cacheCreationInputTokens5m: self.#usageCount.cacheCreationInputTokens5m },
							...self.#usageCount.cacheCreationInputTokens1h !== void 0 && { cacheCreationInputTokens1h: self.#usageCount.cacheCreationInputTokens1h },
							...self.#usageCount.raw !== void 0 && { raw: self.#usageCount.raw }
						};
						const outputResultWriter = { custom: async (data, writerOptions) => {
							persistProcessorDataChunk(self.messageList, resolveProcessorWriterMessageId(self.messageList, self.messageId, writerOptions?.messageId), data);
							self.#emitChunk(data);
							controller.enqueue(data);
						} };
						let outputResultTripwire;
						let outputResultError;
						try {
							if (self.processorRunner && !self.#options.isLLMExecutionStep) {
								const lastStep = self.#bufferedSteps[self.#bufferedSteps.length - 1];
								const lastStepText = lastStep?.text || "";
								const outputResult = {
									text: self.#bufferedText.join(""),
									usage: chunk.payload.output.usage,
									finishReason: self.#status === "failed" ? "error" : self.#finishReason || "unknown",
									steps: [...self.#bufferedSteps]
								};
								if (self.#status === "canceled" && self.#bufferedByStep.text.trim().length > 0) self.messageList.add({
									role: "assistant",
									content: [{
										type: "text",
										text: self.#bufferedByStep.text
									}]
								}, "response", { merge: false });
								const outputTextBeforeProcessing = resolveOutputTextSkippingCompletionChecks(self.messageList);
								const stepMessage = resolveOutputMessageSkippingCompletionChecks(self.messageList);
								const iterationPartOffset = stepMessage ? findIterationPartOffset(self.messageList, stepMessage, lastStepText) : void 0;
								const separatedIteration = stepMessage && iterationPartOffset !== void 0 ? self.messageList.splitResponseMessageAtPartOffset(stepMessage.id, iterationPartOffset) : void 0;
								const earlierStepMessage = separatedIteration ? self.messageList.get.response.db().find((message) => message.id === separatedIteration.earlierMessageId) : void 0;
								const earlierStepPartBoundaries = separatedIteration ? findStepPartBoundaries(earlierStepMessage, self.#bufferedSteps.slice(0, -1)) : void 0;
								const earlierTextBeforeProcessing = earlierStepMessage ? resolveMessageText(earlierStepMessage) : void 0;
								const processorStepMessageId = separatedIteration?.currentMessageId ?? stepMessage?.id;
								const processorStepMessage = processorStepMessageId ? self.messageList.get.response.db().find((message) => message.id === processorStepMessageId) : void 0;
								const processorStepMessageParts = processorStepMessage?.content?.parts;
								const originalProcessorStepMessageParts = processorStepMessageParts ? [...processorStepMessageParts] : void 0;
								let outputText;
								let stepText;
								let processedEarlierText;
								let processedEarlierMessage;
								try {
									self.messageList = await self.processorRunner.runOutputProcessors(self.messageList, resolveObservabilityContext(options), self.#options.requestContext, 0, outputResultWriter, outputResult);
									const responseMessages = self.messageList.get.response.db();
									const resolvedProcessedStepMessage = resolveOutputMessageSkippingCompletionChecks(self.messageList);
									const idMatchedProcessedStepMessage = processorStepMessageId ? responseMessages.find((message) => message.id === processorStepMessageId) : void 0;
									const processedStepMessage = resolvedProcessedStepMessage?.id === separatedIteration?.earlierMessageId ? idMatchedProcessedStepMessage : resolvedProcessedStepMessage ?? idMatchedProcessedStepMessage;
									processedEarlierMessage = separatedIteration ? responseMessages.find((message) => message.id === separatedIteration.earlierMessageId) : void 0;
									processedEarlierText = separatedIteration ? processedEarlierMessage ? resolveMessageText(processedEarlierMessage) : "" : void 0;
									const processedOutputText = resolveOutputTextSkippingCompletionChecks(self.messageList);
									const processedStepParts = processedStepMessage?.content?.parts;
									stepText = separatedIteration || processedOutputText !== outputTextBeforeProcessing ? resolveProcessedStepText({
										processedStepMessage,
										processedStepParts,
										originalMessageId: processorStepMessage?.id,
										originalIterationPartOffset: separatedIteration ? 0 : iterationPartOffset,
										originalPartCount: processorStepMessageParts?.length,
										originalParts: originalProcessorStepMessageParts,
										originalStepText: lastStepText,
										outputText: processedOutputText
									}) : void 0;
									const stepMessageWasReplaced = separatedIteration && processedStepMessage && processedStepMessage.id !== processorStepMessage?.id;
									if (stepMessageWasReplaced && resolveMessageText(processedStepMessage) === processedEarlierText) stepText = "";
									outputText = separatedIteration ? stepMessageWasReplaced ? processedOutputText : `${processedEarlierText}${stepText ?? ""}` : processedOutputText;
									if (processedEarlierText !== void 0) reconcileBufferedStepTexts(self.#bufferedSteps.slice(0, -1), processedEarlierText, processedEarlierMessage, earlierStepPartBoundaries, earlierTextBeforeProcessing);
								} finally {
									clearStepPartIndexes(self.messageList.get.response.db());
									if (separatedIteration) self.messageList.coalesceSplitResponseMessages(separatedIteration.earlierMessageId, separatedIteration.currentMessageId);
								}
								if (self.#status !== "canceled" && lastStep && stepText !== void 0 && stepText !== lastStepText) lastStep.text = stepText;
								this.resolvePromises({
									text: outputText ?? (stepMessage ? "" : lastStepText),
									finishReason: self.#finishReason
								});
								if (chunk.payload.metadata) {
									const { providerMetadata, request, ...otherMetadata } = chunk.payload.metadata;
									response = {
										...otherMetadata,
										messages: self.messageList.get.response.aiV5.model(),
										uiMessages: self.messageList.get.response.aiV5.ui()
									};
								}
								chunk.payload.response = response;
							} else if (!self.#options.isLLMExecutionStep || self.#options.resolveFinalPromises) {
								let rewrittenText;
								if (chunk.payload.textRewritten === true && self.#status !== "canceled") {
									const finalizedText = chunk.payload.output?.steps?.at(-1)?.text;
									const lastStep = self.#bufferedSteps.at(-1);
									if (lastStep && typeof finalizedText === "string") {
										lastStep.text = finalizedText;
										rewrittenText = finalizedText;
									}
								}
								this.resolvePromises({
									text: rewrittenText ?? self.#producedText(),
									finishReason: self.#finishReason
								});
							}
						} catch (error) {
							if (error instanceof TripWire) {
								self.#tripwire = {
									reason: error.message,
									retry: error.options?.retry,
									metadata: error.options?.metadata,
									processorId: error.processorId
								};
								outputResultTripwire = self.#tripwire;
								self.resolvePromises({
									finishReason: "other",
									text: self.#producedText()
								});
							} else {
								self.#error = getErrorFromUnknown(error, { fallbackMessage: "Unknown error in stream" });
								outputResultError = self.#error;
								self.resolvePromises({
									finishReason: "error",
									text: ""
								});
							}
							if (self.#delayedPromises.object.status.type !== "resolved") self.#delayedPromises.object.resolve(self.#bufferedObject);
						}
						const reasoningText = self.#bufferedReasoning.length > 0 ? self.#bufferedReasoning.map((reasoningPart) => reasoningPart.payload.text).join("") : void 0;
						const baseFinishStep = self.#bufferedSteps[self.#bufferedSteps.length - 1];
						if (baseFinishStep && baseFinishStep.providerMetadata === void 0 && finalProviderMetadata !== void 0) baseFinishStep.providerMetadata = finalProviderMetadata;
						self.#request = getTerminalRequest?.() ?? self.#request;
						this.resolvePromises({
							usage: self.#usageCount,
							warnings: self.#warnings,
							providerMetadata: finalProviderMetadata,
							response: {
								...response,
								dbMessages: self.messageList.get.response.db()
							},
							request: self.#request || {},
							reasoningText,
							reasoning: Object.values(self.#bufferedReasoningDetails || {}),
							sources: self.#bufferedSources,
							files: self.#bufferedFiles,
							toolCalls: self.#toolCalls,
							toolResults: self.#toolResults,
							steps: self.#bufferedSteps,
							totalUsage: self.#getTotalUsage(),
							content: messageList.get.response.aiV5.stepContent(),
							suspendPayload: void 0,
							resumeSchema: void 0
						});
						if (baseFinishStep) {
							const onFinishPayload = {
								providerMetadata: baseFinishStep.providerMetadata ?? finalProviderMetadata,
								text: self.#bufferedText.join(""),
								warnings: baseFinishStep.warnings ?? [],
								finishReason: outputResultError || self.#status === "failed" ? "error" : chunk.payload.stepResult.reason,
								content: messageList.get.response.aiV5.stepContent(),
								request: self.#request || {},
								error: self.error,
								reasoning: Object.values(self.#bufferedReasoningDetails || {}),
								reasoningText,
								sources: self.#bufferedSources,
								files: self.#bufferedFiles,
								steps: self.#bufferedSteps,
								response: {
									...response,
									...baseFinishStep.response,
									messages: messageList.get.response.aiV5.model(),
									dbMessages: self.messageList.get.response.db()
								},
								usage: chunk.payload.output.usage,
								totalUsage: self.#getTotalUsage(),
								...self.#generationReportedUsage && { generationReportedUsage: self.#generationReportedUsage },
								...self.#generationReportedStepCount > 0 && { generationStepProviderMetadata: self.#bufferedSteps.slice(self.#generationReportedStepCount).map((step) => step.providerMetadata) },
								toolCalls: self.#toolCalls,
								toolResults: self.#toolResults,
								staticToolCalls: self.#toolCalls.filter((toolCall) => toolCall?.payload?.dynamic === false),
								staticToolResults: self.#toolResults.filter((toolResult) => toolResult?.payload?.dynamic === false),
								dynamicToolCalls: self.#toolCalls.filter((toolCall) => toolCall?.payload?.dynamic === true),
								dynamicToolResults: self.#toolResults.filter((toolResult) => toolResult?.payload?.dynamic === true),
								...self.#model.modelId && self.#model.provider && self.#model.version ? { model: self.#model } : {},
								usedFallbackValue: self.#usedFallbackValue,
								object: self.#delayedPromises.object.status.type === "rejected" ? void 0 : self.#delayedPromises.object.status.type === "resolved" ? self.#delayedPromises.object.status.value : self.#bufferedObject !== void 0 ? self.#bufferedObject : self.#structuredOutputMode === "direct" && baseFinishStep.text ? (() => {
									try {
										return JSON.parse(baseFinishStep.text);
									} catch {
										return;
									}
								})() : void 0
							};
							if (!self.#finishCallbackSent) {
								self.#finishCallbackSent = true;
								await options?.onFinish?.(onFinishPayload, {
									writer: outputResultWriter,
									...outputResultTripwire && { outputResultTripwire }
								});
							}
						}
						if (outputResultError) throw outputResultError;
						await onFinishComplete?.();
						self.#closeTransportIfNeeded();
						if (outputResultTripwire) {
							if (self.#status !== "failed" && self.#status !== "canceled") self.#status = "tripwire";
							const tripwireChunk = {
								type: "tripwire",
								runId: chunk.runId,
								from: chunk.from,
								payload: { ...outputResultTripwire }
							};
							self.#emitChunk(tripwireChunk);
							controller.enqueue(tripwireChunk);
							return;
						}
						break;
					case "goal":
						if (chunk.payload.shouldContinue === true) {
							self.#truncateRunBuffers();
							const byStep = self.#bufferedByStep;
							if (byStep.text.length > 0 || byStep.toolCalls.length > 0 || byStep.reasoning.length > 0 || byStep.sources.length > 0 || byStep.files.length > 0) self.#truncateAtNextStepFinish = true;
						}
						break;
					case "error":
						const error = getErrorFromUnknown(chunk.payload.error, { fallbackMessage: "Unknown error chunk in stream" });
						self.#error = error;
						self.#status = "failed";
						const beforeDeadlineSave = self.#options.beforeDeadlineSave;
						if (isMastraTimeoutError(error) && error.timeoutType === "total" && self.processorRunner && !self.#options.isLLMExecutionStep && beforeDeadlineSave) {
							let streamOpen = true;
							const { turn, inFlightMessageId } = self.messageList.cloneWithCompletedSteps(self.#bufferedByStep.text);
							const cutOffStep = self.#bufferedByStep;
							await settledOrElapsed((async () => {
								try {
									if (await beforeDeadlineSave() === false) return;
								} catch (authError) {
									self.logger?.warn("Memory write denied at the total deadline, the turn is not saved", { error: authError });
									return;
								}
								let heldDataChunks;
								const writer = { custom: async (data, writerOptions) => {
									if (heldDataChunks && (!writerOptions?.messageId || writerOptions.messageId === inFlightMessageId)) heldDataChunks.push({
										data,
										messageId: writerOptions?.messageId
									});
									else persistProcessorDataChunk(turn, resolveProcessorWriterMessageId(turn, self.messageId, writerOptions?.messageId), data);
									if (!streamOpen) return;
									self.#emitChunk(data);
									controller.enqueue(data);
								} };
								let cutOffTextDropped = false;
								if (inFlightMessageId) {
									heldDataChunks = [];
									try {
										const stepList = turn.clone();
										stepList.removeByIds(stepList.get.all.db().map((message) => message.id).filter((id) => id !== inFlightMessageId));
										await self.processorRunner.runProcessOutputStep({
											steps: [...self.#bufferedSteps],
											messages: stepList.get.all.db(),
											messageList: stepList,
											stepNumber: self.#bufferedSteps.length,
											finishReason: "error",
											toolCalls: cutOffStep.toolCalls.length ? cutOffStep.toolCalls.map(({ payload }) => ({
												toolName: payload.toolName,
												toolCallId: payload.toolCallId,
												args: payload.args
											})) : void 0,
											text: cutOffStep.text,
											usage: self.#usageCount,
											...resolveObservabilityContext(options),
											requestContext: self.#options.requestContext,
											writer
										});
										turn.removeByIds([inFlightMessageId]);
										for (const message of stepList.get.all.db()) turn.add(message, "response", { merge: false });
									} catch (stepError) {
										turn.removeByIds([inFlightMessageId]);
										cutOffTextDropped = true;
										self.logger?.warn("Output step processors failed on the text cut off at the total deadline", { error: stepError });
									}
									for (const { data, messageId } of heldDataChunks) {
										const target = messageId && turn.get.all.db().some((message) => message.id === messageId) ? messageId : resolveProcessorWriterMessageId(turn, self.messageId);
										persistProcessorDataChunk(turn, target, data);
									}
									heldDataChunks = void 0;
								}
								try {
									await self.processorRunner.runOutputProcessors(turn, resolveObservabilityContext(options), self.#options.requestContext, 0, writer, {
										text: cutOffTextDropped ? self.#bufferedSteps.map((step) => step.text).join("") : self.#bufferedText.join(""),
										usage: self.#usageCount,
										finishReason: "error",
										steps: [...self.#bufferedSteps]
									});
								} catch (processorError) {
									if (processorError instanceof TripWire) await self.#options.onDeadlineTripwire?.(turn);
									throw processorError;
								}
							})().catch((processorError) => {
								self.logger?.error("Output processors failed at the total deadline", { error: processorError });
							}), DEADLINE_SAVE_WAIT_MS);
							streamOpen = false;
						}
						self.#streamFinished = true;
						Object.values(self.#delayedPromises).forEach((promise) => {
							if (promise.status.type === "pending") promise.reject(self.#error);
						});
						self.#closeTransportIfNeeded();
						self.#emitChunk(chunk);
						controller.enqueue(chunk);
						self.#emitter.emit("settled");
						return;
				}
				self.#emitChunk(chunk);
				controller.enqueue(chunk);
			},
			flush: () => {
				if (self.#delayedPromises.object.status.type === "pending") self.#delayedPromises.object.resolve(self.#bufferedObject);
				if (self.#status === "suspended") self.#resolveSuspendedPromises();
				Object.entries(self.#delayedPromises).forEach(([key, promise]) => {
					if (promise.status.type === "pending") promise.reject(/* @__PURE__ */ new Error(`promise '${key}' was not resolved or rejected when stream finished`));
				});
				self.#closeTransportIfNeeded();
				self.#streamFinished = true;
				self.#emitter.emit("finish");
			}
		}));
		if (initialState) this.deserializeState(initialState);
		else {
			if (initialToolCalls) this.#toolCalls = initialToolCalls;
			if (resumedText) {
				const { priorText, stepText } = resumedText;
				this.#resumedPriorText = priorText;
				this.#bufferedText = [priorText, stepText].filter(Boolean);
				this.#bufferedTextAtStepStart = priorText ? 1 : 0;
				this.#bufferedByStep.text = stepText;
				this.#wasSuspended = true;
			}
		}
	}
	resolvePromise(key, value) {
		if (this.#suspendedUsageIsProvisional && (key === "usage" || key === "totalUsage" || key === "finishReason")) this.#suspendedUsageIsProvisional = false;
		if (!(key in this.#delayedPromises)) throw new MastraError({
			id: "MASTRA_MODEL_OUTPUT_INVALID_PROMISE_KEY",
			domain: ErrorDomain.LLM,
			category: ErrorCategory.SYSTEM,
			text: `Attempted to resolve invalid promise key '${key}' with value '${typeof value === "object" ? JSON.stringify(value, null, 2) : value}'`
		});
		this.#delayedPromises[key].resolve(value);
	}
	resolvePromises(data) {
		for (const keyString in data) {
			const key = keyString;
			this.resolvePromise(key, data[key]);
		}
	}
	#settleSuspendedUsage() {
		const usage = this.#getUsageCountWithSuspendedStep();
		this.#delayedPromises.usage.resolve(usage);
		this.#delayedPromises.totalUsage.resolve(this.#getTotalUsage(usage));
		this.#delayedPromises.finishReason.resolve("suspended");
		this.#suspendedUsageIsProvisional = true;
	}
	#closeTransportIfNeeded() {
		const transport = this.#transportRef?.current;
		if (!transport || !transport.closeOnFinish || this.#transportClosed) return;
		this.#transportClosed = true;
		try {
			transport.close();
		} catch {}
	}
	#getDelayedPromise(promise) {
		if (!this.#consumptionStarted) this.consumeStream().catch((error) => {
			this.logger?.error("Error consuming stream", error);
		});
		return promise.promise;
	}
	/**
	* Resolves to the complete text response after streaming completes.
	*/
	get text() {
		return this.#getDelayedPromise(this.#delayedPromises.text);
	}
	/**
	* Resolves to reasoning parts array for models that support reasoning.
	*/
	get reasoning() {
		return this.#getDelayedPromise(this.#delayedPromises.reasoning);
	}
	/**
	* Resolves to complete reasoning text for models that support reasoning.
	*/
	get reasoningText() {
		return this.#getDelayedPromise(this.#delayedPromises.reasoningText);
	}
	get sources() {
		return this.#getDelayedPromise(this.#delayedPromises.sources);
	}
	get files() {
		return this.#getDelayedPromise(this.#delayedPromises.files);
	}
	get steps() {
		return this.#getDelayedPromise(this.#delayedPromises.steps);
	}
	get suspendPayload() {
		return this.#getDelayedPromise(this.#delayedPromises.suspendPayload);
	}
	get resumeSchema() {
		return this.#getDelayedPromise(this.#delayedPromises.resumeSchema);
	}
	/**
	* Stream of all chunks. Provides complete control over stream processing.
	*/
	get fullStream() {
		const stream = this.__getUnfilteredFullStream();
		const hideSignals = this.#options.hideSignals;
		if (!hideSignals || Array.isArray(hideSignals) && hideSignals.length === 0) return stream;
		return stream.pipeThrough(new TransformStream$1({ transform(chunk, controller) {
			if (!isSignalChunkExcluded(chunk, hideSignals)) controller.enqueue(chunk);
		} }));
	}
	/** @internal Shared fanout must retain signal chunks, with the existing transforms applied. */
	__getUnfilteredFullStream() {
		const configuredTransforms = this.#options.experimentalTransform;
		if (!configuredTransforms) return this.#createEventedStream();
		const transforms = typeof configuredTransforms === "function" ? [configuredTransforms] : configuredTransforms;
		let stream = this.#createEventedStream();
		for (const transform of transforms) stream = stream.pipeThrough(transform());
		return stream;
	}
	/**
	* Resolves to the reason generation finished.
	*/
	get finishReason() {
		return this.#getDelayedPromise(this.#delayedPromises.finishReason);
	}
	/**
	* Resolves to array of all tool calls made during execution.
	*/
	get toolCalls() {
		return this.#getDelayedPromise(this.#delayedPromises.toolCalls);
	}
	/**
	* Resolves to array of all tool execution results.
	*/
	get toolResults() {
		return this.#getDelayedPromise(this.#delayedPromises.toolResults);
	}
	/**
	* Resolves to token usage statistics including inputTokens, outputTokens, and totalTokens.
	*/
	get usage() {
		return this.#getDelayedPromise(this.#delayedPromises.usage);
	}
	/**
	* Resolves to array of all warnings generated during execution.
	*/
	get warnings() {
		return this.#getDelayedPromise(this.#delayedPromises.warnings);
	}
	/**
	* Resolves to provider metadata generated during execution.
	*/
	get providerMetadata() {
		return this.#getDelayedPromise(this.#delayedPromises.providerMetadata);
	}
	/**
	* Resolves to the complete response from the model.
	*/
	get response() {
		return this.#getDelayedPromise(this.#delayedPromises.response);
	}
	/**
	* Resolves to the complete request sent to the model.
	*/
	get request() {
		return this.#getDelayedPromise(this.#delayedPromises.request);
	}
	/**
	* Transport handle for the current stream (when available).
	*/
	get transport() {
		return this.#transportRef?.current;
	}
	/**
	* Resolves to an error if an error occurred during streaming.
	*/
	get error() {
		return this.#error;
	}
	updateUsageCount(usage) {
		if (!usage) return;
		accumulateUsage(this.#usageCount, this.#usageCountMissing, usage);
	}
	populateUsageCount(usage) {
		if (!usage) return;
		for (const key of primaryUsageCountKeys) {
			const value = usage[key];
			if (value !== void 0 && this.#usageCount[key] === void 0 && !this.#usageCountMissing.has(key)) this.#usageCount[key] = value;
		}
		for (const key of detailUsageCountKeys) {
			const value = usage[key];
			if (value !== void 0 && this.#usageCount[key] === void 0) this.#usageCount[key] = value;
		}
		if (usage.raw !== void 0 && this.#usageCount.raw === void 0) this.#usageCount.raw = usage.raw;
	}
	async consumeStream(options) {
		if (!this.#consumeStreamPromise) {
			this.#consumptionStarted = true;
			this.#consumeStreamPromise = consumeStream$1({
				stream: this.#baseStream,
				onError: (error) => {
					const streamError = getErrorFromUnknown(error, { fallbackMessage: "Unknown error consuming stream" });
					this.#consumeStreamErrored = true;
					this.#consumeStreamError = streamError;
					this.#error = streamError;
					this.#status = "failed";
					this.#streamFinished = true;
					Object.values(this.#delayedPromises).forEach((promise) => {
						if (promise.status.type === "pending") promise.reject(streamError);
					});
					this.#closeTransportIfNeeded();
					this.#emitter.emit("stream-error", streamError);
					this.#emitter.emit("settled");
				},
				logger: this.logger
			});
		}
		await this.#consumeStreamPromise;
		if (this.#consumeStreamErrored) options?.onError?.(this.#consumeStreamError);
	}
	/**
	* Returns complete output including text, usage, tool calls, and all metadata.
	*/
	async getFullOutput() {
		await this.consumeStream({ onError: (error) => {
			this.logger.error("Error consuming stream", error);
			throw error;
		} });
		let scoringData;
		if (this.#returnScorerData) try {
			scoringData = {
				input: {
					inputMessages: this.messageList.getPersisted.input.db(),
					rememberedMessages: this.messageList.getPersisted.remembered.db(),
					systemMessages: this.messageList.getSystemMessages(),
					taggedSystemMessages: this.messageList.getPersisted.taggedSystemMessages
				},
				output: await this.messageList.getRunResponseMessages(this.#options.loadStoredMessages)
			};
		} catch (error) {
			this.logger.warn("Failed to load run response messages for scoring data", { error });
		}
		const steps = await this.steps;
		const textFromSteps = steps.map((step) => step.text || "").join("") + (this.#status === "suspended" ? this.#bufferedByStep.text : "");
		return {
			text: this.tripwire || steps.length === 0 ? await this.text : this.#resumedPriorText + textFromSteps,
			usage: await this.usage,
			steps,
			finishReason: await this.finishReason,
			warnings: await this.warnings,
			providerMetadata: await this.providerMetadata,
			request: await this.request,
			reasoning: await this.reasoning,
			reasoningText: await this.reasoningText,
			toolCalls: await this.toolCalls,
			toolResults: await this.toolResults,
			sources: await this.sources,
			files: await this.files,
			response: await this.response,
			totalUsage: await this.totalUsage,
			object: await this.object,
			usedFallbackValue: this.#usedFallbackValue,
			error: this.error,
			tripwire: this.#tripwire,
			...scoringData ? { scoringData } : {},
			traceId: this.traceId,
			spanId: this.spanId,
			runId: this.runId,
			suspendPayload: await this.suspendPayload,
			resumeSchema: await this.resumeSchema,
			messages: this.messageList.get.all.db(),
			rememberedMessages: this.messageList.get.remembered.db()
		};
	}
	/**
	* Tripwire data if the stream was aborted due to an output processor blocking the content.
	* Returns undefined if no tripwire was triggered.
	*/
	get tripwire() {
		return this.#tripwire;
	}
	/**
	* The total usage of the stream.
	*/
	get totalUsage() {
		return this.#getDelayedPromise(this.#delayedPromises.totalUsage);
	}
	get content() {
		return this.#getDelayedPromise(this.#delayedPromises.content);
	}
	/**
	* Stream of valid JSON chunks. The final JSON result is validated against the output schema when the stream ends.
	*
	* @example
	* ```typescript
	* const stream = await agent.stream("Extract data", {
	*   structuredOutput: {
	*     schema: z.object({ name: z.string(), age: z.number() }),
	*     model: 'gpt-4o-mini' // optional to use a model for structuring json output
	*   }
	* });
	* // partial json chunks
	* for await (const data of stream.objectStream) {
	*   console.log(data); // { name: 'John' }, { name: 'John', age: 30 }
	* }
	* ```
	*/
	get objectStream() {
		return this.#createEventedStream().pipeThrough(new TransformStream$1({ transform(chunk, controller) {
			if (chunk.type === "object") controller.enqueue(chunk.object);
		} }));
	}
	/**
	* Stream of individual array elements when output schema is an array type.
	*/
	get elementStream() {
		let publishedElements = 0;
		let latestArray = [];
		return this.#createEventedStream().pipeThrough(new TransformStream$1({
			transform(chunk, controller) {
				if (chunk.type === "object") {
					if (Array.isArray(chunk.object)) {
						latestArray = chunk.object;
						for (; publishedElements < chunk.object.length - 1; publishedElements++) controller.enqueue(chunk.object[publishedElements]);
					}
				}
			},
			flush(controller) {
				for (; publishedElements < latestArray.length; publishedElements++) controller.enqueue(latestArray[publishedElements]);
			}
		}));
	}
	/**
	* Stream of only text content, filtering out metadata and other chunk types.
	*/
	get textStream() {
		if (this.#structuredOutputMode === "direct") {
			if (getTransformedSchema(this.#options.structuredOutput?.schema)?.outputFormat === "array") return this.#createEventedStream().pipeThrough(createJsonTextStreamTransformer(this.#options.structuredOutput?.schema));
		}
		return this.#createEventedStream().pipeThrough(new TransformStream$1({ transform(chunk, controller) {
			if (chunk.type === "text-delta") controller.enqueue(chunk.payload.text);
		} }));
	}
	/**
	* Resolves to the complete object response from the model. Validated against the 'output' schema when the stream ends.
	*
	* @example
	* ```typescript
	* const stream = await agent.stream("Extract data", {
	*   structuredOutput: {
	*     schema: z.object({ name: z.string(), age: z.number() }),
	*     model: 'gpt-4o-mini' // optionally use a model for structuring json output
	*   }
	* });
	* // final validated json
	* const data = await stream.object // { name: 'John', age: 30 }
	* ```
	*/
	get object() {
		if (!this.processorRunner && !this.#options.structuredOutput?.schema && this.#delayedPromises.object.status.type === "pending") this.#delayedPromises.object.resolve(void 0);
		return this.#getDelayedPromise(this.#delayedPromises.object);
	}
	/** @internal */
	_getImmediateToolCalls() {
		return this.#toolCalls;
	}
	/** @internal */
	_getImmediateToolResults() {
		return this.#toolResults;
	}
	/** @internal */
	_getImmediateText() {
		return this.#bufferedText.join("");
	}
	/** @internal */
	_getImmediateObject() {
		return this.#bufferedObject;
	}
	/**
	* Whether the structured object is the configured `fallbackValue`, substituted because
	* the model output failed schema validation — or the separate structuring model failed —
	* under `errorStrategy: 'fallback'`.
	*
	* Starts `false` and reflects the most recently processed object. On a live stream, await
	* `stream.object` or `stream.getFullOutput()` before reading it.
	*/
	get usedFallbackValue() {
		return this.#usedFallbackValue;
	}
	/** @internal */
	_getImmediateUsage() {
		return this.#usageCount;
	}
	/** @internal */
	_getImmediateWarnings() {
		return this.#warnings;
	}
	/** @internal */
	_getImmediateFinishReason() {
		return this.#finishReason;
	}
	/** @internal */
	_getImmediateProviderMetadata() {
		return this.#stepProviderMetadata;
	}
	/** @internal  */
	_getBaseStream() {
		this.#consumptionStarted = true;
		return this.#baseStream;
	}
	/** @internal */
	_waitUntilFinished() {
		if (this.#streamFinished) return Promise.resolve();
		return new Promise((resolve) => {
			const done = () => {
				this.#emitter.off("finish", done);
				this.#emitter.off("settled", done);
				resolve();
			};
			this.#emitter.once("finish", done);
			this.#emitter.once("settled", done);
		});
	}
	#getTotalUsage(usageCount = this.#usageCount) {
		let total = usageCount.totalTokens;
		if (total === void 0 && usageCount.inputTokens !== void 0 && usageCount.outputTokens !== void 0) total = usageCount.inputTokens + usageCount.outputTokens;
		return {
			inputTokens: usageCount.inputTokens,
			outputTokens: usageCount.outputTokens,
			totalTokens: total,
			reasoningTokens: usageCount.reasoningTokens,
			cachedInputTokens: usageCount.cachedInputTokens,
			cacheCreationInputTokens: usageCount.cacheCreationInputTokens,
			cacheCreationInputTokens5m: usageCount.cacheCreationInputTokens5m,
			cacheCreationInputTokens1h: usageCount.cacheCreationInputTokens1h,
			...usageCount.raw !== void 0 && { raw: usageCount.raw }
		};
	}
	/** `#usageCount` plus the suspended step's usage, following the same missing-key rules. */
	#getUsageCountWithSuspendedStep(suspendedStepUsage = this.#suspendedStepUsage) {
		if (!suspendedStepUsage) return this.#usageCount;
		const usageCount = { ...this.#usageCount };
		accumulateUsage(usageCount, new Set(this.#usageCountMissing), suspendedStepUsage);
		return usageCount;
	}
	#createAbortedOnFinishPayload() {
		const emptyUsage = {
			inputTokens: void 0,
			outputTokens: void 0,
			totalTokens: void 0
		};
		return {
			finishReason: "aborted",
			text: this.#bufferedText.join(""),
			reasoning: [],
			reasoningText: void 0,
			sources: [],
			files: [],
			toolCalls: [],
			toolResults: [],
			staticToolCalls: [],
			staticToolResults: [],
			dynamicToolCalls: [],
			dynamicToolResults: [],
			content: [],
			usage: this.#lastStepUsage ?? emptyUsage,
			warnings: [],
			providerMetadata: void 0,
			request: {},
			response: {},
			steps: [],
			totalUsage: this.#lastStepUsage ? this.#getTotalUsage() : emptyUsage,
			...this.#generationReportedUsage && { generationReportedUsage: this.#generationReportedUsage },
			object: void 0
		};
	}
	#createTripwireOnFinishPayload() {
		return {
			...this.#createAbortedOnFinishPayload(),
			finishReason: "other",
			steps: this.#bufferedSteps,
			tripwire: this.#tripwire
		};
	}
	#createSuspendedOnFinishPayload(chunk) {
		const totalUsage = this.#getTotalUsage(this.#getUsageCountWithSuspendedStep());
		const generationReportedUsage = this.#generationReportedUsage;
		this.#generationReportedUsage = totalUsage;
		const generationStepProviderMetadata = [];
		if (hasTokenCounts(totalUsage)) {
			for (const step of this.#bufferedSteps.slice(this.#generationReportedStepCount)) generationStepProviderMetadata.push(step.providerMetadata);
			generationStepProviderMetadata.push(chunk.payload.providerMetadata);
			this.#generationReportedStepCount = this.#bufferedSteps.length + 1;
		}
		return {
			finishReason: "suspended",
			suspendReason: chunk.type,
			toolName: chunk.payload.toolName,
			toolCallId: chunk.payload.toolCallId,
			text: "",
			reasoning: [],
			reasoningText: void 0,
			sources: [],
			files: [],
			toolCalls: [],
			toolResults: [],
			staticToolCalls: [],
			staticToolResults: [],
			dynamicToolCalls: [],
			dynamicToolResults: [],
			content: [],
			usage: this.#getUsageCountWithSuspendedStep(),
			warnings: [],
			providerMetadata: void 0,
			request: {},
			response: {},
			steps: [],
			totalUsage,
			...generationReportedUsage && { generationReportedUsage },
			generationStepProviderMetadata,
			object: void 0
		};
	}
	/** Resolves the result promises with what the run produced before it suspended. */
	#resolveSuspendedPromises() {
		const reasoningText = this.#bufferedReasoning.length > 0 ? this.#bufferedReasoning.map((reasoningPart) => reasoningPart.payload.text).join("") : void 0;
		this.resolvePromises({
			toolResults: this.#toolResults,
			toolCalls: this.#toolCalls,
			text: this.#bufferedText.join(""),
			reasoning: Object.values(this.#bufferedReasoningDetails || {}),
			reasoningText,
			sources: this.#bufferedSources,
			files: this.#bufferedFiles,
			steps: this.#bufferedSteps,
			usage: this.#getUsageCountWithSuspendedStep(),
			totalUsage: this.#getTotalUsage(this.#getUsageCountWithSuspendedStep()),
			warnings: this.#warnings,
			finishReason: "suspended",
			content: this.messageList.get.response.aiV5.stepContent(),
			object: void 0,
			request: this.#request,
			response: { dbMessages: this.messageList.get.response.db() },
			providerMetadata: void 0
		});
	}
	#emitChunk(chunk) {
		if (getChunkProducedAt(chunk) === void 0) stampChunkProducedAt(chunk, Date.now());
		if (this.traceId && !isDataChunk(chunk) && !chunk.traceId) chunk.traceId = this.traceId;
		this.#bufferedChunks.push(chunk);
		this.#emitter.emit("chunk", chunk);
	}
	/**
	* Text produced by the run: the last step's text for tool-driven multi-step runs (excluding
	* pre-tool narration), otherwise the aggregate stream text. Suspended/resumed runs keep the
	* aggregate because pre-approval text is part of the resumed run.
	*/
	#producedText() {
		const lastStep = this.#bufferedSteps[this.#bufferedSteps.length - 1];
		const hasToolStep = this.#bufferedSteps.some((step) => step.toolCalls.length > 0 || step.toolResults.length > 0);
		if (!hasToolStep && !this.#wasSuspended && this.#options.resolveFinalPromises) return this.#bufferedSteps.map((step) => step.text).join("") + this.#bufferedByStep.text;
		return hasToolStep && !this.#wasSuspended && lastStep ? lastStep.text : this.#bufferedText.join("");
	}
	/**
	* Drops all run-lifetime accumulators. Called at goal-evaluation boundaries,
	* where every completed step has already been persisted to the MessageList.
	* After truncation, run-end results (`text`, `steps`, `toolCalls`, …,
	* `getFullOutput()`) cover only the segment after the last evaluation —
	* for goal runs that segment is the completion answer. Token usage
	* (`#usageCount`), in-flight per-step state (`#bufferedByStep`), structured
	* output, and the MessageList are intentionally untouched.
	*/
	#truncateRunBuffers() {
		this.#bufferedChunks.length = 0;
		this.#bufferedSteps.length = 0;
		this.#generationReportedStepCount = 0;
		this.#bufferedText.length = 0;
		this.#resumedPriorText = "";
		this.#bufferedTextAtStepStart = 0;
		this.#bufferedTextChunks = {};
		this.#bufferedSources.length = 0;
		this.#bufferedReasoning.length = 0;
		this.#bufferedReasoningDetails = {};
		this.#reasoningAtStepStart = void 0;
		this.#runOutputAtStepStart = void 0;
		this.#bufferedFiles.length = 0;
		this.#toolCalls.length = 0;
		this.#toolResults.length = 0;
		this.#toolCallArgsDeltas = Object.create(null);
		this.#toolCallDeltaIdNameMap = Object.create(null);
		this.#toolCallStreamingMeta = Object.create(null);
		this.#pendingToolCalls = Object.create(null);
		this.#replaceableToolCallIds.clear();
		this.#attemptToolCallIds.clear();
	}
	#createEventedStream() {
		const self = this;
		let detach;
		let pendingError;
		const fail = (controller, error) => {
			if ((controller.desiredSize ?? 0) > 0) controller.error(error);
			else pendingError = { error };
		};
		return new ReadableStream$1({
			start(controller) {
				self.#bufferedChunks.forEach((chunk) => {
					controller.enqueue(chunk);
				});
				if (self.#streamFinished) {
					if (self.#consumeStreamErrored) fail(controller, self.#consumeStreamError);
					else controller.close();
					return;
				}
				const chunkHandler = (chunk) => {
					safeEnqueue(controller, chunk);
				};
				const detachListeners = () => {
					self.#emitter.off("chunk", chunkHandler);
					self.#emitter.off("finish", finishHandler);
					self.#emitter.off("stream-error", errorHandler);
				};
				const finishHandler = () => {
					detachListeners();
					safeClose(controller);
				};
				const errorHandler = (error) => {
					detachListeners();
					fail(controller, error);
				};
				self.#emitter.on("chunk", chunkHandler);
				self.#emitter.on("finish", finishHandler);
				self.#emitter.on("stream-error", errorHandler);
				detach = detachListeners;
			},
			pull(controller) {
				if (pendingError) {
					controller.error(pendingError.error);
					return;
				}
				if (!self.#consumptionStarted) self.consumeStream().catch((error) => {
					self.logger?.error("Error consuming stream", error);
				});
			},
			cancel() {
				detach?.();
			}
		});
	}
	get status() {
		return this.#status;
	}
	/**
	* @param pendingSuspension A suspension chunk the step has emitted but this output may not have
	* processed yet. Tool suspension snapshots the stream state right after emitting the chunk, so
	* the state is serialized as if the chunk was processed; otherwise a resumed run would not know
	* which usage its suspended leg already reported.
	*/
	serializeState(pendingSuspension) {
		const { steps, requests } = dedupeStepRequests(packStepMessageMirrors(this.#bufferedSteps));
		const recordSuspension = pendingSuspension !== void 0 && (this.#status !== "suspended" || this.#suspendedStepUsage === void 0);
		const suspendedStepUsage = recordSuspension ? this.#suspendedStepUsage ?? pendingSuspension.usage : this.#suspendedStepUsage;
		const generationReportedUsage = recordSuspension ? this.#getTotalUsage(this.#getUsageCountWithSuspendedStep(suspendedStepUsage)) : this.#generationReportedUsage;
		const generationReportedStepCount = recordSuspension && hasTokenCounts(generationReportedUsage) ? this.#bufferedSteps.length + 1 : this.#generationReportedStepCount;
		return {
			status: recordSuspension ? "suspended" : this.#status,
			bufferedSteps: steps,
			bufferedStepRequests: requests,
			bufferedReasoningDetails: this.#bufferedReasoningDetails,
			bufferedByStepReasoningDetails: this.#bufferedByStepReasoningDetails,
			bufferedByStep: this.#bufferedByStep,
			bufferedText: this.#bufferedText,
			bufferedTextAtStepStart: this.#bufferedTextAtStepStart,
			bufferedTextChunks: this.#bufferedTextChunks,
			bufferedSources: this.#bufferedSources,
			bufferedReasoning: this.#bufferedReasoning,
			bufferedFiles: this.#bufferedFiles,
			toolCallArgsDeltas: this.#toolCallArgsDeltas,
			toolCallDeltaIdNameMap: this.#toolCallDeltaIdNameMap,
			toolCallStreamingMeta: this.#toolCallStreamingMeta,
			pendingToolCalls: this.#pendingToolCalls,
			replaceableToolCallIds: [...this.#replaceableToolCallIds],
			attemptToolCallIds: [...this.#attemptToolCallIds],
			toolCalls: this.#toolCalls,
			toolResults: this.#toolResults,
			warnings: this.#warnings,
			finishReason: this.#finishReason,
			request: this.#request,
			usageCount: this.#usageCount,
			usageCountMissing: [...this.#usageCountMissing],
			lastStepUsage: this.#lastStepUsage,
			suspendedStepUsage,
			generationReportedUsage,
			generationReportedStepCount,
			tripwire: this.#tripwire,
			wasSuspended: this.#wasSuspended || recordSuspension,
			messageList: this.messageList.serialize()
		};
	}
	deserializeState(state) {
		this.#status = state.status;
		this.#bufferedReasoningDetails = state.bufferedReasoningDetails;
		this.#bufferedByStepReasoningDetails = state.bufferedByStepReasoningDetails ?? {};
		this.#bufferedByStep = state.bufferedByStep;
		this.#bufferedText = state.bufferedText;
		this.#bufferedTextAtStepStart = state.bufferedTextAtStepStart ?? state.bufferedText.length;
		this.#bufferedTextChunks = state.bufferedTextChunks;
		this.#bufferedSources = state.bufferedSources;
		this.#bufferedReasoning = state.bufferedReasoning;
		this.#bufferedFiles = state.bufferedFiles;
		this.#toolCallArgsDeltas = Object.assign(Object.create(null), state.toolCallArgsDeltas);
		this.#toolCallDeltaIdNameMap = Object.assign(Object.create(null), state.toolCallDeltaIdNameMap);
		this.#toolCallStreamingMeta = Object.assign(Object.create(null), state.toolCallStreamingMeta);
		this.#pendingToolCalls = Object.assign(Object.create(null), state.pendingToolCalls);
		this.#replaceableToolCallIds = new Set(state.replaceableToolCallIds ?? []);
		this.#attemptToolCallIds = new Set(state.attemptToolCallIds ?? []);
		this.#toolCalls = state.toolCalls;
		this.#toolResults = state.toolResults;
		this.#warnings = state.warnings;
		this.#finishReason = state.finishReason;
		this.#request = state.request;
		this.#usageCount = state.usageCount;
		if (state.usageCountMissing === void 0) {
			const hasPriorUsage = Array.isArray(state.bufferedSteps) && state.bufferedSteps.length > 0 || primaryUsageCountKeys.some((key) => state.usageCount?.[key] !== void 0);
			this.#usageCountMissing = hasPriorUsage ? new Set(primaryUsageCountKeys) : /* @__PURE__ */ new Set();
			if (hasPriorUsage) for (const key of primaryUsageCountKeys) this.#usageCount[key] = void 0;
		} else this.#usageCountMissing = new Set(state.usageCountMissing);
		this.#tripwire = state.tripwire;
		this.#lastStepUsage = state.lastStepUsage ?? state.bufferedSteps?.at(-1)?.usage;
		this.#suspendedStepUsage = state.suspendedStepUsage;
		this.#generationReportedUsage = state.generationReportedUsage;
		this.#generationReportedStepCount = state.generationReportedStepCount ?? 0;
		this.#wasSuspended = state.wasSuspended ?? state.status === "suspended";
		this.messageList = this.messageList.deserialize(state.messageList);
		this.#bufferedSteps = unpackStepMessageMirrors(rehydrateStepRequests(state.bufferedSteps, state.bufferedStepRequests), this.messageList);
	}
};
// src/agent/trip-wire.ts
/**
* TripWire is a custom Error class for aborting processing with optional retry and metadata.
*
* When thrown from a processor, it signals that processing should stop.
* The `options` field controls how the tripwire should be handled:
* - `retry: true` - The agent will retry with the reason as feedback
* - `metadata` - Strongly typed data about what triggered the tripwire
*/
var TripWire = class extends Error {
	options;
	processorId;
	constructor(reason, options = {}, processorId) {
		super(reason);
		this.name = "TripWire";
		this.options = options;
		this.processorId = processorId;
		Object.setPrototypeOf(this, new.target.prototype);
	}
};
const getModelOutputForTripwire = async ({ tripwire, runId, options, model, messageList, ...rest }) => {
	const observabilityContext = resolveObservabilityContext(rest);
	const tripwireStream = new ReadableStream$1({ start(controller) {
		controller.enqueue({
			type: "tripwire",
			runId,
			from: "AGENT",
			payload: {
				reason: tripwire.reason || "",
				retry: tripwire.retry,
				metadata: tripwire.metadata,
				processorId: tripwire.processorId
			}
		});
		controller.close();
	} });
	return new MastraModelOutput({
		model: {
			modelId: model.modelId,
			provider: model.provider,
			version: model.specificationVersion
		},
		stream: tripwireStream,
		messageList,
		options: {
			runId,
			structuredOutput: options.structuredOutput,
			...observabilityContext,
			onFinish: options.onFinish,
			onStepFinish: options.onStepFinish,
			returnScorerData: options.returnScorerData,
			requestContext: options.requestContext
		},
		messageId: globalThis.crypto.randomUUID()
	});
};
// src/stream/base/consume-stream.ts
async function consumeStream({ stream, onError }) {
	let reader;
	try {
		reader = stream.getReader();
		while (true) {
			const { done } = await reader.read();
			if (done) break;
		}
	} catch (error) {
		onError?.(error);
	} finally {
		reader?.releaseLock();
	}
}
// src/stream/RunOutput.ts
const primaryUsageKeys$1 = [
	"inputTokens",
	"outputTokens",
	"totalTokens"
];
var WorkflowRunOutput = class {
	#status = "running";
	#tripwireData;
	#usageCount = {
		inputTokens: void 0,
		outputTokens: void 0,
		totalTokens: void 0
	};
	#usageCountMissing = /* @__PURE__ */ new Set();
	#consumptionStarted = false;
	#baseStream;
	#emitter = new EventEmitter$1();
	#bufferedChunks = [];
	#streamFinished = false;
	#streamError;
	#finalWorkflowResult;
	#delayedPromises = {
		usage: new DelayedPromise(),
		result: new DelayedPromise()
	};
	/**
	* Unique identifier for this workflow run
	*/
	runId;
	/**
	* Unique identifier for this workflow
	*/
	workflowId;
	constructor({ runId, workflowId, stream }) {
		const self = this;
		this.runId = runId;
		this.workflowId = workflowId;
		this.#baseStream = stream;
		stream.pipeTo(new WritableStream$1({
			start() {
				const chunk = {
					type: "workflow-start",
					runId: self.runId,
					from: "WORKFLOW",
					payload: { workflowId: self.workflowId }
				};
				self.#bufferedChunks.push(chunk);
				self.#emitter.emit("chunk", chunk);
			},
			write(chunk) {
				if (chunk.type !== "workflow-step-finish") {
					self.#bufferedChunks.push(chunk);
					self.#emitter.emit("chunk", chunk);
				}
				if (chunk.type === "workflow-step-output") {
					if ("output" in chunk.payload && chunk.payload.output) {
						const output = chunk.payload.output;
						if (output.type === "finish") {
							if (output.payload && "usage" in output.payload && output.payload.usage) self.#updateUsageCount(output.payload.usage);
							else if (output.payload && "output" in output.payload && output.payload.output) {
								const outputPayload = output.payload.output;
								if ("usage" in outputPayload && outputPayload.usage) self.#updateUsageCount(outputPayload.usage);
							}
						}
					}
				} else if (chunk.type === "workflow-canceled") self.#status = "canceled";
				else if (chunk.type === "workflow-step-suspended") self.#status = "suspended";
				else if (chunk.type === "workflow-step-result" && chunk.payload.status === "failed") {
					if (chunk.payload.tripwire) {
						self.#status = "tripwire";
						self.#tripwireData = chunk.payload.tripwire;
					} else self.#status = "failed";
				} else if (chunk.type === "workflow-paused") self.#status = "paused";
			},
			close() {
				if (self.#status === "running") self.#status = "success";
				self.#emitter.emit("chunk", {
					type: "workflow-finish",
					runId: self.runId,
					from: "WORKFLOW",
					payload: {
						workflowStatus: self.#status,
						metadata: self.#streamError ? {
							error: self.#streamError,
							errorMessage: self.#streamError?.message
						} : {},
						output: { usage: self.#usageCount },
						...self.#status === "success" && self.#finalWorkflowResult !== void 0 ? { finalWorkflowResult: self.#finalWorkflowResult } : {},
						...self.#status === "tripwire" && self.#tripwireData ? { tripwire: self.#tripwireData } : {}
					}
				});
				self.#delayedPromises.usage.resolve(self.#usageCount);
				Object.entries(self.#delayedPromises).forEach(([key, promise]) => {
					if (promise.status.type === "pending") promise.reject(/* @__PURE__ */ new Error(`promise '${key}' was not resolved or rejected when stream finished`));
				});
				self.#streamFinished = true;
				self.#emitter.emit("finish");
			}
		})).catch((reason) => {
			self.#finalizeWithError(reason);
		});
	}
	#getDelayedPromise(promise) {
		if (!this.#consumptionStarted) this.consumeStream();
		return promise.promise;
	}
	#updateUsageCount(usage) {
		const primaryUsage = {
			inputTokens: "inputTokens" in usage ? usage.inputTokens : "promptTokens" in usage ? usage.promptTokens : void 0,
			outputTokens: "outputTokens" in usage ? usage.outputTokens : "completionTokens" in usage ? usage.completionTokens : void 0,
			totalTokens: usage.totalTokens
		};
		for (const key of primaryUsageKeys$1) {
			const value = primaryUsage[key] === void 0 ? void 0 : Number(primaryUsage[key]);
			if (value === void 0) {
				this.#usageCountMissing.add(key);
				this.#usageCount[key] = void 0;
			} else if (!this.#usageCountMissing.has(key)) this.#usageCount[key] = (this.#usageCount[key] ?? 0) + value;
		}
		for (const key of [
			"reasoningTokens",
			"cachedInputTokens",
			"cacheCreationInputTokens"
		]) {
			const value = usage[key] === void 0 ? void 0 : Number(usage[key]);
			if (value !== void 0) this.#usageCount[key] = (this.#usageCount[key] ?? 0) + value;
		}
	}
	/**
	* Finalize the run when the underlying stream pipeline rejects.
	*
	* When `pipeTo` rejects, the WritableStream's `close()` never runs, so without
	* this the terminal `workflow-finish` event would never fire, the delayed
	* `result`/`usage` promises would never settle, and every `fullStream` consumer
	* would hang forever. Mirror the `close()` path but mark the run as failed.
	*/
	#finalizeWithError(reason) {
		if (this.#streamFinished) return;
		const error = reason instanceof Error ? reason : new Error(String(reason));
		this.#streamError = error;
		this.#status = "failed";
		this.#emitter.emit("chunk", {
			type: "workflow-finish",
			runId: this.runId,
			from: "WORKFLOW",
			payload: {
				workflowStatus: this.#status,
				metadata: {
					error: this.#streamError,
					errorMessage: this.#streamError.message
				},
				output: { usage: this.#usageCount }
			}
		});
		Object.entries(this.#delayedPromises).forEach(([_key, promise]) => {
			if (promise.status.type === "pending") promise.reject(error);
		});
		this.#streamFinished = true;
		this.#emitter.emit("finish");
		console.error("[WorkflowRunOutput] workflow stream pipeline error", error);
	}
	/**
	* @internal
	*/
	updateResults(results) {
		if (results.status === "success") this.#finalWorkflowResult = results.result;
		this.#delayedPromises.result.resolve(results);
	}
	/**
	* @internal
	*/
	rejectResults(error) {
		this.#delayedPromises.result.reject(error);
		this.#status = "failed";
		this.#streamError = error;
	}
	/**
	* @internal
	*/
	resume(stream) {
		this.#baseStream = stream;
		this.#streamFinished = false;
		this.#consumptionStarted = false;
		this.#status = "running";
		this.#delayedPromises = {
			usage: new DelayedPromise(),
			result: new DelayedPromise()
		};
		const self = this;
		stream.pipeTo(new WritableStream$1({
			start() {
				const chunk = {
					type: "workflow-start",
					runId: self.runId,
					from: "WORKFLOW",
					payload: { workflowId: self.workflowId }
				};
				self.#bufferedChunks.push(chunk);
				self.#emitter.emit("chunk", chunk);
			},
			write(chunk) {
				if (chunk.type !== "workflow-step-finish") {
					self.#bufferedChunks.push(chunk);
					self.#emitter.emit("chunk", chunk);
				}
				if (chunk.type === "workflow-step-output") {
					if ("output" in chunk.payload && chunk.payload.output) {
						const output = chunk.payload.output;
						if (output.type === "finish") {
							if (output.payload && "usage" in output.payload && output.payload.usage) self.#updateUsageCount(output.payload.usage);
							else if (output.payload && "output" in output.payload && output.payload.output) {
								const outputPayload = output.payload.output;
								if ("usage" in outputPayload && outputPayload.usage) self.#updateUsageCount(outputPayload.usage);
							}
						}
					}
				} else if (chunk.type === "workflow-canceled") self.#status = "canceled";
				else if (chunk.type === "workflow-step-suspended") self.#status = "suspended";
				else if (chunk.type === "workflow-step-result" && chunk.payload.status === "failed") {
					if (chunk.payload.tripwire) {
						self.#status = "tripwire";
						self.#tripwireData = chunk.payload.tripwire;
					} else self.#status = "failed";
				} else if (chunk.type === "workflow-paused") self.#status = "paused";
			},
			close() {
				if (self.#status === "running") self.#status = "success";
				self.#emitter.emit("chunk", {
					type: "workflow-finish",
					runId: self.runId,
					from: "WORKFLOW",
					payload: {
						workflowStatus: self.#status,
						metadata: self.#streamError ? {
							error: self.#streamError,
							errorMessage: self.#streamError?.message
						} : {},
						output: { usage: self.#usageCount },
						...self.#status === "success" && self.#finalWorkflowResult !== void 0 ? { finalWorkflowResult: self.#finalWorkflowResult } : {},
						...self.#status === "tripwire" && self.#tripwireData ? { tripwire: self.#tripwireData } : {}
					}
				});
				self.#streamFinished = true;
				self.#emitter.emit("finish");
			}
		})).catch((reason) => {
			self.#finalizeWithError(reason);
		});
	}
	async consumeStream(options) {
		if (this.#consumptionStarted) return;
		this.#consumptionStarted = true;
		try {
			await consumeStream({
				stream: this.#baseStream,
				onError: options?.onError
			});
		} catch (error) {
			options?.onError?.(error);
		}
	}
	get fullStream() {
		const self = this;
		let detach;
		return new ReadableStream$1({
			start(controller) {
				self.#bufferedChunks.forEach((chunk) => {
					controller.enqueue(chunk);
				});
				if (self.#streamFinished) {
					controller.close();
					return;
				}
				const chunkHandler = (chunk) => {
					controller.enqueue(chunk);
				};
				const finishHandler = () => {
					self.#emitter.off("chunk", chunkHandler);
					self.#emitter.off("finish", finishHandler);
					controller.close();
				};
				self.#emitter.on("chunk", chunkHandler);
				self.#emitter.on("finish", finishHandler);
				detach = () => {
					self.#emitter.off("chunk", chunkHandler);
					self.#emitter.off("finish", finishHandler);
				};
			},
			pull(_controller) {
				if (!self.#consumptionStarted) self.consumeStream();
			},
			cancel() {
				detach?.();
			}
		});
	}
	get status() {
		return this.#status;
	}
	get result() {
		return this.#getDelayedPromise(this.#delayedPromises.result);
	}
	get usage() {
		return this.#getDelayedPromise(this.#delayedPromises.usage);
	}
	/**
	* @deprecated Use `fullStream.locked` instead
	*/
	get locked() {
		console.warn("WorkflowRunOutput.locked is deprecated. Use fullStream.locked instead.");
		return this.fullStream.locked;
	}
	/**
	* @deprecated Use `fullStream.cancel()` instead
	*/
	cancel(reason) {
		console.warn("WorkflowRunOutput.cancel() is deprecated. Use fullStream.cancel() instead.");
		return this.fullStream.cancel(reason);
	}
	/**
	* @deprecated Use `fullStream.getReader()` instead
	*/
	getReader(options) {
		console.warn("WorkflowRunOutput.getReader() is deprecated. Use fullStream.getReader() instead.");
		return this.fullStream.getReader(options);
	}
	/**
	* @deprecated Use `fullStream.pipeThrough()` instead
	*/
	pipeThrough(transform, options) {
		console.warn("WorkflowRunOutput.pipeThrough() is deprecated. Use fullStream.pipeThrough() instead.");
		return this.fullStream.pipeThrough(transform, options);
	}
	/**
	* @deprecated Use `fullStream.pipeTo()` instead
	*/
	pipeTo(destination, options) {
		console.warn("WorkflowRunOutput.pipeTo() is deprecated. Use fullStream.pipeTo() instead.");
		return this.fullStream.pipeTo(destination, options);
	}
	/**
	* @deprecated Use `fullStream.tee()` instead
	*/
	tee() {
		console.warn("WorkflowRunOutput.tee() is deprecated. Use fullStream.tee() instead.");
		return this.fullStream.tee();
	}
	/**
	* @deprecated Use `fullStream[Symbol.asyncIterator]()` instead
	*/
	[Symbol.asyncIterator]() {
		console.warn("WorkflowRunOutput[Symbol.asyncIterator]() is deprecated. Use fullStream[Symbol.asyncIterator]() instead.");
		return this.fullStream[Symbol.asyncIterator]();
	}
	/**
	* Helper method to treat this object as a ReadableStream
	* @deprecated Use `fullStream` directly instead
	*/
	toReadableStream() {
		console.warn("WorkflowRunOutput.toReadableStream() is deprecated. Use fullStream directly instead.");
		return this.fullStream;
	}
};
// src/stream/MastraAgentNetworkStream.ts
const primaryUsageKeys = [
	"inputTokens",
	"outputTokens",
	"totalTokens"
];
var MastraAgentNetworkStream = class extends ReadableStream$1 {
	#usageCount = {
		inputTokens: void 0,
		outputTokens: void 0,
		totalTokens: void 0
	};
	#usageCountMissing = /* @__PURE__ */ new Set();
	#streamPromise;
	#objectPromise;
	#objectStreamController = null;
	#objectStream = null;
	#run;
	runId;
	constructor({ createStream, run }) {
		const deferredPromise = {
			promise: null,
			resolve: null,
			reject: null
		};
		deferredPromise.promise = new Promise((resolve, reject) => {
			deferredPromise.resolve = resolve;
			deferredPromise.reject = reject;
		});
		const objectDeferredPromise = {
			promise: null,
			resolve: null,
			reject: null
		};
		objectDeferredPromise.promise = new Promise((resolve, reject) => {
			objectDeferredPromise.resolve = resolve;
			objectDeferredPromise.reject = reject;
		});
		let objectStreamController = null;
		const updateUsageCount = (usage) => {
			for (const key of primaryUsageKeys) {
				const value = usage[key] === void 0 ? void 0 : Number(usage[key]);
				if (value === void 0) {
					this.#usageCountMissing.add(key);
					this.#usageCount[key] = void 0;
				} else if (!this.#usageCountMissing.has(key)) this.#usageCount[key] = (this.#usageCount[key] ?? 0) + value;
			}
			for (const key of [
				"reasoningTokens",
				"cachedInputTokens",
				"cacheCreationInputTokens"
			]) {
				const value = usage[key] === void 0 ? void 0 : Number(usage[key]);
				if (value !== void 0) this.#usageCount[key] = (this.#usageCount[key] ?? 0) + value;
			}
		};
		super({ start: async (controller) => {
			try {
				const stream = await createStream(new WritableStream({ write: (chunk) => {
					if (chunk.type === "step-output" && chunk.payload?.output?.from === "AGENT" && chunk.payload?.output?.type === "finish" || chunk.type === "step-output" && chunk.payload?.output?.from === "WORKFLOW" && chunk.payload?.output?.type === "finish") {
						const output = chunk.payload?.output;
						if (output && "payload" in output && output.payload) {
							const finishPayload = output.payload;
							if ("usage" in finishPayload && finishPayload.usage) updateUsageCount(finishPayload.usage);
							else if ("output" in finishPayload && finishPayload.output) {
								const outputPayload = finishPayload.output;
								if ("usage" in outputPayload && outputPayload.usage) updateUsageCount(outputPayload.usage);
							}
						}
					}
					controller.enqueue(chunk);
				} }));
				const getInnerChunk = (chunk) => {
					if (chunk.type === "workflow-step-output") return getInnerChunk(chunk.payload.output);
					return chunk;
				};
				let objectResolved = false;
				for await (const chunk of stream) if (chunk.type === "workflow-step-output") {
					const innerChunk = getInnerChunk(chunk);
					if (innerChunk.type === "routing-agent-end" || innerChunk.type === "agent-execution-end" || innerChunk.type === "workflow-execution-end") {
						if (innerChunk.payload?.usage) updateUsageCount(innerChunk.payload.usage);
					}
					if (innerChunk.type === "network-object") {
						if (objectStreamController) objectStreamController.enqueue(innerChunk.payload?.object);
						controller.enqueue(innerChunk);
					} else if (innerChunk.type === "network-object-result") {
						if (!objectResolved) {
							objectResolved = true;
							objectDeferredPromise.resolve(innerChunk.payload?.object);
							if (objectStreamController) objectStreamController.close();
						}
						controller.enqueue(innerChunk);
					} else if (innerChunk.type === "network-execution-event-finish") {
						const finishPayload = {
							...innerChunk.payload,
							usage: this.#usageCount
						};
						controller.enqueue({
							...innerChunk,
							payload: finishPayload
						});
					} else controller.enqueue(innerChunk);
				}
				if (!objectResolved) {
					objectDeferredPromise.resolve(void 0);
					if (objectStreamController) objectStreamController.close();
				}
				controller.close();
				deferredPromise.resolve();
			} catch (error) {
				controller.error(error);
				deferredPromise.reject(error);
				objectDeferredPromise.reject(error);
				if (objectStreamController) objectStreamController.error(error);
			}
		} });
		this.#run = run;
		this.#streamPromise = deferredPromise;
		this.runId = run.runId;
		this.#objectPromise = objectDeferredPromise;
		this.#objectStream = new ReadableStream$1({ start: (ctrl) => {
			objectStreamController = ctrl;
			this.#objectStreamController = ctrl;
		} });
	}
	get status() {
		return this.#streamPromise.promise.then(() => this.#run._getExecutionResults()).then((res) => res.status);
	}
	get result() {
		return this.#streamPromise.promise.then(() => this.#run._getExecutionResults());
	}
	get usage() {
		return this.#streamPromise.promise.then(() => this.#usageCount);
	}
	/**
	* Returns a promise that resolves to the structured output object.
	* Only available when structuredOutput option is provided to network().
	* Resolves to undefined if no structuredOutput was requested.
	*/
	get object() {
		return this.#objectPromise.promise;
	}
	/**
	* Returns a ReadableStream of partial objects during structured output generation.
	* Useful for streaming partial results as they're being generated.
	*/
	get objectStream() {
		return this.#objectStream;
	}
};
// src/stream/aisdk/v5/transform.ts
/**
* Sanitizes tool-call input strings for safe JSON parsing.
*
* LLMs sometimes append internal tokens like `<|call|>`, `<|endoftext|>`, or `<|end|>`
* to otherwise valid JSON in streamed tool-call arguments, causing JSON.parse to fail.
*
* This function first attempts JSON.parse on the original input. If parsing succeeds,
* the original string is returned unchanged — this avoids corrupting valid JSON payloads
* that legitimately contain `<|...|>` patterns inside string values.
*
* Only when the original input is not valid JSON does the function fall back to stripping
* `<|...|>` token patterns and surrounding whitespace via regex.
*
* @see https://github.com/mastra-ai/mastra/issues/13261
* @see https://github.com/mastra-ai/mastra/issues/13185
*/
function sanitizeToolCallInput(input) {
	try {
		JSON.parse(input);
		return input;
	} catch {
		return input.replace(/<\|[^|]*\|>\s*/g, "").trim();
	}
}
/**
* Attempts to repair common JSON malformations produced by LLM providers.
*
* Some LLM providers (e.g., Kimi/K2) occasionally generate malformed JSON for
* tool call arguments. This function applies a sequence of targeted fixes for
* the most common errors before giving up.
*
* Repairs applied (in order):
* 1. Missing quote before property name: `{"a":"b",c":"d"}` → `{"a":"b","c":"d"}`
* 2. Unquoted property names: `{command:"value"}` → `{"command":"value"}`
* 3. Single quotes → double quotes (only outside already-double-quoted strings)
* 4. Trailing commas: `{"a":1,}` → `{"a":1}`
*
* @returns The parsed object if repair succeeds, or null if the JSON is unrecoverable.
* @see https://github.com/mastra-ai/mastra/issues/11078
*/
function tryRepairJson(input) {
	let repaired = input.trim();
	repaired = repaired.replace(/([{,]\s*)([a-zA-Z_$][a-zA-Z0-9_$]*)"/g, (match, prefix, name) => {
		if (prefix.trimEnd().endsWith("\"")) return match;
		return `${prefix}"${name}"`;
	});
	repaired = repaired.replace(/([{,]\s*)([a-zA-Z_$][a-zA-Z0-9_$]*)\s*:/g, "$1\"$2\":");
	repaired = repaired.replace(/'/g, "\"");
	repaired = repaired.replace(/,(\s*[}\]])/g, "$1");
	repaired = repaired.replace(/:\s*(\d{4}-\d{2}-\d{2}(?:T[\d:]+)?)\s*([,}])/g, ": \"$1\"$2");
	try {
		return JSON.parse(repaired);
	} catch {
		return null;
	}
}
function convertFullStreamChunkToMastra(value, ctx) {
	switch (value.type) {
		case "stream-start": return;
		case "response-metadata": return {
			type: "response-metadata",
			runId: ctx.runId,
			from: "AGENT",
			payload: { ...value }
		};
		case "text-start": return {
			type: "text-start",
			runId: ctx.runId,
			from: "AGENT",
			payload: {
				id: value.id,
				providerMetadata: value.providerMetadata
			}
		};
		case "text-delta":
			if (value.delta || value.providerMetadata != null) return {
				type: "text-delta",
				runId: ctx.runId,
				from: "AGENT",
				payload: {
					id: value.id,
					providerMetadata: value.providerMetadata,
					text: value.delta
				}
			};
			return;
		case "text-end": return {
			type: "text-end",
			runId: ctx.runId,
			from: "AGENT",
			payload: value
		};
		case "reasoning-start": return {
			type: "reasoning-start",
			runId: ctx.runId,
			from: "AGENT",
			payload: {
				id: value.id,
				providerMetadata: value.providerMetadata
			}
		};
		case "reasoning-delta": return {
			type: "reasoning-delta",
			runId: ctx.runId,
			from: "AGENT",
			payload: {
				id: value.id,
				providerMetadata: value.providerMetadata,
				text: value.delta
			}
		};
		case "reasoning-end": return {
			type: "reasoning-end",
			runId: ctx.runId,
			from: "AGENT",
			payload: {
				id: value.id,
				providerMetadata: value.providerMetadata
			}
		};
		case "source": return {
			type: "source",
			runId: ctx.runId,
			from: "AGENT",
			payload: {
				id: value.id,
				sourceType: value.sourceType,
				title: value.title || "",
				mimeType: value.sourceType === "document" ? value.mediaType : void 0,
				filename: value.sourceType === "document" ? value.filename : void 0,
				url: value.sourceType === "url" ? value.url : void 0,
				providerMetadata: value.providerMetadata
			}
		};
		case "file": {
			const pm = value.providerMetadata;
			return {
				type: "file",
				runId: ctx.runId,
				from: "AGENT",
				payload: {
					data: value.data,
					base64: typeof value.data === "string" && !isUrlString(value.data) ? value.data : void 0,
					mimeType: value.mediaType,
					...pm != null ? { providerMetadata: pm } : {}
				}
			};
		}
		case "tool-call": {
			let toolCallInput = void 0;
			if (value.input) {
				const sanitized = sanitizeToolCallInput(value.input);
				if (sanitized) try {
					toolCallInput = JSON.parse(sanitized);
				} catch {
					const repaired = tryRepairJson(sanitized);
					if (repaired) toolCallInput = repaired;
					else {
						console.error("Error converting tool call input to JSON", {
							toolCallId: value.toolCallId,
							toolName: value.toolName,
							inputLength: value.input.length
						});
						toolCallInput = void 0;
					}
				}
			}
			return {
				type: "tool-call",
				runId: ctx.runId,
				from: "AGENT",
				payload: {
					toolCallId: value.toolCallId,
					toolName: value.toolName,
					args: toolCallInput,
					providerExecuted: value.providerExecuted,
					providerMetadata: value.providerMetadata,
					...value.observability ? { observability: value.observability } : {}
				}
			};
		}
		case "tool-result": return {
			type: "tool-result",
			runId: ctx.runId,
			from: "AGENT",
			payload: {
				toolCallId: value.toolCallId,
				toolName: value.toolName,
				result: value.result,
				isError: value.isError,
				providerExecuted: value.providerExecuted,
				providerMetadata: value.providerMetadata,
				...value.preliminary ? { preliminary: true } : {}
			}
		};
		case "tool-input-start": return {
			type: "tool-call-input-streaming-start",
			runId: ctx.runId,
			from: "AGENT",
			payload: {
				toolCallId: value.id,
				toolName: value.toolName,
				providerExecuted: value.providerExecuted,
				providerMetadata: value.providerMetadata,
				dynamic: value.dynamic,
				...value.observability ? { observability: value.observability } : {}
			}
		};
		case "tool-input-delta":
			if (value.delta) return {
				type: "tool-call-delta",
				runId: ctx.runId,
				from: "AGENT",
				payload: {
					argsTextDelta: value.delta,
					toolCallId: value.id,
					providerMetadata: value.providerMetadata
				}
			};
			return;
		case "tool-input-end": return {
			type: "tool-call-input-streaming-end",
			runId: ctx.runId,
			from: "AGENT",
			payload: {
				toolCallId: value.id,
				providerMetadata: value.providerMetadata
			}
		};
		case "finish":
			const { finishReason, usage, providerMetadata, messages, ...rest } = value;
			const rawFinishReason = extractRawFinishReason(finishReason);
			return {
				type: "finish",
				runId: ctx.runId,
				from: "AGENT",
				payload: {
					providerMetadata: value.providerMetadata,
					stepResult: {
						reason: normalizeFinishReason(value.finishReason),
						...rawFinishReason !== void 0 && { rawReason: rawFinishReason }
					},
					output: { usage: normalizeUsage(value.usage, value.providerMetadata) },
					metadata: { providerMetadata: value.providerMetadata },
					messages: messages ?? {
						all: [],
						user: [],
						nonUser: []
					},
					...rest
				}
			};
		case "error": return {
			type: "error",
			runId: ctx.runId,
			from: "AGENT",
			payload: value
		};
		case "raw": return {
			type: "raw",
			runId: ctx.runId,
			from: "AGENT",
			payload: value.rawValue
		};
		case "reasoning-file": return {
			type: "reasoning-file",
			runId: ctx.runId,
			from: "AGENT",
			payload: {
				data: value.data,
				base64: typeof value.data === "string" && !isUrlString(value.data) ? value.data : void 0,
				mimeType: value.mediaType,
				...value.providerMetadata != null ? { providerMetadata: value.providerMetadata } : {}
			}
		};
		case "custom": return {
			type: "custom",
			runId: ctx.runId,
			from: "AGENT",
			payload: {
				kind: value.kind,
				...value.providerMetadata != null ? { providerMetadata: value.providerMetadata } : {}
			}
		};
		default: return {
			type: "raw",
			runId: ctx.runId,
			from: "AGENT",
			payload: value
		};
	}
}
function convertMastraChunkToAISDKv5({ chunk, mode = "stream" }) {
	switch (chunk.type) {
		case "start": return { type: "start" };
		case "step-start":
			const { messageId: _messageId, ...rest } = chunk.payload;
			return {
				type: "start-step",
				request: rest.request,
				warnings: rest.warnings || []
			};
		case "raw": return {
			type: "raw",
			rawValue: chunk.payload
		};
		case "finish": return {
			type: "finish",
			finishReason: chunk.payload.stepResult.reason,
			totalUsage: chunk.payload.output.usage
		};
		case "reasoning-start": return {
			type: "reasoning-start",
			id: chunk.payload.id,
			providerMetadata: chunk.payload.providerMetadata
		};
		case "reasoning-delta": return {
			type: "reasoning-delta",
			id: chunk.payload.id,
			text: chunk.payload.text,
			providerMetadata: chunk.payload.providerMetadata
		};
		case "reasoning-signature": throw new Error("AISDKv5 chunk type \"reasoning-signature\" not supported");
		case "redacted-reasoning": throw new Error("AISDKv5 chunk type \"redacted-reasoning\" not supported");
		case "reasoning-end": return {
			type: "reasoning-end",
			id: chunk.payload.id,
			providerMetadata: chunk.payload.providerMetadata
		};
		case "source":
			if (chunk.payload.sourceType === "url") return {
				type: "source",
				sourceType: "url",
				id: chunk.payload.id,
				url: chunk.payload.url,
				title: chunk.payload.title,
				providerMetadata: chunk.payload.providerMetadata
			};
			return {
				type: "source",
				sourceType: "document",
				id: chunk.payload.id,
				mediaType: chunk.payload.mimeType,
				title: chunk.payload.title,
				filename: chunk.payload.filename,
				providerMetadata: chunk.payload.providerMetadata
			};
		case "file": {
			const filePart = mode === "generate" ? {
				type: "file",
				file: new DefaultGeneratedFile({
					data: chunk.payload.data,
					mediaType: chunk.payload.mimeType
				})
			} : {
				type: "file",
				file: new DefaultGeneratedFileWithType({
					data: chunk.payload.data,
					mediaType: chunk.payload.mimeType
				})
			};
			if (chunk.payload.providerMetadata) filePart.providerMetadata = chunk.payload.providerMetadata;
			return filePart;
		}
		case "tool-call": {
			const toolCallPart = {
				type: "tool-call",
				toolCallId: chunk.payload.toolCallId,
				providerMetadata: chunk.payload.providerMetadata,
				providerExecuted: chunk.payload.providerExecuted,
				toolName: chunk.payload.toolName,
				input: chunk.payload.args
			};
			if (chunk.payload.observability) toolCallPart.observability = chunk.payload.observability;
			return toolCallPart;
		}
		case "tool-call-input-streaming-start": return {
			type: "tool-input-start",
			id: chunk.payload.toolCallId,
			toolName: chunk.payload.toolName,
			dynamic: !!chunk.payload.dynamic,
			providerMetadata: chunk.payload.providerMetadata,
			providerExecuted: chunk.payload.providerExecuted,
			...chunk.payload.observability ? { observability: chunk.payload.observability } : {}
		};
		case "tool-call-input-streaming-end": return {
			type: "tool-input-end",
			id: chunk.payload.toolCallId,
			providerMetadata: chunk.payload.providerMetadata
		};
		case "tool-call-delta": return {
			type: "tool-input-delta",
			id: chunk.payload.toolCallId,
			delta: chunk.payload.argsTextDelta,
			providerMetadata: chunk.payload.providerMetadata
		};
		case "step-finish": {
			const { request: _request, providerMetadata: metadataProviderMetadata, ...rest } = chunk.payload.metadata;
			return {
				type: "finish-step",
				response: {
					id: chunk.payload.id || "",
					timestamp: /* @__PURE__ */ new Date(),
					modelId: rest.modelId || "",
					...rest
				},
				usage: chunk.payload.output.usage,
				finishReason: chunk.payload.stepResult.reason,
				providerMetadata: metadataProviderMetadata ?? chunk.payload.providerMetadata
			};
		}
		case "text-delta": return {
			type: "text-delta",
			id: chunk.payload.id,
			text: chunk.payload.text,
			providerMetadata: chunk.payload.providerMetadata
		};
		case "text-end": return {
			type: "text-end",
			id: chunk.payload.id,
			providerMetadata: chunk.payload.providerMetadata
		};
		case "text-start": return {
			type: "text-start",
			id: chunk.payload.id,
			providerMetadata: chunk.payload.providerMetadata
		};
		case "tool-result": return {
			type: "tool-result",
			input: chunk.payload.args,
			toolCallId: chunk.payload.toolCallId,
			providerExecuted: chunk.payload.providerExecuted,
			toolName: chunk.payload.toolName,
			output: chunk.payload.result,
			...chunk.payload.preliminary ? { preliminary: true } : {}
		};
		case "tool-error": return {
			type: "tool-error",
			error: chunk.payload.error,
			input: chunk.payload.args,
			toolCallId: chunk.payload.toolCallId,
			providerExecuted: chunk.payload.providerExecuted,
			toolName: chunk.payload.toolName
		};
		case "abort": return { type: "abort" };
		case "error": return {
			type: "error",
			error: chunk.payload.error
		};
		case "object": return {
			type: "object",
			object: chunk.object
		};
		default:
			if (chunk.type && "payload" in chunk && chunk.payload) return {
				type: chunk.type,
				...chunk.payload || {}
			};
			return;
	}
}
/**
* Type guard to check if usage is in V3 format (nested objects)
*/
function isV3Usage(usage) {
	if (!usage || typeof usage !== "object") return false;
	const u = usage;
	return typeof u.inputTokens === "object" && u.inputTokens !== null && "total" in u.inputTokens && typeof u.outputTokens === "object" && u.outputTokens !== null && "total" in u.outputTokens;
}
/**
* Peel `{ total: { total: … } }` down to the innermost token-detail object.
*
* AI SDK v7 wraps any model that advertises `specificationVersion: 'v2'` in a
* compatibility shim that nests flat usage as `{ total: usage.inputTokens }`.
* Mastra's model router advertises 'v2' but forwards V3/V4 usage untouched, so
* wrapping it with `wrapLanguageModel` nests the already-nested counts once more.
* Only the innermost object carries the real counts and cache/reasoning details;
* the wrapper's own detail fields are `undefined`.
*/
function innermostTokens(tokens) {
	let current = tokens;
	while (typeof current.total === "object" && current.total !== null) current = current.total;
	return current;
}
/**
* Normalizes usage from either V2 (flat) or V3 (nested) format to Mastra's flat format.
* V2 format: { inputTokens: number, outputTokens: number, totalTokens?: number }
* V3 format: { inputTokens: { total, noCache, cacheRead, cacheWrite }, outputTokens: { total, text, reasoning } }
*
* The original usage data is preserved in the `raw` field for advanced use cases.
*/
function getAnthropicCacheCreationUsage(usage, providerMetadata) {
	const anthropic = providerMetadata?.anthropic;
	const cacheCreation = anthropic?.cacheCreation ?? (anthropic?.usage)?.cache_creation ?? usage?.raw?.cache_creation;
	if (typeof cacheCreation !== "object" || cacheCreation === null) return {};
	const details = cacheCreation;
	const cacheCreationInputTokens5m = details.ephemeral_5m_input_tokens ?? details.ephemeral5mInputTokens;
	const cacheCreationInputTokens1h = details.ephemeral_1h_input_tokens ?? details.ephemeral1hInputTokens;
	return {
		...typeof cacheCreationInputTokens5m === "number" && { cacheCreationInputTokens5m },
		...typeof cacheCreationInputTokens1h === "number" && { cacheCreationInputTokens1h }
	};
}
function normalizeUsage(usage, providerMetadata) {
	const cacheCreationUsage = getAnthropicCacheCreationUsage(usage, providerMetadata);
	if (!usage) return {
		inputTokens: void 0,
		outputTokens: void 0,
		totalTokens: void 0,
		reasoningTokens: void 0,
		cachedInputTokens: void 0,
		cacheCreationInputTokens: void 0,
		...cacheCreationUsage,
		raw: void 0
	};
	if (isV3Usage(usage)) {
		const input = innermostTokens(usage.inputTokens);
		const output = innermostTokens(usage.outputTokens);
		const inputTokens = input.total;
		const outputTokens = output.total;
		return {
			inputTokens,
			outputTokens,
			totalTokens: inputTokens !== void 0 && outputTokens !== void 0 ? inputTokens + outputTokens : void 0,
			reasoningTokens: output.reasoning,
			cachedInputTokens: input.cacheRead,
			cacheCreationInputTokens: input.cacheWrite,
			...cacheCreationUsage,
			raw: usage
		};
	}
	const v2Usage = usage;
	return {
		inputTokens: v2Usage.inputTokens,
		outputTokens: v2Usage.outputTokens,
		totalTokens: v2Usage.totalTokens ?? (v2Usage.inputTokens !== void 0 && v2Usage.outputTokens !== void 0 ? v2Usage.inputTokens + v2Usage.outputTokens : void 0),
		reasoningTokens: v2Usage.reasoningTokens,
		cachedInputTokens: v2Usage.cachedInputTokens,
		cacheCreationInputTokens: v2Usage.cacheCreationInputTokens,
		...cacheCreationUsage,
		raw: usage
	};
}
/**
* Type guard to check if a finish reason is V3 format (object with unified/raw properties)
*/
function isV3FinishReason(finishReason) {
	return typeof finishReason === "object" && finishReason !== null && "unified" in finishReason;
}
/**
* Normalize finish reason from either V2/V5 (string) or V3/V6 (object) format to a string.
*
* V2/V5 format: 'stop' | 'length' | 'content-filter' | 'tool-calls' | 'error' | 'other' | 'unknown'
* V3/V6 format: { unified: 'stop' | 'length' | 'content-filter' | 'tool-calls' | 'error' | 'other', raw: string | undefined }
*
* We normalize to the unified string value for internal Mastra use.
* Note: V6 removed 'unknown' and merged it into 'other'.
*/
function normalizeFinishReason(finishReason) {
	let reason = finishReason;
	while (isV3FinishReason(reason)) reason = reason.unified;
	if (!reason) return "other";
	if (reason === "tripwire" || reason === "retry") return reason;
	return reason === "unknown" ? "other" : reason;
}
/**
* Extract the provider's raw finish reason, when the provider supplies one.
*
* V3/V6 providers report both a unified reason and the provider's own string
* (e.g. Google sends `raw: 'MALFORMED_FUNCTION_CALL'` alongside `unified: 'error'`).
* The unified value alone collapses distinct provider outcomes into one bucket,
* so we keep the raw value next to it — mirroring how `normalizeUsage` retains `raw`.
*
* V2/V5 providers only ever send a string, so there is no raw value to preserve.
*/
function extractRawFinishReason(finishReason) {
	let raw;
	let reason = finishReason;
	while (isV3FinishReason(reason)) {
		raw = reason.raw ?? raw;
		reason = reason.unified;
	}
	return raw;
}
// src/stream/caching-transform-stream.ts
/**
* Creates a TransformStream that caches all chunks passing through it.
*
* Use this for workflow streaming where you need resumable streams
* without changing to a PubSub-based architecture.
*
* @example
* ```typescript
* const cache = mastra.getServerCache();
* const { transform, getHistory } = createCachingTransformStream({
*   cache,
*   cacheKey: runId,
* });
*
* // Use the transform stream
* const cachedStream = sourceStream.pipeThrough(transform);
*
* // Later, get cached history for replay
* const history = await getHistory();
* ```
*/
function createCachingTransformStream(options) {
	const { cache, cacheKey, serialize = (x) => x, deserialize = (x) => x } = options;
	const transform = new TransformStream({ transform(chunk, controller) {
		const serialized = serialize(chunk);
		cache.listPush(cacheKey, serialized).catch(() => {});
		controller.enqueue(chunk);
	} });
	const getHistory = async (offset = 0) => {
		return (await cache.listFromTo(cacheKey, offset)).map((item) => deserialize(item));
	};
	const clearCache = async () => {
		await cache.delete(cacheKey);
	};
	return {
		transform,
		getHistory,
		clearCache
	};
}
/**
* Creates a ReadableStream that first emits cached history, then pipes from a live source.
*
* Use this when a client reconnects and needs to receive missed chunks
* before continuing with the live stream.
*
* @example
* ```typescript
* const cache = mastra.getServerCache();
*
* // Get cached history
* const history = await cache.listFromTo(runId, 0);
*
* // Create combined stream
* const stream = createReplayStream({
*   history: history as ChunkType[],
*   liveSource: workflow.stream(),
*   cache,
*   cacheKey: runId,
* });
* ```
*/
function createReplayStream(options) {
	const { history, liveSource, cache, cacheKey, serialize = (x) => x } = options;
	let historyIndex = 0;
	let liveReader = null;
	let historyComplete = false;
	return new ReadableStream({
		async pull(controller) {
			if (!historyComplete) {
				if (historyIndex < history.length) {
					controller.enqueue(history[historyIndex]);
					historyIndex++;
					return;
				}
				historyComplete = true;
				liveReader = liveSource.getReader();
			}
			if (liveReader) try {
				const { done, value } = await liveReader.read();
				if (done) {
					controller.close();
					return;
				}
				if (cache && cacheKey) {
					const serialized = serialize(value);
					cache.listPush(cacheKey, serialized).catch(() => {});
				}
				controller.enqueue(value);
			} catch (error) {
				controller.error(error);
			}
		},
		cancel(reason) {
			if (liveReader) return liveReader.cancel(reason);
			return liveSource.cancel(reason);
		}
	});
}
/**
* Helper to create a caching transform and get history in one call.
*
* This is the recommended way to add caching to workflow streams.
*
* @example
* ```typescript
* const { pipeThrough, getHistory, clearCache } = withStreamCaching({
*   cache: mastra.getServerCache(),
*   cacheKey: runId,
* });
*
* // Apply caching to a stream
* const cachedStream = workflow.fullStream.pipeThrough(pipeThrough());
*
* // On reconnect, get history and create replay stream
* const history = await getHistory();
* const replayStream = createReplayStream({
*   history,
*   liveSource: workflow.resumeStream(),
* });
* ```
*/
function withStreamCaching(options) {
	const { cache, cacheKey, serialize, deserialize } = options;
	return {
		pipeThrough: () => {
			const { transform } = createCachingTransformStream({
				cache,
				cacheKey,
				serialize,
				deserialize
			});
			return transform;
		},
		getHistory: async (offset = 0) => {
			const deserializeFn = deserialize ?? ((x) => x);
			return (await cache.listFromTo(cacheKey, offset)).map((item) => deserializeFn(item));
		},
		clearCache: async () => {
			await cache.delete(cacheKey);
		}
	};
}
// src/stream/smooth-stream.ts
const CHUNKING_PATTERNS = {
	word: /\S+\s+/m,
	line: /\n+/m
};
const wait = (delayInMs) => new Promise((resolve) => setTimeout(resolve, delayInMs));
function createChunkDetector(chunking) {
	if (typeof chunking === "object" && "segment" in chunking && typeof chunking.segment === "function") return (buffer) => {
		if (!buffer) return null;
		return chunking.segment(buffer)[Symbol.iterator]().next().value?.segment || null;
	};
	if (typeof chunking === "function") return (buffer) => {
		const match = chunking(buffer);
		if (match == null) return null;
		if (!match.length) throw new TypeError("The chunking function must return a non-empty string.");
		if (!buffer.startsWith(match)) throw new TypeError("The chunking function must return a prefix of the buffered text.");
		return match;
	};
	const pattern = typeof chunking === "string" ? CHUNKING_PATTERNS[chunking] : chunking;
	if (!(pattern instanceof RegExp)) throw new TypeError("chunking must be \"word\", \"line\", a RegExp, an Intl.Segmenter, or a chunk detector function.");
	return (buffer) => {
		pattern.lastIndex = 0;
		const match = pattern.exec(buffer);
		if (!match) return null;
		const detected = buffer.slice(0, match.index) + match[0];
		if (!detected.length) throw new TypeError("The chunking RegExp must match a non-empty string.");
		return detected;
	};
}
/**
* Creates a transform stream that buffers text and reasoning deltas and emits
* them in consistent, delayed chunks. Other stream parts pass through without
* modification after any buffered content has been emitted.
*
* @experimental This API may change in a future release.
*/
function smoothStream({ delayInMs = 10, chunking = "word" } = {}) {
	const detectChunk = createChunkDetector(chunking);
	let buffer = "";
	let bufferedChunk;
	let bufferedMetadata;
	let bufferedProviderMetadata;
	const enqueueBufferedText = (controller, text) => {
		if (!bufferedChunk || !text && !(bufferedMetadata !== void 0 || bufferedProviderMetadata !== void 0)) return;
		const { metadata: _metadata, ...chunkWithoutMetadata } = bufferedChunk;
		const { providerMetadata: _providerMetadata, ...payloadWithoutProviderMetadata } = bufferedChunk.payload;
		controller.enqueue({
			...chunkWithoutMetadata,
			...bufferedMetadata !== void 0 ? { metadata: bufferedMetadata } : {},
			payload: {
				...payloadWithoutProviderMetadata,
				...bufferedProviderMetadata !== void 0 ? { providerMetadata: bufferedProviderMetadata } : {},
				text
			}
		});
		bufferedMetadata = void 0;
		bufferedProviderMetadata = void 0;
	};
	const flushBuffer = (controller) => {
		enqueueBufferedText(controller, buffer);
		buffer = "";
		bufferedChunk = void 0;
		bufferedMetadata = void 0;
		bufferedProviderMetadata = void 0;
	};
	return new TransformStream$1({
		async transform(chunk, controller) {
			if (chunk.type !== "text-delta" && chunk.type !== "reasoning-delta") {
				flushBuffer(controller);
				controller.enqueue(chunk);
				return;
			}
			if (bufferedChunk && (chunk.type !== bufferedChunk.type || chunk.payload.id !== bufferedChunk.payload.id)) flushBuffer(controller);
			buffer += chunk.payload.text;
			bufferedChunk = chunk;
			bufferedMetadata = chunk.metadata ?? bufferedMetadata;
			bufferedProviderMetadata = chunk.payload.providerMetadata ?? bufferedProviderMetadata;
			let match;
			while ((match = detectChunk(buffer)) != null) {
				enqueueBufferedText(controller, match);
				buffer = buffer.slice(match.length);
				if (delayInMs !== null) await wait(delayInMs);
			}
		},
		flush(controller) {
			flushBuffer(controller);
		}
	});
}
export { RunJournal as $, normalizeModelOutput as $t, findOwnModelStepSpan as A, materializeWorkflowRun as At, REPROCESS_PART_KEY as B, getThreadOMMetadata as Bt, getResponseFormat as C, safeError as Cn, getSnapshotMemoryInfo as Ct, ProcessorState as D, isStateCheckpointDue as Dt, ProcessorRunner as E, applyStateColumnsWrite as Et, ProviderHistoryCompat as F, applyStatePatch as Ft, summarizeProcessorResultForSpan as G, commitToolResult as Gt, withoutHeldContent as H, isThreadTitlePinned as Ht, anthropicToolIdFormat as I, diffState as It, resolveProcessorSpanAttributes as J, latestProcessedModelOutput as Jt, summarizeProcessorToolsForSpan as K, computeModelOutputProviderMetadata as Kt, cerebrasStripReasoningContent as L, diffStateAsJson as Lt, isTrailingAssistantGuardContinuation as M, stateBaseOf as Mt, needsTrailingAssistantGuard as N, stateColumnsWrite as Nt, endOutputStreamSpanAtStepEnd as O, latestStepResults as Ot, removeTrailingAssistantGuardContinuations as P, summarizeStepResult as Pt, createProcessorSendSignal as Q, withAgentWorkflowToolMarker as Qt, openaiOrphanItemId as R, patchState as Rt, asJsonSchema as S, safeEnqueue as Sn, getStepResultAsync as St, OUTPUT_STREAM_HOOK_DURATION_KEY_PREFIX as T, createRunScopeKey as Tn, STEP_RESULT_SUMMARY_FIELDS as Tt, summarizeActiveToolsForSpan as U, parseMemoryRequestContext as Ut, takeHeldParts as V, isObservationalMemoryEnabled as Vt, summarizeProcessorModelForSpan as W, setThreadOMMetadata as Wt, toProcessorSpanPhase as X, resolveModelOutputAfterToolResultProcessors as Xt, resolveProcessorSpanName as Y, readModelOutput as Yt, PROCESSOR_LATE_SIGNAL_SINK as Z, snapshotToolResult as Zt, stampChunkProducedAt as _, raceAgainstAbort as _n, resolveTemplate as _t, convertFullStreamChunkToMastra as a, supportedLanguageModelSpecifications as an, loadStepResults as at, escapeUnescapedControlCharsInJsonStrings as b, MastraModelInput as bn, validateTemplate as bt, WorkflowRunOutput as c, applyStateSignal as cn, residentStepResultsLoader as ct, MastraModelOutput as d, MastraTimeoutError as dn, collectMappingStepRefs as dt, validationErrorModelOutput as en, buildStepResultAccessors as et, createDestructurableOutput as f, createTimeoutAbortSignal as fn, collectPredicateStepRefs as ft, getChunkProducedAt as g, isMastraTimeoutError as gn, collectTemplateStepIds as gt, resolveProcessorWriterMessageId as h, guardStreamWithAbort as hn, stepRefId as ht, withStreamCaching as i, resolveThreadIdFromArgs as in, lazyStepResults as it, runner_exports as j, pickStateKeys as jt, endOutputStreamSpanOutsideStep as k, materializeState as kt, TripWire as l, DEADLINE_SAVE_CLAIM_HOLD_MS as ln, storageV2StepResultAccessors as lt, resolveOutputMessageSkippingCompletionChecks as m, guardStreamUntilMatch as mn, resolveStepOutputs as mt, createCachingTransformStream as n, isSupportedLanguageModel as nn, hydrateStepResults as nt, convertMastraChunkToAISDKv5 as o, tryGenerateWithJsonFallback as on, loadedStepResults as ot, persistProcessorDataChunk as p, getAbortReason as pn, predicateReadsState as pt, summarizeToolChoiceForSpan as q, hasToolResultProcessor as qt, createReplayStream as r, resolveSuspendedToolRunId as rn, isStepResultStub as rt, MastraAgentNetworkStream as s, tryStreamWithJsonFallback as sn, residentStepResults as st, smoothStream as t, isProcessorWorkflow as tn, getHydratedStepResult as tt, getModelOutputForTripwire as u, DEADLINE_SAVE_WAIT_MS as un, stubStepResult as ut, markChunkOutputProcessed as v, settledOrElapsed as vn, templateReadsState as vt, isSignalChunkExcluded as w, createRunScope as wn, STATE_CHECKPOINT_PATCHES as wt, isStructuredOutputError as x, safeClose as xn, getStepResult as xt, createOutputHandler as y, convertFullStreamChunkToUIMessageStream as yn, traverseMappingPath as yt, FLUSH_HELD_PARTS_KEY as z, TITLE_PINNED_THREAD_METADATA_KEY as zt };

//# sourceMappingURL=stream-sJ8FGaH9.js.map