UNPKG

@mastra/core

Version:
1 lines • 161 kB
{"version":3,"file":"utils-DdUtwAiS.cjs","names":["isToolBackgroundEligible","z","RequestContext","toStandardSchema","MastraError","MastraBase","isToolBackgroundEligible","isVercelTool","isProviderDefinedTool","isStandardSchemaWithJSON","isZodObject","safeExtendZodObject","backgroundOverrideZodSchema","standardSchemaToJSONSchema","backgroundOverrideJsonSchema","convertZodSchemaToAISDKSchema","MastraFGAPermissions","executeWithContext","wrapMastra","createToolObserve","ToolStream","createObservabilityContext","validateToolInput","getValidationIssuePaths","executionFailureTermination","validateToolSuspendData","validateToolOutput","isValidationError","getErrorFromUnknown","getOrCreateSpan","EntityType","ErrorDomain","ErrorCategory","OpenAIReasoningSchemaCompatLayer","OpenAISchemaCompatLayer","GoogleSchemaCompatLayer","AnthropicSchemaCompatLayer","DeepSeekSchemaCompatLayer","MetaSchemaCompatLayer","isZodType","jsonSchema","createStandardSchemaIssuesError","applyCompatLayer","getNeedsApprovalFn","markBuiltBeforeApproval","z","createHash","Tool","isVercelTool","MastraError","ErrorDomain","ErrorCategory","jsonSchemaToZod"],"sources":["../src/agent/run-lease-fence.ts","../src/loop/shared/tool-abort-grace.ts","../src/loop/workflows/agentic-execution/eager-tool-execution.ts","../src/tools/tool-builder/builder.ts","../src/utils.ts"],"sourcesContent":["/**\n * Checks registered by the thread runtime for runs that hold a cross-process thread\n * lease. A tool awaits its run's check before it executes, so a run whose lease was\n * taken over stops before it acts beside its successor instead of at its next renewal.\n */\nconst fences = new Map<string, () => Promise<void>>();\n\nexport function setRunLeaseFence(runId: string, fence: () => Promise<void>): void {\n  fences.set(runId, fence);\n}\n\n/**\n * Another runtime in the process (for example a second Mastra instance) may have registered\n * the same run id since, so a run that ends clears only its own check.\n */\nexport function clearRunLeaseFence(runId: string, fence: () => Promise<void>): void {\n  if (fences.get(runId) === fence) fences.delete(runId);\n}\n\n/** Drop every registered check. Tests only: a worker that runs files without isolation reuses run ids. */\nexport function __resetRunLeaseFencesForTests(): void {\n  fences.clear();\n}\n\n/** Throws when the run no longer holds its thread lease. */\nexport async function verifyRunLease(runId: string | undefined): Promise<void> {\n  if (runId) await fences.get(runId)?.();\n}\n\n/**\n * The steps (model requests and tool calls) each run has running now, keyed by the object that run's caller declares\n * as its owner: the abort signal the thread runtime prepared for it, or a durable run's registry entry. It has to be\n * that object and not a signal derived from it further down — the runtime only knows the one it prepared, so a derived\n * signal would silently read as idle. Runs that share a run id, agent or thread never share one.\n */\nconst runningSteps = new WeakMap<object, { count: number; onSettled: Array<() => void> }>();\n/** When each run's last step settled, so the moment between one step and the next doesn't read as idle. */\nconst lastStepSettledAt = new WeakMap<object, number>();\n\n/** Marks a step of the run this object owns as running. Call the returned function once the step has settled. */\nexport function startRunStep(owner: object | undefined): () => void {\n  if (!owner) return () => {};\n  const entry = runningSteps.get(owner) ?? { count: 0, onSettled: [] };\n  entry.count++;\n  runningSteps.set(owner, entry);\n  let settled = false;\n  return () => {\n    if (settled) return;\n    settled = true;\n    if (--entry.count > 0) return;\n    if (runningSteps.get(owner) === entry) runningSteps.delete(owner);\n    lastStepSettledAt.set(owner, Date.now());\n    for (const callback of entry.onSettled) callback();\n  };\n}\n\n/** Calls `callback` once no step of the run this object owns is running: right away when none is. */\nexport function whenRunStepsSettle(owner: object | undefined, callback: () => void): void {\n  const entry = owner ? runningSteps.get(owner) : undefined;\n  if (entry) entry.onSettled.push(callback);\n  else callback();\n}\n\n/** Whether a step of the run this object owns is running right now. */\nexport function hasRunningRunStep(owner: object | undefined): boolean {\n  return !!owner && runningSteps.has(owner);\n}\n\n/**\n * Whether the run this object owns has a step running, or had one settle within the last `withinMs`. A run that was\n * aborted has none worth waiting for, even while a step is still winding down.\n */\nexport function isRunStepActive(owner: object | undefined, withinMs: number): boolean {\n  if (!owner) return false;\n  const signal = owner instanceof AbortSignal ? owner : (owner as { abortSignal?: unknown }).abortSignal;\n  if (signal instanceof AbortSignal && signal.aborted) return false;\n  if (runningSteps.has(owner)) return true;\n  const settledAt = lastStepSettledAt.get(owner);\n  return settledAt !== undefined && Date.now() - settledAt < withinMs;\n}\n","/**\n * Maximum time to retain a running tool's result after caller cancellation.\n * Review probes measured two competing bounds, not a rationale for choosing 250 ms:\n * - A tool unwinding for 120 ms kept its result with a 150 ms window, but got a notice at 100 ms.\n * - With totalMs: 300, an uncooperative tool recorded a notice at 250 ms; a 1000 ms window\n *   lost to MastraTimeoutError before recording one (in-process engine only).\n * Cleanup needs time to finish, but the remaining run budget can pre-empt this window.\n */\nexport const TOOL_ABORT_GRACE_MS = 250;\n\n/** Time past the grace window for an aborted tool's step to record its result. */\nexport const TOOL_SETTLE_MARGIN_MS = 250;\n\nexport const TOOL_ABORT_NOTICE =\n  'Tool execution was aborted while running. The tool may still be running and its effects are unknown. Check its status before retrying.';\n","import { isToolBackgroundEligible } from '../../../background-tasks/resolve-config';\nimport type { AgentBackgroundConfig, ToolBackgroundConfig } from '../../../background-tasks/types';\nimport { TOOL_ABORT_GRACE_MS, TOOL_ABORT_NOTICE } from '../../shared/tool-abort-grace';\n\ntype EagerToolResult = unknown;\n\n/**\n * Marker placed on the workflow execution context when `toolCallStep` is invoked\n * eagerly from the LLM execution step. Its presence tells the step not to look\n * for (and await) an eager execution of itself.\n */\nexport const EAGER_TOOL_EXECUTION_MARKER = Symbol('eager-tool-execution');\n\n/**\n * Carries the coordinator's per-execution abort signal into `toolCallStep`. A dedicated\n * key rather than the step's own `abortSignal` argument, so no other caller's behaviour\n * changes: the step combines this with the run signal only when it is present.\n */\nexport const EAGER_TOOL_ABORT_SIGNAL = Symbol('eager-tool-abort-signal');\n\n/**\n * Carries a per-dispatch bailout record into `toolCallStep`, so a call that turns out to\n * need suspension can mark itself unusable *before* throwing.\n *\n * The throw alone is not fail-safe: it unwinds through the tool's own body, and a tool\n * that wraps its work in try/catch swallows it and returns normally. The step would then\n * resolve an ordinary-looking envelope and the foreach would adopt a result for a call\n * that asked to suspend. The dispatcher re-reads this record after the step settles and\n * converts any marked settlement back into a rejection.\n *\n * One record per dispatch, so a later attempt reusing the same toolCallId cannot observe\n * a previous attempt's bailout.\n */\nexport const EAGER_TOOL_BAILOUT = Symbol('eager-tool-bailout');\n\n/** Set by `toolCallStep` when an eagerly dispatched call bails out. */\n/**\n * What an eagerly dispatched tool asked for when it called `suspend()` at runtime.\n *\n * The eager attempt is abandoned before any suspension side effect happens, so this\n * intent is what the adopting foreach iteration replays: it raises the real suspension\n * from the owning iteration instead of re-running the tool body from the top.\n *\n * The options are an explicit pick rather than the whole `SuspendOptions`, which is\n * `{ resumeLabel?: string | string[] } & Record<string, any>` — carrying it verbatim\n * would make the carrier unbounded and let a caller smuggle arbitrary keys across.\n */\nexport type EagerSuspensionIntent = {\n  suspendPayload: unknown;\n  options: {\n    resumeLabel?: string | string[];\n    resumeSchema?: unknown;\n    runId?: string;\n    requireToolApproval?: boolean | { toolName?: string; args?: unknown };\n  };\n};\n\nexport type EagerToolBailout = {\n  reason?: string;\n  /**\n   * Set when the bailout was caused by a runtime `suspend()` call, carrying what the\n   * tool asked to suspend with. Recorded before the throw for the same reason `reason`\n   * is: a tool that catches the throw would otherwise return normally and lose it.\n   */\n  suspension?: EagerSuspensionIntent;\n  /**\n   * Set once the eager attempt has run the tool's `onInputAvailable`. The hook is\n   * announced before `execute`, so a bailout that happens inside the tool body has\n   * already fired it; the foreach re-runs the same `execute` function and would\n   * otherwise announce the same `toolCallId` a second time.\n   */\n  inputAvailableCalled?: boolean;\n};\n\n/** Brands errors whose eager attempt produced no adoptable result. */\nconst EAGER_NOT_EXECUTED = Symbol('eager-tool-not-executed');\n\n/** Brands a bailout whose eager attempt already announced `onInputAvailable`. */\nconst EAGER_INPUT_ANNOUNCED = Symbol('eager-tool-input-announced');\n\n/** Carries a runtime suspension's intent out of the attempt that was abandoned for it. */\nconst EAGER_SUSPENSION_INTENT = Symbol('eager-tool-suspension-intent');\n\ntype RunningExecution = {\n  controller: AbortController;\n  releasePermit: () => void;\n  work?: CompletedEagerWork;\n};\n\n/**\n * A tool call that ran to completion eagerly but was never adopted, because the model\n * attempt it belonged to was thrown away. The side effect already happened, so the\n * caller commits this into the conversation rather than letting the replacement\n * attempt run the same tool a second time.\n */\nexport type CompletedEagerWork = {\n  toolCallId: string;\n  toolName: string;\n  args: unknown;\n  /** The tool's own output, unwrapped from the step's envelope. Absent when it threw. */\n  result?: unknown;\n  /** What the tool threw. A failed call is still a call that ran. */\n  error?: unknown;\n  /**\n   * The tool started but had no outcome when the run's cancellation window expired.\n   * Kept so the aborted run emits and records a cancellation notice as its tool result.\n   */\n  incomplete?: true;\n  /**\n   * The order the model emitted this call in. Executions settle in whatever order they\n   * finish, and history is written in model-call order everywhere else, so the caller\n   * sorts by this before committing anything.\n   */\n  sequence: number;\n};\n\ntype QueuedExecution = {\n  toolCallId: string;\n  run: () => void;\n  cancel: () => void;\n};\n\n/**\n * Starts eligible server-side tool executions while the model is still streaming,\n * and hands the in-flight promise to `toolCallStep` so the existing foreach remains\n * the owner of result ordering and history.\n *\n * The permit limit is read through `getConcurrency` rather than copied, because\n * `map-tool-calls` recomputes the effective limit per step (an approval- or\n * suspend-capable tool entering the step forces the foreach down to 1). Reading it\n * late keeps one source of truth for the limit.\n */\nexport class EagerToolExecutionCoordinator {\n  readonly #executions = new Map<string, { promise: Promise<EagerToolResult>; token: object }>();\n  readonly #queued: QueuedExecution[] = [];\n  readonly #controllers = new Map<string, RunningExecution>();\n  /**\n   * Results of executions that finished but have not been adopted yet. Held so that an\n   * attempt thrown away mid-stream can still surrender the work it already did, instead\n   * of the side effect happening twice.\n   */\n  readonly #completed = new Map<string, CompletedEagerWork>();\n  /**\n   * Calls whose eager attempt already ran the body up to a runtime `suspend()`. Retrying\n   * the model would re-emit the call and run that pre-suspend work a second time, so an\n   * attempt holding one of these must not be retried.\n   */\n  readonly #suspended = new Set<string>();\n  /** Executions that have started and not yet settled, so a discard can wait them out. */\n  readonly #inFlight = new Set<Promise<unknown>>();\n  #running = 0;\n  #dispatchSequence = 0;\n  #stopped = false;\n  #stoppedPermanently = false;\n  #abortSettlement?: Promise<void>;\n\n  constructor(private readonly getConcurrency: () => number) {}\n\n  /**\n   * Hand over the in-flight eager execution for a tool call, if one was started,\n   * and forget it. Taking rather than reading keeps adoption exactly-once: a later\n   * iteration that reuses the same `toolCallId` executes again instead of adopting\n   * the previous iteration's settled result.\n   */\n  take(toolCallId: string) {\n    const execution = this.#executions.get(toolCallId);\n    this.#executions.delete(toolCallId);\n    this.#completed.delete(toolCallId);\n    this.#suspended.delete(toolCallId);\n    return execution?.promise;\n  }\n\n  /**\n   * Start an eager execution keyed by canonical `toolCallId`. Returns false when the\n   * coordinator is stopped or the id is already in flight, so a replayed or duplicate\n   * id within the same step can never execute twice.\n   */\n  start(\n    toolCallId: string,\n    execute: (abortSignal: AbortSignal) => Promise<EagerToolResult>,\n    call?: { toolName: string; args: unknown },\n  ) {\n    if (this.#stopped || this.#executions.has(toolCallId)) return false;\n\n    // Dispatch happens on complete tool-call chunks as the model emits them, so the order\n    // calls arrive here is the model-call order the rest of the pipeline preserves.\n    const sequence = this.#dispatchSequence++;\n\n    // Its own controller, so work started for an attempt the pipeline later discards can\n    // be cancelled without touching the run's signal.\n    const controller = new AbortController();\n    const ownershipToken = {};\n\n    // Held once, released once — by whichever comes first, the execution settling or the\n    // execution being cancelled. A tool that ignores its abort signal must not keep a\n    // permit that the surviving attempt's calls are waiting on.\n    let holdsPermit = false;\n    const releasePermit = () => {\n      if (!holdsPermit) return;\n      holdsPermit = false;\n      this.#running--;\n      this.#queued.shift()?.run();\n    };\n\n    const promise = new Promise<EagerToolResult>((resolve, reject) => {\n      const run = () => {\n        this.#running++;\n        holdsPermit = true;\n        this.#controllers.set(toolCallId, {\n          controller,\n          releasePermit,\n          work: call ? { toolCallId, ...call, sequence, incomplete: true } : undefined,\n        });\n        const inFlight: Promise<unknown> = execute(controller.signal)\n          .then(\n            result => {\n              // Recorded before resolving, so a discard racing the settlement still sees\n              // work that is done rather than work it is entitled to abandon.\n              //\n              // The step resolves an envelope rather than the tool's value, and it resolves\n              // rather than rejects on failure: `{ result, ...call }` when the tool returned,\n              // `{ error, ...call }` when it threw, `{ aborted: true, ...call }` when it was\n              // cancelled. A result or an error is committed as what it is. An abort gets\n              // a cancellation notice so the next model knows the tool's effects are unknown.\n              // Unwrap here so the caller holds the tool's own output.\n              const envelope = result as { result?: unknown; error?: unknown; aborted?: boolean } | undefined;\n              const settled = !!envelope && typeof envelope === 'object';\n              const outcome = !settled\n                ? undefined\n                : envelope.aborted\n                  ? { result: TOOL_ABORT_NOTICE }\n                  : 'error' in envelope\n                    ? { error: envelope.error }\n                    : 'result' in envelope\n                      ? { result: envelope.result }\n                      : undefined;\n\n              if (\n                call &&\n                outcome &&\n                !controller.signal.aborted &&\n                this.#executions.get(toolCallId)?.token === ownershipToken\n              ) {\n                this.#completed.set(toolCallId, {\n                  toolCallId,\n                  toolName: call.toolName,\n                  args: call.args,\n                  ...outcome,\n                  sequence,\n                });\n              }\n              resolve(result);\n            },\n            error => {\n              if (\n                eagerToolCallSuspensionIntent(error) &&\n                !controller.signal.aborted &&\n                this.#executions.get(toolCallId)?.token === ownershipToken\n              ) {\n                this.#suspended.add(toolCallId);\n              }\n              reject(error);\n            },\n          )\n          .finally(() => {\n            // Identity-checked: a discarded attempt and its retry can carry the same\n            // toolCallId, so the late settlement of the old one must not evict the\n            // controller belonging to the live one.\n            if (this.#controllers.get(toolCallId)?.controller === controller) {\n              this.#controllers.delete(toolCallId);\n            }\n            this.#inFlight.delete(inFlight);\n            releasePermit();\n          });\n        this.#inFlight.add(inFlight);\n      };\n\n      if (this.#running < this.getConcurrency()) {\n        run();\n      } else {\n        this.#queued.push({\n          toolCallId,\n          run,\n          cancel: () => reject(new EagerToolExecutionNotRun(`\"${toolCallId}\" was cancelled before it started`)),\n        });\n      }\n    });\n\n    // The foreach adopts this promise later (or never, if the run is cancelled).\n    // Keep a handler attached so a rejection is never unhandled.\n    promise.catch(() => {});\n    this.#executions.set(toolCallId, { promise, token: ownershipToken });\n    return true;\n  }\n\n  /** Number of executions currently running. Exposed for assertions in tests. */\n  get running() {\n    return this.#running;\n  }\n\n  /**\n   * Stop dispatching and drop everything that has not started.\n   *\n   * Without `cancelRunning`, executions already in flight are left alone: the step that\n   * follows an unsafe *finish* still runs its foreach, so their results are adopted\n   * exactly as the default pipeline would have produced them.\n   *\n   * With `cancelRunning`, the surrounding model attempt is being thrown away entirely.\n   * Those executions are aborted *and* forgotten, so nothing downstream can adopt work\n   * belonging to an attempt that no longer exists — including a retry that happens to\n   * reuse the same toolCallId, which must execute fresh. Their concurrency permits are\n   * released at the same moment: abort is cooperative, and a tool that declines to\n   * observe it must not stall the attempt that replaced it.\n   */\n  stop({\n    permanent = false,\n    cancelRunning = false,\n    keepIncomplete = false,\n  }: { permanent?: boolean; cancelRunning?: boolean; keepIncomplete?: boolean } = {}): CompletedEagerWork[] {\n    this.#stopped = true;\n    this.#stoppedPermanently ||= permanent;\n    for (const queued of this.#queued.splice(0)) {\n      this.#executions.delete(queued.toolCallId);\n      queued.cancel();\n    }\n\n    // `cancelRunning` is for the one case where the surrounding attempt is thrown away\n    // entirely (a model failing mid-stream, then retried or failed over): the normal\n    // pipeline never runs those calls, so neither may we. After an unsafe *finish* the\n    // foreach still runs and adopts, so running work is left alone there.\n    if (!cancelRunning) return [];\n\n    // Work that already finished is the one thing a discard must not throw away: the\n    // tool has run, and the replacement attempt would otherwise run it again. Handed\n    // back so the caller can commit it into the conversation the replacement sees.\n    // Sorted back into model-call order. The map is in settlement order, and a fast\n    // second call would otherwise be written into history ahead of a slow first one,\n    // which is the one thing this feature promises never to do.\n    const completed = [...this.#completed.values()].sort((a, b) => a.sequence - b.sequence);\n    this.#completed.clear();\n\n    {\n      const cancelled = [...this.#controllers];\n      // Cleared first: releasing a permit can start queued work, which must not observe\n      // a controller map that still holds the executions being abandoned.\n      this.#controllers.clear();\n      for (const [toolCallId, running] of cancelled) {\n        if (keepIncomplete && running.work && this.#executions.has(toolCallId)) completed.push(running.work);\n        // Deleting here is belt-and-braces at today's only call site, which opens a new\n        // turn immediately after. It is the coordinator's own invariant: cancelled work\n        // is never adoptable, whoever calls this and whatever they do next.\n        this.#executions.delete(toolCallId);\n        running.controller.abort();\n        running.releasePermit();\n      }\n    }\n\n    return completed.sort((a, b) => a.sequence - b.sequence);\n  }\n\n  /** Start once at run abort, including when the foreach is already awaiting adoption. */\n  settleOnAbort(): Promise<void> {\n    this.#abortSettlement ??= (async () => {\n      this.stop({ permanent: true });\n      const deadline = new AbortController();\n      const timer = setTimeout(() => deadline.abort(), TOOL_ABORT_GRACE_MS);\n      try {\n        await this.settleRunning(deadline.signal);\n        this.carryDiscardedWork(this.stop({ permanent: true, cancelRunning: true, keepIncomplete: true }));\n      } finally {\n        clearTimeout(timer);\n      }\n    })();\n    return this.#abortSettlement;\n  }\n\n  /**\n   * Wait until every execution that has started has settled, however it settles. Called\n   * with dispatch already stopped, so nothing new starts meanwhile.\n   *\n   * A discarded attempt waits here instead of cancelling: a running tool may already have\n   * done its side effect, and cancelling it would leave the replacement attempt free to\n   * call it again. Settled, its outcome is committed and the replacement sees it as done.\n   * An abort of the run stops the wait; the abort exit then waits the work out itself.\n   */\n  async settleRunning(signal?: AbortSignal) {\n    if (signal?.aborted) return;\n    let onAbort: (() => void) | undefined;\n    const aborted = signal\n      ? new Promise<void>(resolve => {\n          onAbort = resolve;\n          signal.addEventListener('abort', onAbort, { once: true });\n        })\n      : undefined;\n    try {\n      while (this.#inFlight.size && !signal?.aborted) {\n        const settled = Promise.allSettled([...this.#inFlight]);\n        await (aborted ? Promise.race([settled, aborted]) : settled);\n      }\n    } finally {\n      if (onAbort) signal!.removeEventListener('abort', onAbort);\n    }\n  }\n\n  /**\n   * Open a new model turn. A stop caused by a bad turn is scoped to that turn — the\n   * next one is a fresh model call and may dispatch again — but a caller abort is\n   * permanent. Executions from the previous turn that nothing ever adopted are dropped\n   * here so the map cannot grow across a long loop.\n   */\n  beginTurn() {\n    if (this.#stoppedPermanently) return;\n    this.#stopped = false;\n    this.#completed.clear();\n    this.#suspended.clear();\n    // Anything the previous turn's foreach never adopted is unreachable now, so drop it\n    // rather than let the map grow across a long loop. Entries belonging to a cancelled\n    // attempt are already gone; these are merely unclaimed.\n    this.#executions.clear();\n  }\n\n  /** Whether a call in this attempt has already run up to a runtime `suspend()`. */\n  get hasSuspendedHandback() {\n    return this.#suspended.size > 0;\n  }\n\n  /** Ids currently held for adoption. Exposed for assertions in tests. */\n  get pendingAdoptions() {\n    return this.#executions.size;\n  }\n\n  /**\n   * Work surrendered by a discarded attempt, held until a replacement attempt actually\n   * starts. Kept on the coordinator rather than in the step's own scope because a retry\n   * re-enters the step as a fresh invocation: anything local to the dying attempt is gone\n   * by the time its replacement exists. Never committed if no replacement comes — a run\n   * that dies must not leave an assistant turn the caller never saw streamed.\n   */\n  readonly #carried: CompletedEagerWork[] = [];\n\n  /**\n   * What has been written into the conversation, by the message id it was written under.\n   * Held so that a path which deletes that message can hand the work back to the carry\n   * buffer instead of destroying the only record of a side effect that happened.\n   *\n   * Accumulated per id rather than kept as \"the last batch\": a chain of failing attempts\n   * commits under the same id more than once, and forgetting the earlier batch would let\n   * a single `removeByIds` delete work nothing could recover.\n   *\n   * Entries are only removed by the message they describe being removed, so a run that\n   * never does that keeps them until it ends. It holds one entry per attempt that died\n   * with finished work, which retry limits bound to a handful.\n   */\n  readonly #committed = new Map<string, CompletedEagerWork[]>();\n\n  /**\n   * Hold a discarded attempt's finished work until a replacement attempt starts. Each\n   * batch is sorted into model-call order as it arrives, and batches keep the order they\n   * were discarded in. The dispatch counter happens to be run-global, so sorting the whole\n   * buffer would agree today — sorting per batch keeps that coincidence from becoming\n   * load-bearing.\n   */\n  carryDiscardedWork(work: CompletedEagerWork[]) {\n    this.#carried.push(...[...work].sort((a, b) => a.sequence - b.sequence));\n  }\n\n  /** Drain the carried work for committing into the conversation. */\n  takeCarriedWork(): CompletedEagerWork[] {\n    return this.#carried.splice(0);\n  }\n\n  /** Remember what was written where, so a later removal of that message can undo it. */\n  recordCommittedWork(messageId: string, work: CompletedEagerWork[]) {\n    const existing = this.#committed.get(messageId);\n    if (existing) existing.push(...work);\n    else this.#committed.set(messageId, [...work]);\n  }\n\n  /**\n   * Undo a commit whose message is being removed: the work goes back into the carry\n   * buffer so the next replacement attempt writes it again. Without this, a processor\n   * retry that deletes the attempt's messages would also delete the only record that a\n   * tool already ran, and the tool would run a second time.\n   *\n   * What comes back goes on the end of whatever is already carried, so the resulting\n   * order is \"work already written once, then work never written\".\n   */\n  recarryCommittedWork(messageId: string) {\n    const committed = this.#committed.get(messageId);\n    if (!committed) return false;\n    this.#committed.delete(messageId);\n    this.#carried.push(...committed);\n    return true;\n  }\n\n  /** Discarded work awaiting a replacement attempt. Exposed for assertions in tests. */\n  get carriedWork(): readonly CompletedEagerWork[] {\n    return this.#carried;\n  }\n}\n\n/**\n * Raised when an eager attempt ends without producing an adoptable result, so the\n * normal foreach path must handle the call instead of surfacing the failure. That\n * happens when the attempt is cancelled while still queued, and when an eager call\n * reaches a suspend/bail it should have been excluded from. In the second case the\n * tool's body has already started; only its *result* is discarded.\n */\nexport class EagerToolExecutionNotRun extends Error {\n  readonly [EAGER_NOT_EXECUTED] = true;\n  readonly [EAGER_INPUT_ANNOUNCED]: boolean;\n  readonly [EAGER_SUSPENSION_INTENT]?: EagerSuspensionIntent;\n\n  constructor(reason: string, options?: { inputAvailableCalled?: boolean; suspension?: EagerSuspensionIntent }) {\n    super(`Eager tool execution did not run: ${reason}`);\n    this.name = 'EagerToolExecutionNotRun';\n    this[EAGER_INPUT_ANNOUNCED] = options?.inputAvailableCalled === true;\n    this[EAGER_SUSPENSION_INTENT] = options?.suspension;\n  }\n}\n\n/**\n * The suspension intent behind this rejection, when the eager attempt was abandoned\n * because the tool called `suspend()` at runtime. The adopting foreach iteration uses\n * it to raise the real suspension rather than running the tool body a second time.\n */\nexport function eagerToolCallSuspensionIntent(error: unknown): EagerSuspensionIntent | undefined {\n  // Walk `cause` for the same reason `eagerToolCallDidNotExecute` does, with the same\n  // depth bound: a runtime suspension raises this from inside the tool body, where\n  // CoreToolBuilder wraps it in a TOOL_EXECUTION_FAILED MastraError.\n  let current: unknown = error;\n  for (let depth = 0; depth < 10 && typeof current === 'object' && current !== null; depth++) {\n    if (EAGER_SUSPENSION_INTENT in current) {\n      return (current as Record<symbol, unknown>)[EAGER_SUSPENSION_INTENT] as EagerSuspensionIntent | undefined;\n    }\n    current = (current as { cause?: unknown }).cause;\n  }\n  return undefined;\n}\n\n/**\n * True when the eager attempt behind this rejection already ran the tool's\n * `onInputAvailable`. The foreach re-runs `execute` from the top, so it has to skip\n * the announcement it already produced: one call per adoption, the same count the\n * call gets without eager dispatch. (An attempt abandoned in flight is a separate\n * matter: it is never adopted, so the replacement attempt announces again.)\n */\nexport function eagerToolCallAlreadyAnnouncedInput(error: unknown): boolean {\n  // Walk `cause` for the same reason `eagerToolCallDidNotExecute` does, with the same\n  // depth bound: a runtime suspension raises this from inside the tool body, where\n  // CoreToolBuilder wraps it in a TOOL_EXECUTION_FAILED MastraError.\n  let current: unknown = error;\n  for (let depth = 0; depth < 10 && typeof current === 'object' && current !== null; depth++) {\n    if (EAGER_INPUT_ANNOUNCED in current) return Boolean((current as Record<symbol, unknown>)[EAGER_INPUT_ANNOUNCED]);\n    current = (current as { cause?: unknown }).cause;\n  }\n  return false;\n}\n\n/**\n * True when an eager execution ended without an adoptable result, meaning the normal\n * foreach path must handle the call instead of surfacing the failure. The tool body\n * may have started (a runtime suspension gets here); only its result is discarded.\n */\nexport function eagerToolCallDidNotExecute(error: unknown): boolean {\n  // Walk `cause`: a tool that suspends at runtime raises this from inside its own\n  // execute, and CoreToolBuilder wraps anything thrown there in a TOOL_EXECUTION_FAILED\n  // MastraError. Matching only the top-level error would lose the brand and record the\n  // wrapper as the tool's result instead of handing the call back to the foreach.\n  let current: unknown = error;\n  for (let depth = 0; depth < 10 && typeof current === 'object' && current !== null; depth++) {\n    if (EAGER_NOT_EXECUTED in current) return true;\n    current = (current as { cause?: unknown }).cause;\n  }\n  return false;\n}\n\n/**\n * Whitelist deciding what may be executed before the model has finished streaming.\n *\n * This is deliberately an allow-list rather than a list of exclusions. An eager\n * execution that turns out to need approval, suspension or a background dispatch has\n * already emitted chunks and written metadata by the time it discovers that, and none\n * of it can be taken back — so the only safe posture is to start nothing whose shape\n * is not provably a plain server-side call.\n *\n * Eligible means: a resolved, active, locally-executable Mastra tool, with complete\n * arguments, that cannot suspend (mirroring the `isResumableTool` rule in\n * `tool-builder/builder.ts`), cannot require approval, and is not being dispatched as\n * a background task.\n */\nexport function isEagerlyExecutableToolCall({\n  toolCall,\n  tool,\n  activeTools,\n  requireToolApproval,\n  autoResumeSuspendedTools,\n  hasPostStreamProcessor,\n  hasToolResultProcessor,\n  isProviderTool,\n  getNeedsApprovalFn,\n  backgroundTaskManager,\n  agentBackgroundConfig,\n}: {\n  toolCall: { toolName: string; args?: unknown; providerExecuted?: boolean };\n  tool: unknown;\n  activeTools: string[] | undefined;\n  requireToolApproval: unknown;\n  autoResumeSuspendedTools: boolean | undefined;\n  hasPostStreamProcessor: boolean;\n  hasToolResultProcessor: boolean;\n  isProviderTool: (tool: any) => boolean;\n  getNeedsApprovalFn: (tool: any) => unknown;\n  backgroundTaskManager: unknown;\n  agentBackgroundConfig: AgentBackgroundConfig | undefined;\n}): boolean {\n  // A processor that runs after the stream completes is contractually allowed to\n  // rewrite or drop the response before any tool runs, so nothing may start early.\n  if (hasPostStreamProcessor) return false;\n\n  // Set only when the step carries a provider-executed tool *and* a `processToolResult`\n  // processor. A provider result reaching that hook mid-stream can abort the turn before\n  // the foreach, and the deferred path would then never start the call at all, so\n  // starting one early would make the two schedules disagree about whether it ran.\n  // Without a provider tool the hook only sees results after adoption, so dispatch stays on.\n  if (hasToolResultProcessor) return false;\n\n  // Arguments must be complete. Partial or absent arguments are never executed.\n  if (!toolCall.args || typeof toolCall.args !== 'object') return false;\n\n  // Background dispatch has its own lifecycle in the foreach. The `_background`\n  // argument is only the highest-priority input to that decision: agent- or\n  // tool-level config dispatches to the background with nothing in the args at\n  // all. `isToolBackgroundEligible` is the same base-enabled expression the\n  // resolver uses, and exists so these paths cannot disagree.\n  if ('_background' in (toolCall.args as Record<string, unknown>)) return false;\n  if (\n    backgroundTaskManager &&\n    isToolBackgroundEligible({\n      toolName: toolCall.toolName,\n      toolConfig: (tool as { backgroundConfig?: ToolBackgroundConfig } | undefined)?.backgroundConfig,\n      agentConfig: agentBackgroundConfig,\n    })\n  ) {\n    return false;\n  }\n\n  // Provider-executed and client-side calls are not ours to run.\n  if (toolCall.providerExecuted) return false;\n  if (!tool || isProviderTool(tool)) return false;\n  if (!('execute' in (tool as object)) || typeof (tool as { execute?: unknown }).execute !== 'function') return false;\n\n  // Respect per-step tool filtering. Redundant today, since a filtered tool is absent\n  // from the resolved set above and already fails the `!tool` check; kept because that\n  // is a property of how tools are resolved, not a guarantee this predicate is given.\n  if (activeTools && !activeTools.includes(toolCall.toolName)) return false;\n\n  // Anything that can suspend. `hasSuspendSchema` alone is not enough: agent- and\n  // workflow-derived tools suspend without declaring one, which is exactly the rule\n  // `isResumableTool` encodes in tools/tool-builder/builder.ts.\n  if (autoResumeSuspendedTools) return false;\n  if (toolCall.toolName.startsWith('agent-') || toolCall.toolName.startsWith('workflow-')) return false;\n  if ('hasSuspendSchema' in (tool as object) && Boolean((tool as { hasSuspendSchema?: unknown }).hasSuspendSchema)) {\n    return false;\n  }\n\n  // Anything that can require approval, from any of the three sources the foreach\n  // consults: the run-level policy, the tool's own flag, and its predicate.\n  if (requireToolApproval === true || typeof requireToolApproval === 'function') return false;\n  if ('requireApproval' in (tool as object) && Boolean((tool as { requireApproval?: unknown }).requireApproval)) {\n    return false;\n  }\n  // Also redundant today: every path in tool-builder that attaches a `needsApprovalFn`\n  // sets `requireApproval` to true alongside it, so the check above already caught this.\n  // Kept because this predicate must not depend on that pairing holding forever.\n  if (getNeedsApprovalFn(tool)) return false;\n\n  return true;\n}\n","import type { Schema } from '@internal/ai-v6';\nimport type { ProviderDefinedTool, ToolExecutionOptions } from '@internal/external-types';\nimport {\n  OpenAIReasoningSchemaCompatLayer,\n  OpenAISchemaCompatLayer,\n  GoogleSchemaCompatLayer,\n  AnthropicSchemaCompatLayer,\n  DeepSeekSchemaCompatLayer,\n  MetaSchemaCompatLayer,\n  applyCompatLayer,\n  convertZodSchemaToAISDKSchema,\n  isZodType,\n  jsonSchema,\n} from '@mastra/schema-compat';\nimport type { SchemaCompatLayer } from '@mastra/schema-compat';\nimport type { JSONSchema7Definition } from 'json-schema';\nimport { z } from 'zod/v4';\nimport { verifyRunLease } from '../../agent/run-lease-fence';\nimport { MastraFGAPermissions } from '../../auth/ee';\nimport type { ActorSignal } from '../../auth/ee';\nimport {\n  backgroundOverrideJsonSchema,\n  backgroundOverrideZodSchema,\n  isToolBackgroundEligible,\n} from '../../background-tasks';\nimport { MastraBase } from '../../base';\nimport { ErrorCategory, MastraError, ErrorDomain, getErrorFromUnknown } from '../../error';\nimport { executionFailureTermination } from '../../loop/shared/execution-outcome';\nimport { eagerToolCallSuspensionIntent } from '../../loop/workflows/agentic-execution/eager-tool-execution';\nimport type { Mastra } from '../../mastra';\nimport { SpanType, wrapMastra, EntityType, getOrCreateSpan, createObservabilityContext } from '../../observability';\nimport type { AnySpan } from '../../observability';\nimport { executeWithContext } from '../../observability/utils';\nimport { RequestContext } from '../../request-context';\nimport { isStandardSchemaWithJSON, toStandardSchema, standardSchemaToJSONSchema } from '../../schema';\nimport type { StandardSchemaWithJSON } from '../../schema';\nimport {\n  getNeedsApprovalFn,\n  isVercelTool,\n  isProviderDefinedTool,\n  markBuiltBeforeApproval,\n} from '../../tools/toolchecks';\nimport type { ToolOptions } from '../../utils';\nimport { isZodObject, safeExtendZodObject } from '../../utils/zod-utils';\n\nimport type { SuspendOptions } from '../../workflows';\nimport { markBuilderValidatedInput } from '../builder-validation-context';\nimport { createToolObserve } from '../observe';\nimport { ToolStream } from '../stream';\nimport type {\n  BeforeApprovalContext,\n  BeforeApprovalFn,\n  BeforeApprovalRuntime,\n  CoreTool,\n  McpMetadata,\n  MastraToolInvocationOptions,\n  NeedsApprovalFn,\n  ToolAction,\n  VercelTool,\n  VercelToolV5,\n} from '../types';\nimport {\n  createStandardSchemaIssuesError,\n  getValidationIssuePaths,\n  isValidationError,\n  registerToolOutputValidationSchema,\n  validateToolInput,\n  validateToolOutput,\n  validateToolSuspendData,\n} from '../validation';\n\n// Built once: `.describe()` registers schemas in Zod's global registry, which is a\n// strong Map under zod@3.25.x's `zod/v4` shim, so per-build copies would leak.\nconst resumeFieldsZodShape = {\n  suspendedToolCallId: z.string().describe('The toolCallId of the suspended tool to resume').nullable().optional(),\n  suspendedToolRunId: z.string().describe('The runId of the suspended tool').nullable().optional(),\n  resumeData: z.any().describe('The resumeData object created from the resumeSchema of suspended tool').optional(),\n};\n\n/**\n * Merge two RequestContexts so non-serializable values survive the evented\n * workflow engine's toJSON/reconstruct cycle.\n *\n * The evented engine serialises the RequestContext via `toJSON()` when\n * publishing workflow events.  Values that fail `JSON.stringify` (functions,\n * objects with circular references — e.g. the `controller` context) are silently\n * dropped.  The reconstructed RC handed to steps is therefore *degraded*.\n *\n * Tools, however, also hold a reference to the *original* RC captured during\n * tool conversion (the \"closure\" RC).  By merging both — exec first, then\n * closure on top — keys that survived serialisation are preserved while\n * non-serializable keys from the closure (like `controller`) are restored.\n */\n/**\n * Detect RequestContext-like objects structurally. We cannot use `instanceof`\n * here because duplicate copies of @mastra/core may be loaded in the same\n * process (bundlers, monorepos) and the prototype identity is not guaranteed.\n */\nfunction isRequestContextLike(value: unknown): value is RequestContext {\n  if (!value || typeof value !== 'object') return false;\n  const rc = value as RequestContext;\n  return (\n    typeof rc.get === 'function' &&\n    typeof rc.set === 'function' &&\n    typeof rc.entries === 'function' &&\n    typeof rc.size === 'function'\n  );\n}\n\nfunction mergeRequestContexts(\n  closureRC: RequestContext | undefined,\n  execRC: RequestContext | undefined,\n): RequestContext {\n  if (closureRC && closureRC === execRC) return closureRC;\n  if (!closureRC && !execRC) return new RequestContext();\n  if (!closureRC) return isRequestContextLike(execRC) ? execRC : new RequestContext();\n  if (!execRC || !isRequestContextLike(execRC) || execRC.size() === 0) return closureRC;\n\n  const merged = new RequestContext();\n  // Start with the evented engine's serialised snapshot\n  for (const [key, value] of execRC.entries()) {\n    merged.set(key, value);\n  }\n  // Overlay closure values — restores non-serializable keys and ensures the\n  // authoritative (non-degraded) copy wins for keys present in both.\n  for (const [key, value] of closureRC.entries()) {\n    merged.set(key, value);\n  }\n  return merged;\n}\n\n/**\n * Types that can be converted to Mastra tools.\n * Includes provider-defined tools from external packages via ProviderDefinedTool.\n */\nexport type ToolToConvert = VercelTool | ToolAction<any, any, any> | VercelToolV5 | ProviderDefinedTool;\nexport type LogType = 'tool' | 'toolset' | 'client-tool';\n\ninterface LogOptions {\n  agentName?: string;\n  toolName: string;\n  type?: 'tool' | 'toolset' | 'client-tool';\n}\n\ninterface LogMessageOptions {\n  start: string;\n  error: string;\n  logData: Record<string, unknown>;\n}\n\n/**\n * Detect Zod v4 schemas. Zod v3 stores the type name as `_def.typeName`\n * (e.g. \"ZodObject\"); Zod v4 stores it as `_def.type` (e.g. \"object\"). We\n * cannot use `instanceof` here because both Zod versions may be loaded in the\n * same process and the prototype identity is not guaranteed.\n */\nfunction isZodV4Schema(schema: unknown): boolean {\n  const def = (schema as any)?._def;\n  return !!def && typeof def.type === 'string' && !def.typeName;\n}\n\n/**\n * Build a Standard Schema that:\n *  - exposes the spliced JSON Schema (with `_background`/`suspendedToolRunId`/\n *    `resumeData` properties added) so provider compat layers see the override\n *    fields when serializing the tool to an LLM, and\n *  - delegates runtime `validate` to the *original* schema so Zod v3\n *    `.transform()` / `.default()` / `.refine()` and other Standard Schema\n *    parsing behavior still run before `execute()` sees the args.\n *\n * Injected override keys (`_background`, `suspendedToolRunId`, `resumeData`)\n * are stripped from the input before delegating, then merged back into the\n * validated value so the inner `execute()` still receives them — matching the\n * Zod v4 `.extend()` path's behavior.\n *\n * If the original schema has no `~standard.validate` (e.g. a raw JSON Schema\n * with no Standard Schema wrapper), fall back to validating against the\n * spliced JSON Schema directly.\n */\nfunction buildJsonOverrideSchema(\n  originalSchema: unknown,\n  splicedJsonSchema: JSONSchema7Definition,\n  injectedKeys: readonly string[],\n): StandardSchemaWithJSON {\n  const fallback = toStandardSchema(splicedJsonSchema as any);\n  const original = originalSchema as { '~standard'?: { validate?: (v: unknown) => any } } | undefined;\n  const originalValidate = original?.['~standard']?.validate?.bind(original['~standard']);\n\n  // Standard Schema for *just* the injected override fields, so we can validate\n  // malformed override payloads (e.g. `_background: { enabled: \"yes\" }`) before\n  // merging them into the result. Matches the Zod v4 `.extend()` path's\n  // behavior, which validates these fields as part of the object.\n  // See https://github.com/mastra-ai/mastra/pull/16915#discussion_r3282600679\n  const splicedProperties =\n    splicedJsonSchema && typeof splicedJsonSchema === 'object' && 'properties' in splicedJsonSchema\n      ? ((splicedJsonSchema.properties ?? {}) as Record<string, JSONSchema7Definition>)\n      : {};\n  const injectedProperties: Record<string, JSONSchema7Definition> = {};\n  for (const key of injectedKeys) {\n    if (splicedProperties[key] !== undefined) injectedProperties[key] = splicedProperties[key];\n  }\n  const injectedValidator = toStandardSchema({\n    type: 'object',\n    properties: injectedProperties,\n    additionalProperties: false,\n  } as any);\n\n  const stripInjected = (input: unknown) => {\n    if (!input || typeof input !== 'object' || Array.isArray(input)) return { stripped: input, injected: {} };\n    const injected: Record<string, unknown> = {};\n    const stripped: Record<string, unknown> = {};\n    for (const [k, v] of Object.entries(input as Record<string, unknown>)) {\n      if (injectedKeys.includes(k)) injected[k] = v;\n      else stripped[k] = v;\n    }\n    return { stripped, injected };\n  };\n\n  const validate = (input: unknown) => {\n    const { stripped, injected } = stripInjected(input);\n\n    const baseResult = originalValidate\n      ? (originalValidate(stripped) as\n          | { value: unknown }\n          | { issues: readonly unknown[] }\n          | Promise<{ value: unknown } | { issues: readonly unknown[] }>)\n      : fallback['~standard'].validate(stripped);\n\n    const injectedResult = injectedValidator['~standard'].validate(injected);\n\n    const combine = (\n      base: { value: unknown } | { issues: readonly unknown[] },\n      inj: { value: unknown } | { issues: readonly unknown[] },\n    ) => {\n      const baseIssues = 'issues' in base ? (base.issues ?? []) : [];\n      const injIssues = 'issues' in inj ? (inj.issues ?? []) : [];\n      if (baseIssues.length || injIssues.length) {\n        return { issues: [...baseIssues, ...injIssues] };\n      }\n      const baseValue = (base as { value: unknown }).value;\n      const injValue = (inj as { value: unknown }).value;\n      if (baseValue && typeof baseValue === 'object' && !Array.isArray(baseValue)) {\n        const injMerged =\n          injValue && typeof injValue === 'object' && !Array.isArray(injValue)\n            ? (injValue as Record<string, unknown>)\n            : injected;\n        return { value: { ...(baseValue as Record<string, unknown>), ...injMerged } };\n      }\n      return base;\n    };\n\n    const baseIsPromise = baseResult && typeof (baseResult as Promise<unknown>).then === 'function';\n    const injIsPromise = injectedResult && typeof (injectedResult as Promise<unknown>).then === 'function';\n    if (baseIsPromise || injIsPromise) {\n      return Promise.all([baseResult, injectedResult]).then(([b, i]) =>\n        combine(\n          b as { value: unknown } | { issues: readonly unknown[] },\n          i as { value: unknown } | { issues: readonly unknown[] },\n        ),\n      );\n    }\n    return combine(\n      baseResult as { value: unknown } | { issues: readonly unknown[] },\n      injectedResult as { value: unknown } | { issues: readonly unknown[] },\n    );\n  };\n\n  return {\n    '~standard': {\n      version: 1,\n      vendor: 'mastra-json-override',\n      validate,\n      jsonSchema: fallback['~standard'].jsonSchema,\n    },\n  } as StandardSchemaWithJSON;\n}\n\n/**\n * A remote MCP tool's error text is written by the server and can echo the submitted arguments\n * (Issue #29318). The model still receives it; the tracked exception records only its id.\n * Covers every MCPClient tool failure (execution, task failure, cancellation, polling).\n */\nfunction trackableToolError(mastraError: MastraError, err: unknown, model: string): MastraError {\n  const id = (err as { id?: unknown } | null)?.id;\n  if (typeof id !== 'string' || !id.startsWith('MCP_CLIENT_TOOL_')) return mastraError;\n  return new MastraError({\n    id: mastraError.id,\n    domain: mastraError.domain as ErrorDomain,\n    category: mastraError.category as ErrorCategory,\n    text: `Remote tool failed (${id})`,\n    details: { errorMessage: id, model },\n  });\n}\n\nexport class CoreToolBuilder extends MastraBase {\n  private originalTool: ToolToConvert;\n  private options: ToolOptions;\n  private logType?: LogType;\n  /**\n   * Builder-local copy of the user's input schema with the framework-injected\n   * keys (`_background`, `suspendedToolRunId`, `resumeData`) spliced in.\n   *\n   * It must NOT be written back onto `originalTool.inputSchema`: `createTool()`\n   * results are commonly module-level singletons shared across several agents,\n   * while background eligibility is resolved per agent — a write-back would\n   * leak one agent's injected keys into every other agent's model-facing\n   * parameters (issue #22843).\n   */\n  private injectedInputSchema?: StandardSchemaWithJSON;\n  private isResumableTool: boolean;\n\n  constructor(input: {\n    originalTool: ToolToConvert;\n    options: ToolOptions;\n    logType?: LogType;\n    autoResumeSuspendedTools?: boolean;\n    backgroundTaskEnabled?: boolean;\n  }) {\n    super({ name: 'CoreToolBuilder' });\n    this.originalTool = input.originalTool;\n    this.options = input.options;\n    this.logType = input.logType;\n\n    // Only inject the `_background` override schema for tools that are actually\n    // eligible for background execution: the manager must be enabled AND this\n    // specific tool must be opted in at the agent or tool layer (the same\n    // resolution `resolveBackgroundConfig` uses at dispatch time). Otherwise\n    // every user tool's schema would advertise `_background` even though the\n    // runtime would never honor it (issue #22724), and mutating every schema\n    // with a v4 Zod field breaks v3-authored tools (keyValidator._parse\n    // crashes in schema-compat validation).\n    const isBackgroundEligible =\n      !!input.backgroundTaskEnabled &&\n      isToolBackgroundEligible({\n        toolName: this.options.name,\n        toolConfig: this.options.backgroundConfig,\n        agentConfig: this.options.agentBackgroundConfig,\n      });\n    this.isResumableTool = Boolean(\n      input.autoResumeSuspendedTools ||\n      (this.originalTool as unknown as ToolAction<any, any>).id?.startsWith('agent-') ||\n      (this.originalTool as unknown as ToolAction<any, any>).id?.startsWith('workflow-'),\n    );\n\n    if (!isVercelTool(this.originalTool) && !isProviderDefinedTool(this.originalTool)) {\n      if (isBackgroundEligible || this.isResumableTool) {\n        let schema = this.originalTool.inputSchema;\n        if (typeof schema === 'function' && !isStandardSchemaWithJSON(schema)) {\n          schema = schema();\n        }\n        if (!schema) {\n          schema = z.object({});\n        }\n\n        // Preferred path: when the user's input schema is a Zod v4 ZodObject\n        // (the common case for tools authored with `zod` / `zod/v4`), keep using\n        // `.extend()`. This preserves the exact JSON Schema shape that existing\n        // provider compat layers + LLM recordings expect.\n        //\n        // Fallback path: for everything else (Zod v3 ZodObject, raw JSON Schema,\n        // `JsonSchemaWrapper`, etc.) splice the override fields directly into a\n        // JSON Schema. Mixing a Zod v4 wrapper (`backgroundOverrideZodSchema`,\n        // `.nullable()`, `.optional()`) into a Zod v3 ZodObject's `.shape` is\n        // what triggered the original crash:\n        //   `TypeError: keyValidator._parse is not a function`.\n        if (isZodObject(schema) && isZodV4Schema(schema)) {\n          let nextSchema: z.ZodObject<any> = schema as z.ZodObject<any>;\n          if (isBackgroundEligible) {\n            nextSchema = safeExtendZodObject(nextSchema, {\n              _background: backgroundOverrideZodSchema,\n            });\n          }\n          if (this.isResumableTool) {\n            nextSchema = safeExtendZodObject(nextSchema, resumeFieldsZodShape);\n          }\n          this.injectedInputSchema = toStandardSchema(nextSchema);\n        } else {\n          // Normalize to Standard Schema, extract JSON Schema, splice overrides.\n          const standardSchema = isStandardSchemaWithJSON(schema) ? schema : toStandardSchema(schema);\n          const jsonSchema = standardSchemaToJSONSchema(standardSchema, { io: 'input' });\n\n          if (jsonSchema && typeof jsonSchema === 'object' && jsonSchema.type === 'object') {\n            const properties: Record<string, JSONSchema7Definition> = { ...(jsonSchema.properties ?? {}) };\n            const injectedKeys: string[] = [];\n\n            if (isBackgroundEligible) {\n              properties._background = backgroundOverrideJsonSchema;\n              injectedKeys.push('_background');\n            }\n            if (this.isResumableTool) {\n              properties.suspendedToolCallId = {\n                type: ['string', 'null'],\n                description: 'The toolCallId of the suspended tool to resume',\n              };\n              properties.suspendedToolRunId = {\n                type: ['string', 'null'],\n                description: 'The runId of the suspended tool',\n              };\n              properties.resumeData = {\n                description: 'The resumeData object created from the resumeSchema of suspended tool',\n              };\n              injectedKeys.push('suspendedToolCallId', 'suspendedToolRunId', 'resumeData');\n            }\n\n            // Preserve the original schema's runtime validator (Zod v3\n            // `.transform()` / `.default()` / `.refine()` etc.) while exposing\n            // the spliced JSON Schema for provider serialization. See\n            // https://github.com/mastra-ai/mastra/pull/16915#discussion_r3282520408\n            this.injectedInputSchema = buildJsonOverrideSchema(schema, { ...jsonSchema, properties }, injectedKeys);\n          }\n        }\n      }\n    }\n  }\n\n  // Helper to get parameters based on tool type\n  private getParameters = () => {\n    if (isVercelTool(this.originalTool)) {\n      // Handle both 'parameters' (v4) and 'inputSchema' (v5) properties\n      // Also handle case where the schema is a function that returns a schema\n      let schema =\n        this.originalTool.parameters ??\n        ('inputSchema' in this.originalTool ? (this.originalTool as any).inputSchema : undefined) ??\n        z.object({});\n\n      // If schema is a function, call it to get the actual schema\n      if (typeof schema === 'function' && !isStandardSchemaWithJSON(schema)) {\n        schema = schema();\n      }\n\n      return schema;\n    }\n\n    // For Mastra tools, inputSchema might also be a function. Prefer the\n    // builder-local injected schema (see `injectedInputSchema`) so per-agent\n    // injections never depend on mutation of the shared tool object.\n    let schema = this.injectedInputSchema ?? this.originalTool.inputSchema;\n\n    if (isStandardSchemaWithJSON(schema)) {\n      return schema;\n    }\n\n    // If schema is a function, call it to get the actual schema\n    if (typeof schema === 'function' && !isStandardSchemaWithJSON(schema)) {\n      schema = schema();\n    }\n\n    return schema;\n  };\n\n  /** Compat-layer validation schema for execute-time checks (when a layer applies). */\n  private buildCompatValidationSchema(\n    originalSchema: unknown,\n    schemaCompatLayers: SchemaCompatLayer[],\n  ): StandardSchemaWithJSON | undefined {\n    if (!originalSchema) {\n      return undefined;\n    }\n\n    let schema = originalSchema;\n    if (typeof schema === 'function' && !isStandardSchemaWithJSON(schema)) {\n      schema = schema();\n    }\n\n    if (!isStandardSchemaWithJSON(schema)) {\n      return undefined;\n    }\n\n    const applicableLayer = schemaCompatLayers.find(layer => layer.shouldApply());\n    if (!applicableLayer) {\n      return undefined;\n    }\n\n    return applicableLayer.processToCompatSchema(schema as any);\n  }\n\n  private getOutputSchema = () => {\n    if ('outputSchema' in this.originalTool) {\n      let schema = this.originalTool.outputSchema;\n\n      if (isStandardSchemaWithJSON(schema)) {\n        return schema;\n      }\n\n      // If schema is a function, call it to get the actual schema\n      if (typeof schema === 'function' && !isStandardSchemaWithJSON(schema)) {\n        schema = schema();\n      }\n\n      return schema;\n    }\n\n    return null;\n  };\n\n  private getResumeSchema = () => {\n    if ('resumeSchema' in this.originalTool) {\n      let schema = this.originalTool.resumeSchema;\n\n      // If schema is a function, call it to get the actual schema\n      if (typeof schema === 'function' && !isStandardSchemaWithJSON(schema)) {\n        schema = schema();\n      }\n\n      return schema;\n    }\n    return null;\n  };\n\n  private getSuspendSchema = () => {\n    if ('suspendSchema' in this.originalTool) {\n      let schema = this.originalTool.suspendSchema;\n\n      // If schema is a function, call it to get the actual schema\n      if (typeof schema === 'function' && !isStandardSchemaWithJSON(schema)) {\n        schema = schema();\n      }\n\n      return schema;\n    }\n    return null;\n  };\n\n  // For provider-defined tools, we need to include all required properties\n  // AI SDK v5 uses type: 'provider-defined', AI SDK v6 uses type: 'provider'\n  private buildProviderTool(tool: ToolToConvert): (CoreTool & { id: `${string}.${string}` }) | undefined {\n    if (\n      'type' in tool &&\n      (tool.type === 'provider-defined' || tool.type === 'provider') &&\n      'id' in tool &&\n      typeof tool.id === 'string' &&\n      tool.id.includes('.')\n    ) {\n      // Get schema directly from provider-defined tool (v4 uses parameters, v5 uses inputSchema)\n      let parameters: unknown =\n        'parameters' in tool ? tool.parameters : 'inputSchema' in tool ? (tool as any).inputSchema : undefined;\n\n      // If schema is a function, call it to get the actual schema\n      if (typeof parameters === 'function') {\n        parameters = parameters();\n      }\n\n      // Get output schema directly from provider-defined tool\n      let outputSchema: unknown = 'outputSchema' in tool ? (tool as any).outputSchema : undefined;\n\n      // If schema is a function, call it to get the actual schema\n      if (typeof outputSchema === 'function') {\n        outputSchema = outputSchema();\n      }\n\n      // Convert parameters to AI SDK Schema format\n      let processedParameters;\n      if (parameters !== undefined && parameters !== null) {\n        if (typeof parameters === 'object' && 'jsonSchema' in parameters) {\n          // Already in AI SDK Schema format\n          processedParameters = parameters;\n        } else if (isStandardSchemaWithJSON(parameters)) {\n          // StandardSchemaWithJSON - extract the JSON schema and wrap it\n          // Use input since parameters represent tool input\n          const jsonSchema = standardSchemaToJSONSchema(parameters, { io: 'input' });\n          processedParameters = { jsonSchema };\n        } else {\n          // Assume Zod schema - convert to AI SDK Schema\n          processedParameters = convertZodSchemaToAISDKSchema(parameters as any);\n        }\n      } else {\n        // No schema provided - create default empty object schema for AI SDK v1 compatibility\n        // OpenAI requires at minimum type: \"object\" even for tools without parameters\n        processedParameters = {\n          jsonSchema: {\n            type: 'object',\n            properties: {},\n            additionalProperties: false,\n          },\n        };\n      }\n\n      // Convert output schema to AI SDK Schema format if present\n      let processedOutputSchema;\n      if (outputSchema !== undefined && outputSchema !== null) {\n        if (typeof outputSchema === 'object' && 'jsonSchema' in outputSchema) {\n          // Already in AI SDK Schema format\n          processedOutputSchema = outputSchema;\n        } else if (isStandardSchemaWithJSON(outputSchema)) {\n          // StandardSchemaWithJSON - extract the JSON schema and wrap it\n          const jsonSchema = standardSchemaToJSONSchema(outputSchema);\n          processedOutputSchema = { jsonSchema };\n        } else {\n          // Assume Zod schema - convert to AI SDK Schema\n          processedOutputSchema = convertZodSchemaToAISDKSchema(outputSchema as any);\n        }\n      }\n\n      const builtTool = {\n        ...(processedOutputSchema ? { outputSchema: processedOutputSchema } : {}),\n        type: 'provider-defined' as const,\n        id: tool.id as `${string}.${string}`,\n        // V5 SDK factories set a hardcoded `name` (e.g. \"web_search\" for\n        // anthropic.web_search_20250305). Preserve it so that when this tool\n        // is later used with a V6 provider, the bidirectional toolNameMapping\n        // resolves the correct model-facing name instead of the versioned ID.\n        ...('name' in tool && typeof tool.name === 'string' ? { name: tool.name } : {}),\n        args: ('args' in this.originalTool ? this.originalTool.args : {}) as Record<string, unknown>,\n        description: tool.description,\n        parameters: processedParameters,\n        execute: this.originalTool.execute\n          ? this.createExecute(\n              this.originalTool,\n              { ...this.options, description: this.originalTool.description },\n              this.logType,\n            )\n          : undefined,\n        toModelOutput: 'toModelOutput' in this.originalTool ? this.originalTool.toModelOutput : undefined,\n        transform: 'transform' in this.originalTool ? this.originalTool.transform : undefined,\n        inputExamples: 'inputExamples' in this.originalTool ? this.originalTool.inputExamples : undefined,\n      } as unknown as CoreTool & { id: `${string}.${string}` };\n\n      registerToolOutputValidationSchema(builtTool, outputSchema);\n      return builtTool;\n    }\n\n    return undefined;\n  }\n\n  private createLogMessageOptions({ agentName, toolName, type }: LogOptions): LogMessageOptions {\n    const toolType = type === 'toolset' ? 'toolset' : 'tool';\n    return {\n      start: `Executing ${toolType}`,\n      error: `Failed ${toolType} execution`,\n      logData: { agent: agentName, tool: toolName },\n    };\n  }\n\n  /** Enforces the TOOLS_EXECUTE FGA permission for this tool when an FGA provider is configured. */\n  private async requireToolExecuteFGA(\n    options: ToolOptions,\n    mcpMeta: McpMetadata | undefined,\n    requestContext: RequestContext | undefined,\n    actor: ActorSignal | undefined,\n  ) {\n    const fgaProvider = (options.mastra as any)?.getServer?.()?.fga;\n    if (!fgaProvider) return;\n    const { getAgentToolFGAResourceId, getMCPToolFGAResourceId, getStandaloneToolFGAResourceId, requireFGA } =\n      await import('../../auth/ee/fga-check');\n    const user = requestContext?.get('user');\n    const resolved = await options.resolveExecuteFGA?.({ user, requestContext });\n    const toolResourceId = mcpMeta?.serverName\n      ? getMCPToolFGAResourceId(mcpMeta.serverName, options.name)\n      : options.agentId\n        ? getAgentToolFGAResourceId(options.agentId, options.name)\n        : getStandaloneToolFGAResourceId(options.name);\n    await requireFGA({\n      fgaProvider,\n      user,\n      resource: resolved?.resource ?? { type: 'tool', id: toolResourceId },\n      permission: resolved?.permission ?? MastraFGAPermissions.TOOLS_EXECUTE,\n      requestContext,\n      actor,\n      context: {\n        resourceId: options.resourceId,\n        ...resolved?.context,\n      },\n      metadata: {\n        toolName: options.name,\n        agentId: options.agentId,\n        agentName: options.agentName,\n        runId: options.runId,\n        threadId: options.threadId,\n        executionResourceId: options.resourceId,\n        mcpMetadata: mcpMeta,\n        ...resolved?.metadata,\n      },\n    });\n  }\n\n  private createExecute(\n    tool: ToolToConvert,\n    options: ToolOptions,\n    logType?: 'tool' | 'toolset' | 'client-tool',\n    inputValidationSchema?: StandardSchemaWithJSON,\n  ) {\n    // don't add memory, mastra, or tracing context to logging (tracingContext may contain sensitive observability credentials)\n    const {\n      logger,\n      mastra: _mastra,\n      memory: _memory,\n      requestContext,\n      model,\n      tracingContext: _tracingContext,\n      tracingPolicy: _tracingPolicy,\n      ...rest\n    } = options;\n    const logModelObject = {\n      modelId: model?.modelId,\n      provider: model?.provider,\n      specificationVersion: model?.specificationVersion,\n    };\n\n    const { start, logData } = this.createLogMessageOptions({\n      agentName: options.agentName,\n      toolName: options.name,\n      type: logType,\n    });\n\n    // Extract MCP metadata once with proper typing to avoid repeated unsafe casts\n    const mcpMeta =\n      !isVercelTool(tool) && 'mcpMetadata' in tool ? (tool as { mcpMetadata?: McpMetadata }).mcpMetadata : undefined;\n\n    const execFunction = async (\n      args: unknown,\n      execOptions: MastraToolInvocationOptions,\n      toolSpan?: AnySpan,\n      inputValidated = false,\n    ) => {\n      // Without a tool span (skipToolSpan), nested work attaches to the caller's span instead.\n      const contextSpan = toolSpan ?? (execOptions?.tracingContext || options.tracingContext)?.currentSpan;\n      let suspensionRequested = false;\n      try {\n        let result;\n        let suspendData = null;\n\n        await verifyRunLease(options.runId);\n\n        if (isVercelTool(tool)) {\n          // Handle Vercel tools (AI SDK tools)\n          result = await executeWithContext({\n            span: contextSpan,\n            fn: async () => tool?.execute?.(args, execOptions as ToolExecutionOptions),\n          });\n        } else {\n          // Handle Mastra tools - wrap mastra instance with tracing context for context propagation\n\n          /**\n           * MASTRA INSTANCE TYPES IN TOOL EXECUTION:\n           *\n           * Full Mastra & MastraPrimitives (has getAgent, getWorkflow, etc.):\n           * - Auto-generated workflow tools from agent.listWorkflows()\n           * - These get this.#mastra directly and can be wrapped\n           *\n           * MastraPrimitives only (limited interface):\n           * - Memory tools (from memory.listTools())\n           * - Assigned tools (agent.tools)\n           * - Toolset tools (from toolsets)\n           * - Client tools (passed as tools in generate/stream options)\n           * - These get mastraProxy and have limited functionality\n           *\n           * TODO: Consider providing full Mastra instance to more tool types for enhanced functionality\n           */\n          // Wrap mastra with tracing context - wrapMastra will handle whether it's a full instance or primitives\n          const wrappedMastra = options.mastra\n            ? wrapMastra(options.mastra, { currentSpan: contextSpan })\n            : options.mastra;\n\n          const resumeSchema = this.getResumeSchema();\n          let executionArgs = args;\n          if (this.isResumableTool && args && typeof args === 'object' && !Array.isArray(args)) {\n            const {\n              suspendedToolCallId: _modelAuthoredToolCallId,\n              suspendedToolRunId: _modelAuthoredRunId,\n              ...cleanedArgs\n            } = args as Record<string, unknown>;\n            executionArgs = execOptions.suspendedToolRunId\n              ? { ...cleanedArgs, suspendedToolRunId: execOptions.suspendedToolRunId }\n              : cleanedArgs;\n          }\n\n          // Pass sanitized args as first parameter, context as second\n          // Properly structure context based on execution source\n          const baseContext = {\n            threadId: options.threadId,\n            resourceId: options.resourceId,\n            mastra: wrappedMastra,\n            memory: options.memory,\n            runId: options.runId,\n            requestContext: mergeRequestContexts(options.requestContext, execOptions.requestContext),\n            actor: execOptions.actor,\n            // Workspace for file operations and command execution\n            // Execution-time workspace (from prepareStep/processInputStep) takes precedence over build-time workspace\n            workspace: execOptions.workspace ?? options.workspace,\n            // Browser for web automation (lazily initialized on first use)\n            browser: options.browser,\n            observe: execOptions.observe ?? createToolObserve(contextSpan),\n            writer: new ToolStream(\n              {\n                prefix: 'tool',\n                callId: execOptions.toolCallId,\n                name: options.name,\n                runId: options.runId!,\n              },\n              // The execution-time writer is the step's own writer, which knows the\n              // current response message id. A tool built by a processor carries the\n              // run-level writer captured when the stream started, and that id goes\n              // stale once a signal or retry rotates the response id.\n              execOptions.outputWriter || options.outputWriter,\n            ),\n            ...createObservabilityContext({ currentSpan: contextSpan }),\n            abortSignal: execOptions.abortSignal,\n            background: execOptions.background,\n            suspend: (args: any, suspendOptions?: SuspendOptions) => {\n              suspensionRequested = true;\n              suspendData = args;\n              const newSuspendOptions = {\n                ...(suspendOptions ?? {}),\n                resumeSchema:\n                  suspendOptions?.resumeSchema ??\n                  (resumeSchema\n                    ? JSON.stringify(standardSchemaToJSONSchema(toStandardSchema(resumeSchema), { io: 'input' }))\n                    : undefined),\n              };\n              return execOptions.suspend?.(args, newSuspendOptions);\n            },\n            resumeData: execOptions.resumeData,\n            suspendPayload: execOptions.suspendPayload,\n          };\n\n          // Check if this is agent execution\n          // Agent execution takes precedence over workflow execution because agents may\n          // use workflows internally for their agentic loop\n          // Note: AI SDK v4 doesn't pass toolCallId/messages, so we also check for agentName and threadId\n          const isAgentExecution =\n            (execOptions.toolCallId && execOptions.messages) ||\n            (options.agentName && options.threadId && !options.workflowId);\n\n          // Check if this is workflow execution (has workflow properties in options)\n          // Only consider it workflow execution if it's NOT agent execution\n          const isWorkflowExecution = !isAgentExecution && (options.workflow || options.workflowId);\n\n          let toolContext;\n          if (isAgentExecution) {\n            // Nest agent-specific properties under 'agent' key\n            // Do NOT include workflow context even if workflow properties exist\n            // (agents use workflows internally but tools should see agent context)\n            // Preserve MCP context when the agent run originated from an MCP tools/call\n            // so nested tools can use elicitation/log/progress.\n            const { suspend, resumeData, suspendPayload, threadId, resourceId, ...restBaseContext } = baseContext;\n            toolContext = {\n              ...restBaseContext,\n              ...(execOptions.mcp ? { mcp: execOptions.mcp } : {}),\n              agent: {\n                agentId: options.agentId || '',\n                toolCallId: execOptions.toolCallId || '',\n                messages: execOptions.messages || [],\n                getMessages: execOptions.getMessages,\n                suspend,\n                resumeData,\n                suspendedToolRunId: execOptions.suspendedToolRunId,\n                suspendPayload,\n                threadId,\n                resourceId,\n                outputWriter: execOptions.outputWriter || options.outputWriter,\n                flushMessages: execOptions.flushMessages,\n                ...(execOptions.isBackgroundTask ? { isBackgroundTask: true } : {}),\n              },\n            };\n          } else if (isWorkflowExecution) {\n            // Nest workflow-specific properties under 'workflow' key\n            const { suspend, resumeData, suspendPayload, ...restBaseContext } = baseContext;\n            toolContext = {\n              ...restBaseContext,\n              ...(execOptions.mcp ? { mcp: execOptions.mcp } : {}),\n              workflow: options.workflow\n                ? { ...options.workflow, suspendedToolRunId: execOptions.suspendedToolRunId }\n                : {\n                    runId: options.runId,\n                    workflowId: options.workflowId,\n                    state: options.state,\n                    setState: options.setState,\n                    suspend,\n                    resumeData,\n                    suspendedToolRunId: execOptions.suspendedToolRunId,\n                    suspendPayload,\n                  },\n            };\n          } else if (execOptions.mcp) {\n            // MCP execution context\n            toolContext = {\n              ...baseContext,\n              mcp: execOptions.mcp,\n            };\n          } else {\n            // Direct execution or unknown context\n            toolContext = baseContext;\n          }\n\n          const resumeData = execOptions.resumeData;\n\n          if (resumeData != null) {\n            const resumeValidation = validateToolInput(resumeSchema, resumeData, options.name);\n            if (resumeValidation.error) {\n              logger?.warn('Tool resume data validation failed', {\n                ...logData,\n                issuePaths: getValidationIssuePaths(resumeValidation.error, resumeSchema),\n              });\n              toolSpan?.end({\n                output: resumeValidation.error,\n                ...executionFailureTermination(resumeValidation.error),\n                attributes: { success: false },\n              });\n              return resumeValidation.error as any;\n            }\n          }\n\n          result = await executeWithContext({\n            span: contextSpan,\n            fn: async () => {\n              if (inputValidated || inputValidationSchema || this.injectedInputSchema) {\n                // Skip the second validation in `Tool.execute` once this builder\n                // has validated the args (they are now the schema's output) or a\n                // builder-local schema applies. A transforming schema (e.g.\n                // string -> URL) rejects its own output (#27259), and the user's\n                // original schema would strip the builder-injected keys (breaking\n                // sub-agent/workflow resume via `suspendedToolRunId`).\n                markBuilderValidatedInput(toolContext);\n              }\n              return tool?.execute?.(executionArgs, toolContext);\n            },\n          });\n        }\n\n        if (suspendData) {\n          const suspendSchema = this.getSuspendSchema();\n          const suspendValidation = validateToolSuspendData(suspendSchema, suspendData, options.name);\n          if (suspendValidation.error) {\n            logger?.warn('Tool suspend data validation failed', {\n              ...logData,\n              issuePaths: getValidationIssuePaths(suspendValidation.error, suspendSchema),\n            });\n            toolSpan?.end({\n              output: suspendValidation.error,\n              ...executionFailureTermination(suspendValidation.error),\n              attributes: { success: false },\n            });\n            return suspendValidation.error as any;\n          }\n        }\n\n        // Skip validation if suspend was called without a result\n        const shouldSkipValidation = typeof result === 'undefined' && !!suspendData;\n        if (shouldSkipValidation) {\n          toolSpan?.end({\n            output: result,\n            outcome: suspensionRequested ? 'suspend' : 'success',\n            stopReason: null,\n            stopReasonContext: null,\n            attributes: { success: true },\n          });\n          return result;\n        }\n\n        // Validate output for Vercel/AI SDK tools which don't have built-in validation\n        // Mastra tools handle their own validation in Tool.execute() which properly\n        // applies Zod transforms (e.g., .transform(), .pipe()) to the output\n        if (isVercelTool(tool)) {\n          const outputSchema = this.getOutputSchema();\n          const outputValidation = validateToolOutput(outputSchema, result, options.name, false);\n          if (outputValidation.error) {\n            logger?.warn('Tool output validation failed', {\n              ...logData,\n              issuePaths: getValidationIssuePaths(outputValidation.error, outputSchema, 'output'),\n            });\n            toolSpan?.end({\n              output: outputValidation.error,\n              ...executionFailureTermination(outputValidation.error),\n              attributes: { success: false },\n            });\n            return outputValidation.error;\n          }\n          result = outputValidation.data;\n        } else if (isValidationError(result)) {\n          // Mastra tools validate in Tool.execute() and return the error object instead of throwing\n          toolSpan?.end({ output: result, ...executionFailureTermination(result), attributes: { success: false } });\n          return result;\n        }\n\n        // Return result (validated for Vercel tools, already validated for Mastra tools)\n        toolSpan?.end({\n          output: result,\n          outcome: suspensionRequested ? 'suspend' : 'success',\n          stopReason: null,\n          stopReasonContext: null,\n          attributes: { success: true },\n        });\n        return result;\n      } catch (error) {\n        if (suspensionRequested && eagerToolCallSuspensionIntent(error)) {\n          // Eager suspension deliberately unwinds; other errors must retain their details.\n          toolSpan?.end({ outcome: 'suspend', stopReason: null, stopReasonContext: null });\n        } else {\n          const failure = getErrorFromUnknown(error, { supportSerialization: false });\n          toolSpan?.error({\n            error: failure,\n            ...executionFailureTermination(error),\n            attributes: { success: false },\n          });\n          throw failure;\n        }\n        throw error;\n      }\n    };\n\n    return async (args: unknown, execOptions?: MastraToolInvocationOptions) => {\n      let logger = options.logger || this.logger;\n\n      // Create tool span early so validation failures are always observable.\n      // Prefer execution-time tracingContext (passed at runtime for VNext methods)\n      // Fall back to build-time context for Legacy methods (AI SDK v4 doesn't support passing custom options)\n      const tracingContext = execOptions?.tracingContext || options.tracingContext;\n      const toolRequestContext = execOptions?.requestContext ?? options.requestContext;\n      const toolSpan = execOptions?.skipToolSpan\n        ? undefined\n        : getOrCreateSpan({\n            type: mcpMeta ? SpanType.MCP_TOOL_CALL : SpanType.TOOL_CALL,\n            outcome: null,\n            name: mcpMeta ? `mcp_tool: '${options.name}' on '${mcpMeta.serverName}'` : `tool: '${options.name}'`,\n            input: args,\n            entityType: EntityType.TOOL,\n            entityId: options.name,\n            entityName: options.name,\n            attributes: mcpMeta\n              ? {\n                  mcpServer: mcpMeta.serverName,\n                  serverVersion: mcpMeta.serverVersion,\n                  toolType: logType || 'tool',\n                  toolDescription: options.description,\n                  toolCallId: execOptions?.toolCallId,\n                }\n              : {\n                  toolDescription: options.description,\n                  toolType: logType || 'tool',\n                  toolCallId: execOptions?.toolCallId,\n                },\n            tracingPolicy: options.tracingPolicy,\n            tracingContext: tracingContext,\n            requestContext: toolRequestContext,\n            mastra: options.mastra && 'observability' in options.mastra ? (options.mastra as Mastra) : undefined,\n          });\n\n      try {\n        await this.requireToolExecuteFGA(options, mcpMeta, toolRequestContext, execOptions?.actor);\n      } catch (error) {\n        toolSpan?.error({ error: error as Error, ...executionFailureTermination(error) });\n        throw error;\n      }\n\n      try {\n        logger.debug(start, { ...logData, ...rest, model: logModelObject });\n\n        // When a tool is being resumed (resumeData present in execOptions), skip input\n        // validation unless the builder injected additional fields. The original args\n        // were already validated during the initial execution, but builder-local fields\n        // still need validation before Tool.execute skips its own validation.\n        const isResuming = execOptions?.resumeData != null;\n\n        const parameters = inputValidationSchema ?? this.getParameters();\n        let inputValidated = false;\n        if (!isResuming || this.injectedInputSchema) {\n          const { data, error } = validateToolInput(\n            parameters as StandardSchemaWithJSON | undefined,\n            args,\n            options.name,\n          );\n          //suspendedToolRunId is only required when resumeData is provided\n          const suspendedToolRunIdErrToIgnore =\n            error?.message?.includes('suspendedToolRunId: Required') && !(args as Record<string, unknown>)?.resumeData;\n          if (error && !suspendedToolRunIdErrToIgnore) {\n            logger.warn('Tool input validation failed', {\n              ...logData,\n              issuePaths: getValidationIssuePaths(error, parameters),\n            });\n            toolSpan?.end({ output: error, ...executionFailureTermination(error), attributes: { success: false } });\n            return error;\n          }\n          if (!error) {\n            args = data;\n            inputValidated = true;\n          }\n        }\n\n        // there is a small delay in stream output so we add an immediate to ensure the stream is ready\n        return await new Promise((resolve, reject) => {\n          setImmediate(async () => {\n            try {\n              const result = await execFunction(args, execOptions!, toolSpan, inputValidated);\n              resolve(result);\n            } catch (err) {\n              reject(err);\n            }\n          });\n        });\n      } catch (err) {\n        const mastraError = new MastraError(\n          {\n            id: 'TOOL_EXECUTION_FAILED',\n            domain: ErrorDomain.TOOL,\n            category: ErrorCategory.USER,\n            // Raw args are intentionally omitted: they can carry credentials or PII and\n            // are already recorded on the tool span, where observability redaction applies.\n            details: {\n              errorMessage: String(err),\n              model: model?.modelId ?? '',\n            },\n          },\n          err,\n        );\n        toolSpan?.error({\n          error: mastraError,\n          ...executionFailureTermination(mastraError),\n          attributes: { success: false },\n        });\n        logger.trackException(trackableToolError(mastraError, err, model?.modelId ?? ''), {\n          ...logData,\n          ...rest,\n          model: logModelObject,\n        });\n        throw mastraError;\n      }\n    };\n  }\n\n  buildV5() {\n    const builtTool = this.build();\n\n    if (!builtTool.parameters) {\n      throw new Error('Tool parameters are required');\n    }\n\n    const base = {\n      ...builtTool,\n      inputSchema: builtTool.parameters,\n      onInputStart: 'onInputStart' in this.originalTool ? this.originalTool.onInputStart : undefined,\n      onInputDelta: 'onInputDelta' in this.originalTool ? this.originalTool.onInputDelta : undefined,\n      onInputAvailable: 'onInputAvailable' in this.originalTool ? this.originalTool.onInputAvailable : undefined,\n      onOutput: 'onOutput' in this.originalTool ? this.originalTool.onOutput : undefined,\n    };\n\n    // For provider-defined tools, exclude execute and add name as per v5 spec\n    if (builtTool.type === 'provider-defined') {\n      const { execute, parameters, ...rest } = base;\n      // Prefer the preserved provider name (e.g. \"web_search\" from V5 SDK\n      // factories) over the ID-derived name (e.g. \"web_search_20250305\").\n      const name =\n        ('name' in builtTool && typeof builtTool.name === 'string' ? builtTool.name : null) ||\n        builtTool.id.split('.')[1] ||\n        builtTool.id;\n      return {\n        ...rest,\n        type: builtTool.type,\n        id: builtTool.id,\n        name,\n        args: builtTool.args,\n      } as VercelToolV5;\n    }\n\n    return base as VercelToolV5;\n  }\n\n  build(): CoreTool {\n    const providerTool = this.buildProviderTool(this.originalTool);\n    if (providerTool) {\n      return providerTool;\n    }\n    const model = this.options.model;\n\n    const schemaCompatLayers = [];\n\n    // `strict: false` opts the tool out of strict structured-output schema rewriting.\n    // OpenAI strict mode forces every property into `required` (nullable), which makes it\n    // impossible for a model to genuinely omit a field - tools that rely on partial input\n    // (e.g. working memory merge updates) need the original optionality preserved.\n    const optsOutOfStrictSchemas = 'strict' in this.originalTool && this.originalTool.strict === false;\n\n    if (model && !optsOutOfStrictSchemas) {\n      // Respect the model's own capability flag; do not disable it based solely on specificationVersion.\n      const supportsStructuredOutputs =\n        'supportsStructuredOutputs' in model ? (model.supportsStructuredOutputs ?? false) : false;\n\n      const modelInfo = {\n        modelId: model.modelId,\n        supportsStructuredOutputs,\n        provider: model.provider,\n      };\n\n      schemaCompatLayers.push(\n        new OpenAIReasoningSchemaCompatLayer(modelInfo),\n        new OpenAISchemaCompatLayer(modelInfo),\n        new GoogleSchemaCompatLayer(modelInfo),\n        new AnthropicSchemaCompatLayer(modelInfo),\n        new DeepSeekSchemaCompatLayer(modelInfo),\n        new MetaSchemaCompatLayer(modelInfo),\n      );\n    }\n\n    const parameters = this.getParameters();\n    // JSON Schema (client tools, AI SDK `jsonSchema()`) must not round-trip through Zod: that\n    // conversion turns unions into intersections the compat layers collapse to `{}`.\n    const originalSchema =\n      parameters && !isZodType(parameters) && !isStandardSchemaWithJSON(parameters)\n        ? toStandardSchema(parameters)\n        : parameters;\n    const inputValidationSchema = this.buildCompatValidationSchema(originalSchema, schemaCompatLayers);\n    let processedInputSchema: Schema | undefined;\n\n    if (originalSchema) {\n      if (isStandardSchemaWithJSON(originalSchema)) {\n        // Find the first applicable compatibility layer\n        const applicableLayer = schemaCompatLayers.find(layer => layer.shouldApply());\n\n        let schemaToUse: StandardSchemaWithJSON;\n        if (applicableLayer) {\n          schemaToUse = applicableLayer.processToCompatSchema(originalSchema as any);\n        } else {\n          schemaToUse = toStandardSchema(originalSchema);\n        }\n\n        processedInputSchema = jsonSchema(\n          standardSchemaToJSONSchema(schemaToUse, {\n            io: 'input',\n          }),\n          {\n            validate: (value: unknown) => {\n              const result = schemaToUse['~standard'].validate(value);\n              // standard-schema validate may return a Promise\n              if (result instanceof Promise) {\n                return result.then(r => {\n                  if ('issues' in r && r.issues) {\n                    return {\n                      success: false as const,\n                      error: createStandardSchemaIssuesError(r.issues),\n                    };\n                  }\n                  return { success: true as const, value: (r as { value: unknown }).value };\n                });\n              }\n              // standard-schema returns { value } on success or { issues } on failure,\n              // but AI SDK expects { success: boolean, value/error }\n              if ('issues' in result && result.issues) {\n                return {\n                  success: false as const,\n                  error: createStandardSchemaIssuesError(result.issues),\n                };\n              }\n              return { success: true as const, value: (result as { value: unknown }).value };\n            },\n          },\n        );\n      } else {\n        processedInputSchema = applyCompatLayer({\n          schema: originalSchema,\n          compatLayers: schemaCompatLayers,\n          mode: 'aiSdkSchema',\n        });\n      }\n    }\n\n    const outputSchema = this.getOutputSchema();\n    let processedOutputSchema;\n\n    if (outputSchema) {\n      if (isStandardSchemaWithJSON(outputSchema)) {\n        processedOutputSchema = standardSchemaToJSONSchema(outputSchema, { io: 'output' });\n      } else {\n        processedOutputSchema = applyCompatLayer({\n          schema: outputSchema,\n          compatLayers: [],\n          mode: 'aiSdkSchema',\n        });\n      }\n    }\n\n    // Map AI SDK's needsApproval to our requireApproval\n    // needsApproval can be boolean or a function that takes input and returns boolean\n    let requireApproval = false;\n    let needsApprovalFn: NeedsApprovalFn | undefined;\n\n    if (typeof this.options.requireApproval === 'function') {\n      requireApproval = true;\n      needsApprovalFn = this.options.requireApproval;\n    } else if (typeof this.options.requireApproval === 'boolean') {\n      requireApproval = this.options.requireApproval;\n      needsApprovalFn = undefined;\n    }\n\n    if (isVercelTool(this.originalTool) && 'needsApproval' in this.originalTool) {\n      const needsApproval = (this.originalTool as any).needsApproval;\n      if (typeof needsApproval === 'boolean') {\n        requireApproval = needsApproval;\n        needsApprovalFn = undefined;\n      } else if (typeof needsApproval === 'function') {\n        // Store the function to evaluate it per-call\n        needsApprovalFn = needsApproval;\n        // Set requireApproval to true so the tool-call-step knows to check the function\n        requireApproval = true;\n      }\n    }\n\n    // Preserve a needsApprovalFn that was attached directly to the tool instance\n    // (e.g. MCP tools wrap a server-level `requireToolApproval` function and set\n    // `needsApprovalFn` on the tool while keeping `requireApproval` as a boolean).\n    // The branches above only derive needsApprovalFn from options/AI SDK shapes, so\n    // without this it would be dropped during conversion and conditional approval\n    // would silently fall back to the boolean flag.\n    const instanceNeedsApprovalFn = getNeedsApprovalFn(this.originalTool);\n    if (!needsApprovalFn && instanceNeedsApprovalFn) {\n      needsApprovalFn = instanceNeedsApprovalFn;\n      // Ensure the tool-call-step knows to evaluate the function per call.\n      requireApproval = true;\n    }\n\n    const originalBeforeApproval =\n      'beforeApproval' in this.originalTool && typeof this.originalTool.beforeApproval === 'function'\n        ? (this.originalTool.beforeApproval as BeforeApprovalFn)\n        : undefined;\n    const mcpMeta =\n      !isVercelTool(this.originalTool) && 'mcpMetadata' in this.originalTool\n        ? (this.originalTool as { mcpMetadata?: McpMetadata }).mcpMetadata\n        : undefined;\n    // The hook can return data to the model, so it must pass the same TOOLS_EXECUTE check as\n    // execute before it runs; a denial propagates exactly as it would from execute.\n    // The agent runtime validates input with `validateInput` before calling the hook, so the hook\n    // receives parsed input and never runs for invalid calls.\n    const beforeApproval: BeforeApprovalFn | undefined = originalBeforeApproval\n      ? markBuiltBeforeApproval(\n          async (input: unknown, context: BeforeApprovalContext, runtime?: BeforeApprovalRuntime) => {\n            await this.requireToolExecuteFGA(\n              this.options,\n              mcpMeta,\n              runtime?.requestContext ?? this.options.requestContext,\n              runtime?.actor,\n            );\n            return originalBeforeApproval(input, context);\n          },\n        )\n      : undefined;\n\n    const definition = {\n      type: 'function' as const,\n      description: this.originalTool.description,\n      requireApproval,\n      needsApprovalFn,\n      beforeApproval,\n      validateInput: (input: unknown) => {\n        const validation = validateToolInput(\n          (inputValidationSchema ?? originalSchema) as StandardSchemaWithJSON | undefined,\n          input,\n          this.options.name,\n        );\n        // suspendedToolRunId is only required when resumeData is provided (matches execute).\n        if (\n          validation.error?.message?.includes('suspendedToolRunId: Required') &&\n          !(input as Record<string, unknown> | undefined)?.resumeData\n        ) {\n          return { data: input };\n        }\n        return validation;\n      },\n      hasSuspendSchema: !!this.getSuspendSchema(),\n      execute: this.originalTool.execute\n        ? this.createExecute(\n            this.originalTool,\n            { ...this.options, description: this.originalTool.description },\n            this.logType,\n            inputValidationSchema,\n          )\n        : undefined,\n    };\n\n    const builtTool = {\n      ...definition,\n      id: 'id' in this.originalTool ? this.originalTool.id : undefined,\n      title: 'title' in this.originalTool ? this.originalTool.title : undefined,\n      parameters: processedInputSchema ?? z.object({}),\n      outputSchema: processedOutputSchema,\n      strict: 'strict' in this.originalTool ? this.originalTool.strict : undefined,\n      providerOptions: 'providerOptions' in this.originalTool ? this.originalTool.providerOptions : undefined,\n      mcp: 'mcp' in this.originalTool ? this.originalTool.mcp : undefined,\n      toModelOutput: 'toModelOutput' in this.originalTool ? this.originalTool.toModelOutput : undefined,\n      transform: 'transform' in this.originalTool ? this.originalTool.transform : undefined,\n      inputExamples: 'inputExamples' in this.originalTool ? this.originalTool.inputExamples : undefined,\n      onInputStart: 'onInputStart' in this.originalTool ? this.originalTool.onInputStart : undefined,\n      onInputDelta: 'onInputDelta' in this.originalTool ? this.originalTool.onInputDelta : undefined,\n      onInputAvailable: 'onInputAvailable' in this.originalTool ? this.originalTool.onInputAvailable : undefined,\n      onOutput: 'onOutput' in this.originalTool ? this.originalTool.onOutput : undefined,\n      // Preserve tool-level background config so the agentic loop can pick it up\n      // from the converted CoreTool at dispatch time.\n      backgroundConfig: this.options.backgroundConfig,\n    } as unknown as CoreTool;\n\n    registerToolOutputValidationSchema(builtTool, outputSchema);\n    return builtTool;\n  }\n}\n","import { createHash } from 'node:crypto';\nimport type { CoreMessage } from '@internal/ai-sdk-v4';\nimport { jsonSchemaToZod } from '@mastra/schema-compat/json-to-zod';\nimport { z } from 'zod/v4';\nimport type { MastraPrimitives } from './action';\nimport type { ToolsInput } from './agent';\nimport type { FGACheckContext, MastraFGAPermissionInput } from './auth/ee';\nimport type { AgentBackgroundConfig, ToolBackgroundConfig } from './background-tasks';\nimport type { MastraBrowser } from './browser/browser';\nimport { ErrorCategory, ErrorDomain, MastraError } from './error';\nimport type { MastraLanguageModel, MastraLegacyLanguageModel } from './llm/model/shared.types';\nimport type { IMastraLogger } from './logger';\nimport type { Mastra } from './mastra';\nimport type { AiMessageType, MastraMemory } from './memory';\nimport type { ObservabilityContext, TracingPolicy } from './observability';\nimport type { RequestContext } from './request-context';\nimport type { CoreTool, VercelTool, VercelToolV5 } from './tools';\nimport { Tool } from './tools/tool';\nimport { CoreToolBuilder } from './tools/tool-builder/builder';\nimport type { ToolToConvert } from './tools/tool-builder/builder';\nimport { isVercelTool } from './tools/toolchecks';\nimport type { OutputWriter } from './workflows/types';\nimport type { Workspace } from './workspace/workspace';\n\n// Re-export Zod utilities for external use (isZodType is defined locally below)\nexport { getZodTypeName, getZodDef, isZodArray, isZodObject } from './utils/zod-utils';\nexport { fetchWithRetry } from './utils/fetchWithRetry';\nexport type { FetchWithRetryOptions } from './utils/fetchWithRetry';\n\nexport { boundedStringify, ensureSerializable, isBoundedSerializable, safeStringify } from './utils/safe-stringify';\nexport { deepEqual } from './utils/deep-equal';\nexport { getRequestUser, resolveDynamicArgument } from './utils/dynamic-argument';\n\n/** Resolves after `ms`, or as soon as `signal` aborts. */\nexport const delay = (ms: number, signal?: AbortSignal) =>\n  new Promise<void>(resolve => {\n    if (signal?.aborted) return resolve();\n    const onAbort = () => {\n      clearTimeout(timer);\n      resolve();\n    };\n    const timer = setTimeout(() => {\n      signal?.removeEventListener('abort', onAbort);\n      resolve();\n    }, ms);\n    signal?.addEventListener('abort', onAbort, { once: true });\n  });\n\n/**\n * Read a positive-integer environment variable (e.g. a TTL in ms). Unset, empty,\n * non-numeric, fractional, or non-positive values fall back to `fallback`.\n */\nexport function readPositiveIntEnv(name: string, fallback: number): number {\n  const raw = process.env[name];\n  if (!raw) return fallback;\n  const parsed = Number(raw);\n  return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;\n}\n\n/**\n * Checks if a value is a plain object (not an array, function, Date, RegExp, etc.)\n */\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n  if (value === null || typeof value !== 'object') return false;\n  const proto = Object.getPrototypeOf(value);\n  return proto === Object.prototype || proto === null;\n}\n\n/**\n * Deep merges two objects, recursively merging nested plain objects.\n * Arrays, functions, and other non-plain objects are replaced (not merged).\n */\nexport function deepMerge<T extends object = object>(target: T, source: Partial<T>): T {\n  const output = { ...target };\n\n  if (!source) return output;\n\n  Object.keys(source).forEach(key => {\n    const targetValue = (output as Record<string, unknown>)[key];\n    const sourceValue = (source as Record<string, unknown>)[key];\n\n    // Only deep merge if both values are plain objects\n    if (isPlainObject(targetValue) && isPlainObject(sourceValue)) {\n      (output as Record<string, unknown>)[key] = deepMerge(targetValue, sourceValue);\n    } else if (sourceValue !== undefined) {\n      // For arrays, functions, primitives, and other non-plain objects: replace\n      (output as Record<string, unknown>)[key] = sourceValue;\n    }\n  });\n\n  return output;\n}\n\n/**\n * Generate an empty object from a JSON Schema definition.\n * Accepts both a JSON string and a pre-parsed object.\n * Recursively initializes nested object properties and respects default values.\n */\nexport function generateEmptyFromSchema(schema: string | Record<string, unknown>): Record<string, unknown> {\n  try {\n    const parsedSchema = typeof schema === 'string' ? JSON.parse(schema) : schema;\n    if (!parsedSchema || parsedSchema.type !== 'object' || !parsedSchema.properties) return {};\n    const obj: Record<string, unknown> = {};\n    for (const [key, prop] of Object.entries<Record<string, unknown>>(\n      parsedSchema.properties as Record<string, Record<string, unknown>>,\n    )) {\n      if (prop.default !== undefined) {\n        obj[key] =\n          typeof prop.default === 'object' && prop.default !== null\n            ? JSON.parse(JSON.stringify(prop.default))\n            : prop.default;\n      } else if (prop.type === 'object' && prop.properties) {\n        obj[key] = generateEmptyFromSchema(prop);\n      } else if (prop.type === 'object') {\n        obj[key] = {};\n      } else if (prop.type === 'string') {\n        obj[key] = '';\n      } else if (prop.type === 'array') {\n        obj[key] = [];\n      } else if (prop.type === 'number' || prop.type === 'integer') {\n        obj[key] = 0;\n      } else if (prop.type === 'boolean') {\n        obj[key] = false;\n      } else {\n        obj[key] = null;\n      }\n    }\n    return obj;\n  } catch {\n    return {};\n  }\n}\n\nexport interface TagMaskOptions {\n  /** Called when masking begins */\n  onStart?: () => void;\n  /** Called when masking ends */\n  onEnd?: () => void;\n  /** Called for each chunk that is masked */\n  onMask?: (chunk: string) => void;\n}\n\n/**\n * Transforms a stream by masking content between XML tags.\n * @param stream Input stream to transform\n * @param tag Tag name to mask between (e.g. for <foo>...</foo>, use 'foo')\n * @param options Optional configuration for masking behavior\n */\nexport async function* maskStreamTags(\n  stream: AsyncIterable<string>,\n  tag: string,\n  options: TagMaskOptions = {},\n): AsyncIterable<string> {\n  const { onStart, onEnd, onMask } = options;\n  const openTag = `<${tag}>`;\n  const closeTag = `</${tag}>`;\n\n  let buffer = '';\n  let fullContent = '';\n  let isMasking = false;\n  let isBuffering = false;\n\n  // used for checking in chunks that include tags or partial tags + some other non-tag text\n  // eg: \"o <tag_name\" or \"name> w\", can trim before-start to get \"<tag_name\" or after-end to get \"name>\"\n  const trimOutsideDelimiter = (text: string, delimiter: string, trim: 'before-start' | 'after-end') => {\n    if (!text.includes(delimiter)) {\n      return text;\n    }\n\n    const parts = text.split(delimiter);\n\n    if (trim === `before-start`) {\n      return `${delimiter}${parts[1]}`;\n    }\n\n    return `${parts[0]}${delimiter}`;\n  };\n\n  // Helper to check if text starts with pattern (ignoring whitespace)\n  // When checking partial tags: startsWith(buffer, openTag) checks if buffer could be start of tag\n  // When checking full tags: startsWith(chunk, openTag) checks if chunk starts with full tag\n  const startsWith = (text: string, pattern: string) => {\n    // check start of opening tag\n    if (pattern.includes(openTag.substring(0, 3))) {\n      // our pattern for checking the start is always based on xml-like tags\n      // if the pattern looks like our opening tag and the pattern also includes\n      // some other chunked text before it, we just wanted to check the xml part of the pattern\n      pattern = trimOutsideDelimiter(pattern, `<`, `before-start`);\n    }\n\n    return text.trim().startsWith(pattern.trim());\n  };\n\n  for await (const chunk of stream) {\n    fullContent += chunk;\n\n    if (isBuffering) buffer += chunk;\n\n    const chunkHasTag = startsWith(chunk, openTag);\n    const bufferHasTag = !chunkHasTag && isBuffering && startsWith(openTag, buffer);\n\n    let toYieldBeforeMaskedStartTag = ``;\n    // Check if we should start masking chunks\n    if (!isMasking && (chunkHasTag || bufferHasTag)) {\n      isMasking = true;\n      isBuffering = false;\n\n      // check if the buffered text includes text before the start tag. ex \"o <tag_name\", \"o\" should be yielded and not masked\n      const taggedTextToMask = trimOutsideDelimiter(buffer, `<`, `before-start`);\n      if (taggedTextToMask !== buffer.trim()) {\n        toYieldBeforeMaskedStartTag = buffer.replace(taggedTextToMask, ``);\n      }\n\n      buffer = '';\n      onStart?.();\n    }\n\n    // Check if we should start buffering (looks like part of the opening tag but it's not the full <tag> yet eg <ta - could be <table> but we don't know yet)\n    if (!isMasking && !isBuffering && startsWith(openTag, chunk) && chunk.trim() !== '') {\n      isBuffering = true;\n      buffer += chunk;\n      continue;\n    }\n\n    // We're buffering, need to check again if our buffer has deviated from the opening <tag> eg <tag2>\n    if (isBuffering && buffer && !startsWith(openTag, buffer)) {\n      yield buffer;\n      buffer = '';\n      isBuffering = false;\n      continue;\n    }\n\n    // Check if we should stop masking chunks (since the content includes the closing </tag>)\n    if (isMasking && fullContent.includes(closeTag)) {\n      onMask?.(chunk);\n      onEnd?.();\n      isMasking = false;\n      const lastFullContent = fullContent;\n      fullContent = ``; // reset to handle streams with multiple full tags that have text inbetween\n\n      // check to see if we have a partial chunk outside the close tag. if we do we need to yield it so it isn't swallowed with the masked text\n      const textUntilEndTag = trimOutsideDelimiter(lastFullContent, closeTag, 'after-end');\n      if (textUntilEndTag !== lastFullContent) {\n        yield lastFullContent.replace(textUntilEndTag, ``);\n      }\n\n      continue;\n    }\n\n    // We're currently masking chunks inside a <tag>\n    if (isMasking) {\n      onMask?.(chunk);\n      // in the case that there was a chunk that included a tag to mask and some other text, ex \"o <tag_name\" we need to still yield the\n      // text before the tag (\"o \") so it's not swallowed with the masked text\n      if (toYieldBeforeMaskedStartTag) {\n        yield toYieldBeforeMaskedStartTag;\n      }\n      continue;\n    }\n\n    // default yield the chunk\n    yield chunk;\n  }\n}\n\n/**\n * Resolve serialized zod output - This function takes the string output ot the `jsonSchemaToZod` function\n * and instantiates the zod object correctly.\n *\n * @param schema - serialized zod object\n * @returns resolved zod object\n */\nexport function resolveSerializedZodOutput(schema: string): z.ZodType {\n  // Creates and immediately executes a new function that takes 'z' as a parameter\n  // The function body is a string that returns the serialized zod schema\n  // When executed with the 'z' parameter, it reconstructs the zod schema in the current context\n  return Function('z', `\"use strict\";return (${schema});`)(z);\n}\n\nexport interface ToolOptions extends Partial<ObservabilityContext> {\n  name: string;\n  runId?: string;\n  threadId?: string;\n  resourceId?: string;\n  logger?: IMastraLogger;\n  description?: string;\n  mastra?: (Mastra & MastraPrimitives) | MastraPrimitives;\n  requestContext: RequestContext;\n  tracingPolicy?: TracingPolicy;\n  memory?: MastraMemory;\n  agentName?: string;\n  agentId?: string;\n  model?: MastraLanguageModel | MastraLegacyLanguageModel;\n  /**\n   * Optional async writer used to stream tool output chunks back to the caller. Tools should treat this as fire-and-forget I/O.\n   */\n  outputWriter?: OutputWriter;\n  requireApproval?:\n    | boolean\n    | ((\n        input: any,\n        ctx?: { requestContext?: Record<string, unknown>; workspace?: Workspace },\n      ) => boolean | Promise<boolean>);\n  // Workflow-specific properties\n  workflow?: any;\n  workflowId?: string;\n  state?: any;\n  setState?: (state: any) => void;\n  /**\n   * Workspace available for tool execution. When provided, tools can access\n   * workspace.filesystem and workspace.sandbox for file operations and command execution.\n   */\n  workspace?: Workspace;\n  backgroundConfig?: ToolBackgroundConfig;\n  /**\n   * Agent-level backgroundTasks config. Combined with `backgroundConfig` (the\n   * tool-level config) to decide whether the `_background` override schema is\n   * injected for this specific tool. See `isToolBackgroundEligible`.\n   */\n  agentBackgroundConfig?: AgentBackgroundConfig;\n  /**\n   * Browser available for tool execution. When provided, tools can access\n   * browser capabilities for web automation, screenshots, and data extraction.\n   */\n  browser?: MastraBrowser;\n  /**\n   * Resolves what this tool's `tools:execute` check authorizes against, when the tool's owner has its\n   * own rule (`MCPServer` checks its tools against its own resource and `fga` mapping). Without it,\n   * the check uses the standalone or agent tool resource.\n   * @internal\n   */\n  resolveExecuteFGA?: (ctx: { user: unknown; requestContext?: RequestContext }) => Promise<ToolExecuteFGACheck>;\n}\n\n/**\n * The FGA check a tool runs before each execution, as returned by `ToolOptions.resolveExecuteFGA`.\n * @internal\n */\nexport interface ToolExecuteFGACheck {\n  resource: { type: string; id: string };\n  permission: MastraFGAPermissionInput;\n  /** Merged into the check context the FGA provider receives. */\n  context?: FGACheckContext;\n  /** Merged into the check metadata the FGA provider receives. */\n  metadata?: Record<string, unknown>;\n}\n\n/**\n * Checks if a value is a Zod type\n * @param value - The value to check\n * @returns True if the value is a Zod type, false otherwise\n */\nexport function isZodType(value: unknown): value is z.ZodType {\n  // Check if it's a Zod schema by looking for common Zod properties and methods\n  return (\n    typeof value === 'object' &&\n    value !== null &&\n    '_def' in value &&\n    'parse' in value &&\n    typeof (value as any).parse === 'function' &&\n    'safeParse' in value &&\n    typeof (value as any).safeParse === 'function'\n  );\n}\n\n// Helper function to create a deterministic hash\nfunction createDeterministicId(input: string): string {\n  return createHash('sha256').update(input).digest('hex').slice(0, 8); // Take first 8 characters for a shorter but still unique ID\n}\n\n/**\n * Sets the properties for a Vercel Tool, including an ID and inputSchema\n * @param tool - The tool to set the properties for\n * @returns The tool with the properties set\n */\nfunction setVercelToolProperties(tool: VercelTool) {\n  // Check if the tool already has inputSchema (v5 format)\n  // If it does, use it directly (it might be a function)\n  // Otherwise, convert the parameters to inputSchema\n  const inputSchema = 'inputSchema' in tool ? tool.inputSchema : convertVercelToolParameters(tool);\n\n  const toolId = !('id' in tool)\n    ? tool.description\n      ? `tool-${createDeterministicId(tool.description)}`\n      : `tool-${Math.random().toString(36).substring(2, 9)}`\n    : tool.id;\n\n  return {\n    ...tool,\n    id: toolId,\n    inputSchema,\n  };\n}\n\n/**\n * Ensures a tool has an ID and inputSchema by generating one if not present\n * @param tool - The tool to ensure has an ID and inputSchema\n * @returns The tool with an ID and inputSchema\n */\nexport function ensureToolProperties(tools: ToolsInput): ToolsInput {\n  const toolsWithProperties = Object.keys(tools).reduce<ToolsInput>((acc, key) => {\n    const tool = tools?.[key];\n    if (tool) {\n      // Check if the tool is a plain function (not a Tool instance or Vercel tool)\n      // This catches the common mistake of passing a tool factory function instead of the tool itself\n      // We need to cast to unknown first since ToolsInput doesn't include functions in its type,\n      // but users can still pass functions at runtime which causes silent failures\n      if (typeof tool === 'function' && !((tool as unknown) instanceof Tool) && !isVercelTool(tool)) {\n        throw new MastraError({\n          id: 'TOOL_INVALID_FORMAT',\n          domain: ErrorDomain.TOOL,\n          category: ErrorCategory.USER,\n          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.`,\n        });\n      }\n\n      if (isVercelTool(tool)) {\n        acc[key] = setVercelToolProperties(tool) as VercelTool;\n      } else {\n        acc[key] = tool;\n      }\n    }\n    return acc;\n  }, {});\n\n  return toolsWithProperties;\n}\n\nfunction convertVercelToolParameters(tool: VercelTool): z.ZodType {\n  // If the tool is a Vercel Tool, check if the parameters are already a zod object\n  // If not, convert the parameters to a zod object using jsonSchemaToZod\n  // Handle case where parameters (or inputSchema in v5) is a function that returns a schema\n  let schema = tool.parameters ?? z.object({});\n\n  // If schema is a function, call it to get the actual schema\n  if (typeof schema === 'function') {\n    schema = schema();\n  }\n\n  return isZodType(schema) ? schema : resolveSerializedZodOutput(jsonSchemaToZod(schema));\n}\n\n/**\n * Converts a Vercel Tool or Mastra Tool into a CoreTool format\n * @param originalTool - The tool to convert (either VercelTool or ToolAction)\n * @param options - Tool options including Mastra-specific settings\n * @param logType - Type of tool to log (tool or toolset)\n * @returns A CoreTool that can be used by the system\n */\nexport function makeCoreTool(\n  originalTool: ToolToConvert,\n  options: ToolOptions,\n  logType?: 'tool' | 'toolset' | 'client-tool',\n  autoResumeSuspendedTools?: boolean,\n  backgroundTaskEnabled?: boolean,\n): CoreTool {\n  return new CoreToolBuilder({\n    originalTool,\n    options,\n    logType,\n    autoResumeSuspendedTools,\n    backgroundTaskEnabled,\n  }).build();\n}\n\nconst rebindToRequestContext = Symbol('rebindToRequestContext');\n\n/**\n * Converts a raw tool an input processor added during a step. The processor does not run\n * again before a suspended call resumes, so the converted tool remembers how to rebuild\n * itself for the resuming call's request context (see {@link rebindProcessorTools}).\n */\nexport function makeProcessorCoreTool(...args: Parameters<typeof makeCoreTool>): CoreTool {\n  const [originalTool, options, ...rest] = args;\n  const tool = makeCoreTool(originalTool, options, ...rest);\n  Object.defineProperty(tool, rebindToRequestContext, {\n    value: (requestContext: RequestContext) =>\n      makeProcessorCoreTool(originalTool, { ...options, requestContext }, ...rest),\n  });\n  return tool;\n}\n\n/**\n * Rebuilds the processor-added tools in `tools` for `requestContext`, the way request tools\n * are rebuilt when a suspended run resumes, so an approved processor tool runs with the\n * approver's request context like a statically defined tool does.\n */\nexport function rebindProcessorTools<T extends Record<string, unknown>>(tools: T, requestContext: RequestContext): T {\n  const rebound: Record<string, unknown> = { ...tools };\n  for (const [name, tool] of Object.entries(tools)) {\n    const rebind = (tool as { [rebindToRequestContext]?: (rc: RequestContext) => CoreTool } | undefined)?.[\n      rebindToRequestContext\n    ];\n    if (rebind) rebound[name] = rebind(requestContext);\n  }\n  return rebound as T;\n}\n\nexport function makeCoreToolV5(\n  originalTool: ToolToConvert,\n  options: ToolOptions,\n  logType?: 'tool' | 'toolset' | 'client-tool',\n  autoResumeSuspendedTools?: boolean,\n  backgroundTaskEnabled?: boolean,\n): VercelToolV5 {\n  return new CoreToolBuilder({\n    originalTool,\n    options,\n    logType,\n    autoResumeSuspendedTools,\n    backgroundTaskEnabled,\n  }).buildV5();\n}\n\n/**\n * Creates a proxy for a Mastra instance to handle deprecated properties\n * @param mastra - The Mastra instance to proxy\n * @param logger - The logger to use for warnings\n * @returns A proxy for the Mastra instance\n */\nexport function createMastraProxy({ mastra, logger }: { mastra: Mastra; logger: IMastraLogger }) {\n  return new Proxy(mastra, {\n    get(target, prop) {\n      const hasProp = Reflect.has(target, prop);\n\n      if (hasProp) {\n        const value = Reflect.get(target, prop);\n        const isFunction = typeof value === 'function';\n        if (isFunction) {\n          return value.bind(target);\n        }\n        return value;\n      }\n\n      if (prop === 'logger') {\n        logger.warn(\"Please use 'getLogger' instead, logger is deprecated\");\n        return Reflect.apply(target.getLogger, target, []);\n      }\n\n      if (prop === 'storage') {\n        logger.warn(\"Please use 'getStorage' instead, storage is deprecated\");\n        return Reflect.get(target, 'storage');\n      }\n\n      if (prop === 'agents') {\n        logger.warn(\"Please use 'listAgents' instead, agents is deprecated\");\n        return Reflect.apply(target.listAgents, target, []);\n      }\n\n      if (prop === 'tts') {\n        logger.warn(\"Please use 'getTTS' instead, tts is deprecated\");\n        return Reflect.apply(target.getTTS, target, []);\n      }\n\n      if (prop === 'vectors') {\n        logger.warn(\"Please use 'getVectors' instead, vectors is deprecated\");\n        return Reflect.apply(target.getVectors, target, []);\n      }\n\n      if (prop === 'memory') {\n        logger.warn(\"Please use 'getMemory' instead, memory is deprecated\");\n        return Reflect.get(target, 'memory');\n      }\n\n      return Reflect.get(target, prop);\n    },\n  });\n}\n\nexport function checkEvalStorageFields(traceObject: any, logger?: IMastraLogger) {\n  const missingFields = [];\n  if (!traceObject.input) missingFields.push('input');\n  if (!traceObject.output) missingFields.push('output');\n  if (!traceObject.agentName) missingFields.push('agent_name');\n  if (!traceObject.metricName) missingFields.push('metric_name');\n  if (!traceObject.instructions) missingFields.push('instructions');\n  if (!traceObject.globalRunId) missingFields.push('global_run_id');\n  if (!traceObject.runId) missingFields.push('run_id');\n\n  if (missingFields.length > 0) {\n    if (logger) {\n      logger.warn('Skipping evaluation storage due to missing required fields', {\n        missingFields,\n        runId: traceObject.runId,\n        agentName: traceObject.agentName,\n      });\n    } else {\n      console.warn('Skipping evaluation storage due to missing required fields', {\n        missingFields,\n        runId: traceObject.runId,\n        agentName: traceObject.agentName,\n      });\n    }\n    return false;\n  }\n\n  return true;\n}\n\n// lifted from https://github.com/vercel/ai/blob/main/packages/ai/core/prompt/detect-prompt-type.ts#L27\nfunction detectSingleMessageCharacteristics(\n  message: any,\n): 'has-ui-specific-parts' | 'has-core-specific-parts' | 'message' | 'other' {\n  if (\n    typeof message === 'object' &&\n    message !== null &&\n    (message.role === 'function' || // UI-only role\n      message.role === 'data' || // UI-only role\n      'toolInvocations' in message || // UI-specific field\n      'parts' in message || // UI-specific field\n      'experimental_attachments' in message)\n  ) {\n    return 'has-ui-specific-parts';\n  } else if (\n    typeof message === 'object' &&\n    message !== null &&\n    'content' in message &&\n    (Array.isArray(message.content) || // Core messages can have array content\n      'experimental_providerMetadata' in message ||\n      'providerOptions' in message)\n  ) {\n    return 'has-core-specific-parts';\n  } else if (\n    typeof message === 'object' &&\n    message !== null &&\n    'role' in message &&\n    'content' in message &&\n    typeof message.content === 'string' &&\n    ['system', 'user', 'assistant', 'tool'].includes(message.role)\n  ) {\n    return 'message';\n  }\n  return 'other';\n}\n\nexport function isUiMessage(message: CoreMessage | AiMessageType): message is AiMessageType {\n  return detectSingleMessageCharacteristics(message) === `has-ui-specific-parts`;\n}\nexport function isCoreMessage(message: CoreMessage | AiMessageType): message is CoreMessage {\n  return [`has-core-specific-parts`, `message`].includes(detectSingleMessageCharacteristics(message));\n}\n\n/** Represents a validated SQL identifier (e.g., table or column name). */\ntype SqlIdentifier = string & { __brand: 'SqlIdentifier' };\n/** Represents a validated dot-separated SQL field key. */\ntype FieldKey = string & { __brand: 'FieldKey' };\n\nconst SQL_IDENTIFIER_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\n\n/**\n * Parses and returns a valid SQL identifier (such as a table or column name).\n * The identifier must:\n *   - Start with a letter (a-z, A-Z) or underscore (_)\n *   - Contain only letters, numbers, or underscores\n *   - Be at most 63 characters long\n *\n * @param name - The identifier string to parse.\n * @param kind - Optional label for error messages (e.g., 'table name').\n * @returns The validated identifier as a branded type.\n * @throws {Error} If the identifier does not conform to SQL naming rules.\n *\n * @example\n * const id = parseSqlIdentifier('my_table'); // Ok\n * parseSqlIdentifier('123table'); // Throws error\n */\nexport function parseSqlIdentifier(name: string, kind = 'identifier'): SqlIdentifier {\n  if (!SQL_IDENTIFIER_PATTERN.test(name) || name.length > 63) {\n    throw new Error(\n      `Invalid ${kind}: ${name}. Must start with a letter or underscore, contain only letters, numbers, or underscores, and be at most 63 characters long.`,\n    );\n  }\n  return name as SqlIdentifier;\n}\n\n/**\n * Parses and returns a valid dot-separated SQL field key (e.g., 'user.profile.name').\n * Each segment must:\n *   - Start with a letter (a-z, A-Z) or underscore (_)\n *   - Contain only letters, numbers, or underscores\n *   - Be at most 63 characters long\n *\n * @param key - The dot-separated field key string to parse.\n * @returns The validated field key as a branded type.\n * @throws {Error} If any segment of the key is invalid.\n *\n * @example\n * const key = parseFieldKey('user_profile.name'); // Ok\n * parseFieldKey('user..name'); // Throws error\n * parseFieldKey('user.123name'); // Throws error\n */\nexport function parseFieldKey(key: string): FieldKey {\n  if (!key) throw new Error('Field key cannot be empty');\n  const segments = key.split('.');\n  for (const segment of segments) {\n    if (!SQL_IDENTIFIER_PATTERN.test(segment) || segment.length > 63) {\n      throw new Error(`Invalid field key segment: ${segment} in ${key}`);\n    }\n  }\n  return key as FieldKey;\n}\n\n/**\n * Removes specific keys from an object.\n * @param obj - The original object\n * @param keysToOmit - Keys to exclude from the returned object\n * @returns A new object with the specified keys removed\n */\nexport function omitKeys<T extends Record<string, any>>(obj: T, keysToOmit: string[]): Partial<T> {\n  return Object.fromEntries(Object.entries(obj).filter(([key]) => !keysToOmit.includes(key))) as Partial<T>;\n}\n\n/**\n * Selectively extracts specific fields from an object using dot notation.\n * Does not error if fields don't exist - simply omits them from the result.\n * @param obj - The source object to extract fields from\n * @param fields - Array of field paths (supports dot notation like 'output.text')\n * @returns New object containing only the specified fields\n */\nexport function selectFields(obj: any, fields: string[]): any {\n  if (!obj || typeof obj !== 'object') {\n    return obj;\n  }\n\n  const result: any = {};\n\n  for (const field of fields) {\n    const value = getNestedValue(obj, field);\n    if (value !== undefined) {\n      setNestedValue(result, field, value);\n    }\n  }\n\n  return result;\n}\n\n/**\n * Gets a nested value from an object using dot notation\n * @param obj - Source object\n * @param path - Dot notation path (e.g., 'output.text')\n * @returns The value at the path, or undefined if not found\n */\nexport function getNestedValue(obj: any, path: string): any {\n  return path.split('.').reduce((current, key) => {\n    return current && typeof current === 'object' ? current[key] : undefined;\n  }, obj);\n}\n\n/**\n * Sets a nested value in an object using dot notation\n * @param obj - Target object\n * @param path - Dot notation path (e.g., 'output.text')\n * @param value - Value to set\n */\nexport function setNestedValue(obj: any, path: string, value: any): void {\n  const keys = path.split('.');\n  const lastKey = keys.pop();\n  if (!lastKey) return;\n\n  // Validate every segment up-front so we never walk or assign through\n  // a prototype-mutating key like \"__proto__\", \"constructor\", or \"prototype\".\n  for (const key of keys) {\n    if (key === '__proto__' || key === 'constructor' || key === 'prototype') {\n      return;\n    }\n  }\n  if (lastKey === '__proto__' || lastKey === 'constructor' || lastKey === 'prototype') {\n    return;\n  }\n\n  let current = obj;\n  for (const key of keys) {\n    const existing = Object.prototype.hasOwnProperty.call(current, key) ? current[key] : undefined;\n    if (existing === null || typeof existing !== 'object') {\n      // Use a null-prototype object so intermediate containers cannot be\n      // used as a prototype-pollution sink even if a sanitizer check is\n      // bypassed upstream.\n      const container = Object.create(null);\n      Object.defineProperty(current, key, { value: container, writable: true, enumerable: true, configurable: true });\n    }\n    current = current[key];\n  }\n\n  Object.defineProperty(current, lastKey, { value, writable: true, enumerable: true, configurable: true });\n}\n\nexport const removeUndefinedValues = (obj: Record<string, any>) => {\n  return Object.fromEntries(Object.entries(obj).filter(([_, value]) => value !== undefined));\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAKA,MAAM,yBAAS,IAAI,IAAiC;AAEpD,SAAgB,iBAAiB,OAAe,OAAkC;CAChF,OAAO,IAAI,OAAO,KAAK;AACzB;;;;;AAMA,SAAgB,mBAAmB,OAAe,OAAkC;CAClF,IAAI,OAAO,IAAI,KAAK,MAAM,OAAO,OAAO,OAAO,KAAK;AACtD;;AAQA,eAAsB,eAAe,OAA0C;CAC7E,IAAI,OAAO,MAAM,OAAO,IAAI,KAAK,CAAC,GAAG;AACvC;;;;;;;AAQA,MAAM,+BAAe,IAAI,QAAiE;;AAE1F,MAAM,oCAAoB,IAAI,QAAwB;;AAGtD,SAAgB,aAAa,OAAuC;CAClE,IAAI,CAAC,OAAO,aAAa,CAAC;CAC1B,MAAM,QAAQ,aAAa,IAAI,KAAK,KAAK;EAAE,OAAO;EAAG,WAAW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