import { n as A2UIInjectConfig } from "./a2ui-tool-LioaBmzs.mjs"; import { AbstractAgent, AgentConfig, BaseEvent, Message, RunAgentInput } from "@ag-ui/client"; import { RequestContext } from "@mastra/core/request-context"; import { Observable } from "rxjs"; import { Agent } from "@mastra/core/agent"; import { MastraClient } from "@mastra/client-js"; import { Mastra } from "@mastra/core"; import { CoreMessage } from "@mastra/core/llm"; //#region src/utils.d.ts /** * CoreMessage extended with an optional `id` field. * Mastra's `inputToMastraDBMessage` checks `"id" in message` at runtime * and preserves it when present, but the upstream AI SDK type doesn't * declare the field. This type makes the pass-through explicit. * Ref: https://github.com/mastra-ai/mastra/blob/13f46064564fc4aee14aa11878f9352d79f4efc4/packages/core/src/agent/message-list/conversion/input-converter.ts#L79 */ type CoreMessageWithId = CoreMessage & { id?: string; }; declare function convertAGUIMessagesToMastra(messages: Message[], lookupMessages?: Message[]): CoreMessageWithId[]; interface GetRemoteAgentsOptions { mastraClient: MastraClient; resourceId: string; /** * Surface Mastra Observational Memory (OM) background work as AG-UI activity * events (activityType `mastra-observational-memory`). `true` enables it for * every agent; pass an array of agent ids to enable it only for those. * Default OFF. The remote agent must have OM enabled on its Memory server-side * — this only controls whether the bridge surfaces the `data-om-*` chunks it * streams. See `MastraAgentConfig.observationalMemory`. */ observationalMemory?: boolean | string[]; /** Mastra tracing options forwarded to each run. See MastraAgentConfig.tracingOptions. */ tracingOptions?: MastraTracingOptions; } declare function getRemoteAgents({ mastraClient, resourceId, observationalMemory, tracingOptions }: GetRemoteAgentsOptions): Promise>; interface GetLocalAgentsOptions { mastra: Mastra; resourceId: string; requestContext?: RequestContext; /** * Enable Mastra's `untilIdle` run mode (background-task lifecycle piped into * the run's fullStream). `true` enables it for every agent; pass an array of * agent ids to enable it only for those. See `MastraAgentConfig.untilIdle`. */ untilIdle?: boolean | string[]; /** * Surface Mastra Observational Memory (OM) background work as AG-UI activity * events (activityType `mastra-observational-memory`). `true` enables it for * every agent; pass an array of agent ids to enable it only for those. * Default OFF. See `MastraAgentConfig.observationalMemory`. */ observationalMemory?: boolean | string[]; /** Mastra tracing options forwarded to each run. See MastraAgentConfig.tracingOptions. */ tracingOptions?: MastraTracingOptions; } declare function getLocalAgents({ mastra, resourceId, requestContext, untilIdle, observationalMemory, tracingOptions }: GetLocalAgentsOptions): Record; interface GetLocalAgentOptions { mastra: Mastra; agentId: string; resourceId: string; requestContext?: RequestContext; /** Mastra tracing options forwarded to the run. See MastraAgentConfig.tracingOptions. */ tracingOptions?: MastraTracingOptions; } declare function getLocalAgent({ mastra, agentId, resourceId, requestContext, tracingOptions }: GetLocalAgentOptions): AbstractAgent; interface GetNetworkOptions { mastra: Mastra; networkId: string; resourceId: string; requestContext?: RequestContext; /** Mastra tracing options forwarded to the run. See MastraAgentConfig.tracingOptions. */ tracingOptions?: MastraTracingOptions; } declare function getNetwork({ mastra, networkId, resourceId, requestContext, tracingOptions }: GetNetworkOptions): AbstractAgent; //#endregion //#region src/mastra.d.ts type RemoteMastraAgent = ReturnType; /** * AG-UI `activityType` used for Mastra Background Tasks. Background work * (a tool with `background: { enabled: true }`) runs out-of-band while the * agent conversation continues; the bridge surfaces its lifecycle as AG-UI * ACTIVITY_SNAPSHOT / ACTIVITY_DELTA events so the UI can render it distinctly * from normal streamed responses. Renderers register against this string via * CopilotKit's `renderActivityMessages` prop. * * The activity `content` shape (one activity per Mastra task; `messageId` is * the Mastra `taskId`): * * { * taskId: string; // Mastra background task id (== activity messageId) * toolName: string; // the backgrounded tool * toolCallId: string; // originating tool call * status: "started" | "running" | "suspended" | "resumed" * | "completed" | "failed" | "cancelled"; * args?: Record; // tool args, once running * outputs: unknown[]; // streamed tool-output chunks, appended in order * elapsedMs?: number; // wall-clock since dispatch, ticked by progress * result?: unknown; // final result on completion * error?: string; // message on failure * suspendPayload?: unknown; // data passed to suspend(), when suspended * startedAt?: string; // ISO timestamp * completedAt?: string; // ISO timestamp * } * * This shape is a sensible default proposed by the AG-UI bridge; it is intended * to be co-designed with Mastra (see OSS-93) and may evolve. */ declare const MASTRA_BACKGROUND_TASK_ACTIVITY_TYPE = "mastra-background-task"; /** * AG-UI `activityType` used for Mastra Observational Memory (OM). OM is a * Mastra memory feature the developer enables on THEIR agent * (`new Memory({ options: { observationalMemory: true } })`). When enabled, * Mastra runs Observer/Reflector agents out of band that read the conversation, * compress it into observations, and activate them into the context window. OM * surfaces this background work on the agent's `fullStream` as typed * `data-om-*` chunks (see `@mastra/core/channels/om` + the `@mastra/memory` OM * processor). The bridge maps the substantive lifecycle of those chunks to * AG-UI ACTIVITY_SNAPSHOT / ACTIVITY_DELTA events so the UI can render the * "agent is observing / reflecting / compressing memory" activity distinctly * from the streamed response. Renderers register against this string via * CopilotKit's `renderActivityMessages` prop. * * Surfacing is OPT-IN per agent (`MastraAgentConfig.observationalMemory`, * default OFF) — OM is the developer's own opt-in, so the bridge does not * announce it unless asked. With the toggle OFF the `data-om-*` chunks are * swallowed silently (they carry no assistant output), so an OM-enabled agent * still streams cleanly through the bridge and emits no activity. * * The activity `content` shape (one activity per OM cycle; `messageId` is the * Mastra `cycleId`). In the async path the buffering cycle and its activation * share one `cycleId`, so they advance a single activity * running -> completed -> activated: * * { * cycleId: string; // Mastra OM cycle id (== activity messageId) * operationType: "observation" | "reflection"; * phase: "observation" | "buffering" | "activation"; * status: "running" | "completed" | "failed" | "activated"; * threadId?: string; * recordId?: string; * observations?: string; // the observation/reflection summary text * currentTask?: string; // task the Observer extracted * suggestedResponse?: string; // suggestion the Observer extracted * tokensToObserve?: number; // observation/buffering: tokens in this batch * tokensObserved?: number; // observation: tokens observed * bufferedTokens?: number; // buffering: resulting tokens after compress * observationTokens?: number; // resulting observation tokens * tokensActivated?: number; // activation: message tokens activated * chunksActivated?: number; // activation: buffered chunks activated * messagesActivated?: number; // activation: messages observed via activation * generationCount?: number; // activation: reflection generation count * triggeredBy?: "threshold" | "ttl" | "provider_change"; * durationMs?: number; * startedAt?: string; // ISO timestamp * completedAt?: string; // ISO timestamp * error?: string; // message on failure * } * * This shape is a sensible default proposed by the AG-UI bridge; it mirrors the * background-task activity shape and may evolve alongside Mastra's OM data * parts (see OSS-92). */ declare const MASTRA_OBSERVATIONAL_MEMORY_ACTIVITY_TYPE = "mastra-observational-memory"; /** * Mastra tracing options threaded into the underlying `agent.stream(...)` / * `agent.resumeStream(...)` call. Typed structurally (not against * `@mastra/core`) so the bridge compiles on any supported core in the peer * range — cores predating observability v-next simply ignore an unknown * `tracingOptions` key. Mirrors Mastra's `TracingOptions`: * - `traceId`: a caller-chosen trace id to anchor the run under (lets a client * self-assign a trace it already knows, e.g. to attach feedback later). * - `metadata`: arbitrary key/values attached to the run's root trace span. */ interface MastraTracingOptions { traceId?: string; metadata?: Record; } interface MastraAgentConfig extends AgentConfig { agent: Agent | RemoteMastraAgent; resourceId?: string; requestContext?: RequestContext; /** * Forward Mastra tracing options into the run's `agent.stream(...)` (and the * resume path). Chiefly lets a caller inject a self-chosen `traceId` so the * Mastra execution trace is anchored to an id the client already knows, * enabling trace-centric feedback/scores (`createFeedback({ traceId })`). * * NOT per-run: this config (and any `traceId` in it) is stored once on the * agent instance and reused verbatim for EVERY run of that instance. So a * config-level `tracingOptions.traceId` is applied to every run, not to a * single run, meaning a caller who sets a fixed `traceId` here and reuses one * `MastraAgent` across many runs collapses all those runs onto a single trace. * Callers who want a distinct traceId per run should construct a fresh agent * per run (the `registerCopilotKit` / `getLocalAgents` path already does this, * since agents are constructed inside the per-request route handler). * * The OUTBOUND execution traceId surfaced on `RUN_FINISHED.result` IS per-run: * when no inbound `traceId` is set, Mastra generates one for that run, which * the bridge surfaces back to the client (see {@link makeRunFinishedEvent}). * Inert on cores that predate Mastra observability v-next. */ tracingOptions?: MastraTracingOptions; /** * Opt into Mastra's `untilIdle` run mode (local agents only). When set, the * bridge passes `untilIdle` to `agent.stream(...)`, which subscribes to the * background-task manager for the run's memory scope and pipes the task * lifecycle chunks (`background-task-running` / `-output` / `-completed` / * `-failed` / …) into the SAME `fullStream`, re-entering the agentic loop so * the model reacts to the result in the same run. Without it, only * `background-task-started` reaches the run stream and completion is * delivered out of band. Requires a configured storage backend + a memory * scope (Mastra falls through to the default stream otherwise). `true` uses * Mastra's default idle timeout; pass `{ maxIdleMs }` to override. * * CAVEAT (verified against @mastra/core 1.47.0): in practice only * `background-task-started` + `-running` reach the piped stream; * `background-task-completed` does NOT arrive, so the run idles out without a * completion and the activity stays "running". Treat this as the forward- * looking hook for when Mastra delivers terminal lifecycle on the stream; * leave it OFF until then (its only effect today is an idle hold with no * completion payload). */ untilIdle?: boolean | { maxIdleMs?: number; }; /** * Terminate interrupted runs with the AG-UI structured outcome * `RUN_FINISHED.outcome={ type: "interrupt", interrupts: [...] }`, mapping each * Mastra tool suspend to an `Interrupt`. * * Default **true** (opt-out). The structured outcome is the canonical AG-UI * interrupt path; clients on the canonical resume protocol drive resume via * `RunAgentInput.resume`, which the bridge consumes here. * * REQUIRES a CopilotKit client **>= 1.61.2** (the release that reads * `outcome:"interrupt"` and resumes via `RunAgentInput.resume`). On older * clients (<= 1.61.1, incl. 1.60.1/1.61.0) the client records the structured * interrupt but never addresses it on resume, stranding the run with * `Thread has N pending interrupt(s) not addressed by resume`. **If you target * a client below 1.61.2, set this to `false`** to fall back to the legacy * `on_interrupt`-only path. (The bridge can't detect the client version — the * CopilotKit client is the consumer app's dependency, not this package's — * so the floor is a documented requirement, not an enforced one.) * * Independent of the legacy `CUSTOM(name="on_interrupt")` event, which is * always emitted (backward compat). When on, BOTH the legacy event and the * structured outcome are emitted; when off, only the legacy event plus a plain * `RUN_FINISHED` — exactly as before this flag existed. Resume itself consumes * BOTH the legacy `forwardedProps.command.resume` and the standard * `RunAgentInput.resume` channels regardless of this flag. */ emitInterruptOutcome?: boolean; /** * A2UI auto-injection config (local agents). When the runtime/middleware * forwards `injectA2UITool`, the bridge injects a backend-owned `generate_a2ui` * tool (recovery + subagent) per run so the developer wires nothing — the * easy-devex path. Set `injectA2UITool:false` here to force it off; set * `model`/`defaultCatalogId`/`guidelines`/`recovery` to customize. A `model` is * required for auto-inject unless one can be inferred from the wrapped agent. */ a2ui?: A2UIInjectConfig; /** * For REMOTE agents only: the `MastraClient` used to reach the agent. When * set, the bridge syncs `input.state` into the remote server's working memory * (via `client.updateWorkingMemory`) before streaming, so a client-side edit * to shared state reaches a remote agent the same way it does a local one. * Set by `getRemoteAgents`; unused for local agents (which sync through their * own `Memory` instance). */ remoteClient?: MastraClient; /** * When the configured agent uses `outputProcessors` that rewrite assistant * text (e.g. character-voice transforms, redaction, format normalization), * the processor-modified text is available only on the `finish` / * `step-finish` chunk's `payload.response.uiMessages` — surfaced upstream in * https://github.com/mastra-ai/mastra/pull/11549 to expose processor output * through streaming. * * Set to `true` to buffer intermediate `text-delta` chunks and emit only the * processor-modified text extracted from that boundary's `uiMessages`. When a * boundary has no usable `uiMessages` (older Mastra, or processors that did * not modify text), the buffered raw text is emitted on the terminal `finish` * as a fallback so no text is ever dropped. * * Default: `false` (current behavior — text-delta chunks stream to the client * in real time, processor rewrites are not surfaced). * * Trade-off: enabling this loses real-time text streaming — the final * assistant text appears at once after the agent's last step. Required when * downstream consumers (e.g. CopilotKit chat UI) must render the * post-processor text rather than the raw LLM output. * * Tracking: https://github.com/ag-ui-protocol/ag-ui/issues/1726 */ useProcessedFinalText?: boolean; /** * Surface Mastra Observational Memory (OM) background work as AG-UI activity * events (activityType `mastra-observational-memory`). Default OFF. * * OM is the developer's own opt-in (enabled on their Mastra `Memory`), so the * bridge stays silent about it unless explicitly asked. When `true`, the * bridge maps the OM lifecycle chunks Mastra streams on `fullStream` * (`data-om-observation-*`, `data-om-buffering-*`, `data-om-activation`) to * ACTIVITY_SNAPSHOT / ACTIVITY_DELTA events. When `false`/unset, those chunks * are swallowed (no activity emitted) but the stream still flows cleanly. * * Note: this toggle does NOT enable OM — that is configured on the agent's * Memory. It only controls whether the bridge surfaces OM's activity. */ observationalMemory?: boolean; } declare class MastraAgent extends AbstractAgent { private config; agent: Agent | RemoteMastraAgent; resourceId?: string; requestContext?: RequestContext; untilIdle?: boolean | { maxIdleMs?: number; }; observationalMemory?: boolean; tracingOptions?: MastraTracingOptions; headers?: Record; /** See MastraAgentConfig.emitInterruptOutcome. Default true. */ emitInterruptOutcome: boolean; /** See MastraAgentConfig.a2ui — A2UI auto-injection config. */ a2ui?: A2UIInjectConfig; /** See MastraAgentConfig.remoteClient. Set for remote agents only. */ remoteClient?: MastraClient; /** See MastraAgentConfig.useProcessedFinalText. Default false. */ useProcessedFinalText: boolean; /** * Suffix appended to a turn's base (Mastra-stored) messageId to key the * SEPARATE AG-UI message that carries assistant text streamed AFTER a tool * call in the same turn. See {@link continuationMessageId} and the ordering * note in {@link makeStreamCallbacks}. */ private static readonly ASSISTANT_TEXT_CONTINUATION_SUFFIX; /** * Deterministic id for the "trailing text" continuation message split off a * turn whose tool call already rendered under `baseId`. Deterministic (a pure * function of the stored turn id) so re-sent history dedups: `selectNewMessages` * recomputes it from each stored id and filters the continuation message out, * so the split text is never re-forwarded (and duplicated) on later turns. */ private static continuationMessageId; constructor(config: MastraAgentConfig); clone(): MastraAgent; /** * Forwards `input.context` onto the Mastra RequestContext under "ag-ui", so a * tool reads it via `requestContext.get("ag-ui").context`. Called on every * entry path (initial stream + both resume paths) so a resumed run forwards * its own context instead of reusing the prior turn's. */ private applyInputContext; run(input: RunAgentInput): Observable; isLocalMastraAgent(agent: Agent | RemoteMastraAgent): agent is Agent; /** * Maps a Mastra tool suspend to an AG-UI {@link Interrupt}. * * `id` is the suspended tool call id — the correlation key resume sends back * (alongside `runId`) via `resumeStream`. `responseSchema` is the parsed * `resumeSchema` (Mastra hands it over as a JSON string). Everything the * resume round-trip needs that has no first-class Interrupt field * (`toolName`, `suspendPayload`, `args`, the snapshot-keying `runId`) is * preserved under `metadata.mastra`, shaped like the legacy on_interrupt * value so a standard-path client can reconstruct the resume directive. */ private suspendToInterrupt; /** * Builds the terminating RUN_FINISHED for a run. When emitInterruptOutcome is * on AND the run suspended at least one tool, attaches the structured * `outcome: { type: "interrupt", interrupts }`. Otherwise emits a plain * RUN_FINISHED — the legacy/default behavior. Mirrors LangGraph's * `dispatchInterruptFinish`. * * When the run exposed a Mastra execution traceId (Mastra observability * v-next), it is surfaced on `RUN_FINISHED.result` as `{ traceId }` so the * client/runtime can correlate the produced assistant message with its trace * (e.g. to anchor trace-centric feedback/scores). `result` is left unset * otherwise, preserving the prior event shape. */ private makeRunFinishedEvent; /** * Fetches working memory from a local agent and emits a STATE_SNAPSHOT event * if valid working memory is available. * * Best-effort: logs a warning and returns gracefully on failure so callers * can proceed with RUN_FINISHED even when the snapshot could not be delivered. */ private emitWorkingMemorySnapshot; /** * Creates the callback set used by processFullStream to emit AG-UI events. * messageId is accessed/mutated via getter/setter closures so that when * onFinishMessagePart replaces the ID with a new UUID, subsequent callbacks * in the same run() invocation see the updated value. */ private makeStreamCallbacks; /** * Creates a stateful chunk processor that maps Mastra stream chunks to * AG-UI events via callbacks. * * Tool-call args are streamed incrementally: Mastra emits * `tool-call-input-streaming-start` → one or more `tool-call-delta` (each a * raw JSON-text fragment) → `tool-call-input-streaming-end` → a final * `tool-call` (with the assembled args) as the model produces the call. * When those delta chunks are present we emit TOOL_CALL_START on the start * chunk, a TOOL_CALL_ARGS per delta, and TOOL_CALL_END on the end chunk — * so the client renders args as they arrive. The trailing `tool-call` for an * already-streamed id is a no-op (args were already emitted). * * Fall-back (backwards compatibility): older @mastra/core in the supported * 1.0.x floor may emit only the final `tool-call` with no delta chunks. In * that case we buffer the `tool-call` and emit a single START + full-args * ARGS + END when it flushes. This buffered path also preserves the * suspend protocol: if a buffered tool-call is followed by * tool-call-suspended, the TOOL_CALL_* events are suppressed (the tool * hasn't executed yet — emitting them confuses CopilotKit's orchestration * which expects a TOOL_CALL_RESULT to follow). Suspendable tools are * server-side and travel the buffered path; client/generative tools (which * never suspend) are the ones whose args stream incrementally. * * Used by both the local agent path (async iterable) and the remote agent * path (processDataStream callback) — single source of truth for chunk * handling and buffering logic. * * @returns An object with two methods: * - `handleChunk`: processes a single chunk; returns `true` if processing should stop (error or malformed chunk). * - `flush`: emits any buffered tool-call (call at end of stream). */ private createChunkProcessor; /** * Processes a Mastra fullStream (async iterable) using createChunkProcessor. * @returns true if processing stopped early (error chunk or malformed chunk). */ private processFullStream; /** * Returns only the messages Mastra has not already persisted for this thread * — the new turn — so we don't re-feed (and re-persist) history Mastra memory * already owns. Filters the incoming list against the ids Mastra has stored * (recall), mirroring LangGraph's continuation check. * * Faithful because the bridge streams assistant messages under Mastra's * stored id (see onMessageId), so re-sent history matches stored ids and is * dropped. Remote agents and agents without memory get the full list (no * stored history to dedupe against). Defensive: if filtering would drop * everything, or recall fails, forwards the full list. */ private selectNewMessages; /** * The shared-state slice of a run's input.state: everything except the * `messages` list (which the bridge strips before syncing state to working * memory). This is what the client holds as its coagent state, so it is the * correct base for the first mid-run STATE_DELTA. Returns `{}` when there is * no usable state. */ private workingMemoryStateSlice; /** * Coerces a working-memory value read back from Mastra (a JSON string for * schema/json working memory, or already an object, or a `{ workingMemory }` * envelope from the remote HTTP route) into a plain object for merging. * Returns `{}` for markdown/non-JSON/template ($schema) values. */ private coerceWorkingMemoryObject; /** * Syncs the run's `input.state` (the client's shared state, minus `messages`) * into Mastra's resource-scoped working memory BEFORE streaming, so a UI edit * reaches the agent on the next run. Merges the client state over the existing * working memory: keys the client doesn't manage are preserved, while its * shared-state keys (e.g. `recipe`) overwrite wholesale — so a removed value * (an unchecked preference) is actually removed, not left lingering. * * Working memory lives in the RESOURCE store (default scope "resource"), * written via `updateWorkingMemory` — NOT `thread.metadata`, which the model * never reads. Local agents write through their own `Memory`; remote agents * write through the `MastraClient` (`remoteClient`) so the SAME edit reaches a * remote server. No-op when there is no client state or (for remote) no client. */ private syncInputStateToWorkingMemory; /** * Reads the Mastra execution traceId off a consumed stream response, if any. * * `traceId` is exposed by Mastra observability v-next on the stream response * (`MastraModelOutput.traceId`); it may be a plain string or a Promise that * resolves after the stream is consumed, so we await a thenable. Probed * structurally so the bridge stays compatible with cores / remote clients * that don't expose it (they simply yield undefined). Best-effort: a read * that throws is swallowed so it never blocks RUN_FINISHED. */ private resolveTraceId; /** * Streams a local or remote Mastra agent, emitting AG-UI events via callbacks. * For local agents, iterates fullStream with processFullStream. * For remote agents, uses processDataStream with createChunkProcessor. * Calls onRunFinished on success. For errors, onError is called either from * within stream processing (error chunks) or from the catch block (thrown exceptions). */ private streamMastraAgent; static getRemoteAgents(options: GetRemoteAgentsOptions): Promise>; static getLocalAgents(options: GetLocalAgentsOptions): Record; static getLocalAgent(options: GetLocalAgentOptions): AbstractAgent; static getNetwork(options: GetNetworkOptions): AbstractAgent; } //#endregion export { MastraTracingOptions as a, GetNetworkOptions as c, getLocalAgent as d, getLocalAgents as f, MastraAgentConfig as i, GetRemoteAgentsOptions as l, getRemoteAgents as m, MASTRA_OBSERVATIONAL_MEMORY_ACTIVITY_TYPE as n, GetLocalAgentOptions as o, getNetwork as p, MastraAgent as r, GetLocalAgentsOptions as s, MASTRA_BACKGROUND_TASK_ACTIVITY_TYPE as t, convertAGUIMessagesToMastra as u }; //# sourceMappingURL=mastra-BRAcDXP1.d.mts.map