{"version":3,"file":"mastra-BQO6BVT_.mjs","names":[],"sources":["../src/utils.ts","../src/mastra.ts"],"sourcesContent":["import type { InputContent, InputContentDataSource, InputContentUrlSource, Message } from \"@ag-ui/client\";\nimport { AbstractAgent } from \"@ag-ui/client\";\nimport { MastraClient } from \"@mastra/client-js\";\nimport type { Mastra } from \"@mastra/core\";\nimport type { CoreMessage } from \"@mastra/core/llm\";\nimport { Agent as LocalMastraAgent } from \"@mastra/core/agent\";\nimport { RequestContext } from \"@mastra/core/request-context\";\nimport { MastraAgent } from \"./mastra\";\n\nfunction mediaSourceToUrl(source: InputContentDataSource | InputContentUrlSource): string {\n  if (source.type === \"data\") {\n    return `data:${source.mimeType};base64,${source.value}`;\n  }\n  return source.value;\n}\n\nconst toMastraTextContent = (content: Message[\"content\"]): string => {\n  if (!content) {\n    return \"\";\n  }\n\n  if (typeof content === \"string\") {\n    return content;\n  }\n\n  if (!Array.isArray(content)) {\n    return \"\";\n  }\n\n  type TextInput = Extract<InputContent, { type: \"text\" }>;\n\n  const textParts = content\n    .filter((part): part is TextInput => part.type === \"text\")\n    .map((part: TextInput) => part.text.trim())\n    .filter(Boolean);\n\n  return textParts.join(\"\\n\");\n};\n\nconst toMastraContent = (content: Message[\"content\"]): string | any[] => {\n  if (!content) {\n    return \"\";\n  }\n\n  if (typeof content === \"string\") {\n    return content;\n  }\n\n  if (!Array.isArray(content)) {\n    return \"\";\n  }\n\n  // Convert content parts to Mastra format\n  const parts: any[] = [];\n  for (const part of content) {\n    switch (part.type) {\n      case \"text\":\n        parts.push({ type: \"text\", text: part.text });\n        break;\n      case \"image\":\n        parts.push({ type: \"image\", image: mediaSourceToUrl(part.source) });\n        break;\n      case \"audio\":\n      case \"video\":\n      case \"document\":\n        parts.push({\n          type: \"file\",\n          data: mediaSourceToUrl(part.source),\n          mimeType: part.source.mimeType ?? \"application/octet-stream\",\n        });\n        break;\n      case \"binary\": {\n        // Deprecated BinaryInputContent\n        const binaryPart = part as Extract<InputContent, { type: \"binary\" }>;\n        if (binaryPart.url) {\n          parts.push({ type: \"image\", image: binaryPart.url });\n        } else if (binaryPart.data && binaryPart.mimeType) {\n          parts.push({\n            type: \"image\",\n            image: `data:${binaryPart.mimeType};base64,${binaryPart.data}`,\n          });\n        } else {\n          console.warn(\"[toMastraContent] Dropping BinaryInputContent: no url or data provided\");\n        }\n        break;\n      }\n      default:\n        console.warn(`[toMastraContent] Unknown content type \"${part.type}\"; skipping`);\n        break;\n    }\n  }\n  return parts;\n};\n\nexport function convertAGUIMessagesToMastra(messages: Message[]): CoreMessage[] {\n  const result: CoreMessage[] = [];\n\n  for (const message of messages) {\n    if (message.role === \"assistant\") {\n      const assistantContent = toMastraTextContent(message.content);\n      const parts: any[] = [];\n      if (assistantContent) {\n        parts.push({ type: \"text\", text: assistantContent });\n      }\n      for (const toolCall of message.toolCalls ?? []) {\n        parts.push({\n          type: \"tool-call\",\n          toolCallId: toolCall.id,\n          toolName: toolCall.function.name,\n          args: JSON.parse(toolCall.function.arguments),\n        });\n      }\n      result.push({\n        role: \"assistant\",\n        content: parts,\n      });\n    } else if (message.role === \"user\") {\n      const userContent = toMastraContent(message.content);\n      result.push({\n        role: \"user\",\n        content: userContent,\n      });\n    } else if (message.role === \"tool\") {\n      let toolName = \"unknown\";\n      for (const msg of messages) {\n        if (msg.role === \"assistant\") {\n          for (const toolCall of msg.toolCalls ?? []) {\n            if (toolCall.id === message.toolCallId) {\n              toolName = toolCall.function.name;\n              break;\n            }\n          }\n        }\n      }\n      result.push({\n        role: \"tool\",\n        content: [\n          {\n            type: \"tool-result\",\n            toolCallId: message.toolCallId,\n            toolName: toolName,\n            result: message.content,\n          },\n        ],\n      });\n    }\n  }\n\n  return result;\n}\n\nexport interface GetRemoteAgentsOptions {\n  mastraClient: MastraClient;\n  resourceId: string;\n}\n\nexport async function getRemoteAgents({\n  mastraClient,\n  resourceId,\n}: GetRemoteAgentsOptions): Promise<Record<string, AbstractAgent>> {\n  const agents = await mastraClient.listAgents();\n\n  return Object.entries(agents).reduce(\n    (acc, [agentId]) => {\n      const agent = mastraClient.getAgent(agentId);\n\n      acc[agentId] = new MastraAgent({\n        agentId,\n        agent,\n        resourceId,\n      });\n\n      return acc;\n    },\n    {} as Record<string, AbstractAgent>,\n  );\n}\n\nexport interface GetLocalAgentsOptions {\n  mastra: Mastra;\n  resourceId: string;\n  requestContext?: RequestContext;\n}\n\nexport function getLocalAgents({\n  mastra,\n  resourceId,\n  requestContext,\n}: GetLocalAgentsOptions): Record<string, AbstractAgent> {\n  const agents = mastra.listAgents() || {};\n\n  const agentAGUI = Object.entries(agents).reduce(\n    (acc, [agentId, agent]) => {\n      acc[agentId] = new MastraAgent({\n        agentId,\n        agent,\n        resourceId,\n        requestContext,\n      });\n      return acc;\n    },\n    {} as Record<string, AbstractAgent>,\n  );\n\n  return agentAGUI;\n}\n\nexport interface GetLocalAgentOptions {\n  mastra: Mastra;\n  agentId: string;\n  resourceId: string;\n  requestContext?: RequestContext;\n}\n\nexport function getLocalAgent({\n  mastra,\n  agentId,\n  resourceId,\n  requestContext,\n}: GetLocalAgentOptions) {\n  const agent = mastra.getAgent(agentId);\n  if (!agent) {\n    throw new Error(`Agent ${agentId} not found`);\n  }\n  return new MastraAgent({\n    agentId,\n    agent,\n    resourceId,\n    requestContext,\n  }) as AbstractAgent;\n}\n\nexport interface GetNetworkOptions {\n  mastra: Mastra;\n  networkId: string;\n  resourceId: string;\n  requestContext?: RequestContext;\n}\n\nexport function getNetwork({ mastra, networkId, resourceId, requestContext }: GetNetworkOptions) {\n  const network = mastra.getAgent(networkId);\n  if (!network) {\n    throw new Error(`Network ${networkId} not found`);\n  }\n  return new MastraAgent({\n    agentId: network.name!,\n    agent: network as unknown as LocalMastraAgent,\n    resourceId,\n    requestContext,\n  }) as AbstractAgent;\n}\n","import type {\n  AgentConfig,\n  BaseEvent,\n  CustomEvent,\n  ReasoningStartEvent,\n  ReasoningMessageStartEvent,\n  ReasoningMessageContentEvent,\n  ReasoningMessageEndEvent,\n  ReasoningEndEvent,\n  RunAgentInput,\n  RunFinishedEvent,\n  RunStartedEvent,\n  StateSnapshotEvent,\n  TextMessageChunkEvent,\n  ToolCallArgsEvent,\n  ToolCallEndEvent,\n  ToolCallResultEvent,\n  ToolCallStartEvent,\n} from \"@ag-ui/client\";\nimport { AbstractAgent, EventType } from \"@ag-ui/client\";\nimport type { StorageThreadType } from \"@mastra/core/memory\";\nimport type { Agent as LocalMastraAgent } from \"@mastra/core/agent\";\nimport { RequestContext } from \"@mastra/core/request-context\";\nimport { randomUUID } from \"@ag-ui/client\";\nimport { Observable } from \"rxjs\";\nimport type { MastraClient } from \"@mastra/client-js\";\nimport {\n  convertAGUIMessagesToMastra,\n  GetLocalAgentsOptions,\n  getLocalAgents,\n  getRemoteAgents,\n  GetRemoteAgentsOptions,\n  GetLocalAgentOptions,\n  getLocalAgent,\n  GetNetworkOptions,\n  getNetwork,\n} from \"./utils\";\n\ntype RemoteMastraAgent = ReturnType<MastraClient[\"getAgent\"]>;\n\nexport interface MastraAgentConfig extends AgentConfig {\n  agent: LocalMastraAgent | RemoteMastraAgent;\n  resourceId?: string;\n  requestContext?: RequestContext;\n}\n\ninterface MastraAgentStreamOptions {\n  onTextPart?: (text: string) => void;\n  onReasoningStart?: () => void;\n  onReasoningPart?: (text: string) => void;\n  onReasoningEnd?: () => void;\n  onFinishMessagePart?: () => void;\n  onToolCallPart?: (streamPart: {\n    toolCallId: string;\n    toolName: string;\n    args: any;\n  }) => void;\n  onToolResultPart?: (streamPart: { toolCallId: string; result: any }) => void;\n  onError: (error: Error) => void;\n  onRunFinished?: () => Promise<void>;\n  onToolSuspended: (payload: {\n    toolCallId: string;\n    toolName: string;\n    suspendPayload: any;\n    args: Record<string, any>;\n    resumeSchema: string;\n  }) => void;\n}\n\nexport class MastraAgent extends AbstractAgent {\n  agent: LocalMastraAgent | RemoteMastraAgent;\n  resourceId?: string;\n  requestContext?: RequestContext;\n  public headers?: Record<string, string>;\n\n  constructor(private config: MastraAgentConfig) {\n    const { agent, resourceId, requestContext, ...rest } = config;\n    super(rest);\n    this.agent = agent;\n    this.resourceId = resourceId;\n    this.requestContext = requestContext ?? new RequestContext();\n  }\n\n  public clone() {\n    const cloned = new MastraAgent(this.config);\n    if (this.headers) {\n      cloned.headers = { ...this.headers };\n    }\n    return cloned;\n  }\n\n  run(input: RunAgentInput): Observable<BaseEvent> {\n    let messageId = randomUUID();\n\n    return new Observable<BaseEvent>((subscriber) => {\n      const run = async () => {\n        const runStartedEvent: RunStartedEvent = {\n          type: EventType.RUN_STARTED,\n          threadId: input.threadId,\n          runId: input.runId,\n        };\n\n        subscriber.next(runStartedEvent);\n\n        // CopilotKit passes resume data via forwardedProps.command (convention\n        // shared with LangGraph's interrupt bridge). forwardedProps is untyped\n        // (any) — the caller is responsible for shape validation.\n        const forwardedCommand = input.forwardedProps?.command;\n\n        // resume: false means the user explicitly declined the tool call.\n        // Close the run cleanly without calling resumeStream.\n        if (\n          forwardedCommand?.resume === false &&\n          forwardedCommand?.interruptEvent\n        ) {\n          await this.emitWorkingMemorySnapshot(subscriber, input.threadId);\n          subscriber.next({\n            type: EventType.RUN_FINISHED,\n            threadId: input.threadId,\n            runId: input.runId,\n          } as RunFinishedEvent);\n          subscriber.complete();\n          return;\n        }\n\n        if (\n          forwardedCommand?.resume != null &&\n          forwardedCommand?.interruptEvent\n        ) {\n          // Safely parse interruptEvent — client-supplied data\n          let interruptEvent: any;\n          try {\n            interruptEvent =\n              typeof forwardedCommand.interruptEvent === \"string\"\n                ? JSON.parse(forwardedCommand.interruptEvent)\n                : forwardedCommand.interruptEvent;\n          } catch (err) {\n            subscriber.error(\n              new Error(\"Invalid interruptEvent: malformed JSON\", {\n                cause: err,\n              }),\n            );\n            return;\n          }\n\n          // Validate required fields for resume\n          if (!interruptEvent?.toolCallId || !interruptEvent?.runId) {\n            subscriber.error(\n              new Error(\"Invalid interruptEvent: missing toolCallId or runId\"),\n            );\n            return;\n          }\n\n          // Remote agent resume is not yet supported — error, don't fake success\n          if (!this.isLocalMastraAgent(this.agent)) {\n            subscriber.error(\n              new Error(\n                \"Resume from interrupt is not yet supported for remote Mastra agents\",\n              ),\n            );\n            return;\n          }\n\n          try {\n            const resumeOptions: Record<string, unknown> = {\n              toolCallId: interruptEvent.toolCallId,\n              runId: interruptEvent.runId,\n              memory: {\n                thread: input.threadId,\n                resource: this.resourceId ?? input.threadId,\n              },\n              requestContext: this.requestContext,\n            };\n            if (this.headers && Object.keys(this.headers).length > 0) {\n              resumeOptions.modelSettings = {\n                ...((resumeOptions.modelSettings as\n                  | Record<string, unknown>\n                  | undefined) ?? {}),\n                headers: this.headers,\n              };\n            }\n            const response = await this.agent.resumeStream(\n              forwardedCommand.resume,\n              resumeOptions,\n            );\n\n            // Null/invalid response from resumeStream is an error\n            if (\n              !response ||\n              typeof response !== \"object\" ||\n              !response.fullStream\n            ) {\n              subscriber.error(\n                new Error(\n                  \"resumeStream returned no valid response (missing fullStream)\",\n                ),\n              );\n              return;\n            }\n\n            const callbacks = this.makeStreamCallbacks(\n              subscriber,\n              () => messageId,\n              (id) => {\n                messageId = id;\n              },\n              input.runId,\n            );\n            const hadError = await this.processFullStream(response.fullStream, {\n              ...callbacks,\n              onError: (error) => {\n                subscriber.error(error);\n              },\n            });\n\n            if (!hadError) {\n              await this.emitWorkingMemorySnapshot(subscriber, input.threadId);\n              subscriber.next({\n                type: EventType.RUN_FINISHED,\n                threadId: input.threadId,\n                runId: input.runId,\n              } as RunFinishedEvent);\n              subscriber.complete();\n            }\n          } catch (error) {\n            subscriber.error(error);\n          }\n          return;\n        }\n\n        // Sync AG-UI input state into Mastra's working memory before streaming\n        if (this.isLocalMastraAgent(this.agent)) {\n          try {\n            const memory = await this.agent.getMemory({\n              requestContext: this.requestContext,\n            });\n\n            if (memory && input.state && Object.keys(input.state).length > 0) {\n              let thread: StorageThreadType | null = await memory.getThreadById(\n                {\n                  threadId: input.threadId,\n                  // Mastra's abstract Memory.getThreadById type is narrower than\n                  // its runtime contract — concrete Memory subclasses (and\n                  // `AGENT_MEMORY_MISSING_RESOURCE_ID` checks along the thread\n                  // lifecycle) expect `resourceId`. We forward it here to stay\n                  // consistent with the sibling saveThread call below (which\n                  // also normalizes `thread.resourceId`) and the\n                  // `emitWorkingMemorySnapshot` call to `getWorkingMemory`, and\n                  // to match the rest of the run's memory options (`resource:`\n                  // on `.stream()` / `.resumeStream()` in `streamMastraAgent`).\n                  // @ts-expect-error upstream type omits resourceId; runtime accepts it\n                  resourceId: this.resourceId ?? input.threadId,\n                },\n              );\n\n              if (!thread) {\n                thread = {\n                  id: input.threadId,\n                  title: \"\",\n                  metadata: {},\n                  resourceId: this.resourceId ?? input.threadId,\n                  createdAt: new Date(),\n                  updatedAt: new Date(),\n                };\n              }\n\n              let existingMemory: Record<string, any> = {};\n              try {\n                existingMemory = JSON.parse(\n                  (thread.metadata?.workingMemory as string) ?? \"{}\",\n                );\n              } catch {\n                // Working memory metadata is not valid JSON - start fresh\n              }\n              const { messages, ...rest } = input.state;\n              const workingMemory = JSON.stringify({\n                ...existingMemory,\n                ...rest,\n              });\n\n              await memory.saveThread({\n                thread: {\n                  ...thread,\n                  // Ensure resourceId is always set on the persisted thread.\n                  // If storage returned a thread with a stale/missing\n                  // resourceId (migrated data, foreign writer, etc.) the\n                  // naive `...thread` spread would carry that through and\n                  // Mastra's Memory would reject the save with\n                  // AGENT_MEMORY_MISSING_RESOURCE_ID. Normalize to the run's\n                  // authoritative resourceId, matching the sibling\n                  // getThreadById call above.\n                  resourceId: this.resourceId ?? input.threadId,\n                  metadata: {\n                    ...thread.metadata,\n                    workingMemory,\n                  },\n                },\n              });\n            }\n          } catch (error) {\n            subscriber.error(error);\n            return;\n          }\n        }\n\n        try {\n          const streamCallbacks = this.makeStreamCallbacks(\n            subscriber,\n            () => messageId,\n            (id) => {\n              messageId = id;\n            },\n            input.runId,\n          );\n\n          await this.streamMastraAgent(input, {\n            ...streamCallbacks,\n            onError: (error) => {\n              subscriber.error(error);\n            },\n            onRunFinished: async () => {\n              await this.emitWorkingMemorySnapshot(subscriber, input.threadId);\n              subscriber.next({\n                type: EventType.RUN_FINISHED,\n                threadId: input.threadId,\n                runId: input.runId,\n              } as RunFinishedEvent);\n              subscriber.complete();\n            },\n          });\n        } catch (error) {\n          subscriber.error(error);\n        }\n      };\n\n      run().catch((err) => {\n        if (subscriber.closed) return;\n        subscriber.error(err);\n      });\n\n      return () => {};\n    });\n  }\n\n  isLocalMastraAgent(\n    agent: LocalMastraAgent | RemoteMastraAgent,\n  ): agent is LocalMastraAgent {\n    return \"getMemory\" in agent;\n  }\n\n  /**\n   * Fetches working memory from a local agent and emits a STATE_SNAPSHOT event\n   * if valid working memory is available.\n   *\n   * Best-effort: logs a warning and returns gracefully on failure so callers\n   * can proceed with RUN_FINISHED even when the snapshot could not be delivered.\n   */\n  private async emitWorkingMemorySnapshot(\n    subscriber: { next: (event: BaseEvent) => void },\n    threadId: string,\n  ): Promise<boolean> {\n    if (!this.isLocalMastraAgent(this.agent)) return true;\n    try {\n      const memory = await this.agent.getMemory({\n        requestContext: this.requestContext,\n      });\n      if (memory) {\n        const workingMemory = await memory.getWorkingMemory({\n          resourceId: this.resourceId ?? threadId,\n          threadId,\n          memoryConfig: {\n            workingMemory: {\n              enabled: true,\n            },\n          },\n        });\n\n        if (typeof workingMemory === \"string\") {\n          let snapshot: Record<string, any> | null = null;\n          try {\n            snapshot = JSON.parse(workingMemory);\n          } catch {\n            // Working memory is not valid JSON (e.g. markdown template)\n            // Wrap it so the client still receives the state\n            snapshot = { workingMemory };\n          }\n\n          // Skip snapshots containing a JSON Schema definition ($schema) —\n          // these are Mastra's working-memory templates, not actual state.\n          if (snapshot && !(\"$schema\" in snapshot)) {\n            subscriber.next({\n              type: EventType.STATE_SNAPSHOT,\n              snapshot,\n            } as StateSnapshotEvent);\n          }\n        }\n      }\n      return true;\n    } catch (error) {\n      console.warn(\n        `[MastraAgent] Failed to emit working memory snapshot for thread ${threadId}:`,\n        error,\n      );\n      return false;\n    }\n  }\n\n  /**\n   * Creates the callback set used by processFullStream to emit AG-UI events.\n   * messageId is accessed/mutated via getter/setter closures so that when\n   * onFinishMessagePart replaces the ID with a new UUID, subsequent callbacks\n   * in the same run() invocation see the updated value.\n   */\n  private makeStreamCallbacks(\n    subscriber: { next: (event: BaseEvent) => void },\n    getMessageId: () => string,\n    setMessageId: (id: string) => void,\n    runId: string,\n  ): Omit<MastraAgentStreamOptions, \"onError\" | \"onRunFinished\"> {\n    let reasoningMessageId: string | null = null;\n    let isReasoning = false;\n\n    const closeReasoning = () => {\n      if (isReasoning && reasoningMessageId) {\n        subscriber.next({\n          type: EventType.REASONING_MESSAGE_END,\n          messageId: reasoningMessageId,\n        } as ReasoningMessageEndEvent);\n        subscriber.next({\n          type: EventType.REASONING_END,\n          messageId: reasoningMessageId,\n        } as ReasoningEndEvent);\n        isReasoning = false;\n        reasoningMessageId = null;\n      }\n    };\n\n    const openReasoning = () => {\n      if (!isReasoning) {\n        reasoningMessageId = randomUUID();\n        isReasoning = true;\n        subscriber.next({\n          type: EventType.REASONING_START,\n          messageId: reasoningMessageId,\n        } as ReasoningStartEvent);\n        subscriber.next({\n          type: EventType.REASONING_MESSAGE_START,\n          messageId: reasoningMessageId,\n          role: \"reasoning\",\n        } as ReasoningMessageStartEvent);\n      }\n    };\n\n    return {\n      onReasoningStart: () => {\n        openReasoning();\n      },\n      onReasoningPart: (text) => {\n        openReasoning();\n        subscriber.next({\n          type: EventType.REASONING_MESSAGE_CONTENT,\n          messageId: reasoningMessageId!,\n          delta: text,\n        } as ReasoningMessageContentEvent);\n      },\n      onReasoningEnd: () => {\n        closeReasoning();\n      },\n      onTextPart: (text) => {\n        closeReasoning();\n        subscriber.next({\n          type: EventType.TEXT_MESSAGE_CHUNK,\n          role: \"assistant\",\n          messageId: getMessageId(),\n          delta: text,\n        } as TextMessageChunkEvent);\n      },\n      onToolCallPart: (streamPart) => {\n        closeReasoning();\n        subscriber.next({\n          type: EventType.TOOL_CALL_START,\n          parentMessageId: getMessageId(),\n          toolCallId: streamPart.toolCallId,\n          toolCallName: streamPart.toolName,\n        } as ToolCallStartEvent);\n        subscriber.next({\n          type: EventType.TOOL_CALL_ARGS,\n          toolCallId: streamPart.toolCallId,\n          delta: JSON.stringify(streamPart.args),\n        } as ToolCallArgsEvent);\n        subscriber.next({\n          type: EventType.TOOL_CALL_END,\n          toolCallId: streamPart.toolCallId,\n        } as ToolCallEndEvent);\n      },\n      onToolResultPart: (streamPart) => {\n        subscriber.next({\n          type: EventType.TOOL_CALL_RESULT,\n          toolCallId: streamPart.toolCallId,\n          content: JSON.stringify(streamPart.result),\n          messageId: randomUUID(),\n          role: \"tool\",\n        } as ToolCallResultEvent);\n      },\n      onToolSuspended: (payload) => {\n        subscriber.next({\n          type: EventType.CUSTOM,\n          name: \"on_interrupt\",\n          value: JSON.stringify({\n            type: \"mastra_suspend\",\n            toolCallId: payload.toolCallId,\n            toolName: payload.toolName,\n            suspendPayload: payload.suspendPayload,\n            args: payload.args,\n            resumeSchema: payload.resumeSchema,\n            runId,\n          }),\n        } as CustomEvent);\n      },\n      onFinishMessagePart: () => {\n        closeReasoning();\n        setMessageId(randomUUID());\n      },\n    };\n  }\n\n  /**\n   * Creates a stateful chunk processor that maps Mastra stream chunks to\n   * AG-UI events via callbacks. Buffers tool-call chunks: if followed by\n   * tool-call-suspended, the TOOL_CALL_* events are suppressed (the tool\n   * hasn't executed yet — emitting them confuses CopilotKit's orchestration\n   * which expects a TOOL_CALL_RESULT to follow).\n   *\n   * Used by both the local agent path (async iterable) and the remote agent\n   * path (processDataStream callback) — single source of truth for chunk\n   * handling and buffering logic.\n   *\n   * @returns An object with two methods:\n   *   - `handleChunk`: processes a single chunk; returns `true` if processing should stop (error or malformed chunk).\n   *   - `flush`: emits any buffered tool-call (call at end of stream).\n   */\n  private createChunkProcessor(callbacks: MastraAgentStreamOptions) {\n    let pendingToolCall: {\n      toolCallId: string;\n      toolName: string;\n      args: any;\n    } | null = null;\n\n    const flush = () => {\n      if (pendingToolCall) {\n        callbacks.onToolCallPart?.(pendingToolCall);\n        pendingToolCall = null;\n      }\n    };\n\n    const handleChunk = (chunk: any): boolean => {\n      if (!chunk || !chunk.payload) {\n        callbacks.onError(\n          new Error(\n            `Malformed stream chunk: type=${chunk?.type ?? \"undefined\"}, missing payload`,\n          ),\n        );\n        return true;\n      }\n      switch (chunk.type) {\n        case \"reasoning-start\": {\n          callbacks.onReasoningStart?.();\n          break;\n        }\n        case \"reasoning-delta\": {\n          callbacks.onReasoningPart?.(chunk.payload.text);\n          break;\n        }\n        case \"reasoning-end\": {\n          callbacks.onReasoningEnd?.();\n          break;\n        }\n        case \"reasoning-signature\":\n        case \"redacted-reasoning\":\n          break;\n        case \"text-delta\": {\n          flush();\n          callbacks.onTextPart?.(chunk.payload.text);\n          break;\n        }\n        case \"tool-call\": {\n          flush();\n          pendingToolCall = {\n            toolCallId: chunk.payload.toolCallId,\n            toolName: chunk.payload.toolName,\n            args: chunk.payload.args,\n          };\n          break;\n        }\n        case \"tool-result\": {\n          flush();\n          callbacks.onToolResultPart?.({\n            toolCallId: chunk.payload.toolCallId,\n            result: chunk.payload.result,\n          });\n          break;\n        }\n        case \"error\": {\n          const error = new Error(chunk.payload.error as string);\n          callbacks.onError(error);\n          return true;\n        }\n        case \"tool-call-suspended\": {\n          // Always discard the pending tool-call: if it matches, the tool\n          // was suspended before execution; if it doesn't match, the pending\n          // call is orphaned (never executed) so emitting TOOL_CALL_START/\n          // ARGS/END without a TOOL_CALL_RESULT would violate the protocol.\n          pendingToolCall = null;\n          if (!chunk.payload.toolCallId || !chunk.payload.toolName) {\n            callbacks.onError(\n              new Error(\n                `Malformed tool-call-suspended: missing toolCallId or toolName in payload`,\n              ),\n            );\n            return true;\n          }\n          callbacks.onToolSuspended({\n            toolCallId: chunk.payload.toolCallId,\n            toolName: chunk.payload.toolName,\n            suspendPayload: chunk.payload.suspendPayload,\n            args: chunk.payload.args,\n            resumeSchema: chunk.payload.resumeSchema,\n          });\n          break;\n        }\n        // Both \"finish\" and \"step-finish\" flush any pending tool call and rotate\n        // the messageId so the next step's text gets a fresh ID. When a stream\n        // ends with step-finish followed by finish, onFinishMessagePart fires\n        // twice — the second rotation produces an unused messageId, which is harmless.\n        case \"finish\":\n        case \"step-finish\": {\n          flush();\n          callbacks.onFinishMessagePart?.();\n          break;\n        }\n        // Known Mastra lifecycle events with no AG-UI mapping — skip silently\n        case \"start\":\n        case \"step-start\":\n          break;\n        default: {\n          console.warn(\n            `[MastraAgent] Unrecognized stream chunk type: ${chunk.type}`,\n          );\n          break;\n        }\n      }\n      return false;\n    };\n\n    return { handleChunk, flush };\n  }\n\n  /**\n   * Processes a Mastra fullStream (async iterable) using createChunkProcessor.\n   * @returns true if processing stopped early (error chunk or malformed chunk).\n   */\n  private async processFullStream(\n    stream: AsyncIterable<any>,\n    callbacks: MastraAgentStreamOptions,\n  ): Promise<boolean> {\n    const { handleChunk, flush } = this.createChunkProcessor(callbacks);\n    for await (const chunk of stream) {\n      if (handleChunk(chunk)) return true;\n    }\n    flush();\n    return false;\n  }\n\n  /**\n   * Streams a local or remote Mastra agent, emitting AG-UI events via callbacks.\n   * For local agents, iterates fullStream with processFullStream.\n   * For remote agents, uses processDataStream with createChunkProcessor.\n   * Calls onRunFinished on success. For errors, onError is called either from\n   * within stream processing (error chunks) or from the catch block (thrown exceptions).\n   */\n  private async streamMastraAgent(\n    { threadId, runId, messages, tools, context: inputContext }: RunAgentInput,\n    {\n      onTextPart,\n      onReasoningStart,\n      onReasoningPart,\n      onReasoningEnd,\n      onFinishMessagePart,\n      onToolCallPart,\n      onToolResultPart,\n      onToolSuspended,\n      onError,\n      onRunFinished,\n    }: MastraAgentStreamOptions,\n  ): Promise<void> {\n    const clientTools = tools.reduce(\n      (acc, tool) => {\n        acc[tool.name as string] = {\n          id: tool.name,\n          description: tool.description,\n          inputSchema: tool.parameters,\n        };\n        return acc;\n      },\n      {} as Record<string, any>,\n    );\n    const resourceId = this.resourceId ?? threadId;\n\n    const convertedMessages = convertAGUIMessagesToMastra(messages);\n    this.requestContext?.set(\"ag-ui\", { context: inputContext });\n    const requestContext = this.requestContext;\n\n    if (this.isLocalMastraAgent(this.agent)) {\n      try {\n        const streamOptions: Record<string, unknown> = {\n          memory: {\n            thread: threadId,\n            resource: resourceId,\n          },\n          runId,\n          clientTools,\n          requestContext,\n        };\n        if (this.headers && Object.keys(this.headers).length > 0) {\n          streamOptions.modelSettings = {\n            ...((streamOptions.modelSettings as\n              | Record<string, unknown>\n              | undefined) ?? {}),\n            headers: this.headers,\n          };\n        }\n        const response = await this.agent.stream(\n          convertedMessages,\n          streamOptions,\n        );\n\n        if (response && typeof response === \"object\") {\n          const hadError = await this.processFullStream(response.fullStream, {\n            onTextPart,\n            onReasoningStart,\n            onReasoningPart,\n            onReasoningEnd,\n            onFinishMessagePart,\n            onToolCallPart,\n            onToolResultPart,\n            onToolSuspended,\n            onError,\n          });\n\n          if (!hadError) await onRunFinished?.();\n        } else {\n          throw new Error(\"Invalid response from local agent\");\n        }\n      } catch (error) {\n        onError(error as Error);\n      }\n    } else {\n      let stopped = false;\n      try {\n        const streamOptions: Record<string, unknown> = {\n          memory: {\n            thread: threadId,\n            resource: resourceId,\n          },\n          runId,\n          clientTools,\n          requestContext,\n        };\n        if (this.headers && Object.keys(this.headers).length > 0) {\n          streamOptions.modelSettings = {\n            ...((streamOptions.modelSettings as\n              | Record<string, unknown>\n              | undefined) ?? {}),\n            headers: this.headers,\n          };\n        }\n        const response = await this.agent.stream(\n          convertedMessages,\n          streamOptions,\n        );\n\n        // Remote agents use processDataStream (callback-based) — share\n        // chunk handling logic via createChunkProcessor.\n        if (response && typeof response.processDataStream === \"function\") {\n          const { handleChunk, flush } = this.createChunkProcessor({\n            onTextPart,\n            onReasoningStart,\n            onReasoningPart,\n            onReasoningEnd,\n            onFinishMessagePart,\n            onToolCallPart,\n            onToolResultPart,\n            onToolSuspended,\n            onError,\n          });\n\n          await response.processDataStream({\n            onChunk: async (chunk: any) => {\n              if (stopped) return;\n              if (handleChunk(chunk)) stopped = true;\n            },\n          });\n          if (!stopped) flush();\n          if (!stopped) await onRunFinished?.();\n        } else {\n          throw new Error(\"Invalid response from remote agent\");\n        }\n      } catch (error) {\n        if (!stopped) onError(error as Error);\n      }\n    }\n  }\n\n  static async getRemoteAgents(\n    options: GetRemoteAgentsOptions,\n  ): Promise<Record<string, AbstractAgent>> {\n    return getRemoteAgents(options);\n  }\n\n  static getLocalAgents(\n    options: GetLocalAgentsOptions,\n  ): Record<string, AbstractAgent> {\n    return getLocalAgents(options);\n  }\n\n  static getLocalAgent(options: GetLocalAgentOptions) {\n    return getLocalAgent(options);\n  }\n\n  static getNetwork(options: GetNetworkOptions) {\n    return getNetwork(options);\n  }\n}\n"],"mappings":"6KASA,SAAS,EAAiB,EAAgE,CAIxF,OAHI,EAAO,OAAS,OACX,QAAQ,EAAO,SAAS,UAAU,EAAO,QAE3C,EAAO,MAGhB,MAAM,EAAuB,GACtB,EAID,OAAO,GAAY,SACd,EAGJ,MAAM,QAAQ,EAAQ,CAMT,EACf,OAAQ,GAA4B,EAAK,OAAS,OAAO,CACzD,IAAK,GAAoB,EAAK,KAAK,MAAM,CAAC,CAC1C,OAAO,QAAQ,CAED,KAAK;EAAK,CAVlB,GARA,GAqBL,EAAmB,GAAgD,CACvE,GAAI,CAAC,EACH,MAAO,GAGT,GAAI,OAAO,GAAY,SACrB,OAAO,EAGT,GAAI,CAAC,MAAM,QAAQ,EAAQ,CACzB,MAAO,GAIT,IAAM,EAAe,EAAE,CACvB,IAAK,IAAM,KAAQ,EACjB,OAAQ,EAAK,KAAb,CACE,IAAK,OACH,EAAM,KAAK,CAAE,KAAM,OAAQ,KAAM,EAAK,KAAM,CAAC,CAC7C,MACF,IAAK,QACH,EAAM,KAAK,CAAE,KAAM,QAAS,MAAO,EAAiB,EAAK,OAAO,CAAE,CAAC,CACnE,MACF,IAAK,QACL,IAAK,QACL,IAAK,WACH,EAAM,KAAK,CACT,KA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