UNPKG

@mastra/core

Version:
2,011 lines • 82.1 kB
const require_error = require("./error-D90lJ6M7.cjs");
const require_tool = require("./tool-BMl4Lb5_.cjs");
const require_ee_iTj2bRDt = require("./ee-iTj2bRDt-D3-QLGDF.cjs");
const require_background_tasks = require("./background-tasks-CVddYnZ1.cjs");
const require_base = require("./base-BIzR1D3_.cjs");
const require_observability = require("./observability-fxVZWiFW.cjs");
const require_utils = require("./utils-D-eNsgDM.cjs");
const require_storage = require("./storage-CfG0I2aF.cjs");
const require_request_context = require("./request-context-D9RXYCy8.cjs");
const require_toolchecks = require("./toolchecks-BSANSUXW.cjs");
const require_zod_utils = require("./zod-utils-Cl5jw5N_.cjs");
const require_stream = require("./stream-BGbj9jAU.cjs");
let zod_v4 = require("zod/v4");
let crypto = require("crypto");
let _mastra_schema_compat = require("@mastra/schema-compat");
let _mastra_schema_compat_json_to_zod = require("@mastra/schema-compat/json-to-zod");
let _mastra_schema_compat_schema = require("@mastra/schema-compat/schema");
// src/agent/run-lease-fence.ts
/**
* Checks registered by the thread runtime for runs that hold a cross-process thread
* lease. A tool awaits its run's check before it executes, so a run whose lease was
* taken over stops before it acts beside its successor instead of at its next renewal.
*/
const fences = /* @__PURE__ */ new Map();
function setRunLeaseFence(runId, fence) {
	fences.set(runId, fence);
}
/**
* Another runtime in the process (for example a second Mastra instance) may have registered
* the same run id since, so a run that ends clears only its own check.
*/
function clearRunLeaseFence(runId, fence) {
	if (fences.get(runId) === fence) fences.delete(runId);
}
/** Throws when the run no longer holds its thread lease. */
async function verifyRunLease(runId) {
	if (runId) await fences.get(runId)?.();
}
/**
* The steps (model requests and tool calls) each run has running now, keyed by the object that run's caller declares
* as its owner: the abort signal the thread runtime prepared for it, or a durable run's registry entry. It has to be
* that object and not a signal derived from it further down — the runtime only knows the one it prepared, so a derived
* signal would silently read as idle. Runs that share a run id, agent or thread never share one.
*/
const runningSteps = /* @__PURE__ */ new WeakMap();
/** When each run's last step settled, so the moment between one step and the next doesn't read as idle. */
const lastStepSettledAt = /* @__PURE__ */ new WeakMap();
/** Marks a step of the run this object owns as running. Call the returned function once the step has settled. */
function startRunStep(owner) {
	if (!owner) return () => {};
	const entry = runningSteps.get(owner) ?? {
		count: 0,
		onSettled: []
	};
	entry.count++;
	runningSteps.set(owner, entry);
	let settled = false;
	return () => {
		if (settled) return;
		settled = true;
		if (--entry.count > 0) return;
		if (runningSteps.get(owner) === entry) runningSteps.delete(owner);
		lastStepSettledAt.set(owner, Date.now());
		for (const callback of entry.onSettled) callback();
	};
}
/** Calls `callback` once no step of the run this object owns is running: right away when none is. */
function whenRunStepsSettle(owner, callback) {
	const entry = owner ? runningSteps.get(owner) : void 0;
	if (entry) entry.onSettled.push(callback);
	else callback();
}
/** Whether a step of the run this object owns is running right now. */
function hasRunningRunStep(owner) {
	return !!owner && runningSteps.has(owner);
}
/**
* Whether the run this object owns has a step running, or had one settle within the last `withinMs`. A run that was
* aborted has none worth waiting for, even while a step is still winding down.
*/
function isRunStepActive(owner, withinMs) {
	if (!owner) return false;
	const signal = owner instanceof AbortSignal ? owner : owner.abortSignal;
	if (signal instanceof AbortSignal && signal.aborted) return false;
	if (runningSteps.has(owner)) return true;
	const settledAt = lastStepSettledAt.get(owner);
	return settledAt !== void 0 && Date.now() - settledAt < withinMs;
}
// src/loop/shared/tool-abort-grace.ts
const TOOL_ABORT_NOTICE = "Tool execution was aborted while running. The tool may still be running and its effects are unknown. Check its status before retrying.";
// src/loop/workflows/agentic-execution/eager-tool-execution.ts
/**
* Marker placed on the workflow execution context when `toolCallStep` is invoked
* eagerly from the LLM execution step. Its presence tells the step not to look
* for (and await) an eager execution of itself.
*/
const EAGER_TOOL_EXECUTION_MARKER = Symbol("eager-tool-execution");
/**
* Carries the coordinator's per-execution abort signal into `toolCallStep`. A dedicated
* key rather than the step's own `abortSignal` argument, so no other caller's behaviour
* changes: the step combines this with the run signal only when it is present.
*/
const EAGER_TOOL_ABORT_SIGNAL = Symbol("eager-tool-abort-signal");
/**
* Carries a per-dispatch bailout record into `toolCallStep`, so a call that turns out to
* need suspension can mark itself unusable *before* throwing.
*
* The throw alone is not fail-safe: it unwinds through the tool's own body, and a tool
* that wraps its work in try/catch swallows it and returns normally. The step would then
* resolve an ordinary-looking envelope and the foreach would adopt a result for a call
* that asked to suspend. The dispatcher re-reads this record after the step settles and
* converts any marked settlement back into a rejection.
*
* One record per dispatch, so a later attempt reusing the same toolCallId cannot observe
* a previous attempt's bailout.
*/
const EAGER_TOOL_BAILOUT = Symbol("eager-tool-bailout");
/** Brands errors whose eager attempt produced no adoptable result. */
const EAGER_NOT_EXECUTED = Symbol("eager-tool-not-executed");
/** Brands a bailout whose eager attempt already announced `onInputAvailable`. */
const EAGER_INPUT_ANNOUNCED = Symbol("eager-tool-input-announced");
/** Carries a runtime suspension's intent out of the attempt that was abandoned for it. */
const EAGER_SUSPENSION_INTENT = Symbol("eager-tool-suspension-intent");
/**
* Starts eligible server-side tool executions while the model is still streaming,
* and hands the in-flight promise to `toolCallStep` so the existing foreach remains
* the owner of result ordering and history.
*
* The permit limit is read through `getConcurrency` rather than copied, because
* `map-tool-calls` recomputes the effective limit per step (an approval- or
* suspend-capable tool entering the step forces the foreach down to 1). Reading it
* late keeps one source of truth for the limit.
*/
var EagerToolExecutionCoordinator = class {
	getConcurrency;
	#executions = /* @__PURE__ */ new Map();
	#queued = [];
	#controllers = /* @__PURE__ */ new Map();
	/**
	* Results of executions that finished but have not been adopted yet. Held so that an
	* attempt thrown away mid-stream can still surrender the work it already did, instead
	* of the side effect happening twice.
	*/
	#completed = /* @__PURE__ */ new Map();
	/**
	* Calls whose eager attempt already ran the body up to a runtime `suspend()`. Retrying
	* the model would re-emit the call and run that pre-suspend work a second time, so an
	* attempt holding one of these must not be retried.
	*/
	#suspended = /* @__PURE__ */ new Set();
	/** Executions that have started and not yet settled, so a discard can wait them out. */
	#inFlight = /* @__PURE__ */ new Set();
	#running = 0;
	#dispatchSequence = 0;
	#stopped = false;
	#stoppedPermanently = false;
	#abortSettlement;
	constructor(getConcurrency) {
		this.getConcurrency = getConcurrency;
	}
	/**
	* Hand over the in-flight eager execution for a tool call, if one was started,
	* and forget it. Taking rather than reading keeps adoption exactly-once: a later
	* iteration that reuses the same `toolCallId` executes again instead of adopting
	* the previous iteration's settled result.
	*/
	take(toolCallId) {
		const execution = this.#executions.get(toolCallId);
		this.#executions.delete(toolCallId);
		this.#completed.delete(toolCallId);
		this.#suspended.delete(toolCallId);
		return execution?.promise;
	}
	/**
	* Start an eager execution keyed by canonical `toolCallId`. Returns false when the
	* coordinator is stopped or the id is already in flight, so a replayed or duplicate
	* id within the same step can never execute twice.
	*/
	start(toolCallId, execute, call) {
		if (this.#stopped || this.#executions.has(toolCallId)) return false;
		const sequence = this.#dispatchSequence++;
		const controller = new AbortController();
		const ownershipToken = {};
		let holdsPermit = false;
		const releasePermit = () => {
			if (!holdsPermit) return;
			holdsPermit = false;
			this.#running--;
			this.#queued.shift()?.run();
		};
		const promise = new Promise((resolve, reject) => {
			const run = () => {
				this.#running++;
				holdsPermit = true;
				this.#controllers.set(toolCallId, {
					controller,
					releasePermit,
					work: call ? {
						toolCallId,
						...call,
						sequence,
						incomplete: true
					} : void 0
				});
				const inFlight = execute(controller.signal).then((result) => {
					const envelope = result;
					const outcome = !(!!envelope && typeof envelope === "object") ? void 0 : envelope.aborted ? { result: TOOL_ABORT_NOTICE } : "error" in envelope ? { error: envelope.error } : "result" in envelope ? { result: envelope.result } : void 0;
					if (call && outcome && !controller.signal.aborted && this.#executions.get(toolCallId)?.token === ownershipToken) this.#completed.set(toolCallId, {
						toolCallId,
						toolName: call.toolName,
						args: call.args,
						...outcome,
						sequence
					});
					resolve(result);
				}, (error) => {
					if (eagerToolCallSuspensionIntent(error) && !controller.signal.aborted && this.#executions.get(toolCallId)?.token === ownershipToken) this.#suspended.add(toolCallId);
					reject(error);
				}).finally(() => {
					if (this.#controllers.get(toolCallId)?.controller === controller) this.#controllers.delete(toolCallId);
					this.#inFlight.delete(inFlight);
					releasePermit();
				});
				this.#inFlight.add(inFlight);
			};
			if (this.#running < this.getConcurrency()) run();
			else this.#queued.push({
				toolCallId,
				run,
				cancel: () => reject(new EagerToolExecutionNotRun(`"${toolCallId}" was cancelled before it started`))
			});
		});
		promise.catch(() => {});
		this.#executions.set(toolCallId, {
			promise,
			token: ownershipToken
		});
		return true;
	}
	/** Number of executions currently running. Exposed for assertions in tests. */
	get running() {
		return this.#running;
	}
	/**
	* Stop dispatching and drop everything that has not started.
	*
	* Without `cancelRunning`, executions already in flight are left alone: the step that
	* follows an unsafe *finish* still runs its foreach, so their results are adopted
	* exactly as the default pipeline would have produced them.
	*
	* With `cancelRunning`, the surrounding model attempt is being thrown away entirely.
	* Those executions are aborted *and* forgotten, so nothing downstream can adopt work
	* belonging to an attempt that no longer exists — including a retry that happens to
	* reuse the same toolCallId, which must execute fresh. Their concurrency permits are
	* released at the same moment: abort is cooperative, and a tool that declines to
	* observe it must not stall the attempt that replaced it.
	*/
	stop({ permanent = false, cancelRunning = false, keepIncomplete = false } = {}) {
		this.#stopped = true;
		this.#stoppedPermanently ||= permanent;
		for (const queued of this.#queued.splice(0)) {
			this.#executions.delete(queued.toolCallId);
			queued.cancel();
		}
		if (!cancelRunning) return [];
		const completed = [...this.#completed.values()].sort((a, b) => a.sequence - b.sequence);
		this.#completed.clear();
		{
			const cancelled = [...this.#controllers];
			this.#controllers.clear();
			for (const [toolCallId, running] of cancelled) {
				if (keepIncomplete && running.work && this.#executions.has(toolCallId)) completed.push(running.work);
				this.#executions.delete(toolCallId);
				running.controller.abort();
				running.releasePermit();
			}
		}
		return completed.sort((a, b) => a.sequence - b.sequence);
	}
	/** Start once at run abort, including when the foreach is already awaiting adoption. */
	settleOnAbort() {
		this.#abortSettlement ??= (async () => {
			this.stop({ permanent: true });
			const deadline = new AbortController();
			const timer = setTimeout(() => deadline.abort(), 250);
			try {
				await this.settleRunning(deadline.signal);
				this.carryDiscardedWork(this.stop({
					permanent: true,
					cancelRunning: true,
					keepIncomplete: true
				}));
			} finally {
				clearTimeout(timer);
			}
		})();
		return this.#abortSettlement;
	}
	/**
	* Wait until every execution that has started has settled, however it settles. Called
	* with dispatch already stopped, so nothing new starts meanwhile.
	*
	* A discarded attempt waits here instead of cancelling: a running tool may already have
	* done its side effect, and cancelling it would leave the replacement attempt free to
	* call it again. Settled, its outcome is committed and the replacement sees it as done.
	* An abort of the run stops the wait; the abort exit then waits the work out itself.
	*/
	async settleRunning(signal) {
		if (signal?.aborted) return;
		let onAbort;
		const aborted = signal ? new Promise((resolve) => {
			onAbort = resolve;
			signal.addEventListener("abort", onAbort, { once: true });
		}) : void 0;
		try {
			while (this.#inFlight.size && !signal?.aborted) {
				const settled = Promise.allSettled([...this.#inFlight]);
				await (aborted ? Promise.race([settled, aborted]) : settled);
			}
		} finally {
			if (onAbort) signal.removeEventListener("abort", onAbort);
		}
	}
	/**
	* Open a new model turn. A stop caused by a bad turn is scoped to that turn — the
	* next one is a fresh model call and may dispatch again — but a caller abort is
	* permanent. Executions from the previous turn that nothing ever adopted are dropped
	* here so the map cannot grow across a long loop.
	*/
	beginTurn() {
		if (this.#stoppedPermanently) return;
		this.#stopped = false;
		this.#completed.clear();
		this.#suspended.clear();
		this.#executions.clear();
	}
	/** Whether a call in this attempt has already run up to a runtime `suspend()`. */
	get hasSuspendedHandback() {
		return this.#suspended.size > 0;
	}
	/** Ids currently held for adoption. Exposed for assertions in tests. */
	get pendingAdoptions() {
		return this.#executions.size;
	}
	/**
	* Work surrendered by a discarded attempt, held until a replacement attempt actually
	* starts. Kept on the coordinator rather than in the step's own scope because a retry
	* re-enters the step as a fresh invocation: anything local to the dying attempt is gone
	* by the time its replacement exists. Never committed if no replacement comes — a run
	* that dies must not leave an assistant turn the caller never saw streamed.
	*/
	#carried = [];
	/**
	* What has been written into the conversation, by the message id it was written under.
	* Held so that a path which deletes that message can hand the work back to the carry
	* buffer instead of destroying the only record of a side effect that happened.
	*
	* Accumulated per id rather than kept as "the last batch": a chain of failing attempts
	* commits under the same id more than once, and forgetting the earlier batch would let
	* a single `removeByIds` delete work nothing could recover.
	*
	* Entries are only removed by the message they describe being removed, so a run that
	* never does that keeps them until it ends. It holds one entry per attempt that died
	* with finished work, which retry limits bound to a handful.
	*/
	#committed = /* @__PURE__ */ new Map();
	/**
	* Hold a discarded attempt's finished work until a replacement attempt starts. Each
	* batch is sorted into model-call order as it arrives, and batches keep the order they
	* were discarded in. The dispatch counter happens to be run-global, so sorting the whole
	* buffer would agree today — sorting per batch keeps that coincidence from becoming
	* load-bearing.
	*/
	carryDiscardedWork(work) {
		this.#carried.push(...[...work].sort((a, b) => a.sequence - b.sequence));
	}
	/** Drain the carried work for committing into the conversation. */
	takeCarriedWork() {
		return this.#carried.splice(0);
	}
	/** Remember what was written where, so a later removal of that message can undo it. */
	recordCommittedWork(messageId, work) {
		const existing = this.#committed.get(messageId);
		if (existing) existing.push(...work);
		else this.#committed.set(messageId, [...work]);
	}
	/**
	* Undo a commit whose message is being removed: the work goes back into the carry
	* buffer so the next replacement attempt writes it again. Without this, a processor
	* retry that deletes the attempt's messages would also delete the only record that a
	* tool already ran, and the tool would run a second time.
	*
	* What comes back goes on the end of whatever is already carried, so the resulting
	* order is "work already written once, then work never written".
	*/
	recarryCommittedWork(messageId) {
		const committed = this.#committed.get(messageId);
		if (!committed) return false;
		this.#committed.delete(messageId);
		this.#carried.push(...committed);
		return true;
	}
	/** Discarded work awaiting a replacement attempt. Exposed for assertions in tests. */
	get carriedWork() {
		return this.#carried;
	}
};
/**
* Raised when an eager attempt ends without producing an adoptable result, so the
* normal foreach path must handle the call instead of surfacing the failure. That
* happens when the attempt is cancelled while still queued, and when an eager call
* reaches a suspend/bail it should have been excluded from. In the second case the
* tool's body has already started; only its *result* is discarded.
*/
var EagerToolExecutionNotRun = class extends Error {
	[EAGER_NOT_EXECUTED] = true;
	[EAGER_INPUT_ANNOUNCED];
	[EAGER_SUSPENSION_INTENT];
	constructor(reason, options) {
		super(`Eager tool execution did not run: ${reason}`);
		this.name = "EagerToolExecutionNotRun";
		this[EAGER_INPUT_ANNOUNCED] = options?.inputAvailableCalled === true;
		this[EAGER_SUSPENSION_INTENT] = options?.suspension;
	}
};
/**
* The suspension intent behind this rejection, when the eager attempt was abandoned
* because the tool called `suspend()` at runtime. The adopting foreach iteration uses
* it to raise the real suspension rather than running the tool body a second time.
*/
function eagerToolCallSuspensionIntent(error) {
	let current = error;
	for (let depth = 0; depth < 10 && typeof current === "object" && current !== null; depth++) {
		if (EAGER_SUSPENSION_INTENT in current) return current[EAGER_SUSPENSION_INTENT];
		current = current.cause;
	}
}
/**
* True when the eager attempt behind this rejection already ran the tool's
* `onInputAvailable`. The foreach re-runs `execute` from the top, so it has to skip
* the announcement it already produced: one call per adoption, the same count the
* call gets without eager dispatch. (An attempt abandoned in flight is a separate
* matter: it is never adopted, so the replacement attempt announces again.)
*/
function eagerToolCallAlreadyAnnouncedInput(error) {
	let current = error;
	for (let depth = 0; depth < 10 && typeof current === "object" && current !== null; depth++) {
		if (EAGER_INPUT_ANNOUNCED in current) return Boolean(current[EAGER_INPUT_ANNOUNCED]);
		current = current.cause;
	}
	return false;
}
/**
* True when an eager execution ended without an adoptable result, meaning the normal
* foreach path must handle the call instead of surfacing the failure. The tool body
* may have started (a runtime suspension gets here); only its result is discarded.
*/
function eagerToolCallDidNotExecute(error) {
	let current = error;
	for (let depth = 0; depth < 10 && typeof current === "object" && current !== null; depth++) {
		if (EAGER_NOT_EXECUTED in current) return true;
		current = current.cause;
	}
	return false;
}
/**
* Whitelist deciding what may be executed before the model has finished streaming.
*
* This is deliberately an allow-list rather than a list of exclusions. An eager
* execution that turns out to need approval, suspension or a background dispatch has
* already emitted chunks and written metadata by the time it discovers that, and none
* of it can be taken back — so the only safe posture is to start nothing whose shape
* is not provably a plain server-side call.
*
* Eligible means: a resolved, active, locally-executable Mastra tool, with complete
* arguments, that cannot suspend (mirroring the `isResumableTool` rule in
* `tool-builder/builder.ts`), cannot require approval, and is not being dispatched as
* a background task.
*/
function isEagerlyExecutableToolCall({ toolCall, tool, activeTools, requireToolApproval, autoResumeSuspendedTools, hasPostStreamProcessor, hasToolResultProcessor, isProviderTool, getNeedsApprovalFn, backgroundTaskManager, agentBackgroundConfig }) {
	if (hasPostStreamProcessor) return false;
	if (hasToolResultProcessor) return false;
	if (!toolCall.args || typeof toolCall.args !== "object") return false;
	if ("_background" in toolCall.args) return false;
	if (backgroundTaskManager && require_background_tasks.isToolBackgroundEligible({
		toolName: toolCall.toolName,
		toolConfig: tool?.backgroundConfig,
		agentConfig: agentBackgroundConfig
	})) return false;
	if (toolCall.providerExecuted) return false;
	if (!tool || isProviderTool(tool)) return false;
	if (!("execute" in tool) || typeof tool.execute !== "function") return false;
	if (activeTools && !activeTools.includes(toolCall.toolName)) return false;
	if (autoResumeSuspendedTools) return false;
	if (toolCall.toolName.startsWith("agent-") || toolCall.toolName.startsWith("workflow-")) return false;
	if ("hasSuspendSchema" in tool && Boolean(tool.hasSuspendSchema)) return false;
	if (requireToolApproval === true || typeof requireToolApproval === "function") return false;
	if ("requireApproval" in tool && Boolean(tool.requireApproval)) return false;
	if (getNeedsApprovalFn(tool)) return false;
	return true;
}
// src/tools/tool-builder/builder.ts
const resumeFieldsZodShape = {
	suspendedToolCallId: zod_v4.z.string().describe("The toolCallId of the suspended tool to resume").nullable().optional(),
	suspendedToolRunId: zod_v4.z.string().describe("The runId of the suspended tool").nullable().optional(),
	resumeData: zod_v4.z.any().describe("The resumeData object created from the resumeSchema of suspended tool").optional()
};
/**
* Merge two RequestContexts so non-serializable values survive the evented
* workflow engine's toJSON/reconstruct cycle.
*
* The evented engine serialises the RequestContext via `toJSON()` when
* publishing workflow events.  Values that fail `JSON.stringify` (functions,
* objects with circular references — e.g. the `controller` context) are silently
* dropped.  The reconstructed RC handed to steps is therefore *degraded*.
*
* Tools, however, also hold a reference to the *original* RC captured during
* tool conversion (the "closure" RC).  By merging both — exec first, then
* closure on top — keys that survived serialisation are preserved while
* non-serializable keys from the closure (like `controller`) are restored.
*/
/**
* Detect RequestContext-like objects structurally. We cannot use `instanceof`
* here because duplicate copies of @mastra/core may be loaded in the same
* process (bundlers, monorepos) and the prototype identity is not guaranteed.
*/
function isRequestContextLike(value) {
	if (!value || typeof value !== "object") return false;
	const rc = value;
	return typeof rc.get === "function" && typeof rc.set === "function" && typeof rc.entries === "function" && typeof rc.size === "function";
}
function mergeRequestContexts(closureRC, execRC) {
	if (closureRC && closureRC === execRC) return closureRC;
	if (!closureRC && !execRC) return new require_request_context.RequestContext();
	if (!closureRC) return isRequestContextLike(execRC) ? execRC : new require_request_context.RequestContext();
	if (!execRC || !isRequestContextLike(execRC) || execRC.size() === 0) return closureRC;
	const merged = new require_request_context.RequestContext();
	for (const [key, value] of execRC.entries()) merged.set(key, value);
	for (const [key, value] of closureRC.entries()) merged.set(key, value);
	return merged;
}
/**
* Detect Zod v4 schemas. Zod v3 stores the type name as `_def.typeName`
* (e.g. "ZodObject"); Zod v4 stores it as `_def.type` (e.g. "object"). We
* cannot use `instanceof` here because both Zod versions may be loaded in the
* same process and the prototype identity is not guaranteed.
*/
function isZodV4Schema(schema) {
	const def = schema?._def;
	return !!def && typeof def.type === "string" && !def.typeName;
}
/**
* Build a Standard Schema that:
*  - exposes the spliced JSON Schema (with `_background`/`suspendedToolRunId`/
*    `resumeData` properties added) so provider compat layers see the override
*    fields when serializing the tool to an LLM, and
*  - delegates runtime `validate` to the *original* schema so Zod v3
*    `.transform()` / `.default()` / `.refine()` and other Standard Schema
*    parsing behavior still run before `execute()` sees the args.
*
* Injected override keys (`_background`, `suspendedToolRunId`, `resumeData`)
* are stripped from the input before delegating, then merged back into the
* validated value so the inner `execute()` still receives them — matching the
* Zod v4 `.extend()` path's behavior.
*
* If the original schema has no `~standard.validate` (e.g. a raw JSON Schema
* with no Standard Schema wrapper), fall back to validating against the
* spliced JSON Schema directly.
*/
function buildJsonOverrideSchema(originalSchema, splicedJsonSchema, injectedKeys) {
	const fallback = (0, _mastra_schema_compat_schema.toStandardSchema)(splicedJsonSchema);
	const original = originalSchema;
	const originalValidate = original?.["~standard"]?.validate?.bind(original["~standard"]);
	const splicedProperties = splicedJsonSchema && typeof splicedJsonSchema === "object" && "properties" in splicedJsonSchema ? splicedJsonSchema.properties ?? {} : {};
	const injectedProperties = {};
	for (const key of injectedKeys) if (splicedProperties[key] !== void 0) injectedProperties[key] = splicedProperties[key];
	const injectedValidator = (0, _mastra_schema_compat_schema.toStandardSchema)({
		type: "object",
		properties: injectedProperties,
		additionalProperties: false
	});
	const stripInjected = (input) => {
		if (!input || typeof input !== "object" || Array.isArray(input)) return {
			stripped: input,
			injected: {}
		};
		const injected = {};
		const stripped = {};
		for (const [k, v] of Object.entries(input)) if (injectedKeys.includes(k)) injected[k] = v;
		else stripped[k] = v;
		return {
			stripped,
			injected
		};
	};
	const validate = (input) => {
		const { stripped, injected } = stripInjected(input);
		const baseResult = originalValidate ? originalValidate(stripped) : fallback["~standard"].validate(stripped);
		const injectedResult = injectedValidator["~standard"].validate(injected);
		const combine = (base, inj) => {
			const baseIssues = "issues" in base ? base.issues ?? [] : [];
			const injIssues = "issues" in inj ? inj.issues ?? [] : [];
			if (baseIssues.length || injIssues.length) return { issues: [...baseIssues, ...injIssues] };
			const baseValue = base.value;
			const injValue = inj.value;
			if (baseValue && typeof baseValue === "object" && !Array.isArray(baseValue)) {
				const injMerged = injValue && typeof injValue === "object" && !Array.isArray(injValue) ? injValue : injected;
				return { value: {
					...baseValue,
					...injMerged
				} };
			}
			return base;
		};
		const baseIsPromise = baseResult && typeof baseResult.then === "function";
		const injIsPromise = injectedResult && typeof injectedResult.then === "function";
		if (baseIsPromise || injIsPromise) return Promise.all([baseResult, injectedResult]).then(([b, i]) => combine(b, i));
		return combine(baseResult, injectedResult);
	};
	return { "~standard": {
		version: 1,
		vendor: "mastra-json-override",
		validate,
		jsonSchema: fallback["~standard"].jsonSchema
	} };
}
/**
* A remote MCP tool's error text is written by the server and can echo the submitted arguments
* (Issue #29318). The model still receives it; the tracked exception records only its id.
* Covers every MCPClient tool failure (execution, task failure, cancellation, polling).
*/
function trackableToolError(mastraError, err, model) {
	const id = err?.id;
	if (typeof id !== "string" || !id.startsWith("MCP_CLIENT_TOOL_")) return mastraError;
	return new require_error.MastraError({
		id: mastraError.id,
		domain: mastraError.domain,
		category: mastraError.category,
		text: `Remote tool failed (${id})`,
		details: {
			errorMessage: id,
			model
		}
	});
}
var CoreToolBuilder = class extends require_base.MastraBase {
	originalTool;
	options;
	logType;
	/**
	* Builder-local copy of the user's input schema with the framework-injected
	* keys (`_background`, `suspendedToolRunId`, `resumeData`) spliced in.
	*
	* It must NOT be written back onto `originalTool.inputSchema`: `createTool()`
	* results are commonly module-level singletons shared across several agents,
	* while background eligibility is resolved per agent — a write-back would
	* leak one agent's injected keys into every other agent's model-facing
	* parameters (issue #22843).
	*/
	injectedInputSchema;
	isResumableTool;
	constructor(input) {
		super({ name: "CoreToolBuilder" });
		this.originalTool = input.originalTool;
		this.options = input.options;
		this.logType = input.logType;
		const isBackgroundEligible = !!input.backgroundTaskEnabled && require_background_tasks.isToolBackgroundEligible({
			toolName: this.options.name,
			toolConfig: this.options.backgroundConfig,
			agentConfig: this.options.agentBackgroundConfig
		});
		this.isResumableTool = Boolean(input.autoResumeSuspendedTools || this.originalTool.id?.startsWith("agent-") || this.originalTool.id?.startsWith("workflow-"));
		if (!require_toolchecks.isVercelTool(this.originalTool) && !require_toolchecks.isProviderDefinedTool(this.originalTool)) {
			if (isBackgroundEligible || this.isResumableTool) {
				let schema = this.originalTool.inputSchema;
				if (typeof schema === "function" && !(0, _mastra_schema_compat_schema.isStandardSchemaWithJSON)(schema)) schema = schema();
				if (!schema) schema = zod_v4.z.object({});
				if (require_zod_utils.isZodObject(schema) && isZodV4Schema(schema)) {
					let nextSchema = schema;
					if (isBackgroundEligible) nextSchema = require_zod_utils.safeExtendZodObject(nextSchema, { _background: require_background_tasks.backgroundOverrideZodSchema });
					if (this.isResumableTool) nextSchema = require_zod_utils.safeExtendZodObject(nextSchema, resumeFieldsZodShape);
					this.injectedInputSchema = (0, _mastra_schema_compat_schema.toStandardSchema)(nextSchema);
				} else {
					const standardSchema = (0, _mastra_schema_compat_schema.isStandardSchemaWithJSON)(schema) ? schema : (0, _mastra_schema_compat_schema.toStandardSchema)(schema);
					const jsonSchema = (0, _mastra_schema_compat_schema.standardSchemaToJSONSchema)(standardSchema, { io: "input" });
					if (jsonSchema && typeof jsonSchema === "object" && jsonSchema.type === "object") {
						const properties = { ...jsonSchema.properties ?? {} };
						const injectedKeys = [];
						if (isBackgroundEligible) {
							properties._background = require_background_tasks.backgroundOverrideJsonSchema;
							injectedKeys.push("_background");
						}
						if (this.isResumableTool) {
							properties.suspendedToolCallId = {
								type: ["string", "null"],
								description: "The toolCallId of the suspended tool to resume"
							};
							properties.suspendedToolRunId = {
								type: ["string", "null"],
								description: "The runId of the suspended tool"
							};
							properties.resumeData = { description: "The resumeData object created from the resumeSchema of suspended tool" };
							injectedKeys.push("suspendedToolCallId", "suspendedToolRunId", "resumeData");
						}
						this.injectedInputSchema = buildJsonOverrideSchema(schema, {
							...jsonSchema,
							properties
						}, injectedKeys);
					}
				}
			}
		}
	}
	getParameters = () => {
		if (require_toolchecks.isVercelTool(this.originalTool)) {
			let schema = this.originalTool.parameters ?? ("inputSchema" in this.originalTool ? this.originalTool.inputSchema : void 0) ?? zod_v4.z.object({});
			if (typeof schema === "function" && !(0, _mastra_schema_compat_schema.isStandardSchemaWithJSON)(schema)) schema = schema();
			return schema;
		}
		let schema = this.injectedInputSchema ?? this.originalTool.inputSchema;
		if ((0, _mastra_schema_compat_schema.isStandardSchemaWithJSON)(schema)) return schema;
		if (typeof schema === "function" && !(0, _mastra_schema_compat_schema.isStandardSchemaWithJSON)(schema)) schema = schema();
		return schema;
	};
	/** Compat-layer validation schema for execute-time checks (when a layer applies). */
	buildCompatValidationSchema(originalSchema, schemaCompatLayers) {
		if (!originalSchema) return;
		let schema = originalSchema;
		if (typeof schema === "function" && !(0, _mastra_schema_compat_schema.isStandardSchemaWithJSON)(schema)) schema = schema();
		if (!(0, _mastra_schema_compat_schema.isStandardSchemaWithJSON)(schema)) return;
		const applicableLayer = schemaCompatLayers.find((layer) => layer.shouldApply());
		if (!applicableLayer) return;
		return applicableLayer.processToCompatSchema(schema);
	}
	getOutputSchema = () => {
		if ("outputSchema" in this.originalTool) {
			let schema = this.originalTool.outputSchema;
			if ((0, _mastra_schema_compat_schema.isStandardSchemaWithJSON)(schema)) return schema;
			if (typeof schema === "function" && !(0, _mastra_schema_compat_schema.isStandardSchemaWithJSON)(schema)) schema = schema();
			return schema;
		}
		return null;
	};
	getResumeSchema = () => {
		if ("resumeSchema" in this.originalTool) {
			let schema = this.originalTool.resumeSchema;
			if (typeof schema === "function" && !(0, _mastra_schema_compat_schema.isStandardSchemaWithJSON)(schema)) schema = schema();
			return schema;
		}
		return null;
	};
	getSuspendSchema = () => {
		if ("suspendSchema" in this.originalTool) {
			let schema = this.originalTool.suspendSchema;
			if (typeof schema === "function" && !(0, _mastra_schema_compat_schema.isStandardSchemaWithJSON)(schema)) schema = schema();
			return schema;
		}
		return null;
	};
	buildProviderTool(tool) {
		if ("type" in tool && (tool.type === "provider-defined" || tool.type === "provider") && "id" in tool && typeof tool.id === "string" && tool.id.includes(".")) {
			let parameters = "parameters" in tool ? tool.parameters : "inputSchema" in tool ? tool.inputSchema : void 0;
			if (typeof parameters === "function") parameters = parameters();
			let outputSchema = "outputSchema" in tool ? tool.outputSchema : void 0;
			if (typeof outputSchema === "function") outputSchema = outputSchema();
			let processedParameters;
			if (parameters !== void 0 && parameters !== null) {
				if (typeof parameters === "object" && "jsonSchema" in parameters) processedParameters = parameters;
				else if ((0, _mastra_schema_compat_schema.isStandardSchemaWithJSON)(parameters)) processedParameters = { jsonSchema: (0, _mastra_schema_compat_schema.standardSchemaToJSONSchema)(parameters, { io: "input" }) };
				else processedParameters = (0, _mastra_schema_compat.convertZodSchemaToAISDKSchema)(parameters);
			} else processedParameters = { jsonSchema: {
				type: "object",
				properties: {},
				additionalProperties: false
			} };
			let processedOutputSchema;
			if (outputSchema !== void 0 && outputSchema !== null) {
				if (typeof outputSchema === "object" && "jsonSchema" in outputSchema) processedOutputSchema = outputSchema;
				else if ((0, _mastra_schema_compat_schema.isStandardSchemaWithJSON)(outputSchema)) processedOutputSchema = { jsonSchema: (0, _mastra_schema_compat_schema.standardSchemaToJSONSchema)(outputSchema) };
				else processedOutputSchema = (0, _mastra_schema_compat.convertZodSchemaToAISDKSchema)(outputSchema);
			}
			const builtTool = {
				...processedOutputSchema ? { outputSchema: processedOutputSchema } : {},
				type: "provider-defined",
				id: tool.id,
				..."name" in tool && typeof tool.name === "string" ? { name: tool.name } : {},
				args: "args" in this.originalTool ? this.originalTool.args : {},
				description: tool.description,
				parameters: processedParameters,
				execute: this.originalTool.execute ? this.createExecute(this.originalTool, {
					...this.options,
					description: this.originalTool.description
				}, this.logType) : void 0,
				toModelOutput: "toModelOutput" in this.originalTool ? this.originalTool.toModelOutput : void 0,
				transform: "transform" in this.originalTool ? this.originalTool.transform : void 0,
				inputExamples: "inputExamples" in this.originalTool ? this.originalTool.inputExamples : void 0
			};
			require_tool.registerToolOutputValidationSchema(builtTool, outputSchema);
			return builtTool;
		}
	}
	createLogMessageOptions({ agentName, toolName, type }) {
		const toolType = type === "toolset" ? "toolset" : "tool";
		return {
			start: `Executing ${toolType}`,
			error: `Failed ${toolType} execution`,
			logData: {
				agent: agentName,
				tool: toolName
			}
		};
	}
	/** Enforces the TOOLS_EXECUTE FGA permission for this tool when an FGA provider is configured. */
	async requireToolExecuteFGA(options, mcpMeta, requestContext, actor) {
		const fgaProvider = options.mastra?.getServer?.()?.fga;
		if (!fgaProvider) return;
		const { getAgentToolFGAResourceId, getMCPToolFGAResourceId, getStandaloneToolFGAResourceId, requireFGA } = await Promise.resolve().then(() => require("./auth/ee/fga-check.cjs"));
		const user = requestContext?.get("user");
		const resolved = await options.resolveExecuteFGA?.({
			user,
			requestContext
		});
		const toolResourceId = mcpMeta?.serverName ? getMCPToolFGAResourceId(mcpMeta.serverName, options.name) : options.agentId ? getAgentToolFGAResourceId(options.agentId, options.name) : getStandaloneToolFGAResourceId(options.name);
		await requireFGA({
			fgaProvider,
			user,
			resource: resolved?.resource ?? {
				type: "tool",
				id: toolResourceId
			},
			permission: resolved?.permission ?? require_ee_iTj2bRDt.MastraFGAPermissions.TOOLS_EXECUTE,
			requestContext,
			actor,
			context: {
				resourceId: options.resourceId,
				...resolved?.context
			},
			metadata: {
				toolName: options.name,
				agentId: options.agentId,
				agentName: options.agentName,
				runId: options.runId,
				threadId: options.threadId,
				executionResourceId: options.resourceId,
				mcpMetadata: mcpMeta,
				...resolved?.metadata
			}
		});
	}
	createExecute(tool, options, logType, inputValidationSchema) {
		const { logger, mastra: _mastra, memory: _memory, requestContext, model, tracingContext: _tracingContext, tracingPolicy: _tracingPolicy, ...rest } = options;
		const logModelObject = {
			modelId: model?.modelId,
			provider: model?.provider,
			specificationVersion: model?.specificationVersion
		};
		const { start, logData } = this.createLogMessageOptions({
			agentName: options.agentName,
			toolName: options.name,
			type: logType
		});
		const mcpMeta = !require_toolchecks.isVercelTool(tool) && "mcpMetadata" in tool ? tool.mcpMetadata : void 0;
		const execFunction = async (args, execOptions, toolSpan, inputValidated = false) => {
			const contextSpan = toolSpan ?? (execOptions?.tracingContext || options.tracingContext)?.currentSpan;
			let suspensionRequested = false;
			try {
				let result;
				let suspendData = null;
				await verifyRunLease(options.runId);
				if (require_toolchecks.isVercelTool(tool)) result = await require_utils.executeWithContext({
					span: contextSpan,
					fn: async () => tool?.execute?.(args, execOptions)
				});
				else {
					/**
					* MASTRA INSTANCE TYPES IN TOOL EXECUTION:
					*
					* Full Mastra & MastraPrimitives (has getAgent, getWorkflow, etc.):
					* - Auto-generated workflow tools from agent.listWorkflows()
					* - These get this.#mastra directly and can be wrapped
					*
					* MastraPrimitives only (limited interface):
					* - Memory tools (from memory.listTools())
					* - Assigned tools (agent.tools)
					* - Toolset tools (from toolsets)
					* - Client tools (passed as tools in generate/stream options)
					* - These get mastraProxy and have limited functionality
					*
					* TODO: Consider providing full Mastra instance to more tool types for enhanced functionality
					*/
					const wrappedMastra = options.mastra ? require_observability.wrapMastra(options.mastra, { currentSpan: contextSpan }) : options.mastra;
					const resumeSchema = this.getResumeSchema();
					let executionArgs = args;
					if (this.isResumableTool && args && typeof args === "object" && !Array.isArray(args)) {
						const { suspendedToolCallId: _modelAuthoredToolCallId, suspendedToolRunId: _modelAuthoredRunId, ...cleanedArgs } = args;
						executionArgs = execOptions.suspendedToolRunId ? {
							...cleanedArgs,
							suspendedToolRunId: execOptions.suspendedToolRunId
						} : cleanedArgs;
					}
					const baseContext = {
						threadId: options.threadId,
						resourceId: options.resourceId,
						mastra: wrappedMastra,
						memory: options.memory,
						runId: options.runId,
						requestContext: mergeRequestContexts(options.requestContext, execOptions.requestContext),
						actor: execOptions.actor,
						workspace: execOptions.workspace ?? options.workspace,
						browser: options.browser,
						observe: execOptions.observe ?? require_tool.createToolObserve(contextSpan),
						writer: new require_stream.ToolStream({
							prefix: "tool",
							callId: execOptions.toolCallId,
							name: options.name,
							runId: options.runId
						}, execOptions.outputWriter || options.outputWriter),
						...require_observability.createObservabilityContext({ currentSpan: contextSpan }),
						abortSignal: execOptions.abortSignal,
						background: execOptions.background,
						suspend: (args, suspendOptions) => {
							suspensionRequested = true;
							suspendData = args;
							const newSuspendOptions = {
								...suspendOptions ?? {},
								resumeSchema: suspendOptions?.resumeSchema ?? (resumeSchema ? JSON.stringify((0, _mastra_schema_compat_schema.standardSchemaToJSONSchema)((0, _mastra_schema_compat_schema.toStandardSchema)(resumeSchema), { io: "input" })) : void 0)
							};
							return execOptions.suspend?.(args, newSuspendOptions);
						},
						resumeData: execOptions.resumeData,
						suspendPayload: execOptions.suspendPayload
					};
					const isAgentExecution = execOptions.toolCallId && execOptions.messages || options.agentName && options.threadId && !options.workflowId;
					const isWorkflowExecution = !isAgentExecution && (options.workflow || options.workflowId);
					let toolContext;
					if (isAgentExecution) {
						const { suspend, resumeData, suspendPayload, threadId, resourceId, ...restBaseContext } = baseContext;
						toolContext = {
							...restBaseContext,
							...execOptions.mcp ? { mcp: execOptions.mcp } : {},
							agent: {
								agentId: options.agentId || "",
								toolCallId: execOptions.toolCallId || "",
								messages: execOptions.messages || [],
								getMessages: execOptions.getMessages,
								suspend,
								resumeData,
								suspendedToolRunId: execOptions.suspendedToolRunId,
								suspendPayload,
								threadId,
								resourceId,
								outputWriter: execOptions.outputWriter || options.outputWriter,
								flushMessages: execOptions.flushMessages,
								...execOptions.isBackgroundTask ? { isBackgroundTask: true } : {}
							}
						};
					} else if (isWorkflowExecution) {
						const { suspend, resumeData, suspendPayload, ...restBaseContext } = baseContext;
						toolContext = {
							...restBaseContext,
							...execOptions.mcp ? { mcp: execOptions.mcp } : {},
							workflow: options.workflow ? {
								...options.workflow,
								suspendedToolRunId: execOptions.suspendedToolRunId
							} : {
								runId: options.runId,
								workflowId: options.workflowId,
								state: options.state,
								setState: options.setState,
								suspend,
								resumeData,
								suspendedToolRunId: execOptions.suspendedToolRunId,
								suspendPayload
							}
						};
					} else if (execOptions.mcp) toolContext = {
						...baseContext,
						mcp: execOptions.mcp
					};
					else toolContext = baseContext;
					const resumeData = execOptions.resumeData;
					if (resumeData != null) {
						const resumeValidation = require_tool.validateToolInput(resumeSchema, resumeData, options.name);
						if (resumeValidation.error) {
							logger?.warn("Tool resume data validation failed", {
								...logData,
								issuePaths: require_tool.getValidationIssuePaths(resumeValidation.error, resumeSchema)
							});
							toolSpan?.end({
								output: resumeValidation.error,
								...require_observability.executionFailureTermination(resumeValidation.error),
								attributes: { success: false }
							});
							return resumeValidation.error;
						}
					}
					result = await require_utils.executeWithContext({
						span: contextSpan,
						fn: async () => {
							if (inputValidated || inputValidationSchema || this.injectedInputSchema) require_tool.markBuilderValidatedInput(toolContext);
							return tool?.execute?.(executionArgs, toolContext);
						}
					});
				}
				if (suspendData) {
					const suspendSchema = this.getSuspendSchema();
					const suspendValidation = require_tool.validateToolSuspendData(suspendSchema, suspendData, options.name);
					if (suspendValidation.error) {
						logger?.warn("Tool suspend data validation failed", {
							...logData,
							issuePaths: require_tool.getValidationIssuePaths(suspendValidation.error, suspendSchema)
						});
						toolSpan?.end({
							output: suspendValidation.error,
							...require_observability.executionFailureTermination(suspendValidation.error),
							attributes: { success: false }
						});
						return suspendValidation.error;
					}
				}
				if (typeof result === "undefined" && !!suspendData) {
					toolSpan?.end({
						output: result,
						outcome: suspensionRequested ? "suspend" : "success",
						stopReason: null,
						stopReasonContext: null,
						attributes: { success: true }
					});
					return result;
				}
				if (require_toolchecks.isVercelTool(tool)) {
					const outputSchema = this.getOutputSchema();
					const outputValidation = require_tool.validateToolOutput(outputSchema, result, options.name, false);
					if (outputValidation.error) {
						logger?.warn("Tool output validation failed", {
							...logData,
							issuePaths: require_tool.getValidationIssuePaths(outputValidation.error, outputSchema, "output")
						});
						toolSpan?.end({
							output: outputValidation.error,
							...require_observability.executionFailureTermination(outputValidation.error),
							attributes: { success: false }
						});
						return outputValidation.error;
					}
					result = outputValidation.data;
				} else if (require_tool.isValidationError(result)) {
					toolSpan?.end({
						output: result,
						...require_observability.executionFailureTermination(result),
						attributes: { success: false }
					});
					return result;
				}
				toolSpan?.end({
					output: result,
					outcome: suspensionRequested ? "suspend" : "success",
					stopReason: null,
					stopReasonContext: null,
					attributes: { success: true }
				});
				return result;
			} catch (error) {
				if (suspensionRequested && eagerToolCallSuspensionIntent(error)) toolSpan?.end({
					outcome: "suspend",
					stopReason: null,
					stopReasonContext: null
				});
				else {
					const failure = require_error.getErrorFromUnknown(error, { supportSerialization: false });
					toolSpan?.error({
						error: failure,
						...require_observability.executionFailureTermination(error),
						attributes: { success: false }
					});
					throw failure;
				}
				throw error;
			}
		};
		return async (args, execOptions) => {
			let logger = options.logger || this.logger;
			const tracingContext = execOptions?.tracingContext || options.tracingContext;
			const toolRequestContext = execOptions?.requestContext ?? options.requestContext;
			const toolSpan = execOptions?.skipToolSpan ? void 0 : require_utils.getOrCreateSpan({
				type: mcpMeta ? "mcp_tool_call" : "tool_call",
				outcome: null,
				name: mcpMeta ? `mcp_tool: '${options.name}' on '${mcpMeta.serverName}'` : `tool: '${options.name}'`,
				input: args,
				entityType: require_storage.EntityType.TOOL,
				entityId: options.name,
				entityName: options.name,
				attributes: mcpMeta ? {
					mcpServer: mcpMeta.serverName,
					serverVersion: mcpMeta.serverVersion,
					toolType: logType || "tool",
					toolDescription: options.description,
					toolCallId: execOptions?.toolCallId
				} : {
					toolDescription: options.description,
					toolType: logType || "tool",
					toolCallId: execOptions?.toolCallId
				},
				tracingPolicy: options.tracingPolicy,
				tracingContext,
				requestContext: toolRequestContext,
				mastra: options.mastra && "observability" in options.mastra ? options.mastra : void 0
			});
			try {
				await this.requireToolExecuteFGA(options, mcpMeta, toolRequestContext, execOptions?.actor);
			} catch (error) {
				toolSpan?.error({
					error,
					...require_observability.executionFailureTermination(error)
				});
				throw error;
			}
			try {
				logger.debug(start, {
					...logData,
					...rest,
					model: logModelObject
				});
				const isResuming = execOptions?.resumeData != null;
				const parameters = inputValidationSchema ?? this.getParameters();
				let inputValidated = false;
				if (!isResuming || this.injectedInputSchema) {
					const { data, error } = require_tool.validateToolInput(parameters, args, options.name);
					const suspendedToolRunIdErrToIgnore = error?.message?.includes("suspendedToolRunId: Required") && !args?.resumeData;
					if (error && !suspendedToolRunIdErrToIgnore) {
						logger.warn("Tool input validation failed", {
							...logData,
							issuePaths: require_tool.getValidationIssuePaths(error, parameters)
						});
						toolSpan?.end({
							output: error,
							...require_observability.executionFailureTermination(error),
							attributes: { success: false }
						});
						return error;
					}
					if (!error) {
						args = data;
						inputValidated = true;
					}
				}
				return await new Promise((resolve, reject) => {
					setImmediate(async () => {
						try {
							resolve(await execFunction(args, execOptions, toolSpan, inputValidated));
						} catch (err) {
							reject(err);
						}
					});
				});
			} catch (err) {
				const mastraError = new require_error.MastraError({
					id: "TOOL_EXECUTION_FAILED",
					domain: require_error.ErrorDomain.TOOL,
					category: require_error.ErrorCategory.USER,
					details: {
						errorMessage: String(err),
						model: model?.modelId ?? ""
					}
				}, err);
				toolSpan?.error({
					error: mastraError,
					...require_observability.executionFailureTermination(mastraError),
					attributes: { success: false }
				});
				logger.trackException(trackableToolError(mastraError, err, model?.modelId ?? ""), {
					...logData,
					...rest,
					model: logModelObject
				});
				throw mastraError;
			}
		};
	}
	buildV5() {
		const builtTool = this.build();
		if (!builtTool.parameters) throw new Error("Tool parameters are required");
		const base = {
			...builtTool,
			inputSchema: builtTool.parameters,
			onInputStart: "onInputStart" in this.originalTool ? this.originalTool.onInputStart : void 0,
			onInputDelta: "onInputDelta" in this.originalTool ? this.originalTool.onInputDelta : void 0,
			onInputAvailable: "onInputAvailable" in this.originalTool ? this.originalTool.onInputAvailable : void 0,
			onOutput: "onOutput" in this.originalTool ? this.originalTool.onOutput : void 0
		};
		if (builtTool.type === "provider-defined") {
			const { execute, parameters, ...rest } = base;
			const name = ("name" in builtTool && typeof builtTool.name === "string" ? builtTool.name : null) || builtTool.id.split(".")[1] || builtTool.id;
			return {
				...rest,
				type: builtTool.type,
				id: builtTool.id,
				name,
				args: builtTool.args
			};
		}
		return base;
	}
	build() {
		const providerTool = this.buildProviderTool(this.originalTool);
		if (providerTool) return providerTool;
		const model = this.options.model;
		const schemaCompatLayers = [];
		const optsOutOfStrictSchemas = "strict" in this.originalTool && this.originalTool.strict === false;
		if (model && !optsOutOfStrictSchemas) {
			const supportsStructuredOutputs = "supportsStructuredOutputs" in model ? model.supportsStructuredOutputs ?? false : false;
			const modelInfo = {
				modelId: model.modelId,
				supportsStructuredOutputs,
				provider: model.provider
			};
			schemaCompatLayers.push(new _mastra_schema_compat.OpenAIReasoningSchemaCompatLayer(modelInfo), new _mastra_schema_compat.OpenAISchemaCompatLayer(modelInfo), new _mastra_schema_compat.GoogleSchemaCompatLayer(modelInfo), new _mastra_schema_compat.AnthropicSchemaCompatLayer(modelInfo), new _mastra_schema_compat.DeepSeekSchemaCompatLayer(modelInfo), new _mastra_schema_compat.MetaSchemaCompatLayer(modelInfo));
		}
		const parameters = this.getParameters();
		const originalSchema = parameters && !(0, _mastra_schema_compat.isZodType)(parameters) && !(0, _mastra_schema_compat_schema.isStandardSchemaWithJSON)(parameters) ? (0, _mastra_schema_compat_schema.toStandardSchema)(parameters) : parameters;
		const inputValidationSchema = this.buildCompatValidationSchema(originalSchema, schemaCompatLayers);
		let processedInputSchema;
		if (originalSchema) {
			if ((0, _mastra_schema_compat_schema.isStandardSchemaWithJSON)(originalSchema)) {
				const applicableLayer = schemaCompatLayers.find((layer) => layer.shouldApply());
				let schemaToUse;
				if (applicableLayer) schemaToUse = applicableLayer.processToCompatSchema(originalSchema);
				else schemaToUse = (0, _mastra_schema_compat_schema.toStandardSchema)(originalSchema);
				processedInputSchema = (0, _mastra_schema_compat.jsonSchema)((0, _mastra_schema_compat_schema.standardSchemaToJSONSchema)(schemaToUse, { io: "input" }), { validate: (value) => {
					const result = schemaToUse["~standard"].validate(value);
					if (result instanceof Promise) return result.then((r) => {
						if ("issues" in r && r.issues) return {
							success: false,
							error: require_tool.createStandardSchemaIssuesError(r.issues)
						};
						return {
							success: true,
							value: r.value
						};
					});
					if ("issues" in result && result.issues) return {
						success: false,
						error: require_tool.createStandardSchemaIssuesError(result.issues)
					};
					return {
						success: true,
						value: result.value
					};
				} });
			} else processedInputSchema = (0, _mastra_schema_compat.applyCompatLayer)({
				schema: originalSchema,
				compatLayers: schemaCompatLayers,
				mode: "aiSdkSchema"
			});
		}
		const outputSchema = this.getOutputSchema();
		let processedOutputSchema;
		if (outputSchema) {
			if ((0, _mastra_schema_compat_schema.isStandardSchemaWithJSON)(outputSchema)) processedOutputSchema = (0, _mastra_schema_compat_schema.standardSchemaToJSONSchema)(outputSchema, { io: "output" });
			else processedOutputSchema = (0, _mastra_schema_compat.applyCompatLayer)({
				schema: outputSchema,
				compatLayers: [],
				mode: "aiSdkSchema"
			});
		}
		let requireApproval = false;
		let needsApprovalFn;
		if (typeof this.options.requireApproval === "function") {
			requireApproval = true;
			needsApprovalFn = this.options.requireApproval;
		} else if (typeof this.options.requireApproval === "boolean") {
			requireApproval = this.options.requireApproval;
			needsApprovalFn = void 0;
		}
		if (require_toolchecks.isVercelTool(this.originalTool) && "needsApproval" in this.originalTool) {
			const needsApproval = this.originalTool.needsApproval;
			if (typeof needsApproval === "boolean") {
				requireApproval = needsApproval;
				needsApprovalFn = void 0;
			} else if (typeof needsApproval === "function") {
				needsApprovalFn = needsApproval;
				requireApproval = true;
			}
		}
		const instanceNeedsApprovalFn = require_toolchecks.getNeedsApprovalFn(this.originalTool);
		if (!needsApprovalFn && instanceNeedsApprovalFn) {
			needsApprovalFn = instanceNeedsApprovalFn;
			requireApproval = true;
		}
		const originalBeforeApproval = "beforeApproval" in this.originalTool && typeof this.originalTool.beforeApproval === "function" ? this.originalTool.beforeApproval : void 0;
		const mcpMeta = !require_toolchecks.isVercelTool(this.originalTool) && "mcpMetadata" in this.originalTool ? this.originalTool.mcpMetadata : void 0;
		const beforeApproval = originalBeforeApproval ? require_toolchecks.markBuiltBeforeApproval(async (input, context, runtime) => {
			await this.requireToolExecuteFGA(this.options, mcpMeta, runtime?.requestContext ?? this.options.requestContext, runtime?.actor);
			return originalBeforeApproval(input, context);
		}) : void 0;
		const builtTool = {
			type: "function",
			description: this.originalTool.description,
			requireApproval,
			needsApprovalFn,
			beforeApproval,
			validateInput: (input) => {
				const validation = require_tool.validateToolInput(inputValidationSchema ?? originalSchema, input, this.options.name);
				if (validation.error?.message?.includes("suspendedToolRunId: Required") && !input?.resumeData) return { data: input };
				return validation;
			},
			hasSuspendSchema: !!this.getSuspendSchema(),
			execute: this.originalTool.execute ? this.createExecute(this.originalTool, {
				...this.options,
				description: this.originalTool.description
			}, this.logType, inputValidationSchema) : void 0,
			id: "id" in this.originalTool ? this.originalTool.id : void 0,
			title: "title" in this.originalTool ? this.originalTool.title : void 0,
			parameters: processedInputSchema ?? zod_v4.z.object({}),
			outputSchema: processedOutputSchema,
			strict: "strict" in this.originalTool ? this.originalTool.strict : void 0,
			providerOptions: "providerOptions" in this.originalTool ? this.originalTool.providerOptions : void 0,
			mcp: "mcp" in this.originalTool ? this.originalTool.mcp : void 0,
			toModelOutput: "toModelOutput" in this.originalTool ? this.originalTool.toModelOutput : void 0,
			transform: "transform" in this.originalTool ? this.originalTool.transform : void 0,
			inputExamples: "inputExamples" in this.originalTool ? this.originalTool.inputExamples : void 0,
			onInputStart: "onInputStart" in this.originalTool ? this.originalTool.onInputStart : void 0,
			onInputDelta: "onInputDelta" in this.originalTool ? this.originalTool.onInputDelta : void 0,
			onInputAvailable: "onInputAvailable" in this.originalTool ? this.originalTool.onInputAvailable : void 0,
			onOutput: "onOutput" in this.originalTool ? this.originalTool.onOutput : void 0,
			backgroundConfig: this.options.backgroundConfig
		};
		require_tool.registerToolOutputValidationSchema(builtTool, outputSchema);
		return builtTool;
	}
};
// src/utils.ts
/** Resolves after `ms`, or as soon as `signal` aborts. */
const delay = (ms, signal) => new Promise((resolve) => {
	if (signal?.aborted) return resolve();
	const onAbort = () => {
		clearTimeout(timer);
		resolve();
	};
	const timer = setTimeout(() => {
		signal?.removeEventListener("abort", onAbort);
		resolve();
	}, ms);
	signal?.addEventListener("abort", onAbort, { once: true });
});
/**
* Read a positive-integer environment variable (e.g. a TTL in ms). Unset, empty,
* non-numeric, fractional, or non-positive values fall back to `fallback`.
*/
function readPositiveIntEnv(name, fallback) {
	const raw = process.env[name];
	if (!raw) return fallback;
	const parsed = Number(raw);
	return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;
}
/**
* Checks if a value is a plain object (not an array, function, Date, RegExp, etc.)
*/
function isPlainObject(value) {
	if (value === null || typeof value !== "object") return false;
	const proto = Object.getPrototypeOf(value);
	return proto === Object.prototype || proto === null;
}
/**
* Deep merges two objects, recursively merging nested plain objects.
* Arrays, functions, and other non-plain objects are replaced (not merged).
*/
function deepMerge(target, source) {
	const output = { ...target };
	if (!source) return output;
	Object.keys(source).forEach((key) => {
		const targetValue = output[key];
		const sourceValue = source[key];
		if (isPlainObject(targetValue) && isPlainObject(sourceValue)) output[key] = deepMerge(targetValue, sourceValue);
		else if (sourceValue !== void 0) output[key] = sourceValue;
	});
	return output;
}
/**
* Generate an empty object from a JSON Schema definition.
* Accepts both a JSON string and a pre-parsed object.
* Recursively initializes nested object properties and respects default values.
*/
function generateEmptyFromSchema(schema) {
	try {
		const parsedSchema = typeof schema === "string" ? JSON.parse(schema) : schema;
		if (!parsedSchema || parsedSchema.type !== "object" || !parsedSchema.properties) return {};
		const obj = {};
		for (const [key, prop] of Object.entries(parsedSchema.properties)) if (prop.default !== void 0) obj[key] = typeof prop.default === "object" && prop.default !== null ? JSON.parse(JSON.stringify(prop.default)) : prop.default;
		else if (prop.type === "object" && prop.properties) obj[key] = generateEmptyFromSchema(prop);
		else if (prop.type === "object") obj[key] = {};
		else if (prop.type === "string") obj[key] = "";
		else if (prop.type === "array") obj[key] = [];
		else if (prop.type === "number" || prop.type === "integer") obj[key] = 0;
		else if (prop.type === "boolean") obj[key] = false;
		else obj[key] = null;
		return obj;
	} catch {
		return {};
	}
}
/**
* Transforms a stream by masking content between XML tags.
* @param stream Input stream to transform
* @param tag Tag name to mask between (e.g. for <foo>...</foo>, use 'foo')
* @param options Optional configuration for masking behavior
*/
async function* maskStreamTags(stream, tag, options = {}) {
	const { onStart, onEnd, onMask } = options;
	const openTag = `<${tag}>`;
	const closeTag = `</${tag}>`;
	let buffer = "";
	let fullContent = "";
	let isMasking = false;
	let isBuffering = false;
	const trimOutsideDelimiter = (text, delimiter, trim) => {
		if (!text.includes(delimiter)) return text;
		const parts = text.split(delimiter);
		if (trim === `before-start`) return `${delimiter}${parts[1]}`;
		return `${parts[0]}${delimiter}`;
	};
	const startsWith = (text, pattern) => {
		if (pattern.includes(openTag.substring(0, 3))) pattern = trimOutsideDelimiter(pattern, `<`, `before-start`);
		return text.trim().startsWith(pattern.trim());
	};
	for await (const chunk of stream) {
		fullContent += chunk;
		if (isBuffering) buffer += chunk;
		const chunkHasTag = startsWith(chunk, openTag);
		const bufferHasTag = !chunkHasTag && isBuffering && startsWith(openTag, buffer);
		let toYieldBeforeMaskedStartTag = ``;
		if (!isMasking && (chunkHasTag || bufferHasTag)) {
			isMasking = true;
			isBuffering = false;
			const taggedTextToMask = trimOutsideDelimiter(buffer, `<`, `before-start`);
			if (taggedTextToMask !== buffer.trim()) toYieldBeforeMaskedStartTag = buffer.replace(taggedTextToMask, ``);
			buffer = "";
			onStart?.();
		}
		if (!isMasking && !isBuffering && startsWith(openTag, chunk) && chunk.trim() !== "") {
			isBuffering = true;
			buffer += chunk;
			continue;
		}
		if (isBuffering && buffer && !startsWith(openTag, buffer)) {
			yield buffer;
			buffer = "";
			isBuffering = false;
			continue;
		}
		if (isMasking && fullContent.includes(closeTag)) {
			onMask?.(chunk);
			onEnd?.();
			isMasking = false;
			const lastFullContent = fullContent;
			fullContent = ``;
			const textUntilEndTag = trimOutsideDelimiter(lastFullContent, closeTag, "after-end");
			if (textUntilEndTag !== lastFullContent) yield lastFullContent.replace(textUntilEndTag, ``);
			continue;
		}
		if (isMasking) {
			onMask?.(chunk);
			if (toYieldBeforeMaskedStartTag) yield toYieldBeforeMaskedStartTag;
			continue;
		}
		yield chunk;
	}
}
/**
* Resolve serialized zod output - This function takes the string output ot the `jsonSchemaToZod` function
* and instantiates the zod object correctly.
*
* @param schema - serialized zod object
* @returns resolved zod object
*/
function resolveSerializedZodOutput(schema) {
	return Function("z", `"use strict";return (${schema});`)(zod_v4.z);
}
/**
* Checks if a value is a Zod type
* @param value - The value to check
* @returns True if the value is a Zod type, false otherwise
*/
function isZodType(value) {
	return typeof value === "object" && value !== null && "_def" in value && "parse" in value && typeof value.parse === "function" && "safeParse" in value && typeof value.safeParse === "function";
}
function createDeterministicId(input) {
	return (0, crypto.createHash)("sha256").update(input).digest("hex").slice(0, 8);
}
/**
* Sets the properties for a Vercel Tool, including an ID and inputSchema
* @param tool - The tool to set the properties for
* @returns The tool with the properties set
*/
function setVercelToolProperties(tool) {
	const inputSchema = "inputSchema" in tool ? tool.inputSchema : convertVercelToolParameters(tool);
	const toolId = !("id" in tool) ? tool.description ? `tool-${createDeterministicId(tool.description)}` : `tool-${Math.random().toString(36).substring(2, 9)}` : tool.id;
	return {
		...tool,
		id: toolId,
		inputSchema
	};
}
/**
* Ensures a tool has an ID and inputSchema by generating one if not present
* @param tool - The tool to ensure has an ID and inputSchema
* @returns The tool with an ID and inputSchema
*/
function ensureToolProperties(tools) {
	return Object.keys(tools).reduce((acc, key) => {
		const tool = tools?.[key];
		if (tool) {
			if (typeof tool === "function" && !(tool instanceof require_tool.Tool) && !require_toolchecks.isVercelTool(tool)) throw new require_error.MastraError({
				id: "TOOL_INVALID_FORMAT",
				domain: require_error.ErrorDomain.TOOL,
				category: require_error.ErrorCategory.USER,
				text: `Tool "${key}" is not a valid tool format. Tools must be created using createTool() or be a valid Vercel AI SDK tool. Received a function.`
			});
			if (require_toolchecks.isVercelTool(tool)) acc[key] = setVercelToolProperties(tool);
			else acc[key] = tool;
		}
		return acc;
	}, {});
}
function convertVercelToolParameters(tool) {
	let schema = tool.parameters ?? zod_v4.z.object({});
	if (typeof schema === "function") schema = schema();
	return isZodType(schema) ? schema : resolveSerializedZodOutput((0, _mastra_schema_compat_json_to_zod.jsonSchemaToZod)(schema));
}
/**
* Converts a Vercel Tool or Mastra Tool into a CoreTool format
* @param originalTool - The tool to convert (either VercelTool or ToolAction)
* @param options - Tool options including Mastra-specific settings
* @param logType - Type of tool to log (tool or toolset)
* @returns A CoreTool that can be used by the system
*/
function makeCoreTool(originalTool, options, logType, autoResumeSuspendedTools, backgroundTaskEnabled) {
	return new CoreToolBuilder({
		originalTool,
		options,
		logType,
		autoResumeSuspendedTools,
		backgroundTaskEnabled
	}).build();
}
const rebindToRequestContext = Symbol("rebindToRequestContext");
/**
* Converts a raw tool an input processor added during a step. The processor does not run
* again before a suspended call resumes, so the converted tool remembers how to rebuild
* itself for the resuming call's request context (see {@link rebindProcessorTools}).
*/
function makeProcessorCoreTool(...args) {
	const [originalTool, options, ...rest] = args;
	const tool = makeCoreTool(originalTool, options, ...rest);
	Object.defineProperty(tool, rebindToRequestContext, { value: (requestContext) => makeProcessorCoreTool(originalTool, {
		...options,
		requestContext
	}, ...rest) });
	return tool;
}
/**
* Rebuilds the processor-added tools in `tools` for `requestContext`, the way request tools
* are rebuilt when a suspended run resumes, so an approved processor tool runs with the
* approver's request context like a statically defined tool does.
*/
function rebindProcessorTools(tools, requestContext) {
	const rebound = { ...tools };
	for (const [name, tool] of Object.entries(tools)) {
		const rebind = tool?.[rebindToRequestContext];
		if (rebind) rebound[name] = rebind(requestContext);
	}
	return rebound;
}
function makeCoreToolV5(originalTool, options, logType, autoResumeSuspendedTools, backgroundTaskEnabled) {
	return new CoreToolBuilder({
		originalTool,
		options,
		logType,
		autoResumeSuspendedTools,
		backgroundTaskEnabled
	}).buildV5();
}
/**
* Creates a proxy for a Mastra instance to handle deprecated properties
* @param mastra - The Mastra instance to proxy
* @param logger - The logger to use for warnings
* @returns A proxy for the Mastra instance
*/
function createMastraProxy({ mastra, logger }) {
	return new Proxy(mastra, { get(target, prop) {
		if (Reflect.has(target, prop)) {
			const value = Reflect.get(target, prop);
			if (typeof value === "function") return value.bind(target);
			return value;
		}
		if (prop === "logger") {
			logger.warn("Please use 'getLogger' instead, logger is deprecated");
			return Reflect.apply(target.getLogger, target, []);
		}
		if (prop === "storage") {
			logger.warn("Please use 'getStorage' instead, storage is deprecated");
			return Reflect.get(target, "storage");
		}
		if (prop === "agents") {
			logger.warn("Please use 'listAgents' instead, agents is deprecated");
			return Reflect.apply(target.listAgents, target, []);
		}
		if (prop === "tts") {
			logger.warn("Please use 'getTTS' instead, tts is deprecated");
			return Reflect.apply(target.getTTS, target, []);
		}
		if (prop === "vectors") {
			logger.warn("Please use 'getVectors' instead, vectors is deprecated");
			return Reflect.apply(target.getVectors, target, []);
		}
		if (prop === "memory") {
			logger.warn("Please use 'getMemory' instead, memory is deprecated");
			return Reflect.get(target, "memory");
		}
		return Reflect.get(target, prop);
	} });
}
function checkEvalStorageFields(traceObject, logger) {
	const missingFields = [];
	if (!traceObject.input) missingFields.push("input");
	if (!traceObject.output) missingFields.push("output");
	if (!traceObject.agentName) missingFields.push("agent_name");
	if (!traceObject.metricName) missingFields.push("metric_name");
	if (!traceObject.instructions) missingFields.push("instructions");
	if (!traceObject.globalRunId) missingFields.push("global_run_id");
	if (!traceObject.runId) missingFields.push("run_id");
	if (missingFields.length > 0) {
		if (logger) logger.warn("Skipping evaluation storage due to missing required fields", {
			missingFields,
			runId: traceObject.runId,
			agentName: traceObject.agentName
		});
		else console.warn("Skipping evaluation storage due to missing required fields", {
			missingFields,
			runId: traceObject.runId,
			agentName: traceObject.agentName
		});
		return false;
	}
	return true;
}
function detectSingleMessageCharacteristics(message) {
	if (typeof message === "object" && message !== null && (message.role === "function" || message.role === "data" || "toolInvocations" in message || "parts" in message || "experimental_attachments" in message)) return "has-ui-specific-parts";
	else if (typeof message === "object" && message !== null && "content" in message && (Array.isArray(message.content) || "experimental_providerMetadata" in message || "providerOptions" in message)) return "has-core-specific-parts";
	else if (typeof message === "object" && message !== null && "role" in message && "content" in message && typeof message.content === "string" && [
		"system",
		"user",
		"assistant",
		"tool"
	].includes(message.role)) return "message";
	return "other";
}
function isUiMessage(message) {
	return detectSingleMessageCharacteristics(message) === `has-ui-specific-parts`;
}
function isCoreMessage(message) {
	return [`has-core-specific-parts`, `message`].includes(detectSingleMessageCharacteristics(message));
}
const SQL_IDENTIFIER_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
/**
* Parses and returns a valid SQL identifier (such as a table or column name).
* The identifier must:
*   - Start with a letter (a-z, A-Z) or underscore (_)
*   - Contain only letters, numbers, or underscores
*   - Be at most 63 characters long
*
* @param name - The identifier string to parse.
* @param kind - Optional label for error messages (e.g., 'table name').
* @returns The validated identifier as a branded type.
* @throws {Error} If the identifier does not conform to SQL naming rules.
*
* @example
* const id = parseSqlIdentifier('my_table'); // Ok
* parseSqlIdentifier('123table'); // Throws error
*/
function parseSqlIdentifier(name, kind = "identifier") {
	if (!SQL_IDENTIFIER_PATTERN.test(name) || name.length > 63) throw new Error(`Invalid ${kind}: ${name}. Must start with a letter or underscore, contain only letters, numbers, or underscores, and be at most 63 characters long.`);
	return name;
}
/**
* Parses and returns a valid dot-separated SQL field key (e.g., 'user.profile.name').
* Each segment must:
*   - Start with a letter (a-z, A-Z) or underscore (_)
*   - Contain only letters, numbers, or underscores
*   - Be at most 63 characters long
*
* @param key - The dot-separated field key string to parse.
* @returns The validated field key as a branded type.
* @throws {Error} If any segment of the key is invalid.
*
* @example
* const key = parseFieldKey('user_profile.name'); // Ok
* parseFieldKey('user..name'); // Throws error
* parseFieldKey('user.123name'); // Throws error
*/
function parseFieldKey(key) {
	if (!key) throw new Error("Field key cannot be empty");
	const segments = key.split(".");
	for (const segment of segments) if (!SQL_IDENTIFIER_PATTERN.test(segment) || segment.length > 63) throw new Error(`Invalid field key segment: ${segment} in ${key}`);
	return key;
}
/**
* Removes specific keys from an object.
* @param obj - The original object
* @param keysToOmit - Keys to exclude from the returned object
* @returns A new object with the specified keys removed
*/
function omitKeys(obj, keysToOmit) {
	return Object.fromEntries(Object.entries(obj).filter(([key]) => !keysToOmit.includes(key)));
}
/**
* Selectively extracts specific fields from an object using dot notation.
* Does not error if fields don't exist - simply omits them from the result.
* @param obj - The source object to extract fields from
* @param fields - Array of field paths (supports dot notation like 'output.text')
* @returns New object containing only the specified fields
*/
function selectFields(obj, fields) {
	if (!obj || typeof obj !== "object") return obj;
	const result = {};
	for (const field of fields) {
		const value = getNestedValue(obj, field);
		if (value !== void 0) setNestedValue(result, field, value);
	}
	return result;
}
/**
* Gets a nested value from an object using dot notation
* @param obj - Source object
* @param path - Dot notation path (e.g., 'output.text')
* @returns The value at the path, or undefined if not found
*/
function getNestedValue(obj, path) {
	return path.split(".").reduce((current, key) => {
		return current && typeof current === "object" ? current[key] : void 0;
	}, obj);
}
/**
* Sets a nested value in an object using dot notation
* @param obj - Target object
* @param path - Dot notation path (e.g., 'output.text')
* @param value - Value to set
*/
function setNestedValue(obj, path, value) {
	const keys = path.split(".");
	const lastKey = keys.pop();
	if (!lastKey) return;
	for (const key of keys) if (key === "__proto__" || key === "constructor" || key === "prototype") return;
	if (lastKey === "__proto__" || lastKey === "constructor" || lastKey === "prototype") return;
	let current = obj;
	for (const key of keys) {
		const existing = Object.prototype.hasOwnProperty.call(current, key) ? current[key] : void 0;
		if (existing === null || typeof existing !== "object") Object.defineProperty(current, key, {
			value: Object.create(null),
			writable: true,
			enumerable: true,
			configurable: true
		});
		current = current[key];
	}
	Object.defineProperty(current, lastKey, {
		value,
		writable: true,
		enumerable: true,
		configurable: true
	});
}
const removeUndefinedValues = (obj) => {
	return Object.fromEntries(Object.entries(obj).filter(([_, value]) => value !== void 0));
};
Object.defineProperty(exports, "EAGER_TOOL_ABORT_SIGNAL", {
	enumerable: true,
	get: function() {
		return EAGER_TOOL_ABORT_SIGNAL;
	}
});
Object.defineProperty(exports, "EAGER_TOOL_BAILOUT", {
	enumerable: true,
	get: function() {
		return EAGER_TOOL_BAILOUT;
	}
});
Object.defineProperty(exports, "EAGER_TOOL_EXECUTION_MARKER", {
	enumerable: true,
	get: function() {
		return EAGER_TOOL_EXECUTION_MARKER;
	}
});
Object.defineProperty(exports, "EagerToolExecutionCoordinator", {
	enumerable: true,
	get: function() {
		return EagerToolExecutionCoordinator;
	}
});
Object.defineProperty(exports, "EagerToolExecutionNotRun", {
	enumerable: true,
	get: function() {
		return EagerToolExecutionNotRun;
	}
});
Object.defineProperty(exports, "TOOL_ABORT_NOTICE", {
	enumerable: true,
	get: function() {
		return TOOL_ABORT_NOTICE;
	}
});
Object.defineProperty(exports, "checkEvalStorageFields", {
	enumerable: true,
	get: function() {
		return checkEvalStorageFields;
	}
});
Object.defineProperty(exports, "clearRunLeaseFence", {
	enumerable: true,
	get: function() {
		return clearRunLeaseFence;
	}
});
Object.defineProperty(exports, "createMastraProxy", {
	enumerable: true,
	get: function() {
		return createMastraProxy;
	}
});
Object.defineProperty(exports, "deepMerge", {
	enumerable: true,
	get: function() {
		return deepMerge;
	}
});
Object.defineProperty(exports, "delay", {
	enumerable: true,
	get: function() {
		return delay;
	}
});
Object.defineProperty(exports, "eagerToolCallAlreadyAnnouncedInput", {
	enumerable: true,
	get: function() {
		return eagerToolCallAlreadyAnnouncedInput;
	}
});
Object.defineProperty(exports, "eagerToolCallDidNotExecute", {
	enumerable: true,
	get: function() {
		return eagerToolCallDidNotExecute;
	}
});
Object.defineProperty(exports, "eagerToolCallSuspensionIntent", {
	enumerable: true,
	get: function() {
		return eagerToolCallSuspensionIntent;
	}
});
Object.defineProperty(exports, "ensureToolProperties", {
	enumerable: true,
	get: function() {
		return ensureToolProperties;
	}
});
Object.defineProperty(exports, "generateEmptyFromSchema", {
	enumerable: true,
	get: function() {
		return generateEmptyFromSchema;
	}
});
Object.defineProperty(exports, "getNestedValue", {
	enumerable: true,
	get: function() {
		return getNestedValue;
	}
});
Object.defineProperty(exports, "hasRunningRunStep", {
	enumerable: true,
	get: function() {
		return hasRunningRunStep;
	}
});
Object.defineProperty(exports, "isCoreMessage", {
	enumerable: true,
	get: function() {
		return isCoreMessage;
	}
});
Object.defineProperty(exports, "isEagerlyExecutableToolCall", {
	enumerable: true,
	get: function() {
		return isEagerlyExecutableToolCall;
	}
});
Object.defineProperty(exports, "isRunStepActive", {
	enumerable: true,
	get: function() {
		return isRunStepActive;
	}
});
Object.defineProperty(exports, "isUiMessage", {
	enumerable: true,
	get: function() {
		return isUiMessage;
	}
});
Object.defineProperty(exports, "isZodType", {
	enumerable: true,
	get: function() {
		return isZodType;
	}
});
Object.defineProperty(exports, "makeCoreTool", {
	enumerable: true,
	get: function() {
		return makeCoreTool;
	}
});
Object.defineProperty(exports, "makeCoreToolV5", {
	enumerable: true,
	get: function() {
		return makeCoreToolV5;
	}
});
Object.defineProperty(exports, "makeProcessorCoreTool", {
	enumerable: true,
	get: function() {
		return makeProcessorCoreTool;
	}
});
Object.defineProperty(exports, "maskStreamTags", {
	enumerable: true,
	get: function() {
		return maskStreamTags;
	}
});
Object.defineProperty(exports, "omitKeys", {
	enumerable: true,
	get: function() {
		return omitKeys;
	}
});
Object.defineProperty(exports, "parseFieldKey", {
	enumerable: true,
	get: function() {
		return parseFieldKey;
	}
});
Object.defineProperty(exports, "parseSqlIdentifier", {
	enumerable: true,
	get: function() {
		return parseSqlIdentifier;
	}
});
Object.defineProperty(exports, "readPositiveIntEnv", {
	enumerable: true,
	get: function() {
		return readPositiveIntEnv;
	}
});
Object.defineProperty(exports, "rebindProcessorTools", {
	enumerable: true,
	get: function() {
		return rebindProcessorTools;
	}
});
Object.defineProperty(exports, "removeUndefinedValues", {
	enumerable: true,
	get: function() {
		return removeUndefinedValues;
	}
});
Object.defineProperty(exports, "resolveSerializedZodOutput", {
	enumerable: true,
	get: function() {
		return resolveSerializedZodOutput;
	}
});
Object.defineProperty(exports, "selectFields", {
	enumerable: true,
	get: function() {
		return selectFields;
	}
});
Object.defineProperty(exports, "setNestedValue", {
	enumerable: true,
	get: function() {
		return setNestedValue;
	}
});
Object.defineProperty(exports, "setRunLeaseFence", {
	enumerable: true,
	get: function() {
		return setRunLeaseFence;
	}
});
Object.defineProperty(exports, "startRunStep", {
	enumerable: true,
	get: function() {
		return startRunStep;
	}
});
Object.defineProperty(exports, "whenRunStepsSettle", {
	enumerable: true,
	get: function() {
		return whenRunStepsSettle;
	}
});

//# sourceMappingURL=utils-DdUtwAiS.cjs.map