🚀 AgentStack

Configuration

Development

Home Page v1.0.0

Node.js TypeScript Next.js React License

Agents Tools Workflows Networks UI Components

Tests Zod ESLint

GitHub GitMCP wakatime

AgentStack is a production-grade AI agent platform built on Mastra, delivering 57 enterprise tools, 25+ specialized agents, 10+ workflows, 12+ supervisor networks, 105 UI components (50+ AI Elements + 55+ base), and A2A/MCP orchestration for scalable AI systems. Features supervisor networks with delegation hooks, workspace management (AgentFS/Daytona/Local), TanStack Query integration, and LibSQL-backed persistence for agents, workspaces, supervisor networks, and auth. Focuses on financial intelligence, RAG pipelines, enterprise observability, secure governance, and AI chat interfaces.

@mastra/core libSQL @mastra/rag @mastra/memory @mastra/ai-sdk

@ai-sdk/google @ai-sdk/react Langfuse libSQL Vector Search

Gemini OpenAI Anthropic

🎯 Why AgentStack?

AgentStack bridges the gap between basic AI chatbots and enterprise-grade multi-agent orchestration. While other AI agent platforms offer simple automation, AgentStack delivers the observability, security, and scalability required for production deployment.

Feature AgentStack Fleece AI Botpress Vellum AI
Production Observability Real-time traces via TanStack + Langfuse ready ⚠️ Basic ⚠️ Basic ✅ Partial
Dataset Management Full dataset/eval/experiment API with versioning ❌ None ❌ None ⚠️ Basic
Supervisor Networks 12+ coordinator agents with delegation hooks ❌ None ❌ None ❌ None
Financial Intelligence Polygon/Finnhub/AlphaVantage (30+ endpoints) ❌ None ❌ None ❌ None
RAG Pipeline LibSQL HNSW + rerank + graphRAG ⚠️ Basic ⚠️ Basic ✅ External
Multi-Agent Orchestration A2A MCP + supervisor networks (25+ agents) ✅ Advanced ✅ Basic ✅ Partial
Live Browser Automation Local Chrome/CDP browser agent + shared runtime ⚠️ Basic ⚠️ Partial ⚠️ Partial
Workspaces / Sandboxes AgentFS + Daytona + local sandboxes + persistence ⚠️ Basic ❌ None ⚠️ Partial
Enterprise Security Better Auth + RBAC + path traversal protection + HTML sanitization ⚠️ Partial ⚠️ Partial ✅ Partial
Type Safety Zod schemas everywhere (57 tools) ⚠️ Limited ⚠️ Limited ✅ Partial
UI Components 105 components (AI Elements + shadcn/ui) ✅ 30+ ✅ 50+ ✅ 30+
Testing Vitest + 97% coverage + comprehensive mocks ⚠️ Partial ⚠️ Partial ✅ Partial

🚀 Production-Ready from Day One

While other AI agent platforms offer basic chatbot functionality, AgentStack provides enterprise-grade multi-agent orchestration:

  • Zero-config RAG: LibSQL with 3072D embeddings works out of the box
  • Supervisor Networks: 12+ coordinator agents with delegation hooks and scoring
  • Workspace Management: AgentFS, Daytona, and local sandboxes with LSP support and LibSQL-backed persistence
  • Financial Intelligence: Polygon, Finnhub, AlphaVantage with 30+ endpoints
  • Full Observability: Every agent call, tool execution, and workflow step is traced
  • Enterprise Security: Better Auth, RBAC, path validation, HTML sanitization, LibSQL session storage

Core Capabilities

  • 💰 Financial Intelligence: 30+ tools (Polygon quotes/aggs/fundamentals, Finnhub analysis, AlphaVantage indicators)
  • 🔍 Semantic RAG: LibSQL (3072D embeddings) + MDocument chunking + rerank + graph traversal
  • 📊 Dataset Management: Full dataset API with versioning, experiments, and evaluation
  • 🤖 25+ Agents: Individual specialized agents (research, stock analysis, copywriting, etc.)
  • 📋 10+ Workflows: Multi-step orchestrated processes (weather analysis, content creation, financial reports)
  • 🌐 12+ Supervisor Networks: Coordinator agents that route tasks to specialized agents using delegation hooks (primary router, coding team, financial intelligence, content creation, etc.)
  • 🧭 Live Browser Automation: Shared Chrome/CDP browser runtime for local verification, screenshots, and interaction testing
  • 🧩 Workspaces & Sandboxes: AgentFS, Daytona, and local sandbox support with persistent LibSQL-backed state
  • 🔌 A2A/MCP: MCP server coordinates parallel agents (research+stock→report), A2A coordinator for cross-agent communication
  • 🎨 105 UI Components: AI Elements (50 chat/reasoning/canvas components) + shadcn/ui (55 base primitives)
  • 📊 Enterprise Observability: Default tracing + Langfuse integration + 10+ custom scorers + middleware logging
  • 🛡️ Enterprise Security: JWT auth, RBAC, path validation, HTML sanitization, secrets masking, middleware protection
  • ⚡ Extensible: Model registry (Gemini/OpenAI/Anthropic/OpenRouter), Zod schemas everywhere, MastraClient SDK integration

⚛️ TanStack Query Integration

Production-grade data fetching with comprehensive React hooks:

// lib/hooks/use-mastra-query.ts - 1590+ lines of typed hooks
import { useAgentsQuery } from '@/lib/hooks/use-mastra-query'

export function AgentsDashboard() {
    const { data: agents, isLoading, error } = useAgentsQuery()

    // 15+ specialized hooks for agents, workflows, tools, memory, vectors
    // Automatic caching, background refetching, optimistic updates
    // Type-safe with Zod schemas throughout
}

Key Features:

  • 1590+ Lines: Comprehensive hook coverage for all Mastra APIs
  • Type Safety: Full TypeScript with Zod schema validation
  • Caching: Intelligent cache management with React Query
  • Real-time: Automatic background updates and invalidation
  • DevTools: Integrated with @tanstack/react-query-devtools

📊 Dataset Management & Evaluation

Complete dataset and evaluation pipeline with versioning and experiments:

// lib/hooks/use-mastra-query.ts - Full dataset API
const { data: datasets } = useDatasets()
const { data: experiments } = useDatasetExperiments(datasetId)

// Dataset operations
const createDataset = useCreateDatasetMutation()
const addItems = useAddDatasetItemsMutation()
const runExperiment = useTriggerDatasetExperimentMutation()

Features:

  • Dataset Versioning: Full history tracking and rollback capabilities
  • Experiment Management: Compare model performance across datasets
  • Evaluation Scorers: Custom scoring functions for quality assessment
  • Batch Operations: Efficient bulk data operations
  • Type Safety: Full TypeScript support with Zod validation

🔍 Observability & Monitoring

Enterprise-grade observability with easy Langfuse integration:

// src/mastra/index.ts - Default observability setup
observability: new Observability({
  configs: {
    default: {
      sampling: { type: SamplingStrategyType.RATIO, probability: 0.75 },
      spanOutputProcessors: [new SensitiveDataFilter({...})],
      exporters: [new DefaultExporter({...})],
      // Easy Langfuse integration: uncomment and configure
      // exporters: [new LangfuseExporter({...})],
    }
  }
})

Features:

  • Default Tracing: Built-in observability with no setup required
  • Real-time Trace Viewing: View traces in real-time via TanStack Query hooks
  • Langfuse Ready: Drop-in integration for advanced analytics and persistence
  • Custom Scorers: 10+ evaluation metrics for agent performance
  • Sensitive Data Protection: Automatic redaction of credentials
  • Performance Monitoring: Latency, token usage, error tracking

Real-time Trace Monitoring:

// View traces in real-time with TanStack hooks
const { data: traces } = useTraces({ limit: 10 })
const { data: trace } = useTrace(traceId)

// Monitor agent performance metrics
const { data: scores } = useScoresByRun({ runId })

🌐 Middleware & Request Context

AgentStack uses server-side Mastra middleware to populate request context for agents, tools, workflows, and supervisor routes. The frontend does not import these helpers directly.

// src/mastra/index.ts - Middleware configuration
middleware: [
  async (c, next) => {
    const authHeader = c.req.header('Authorization') ?? ''
    const requestContext = c.get('requestContext')

    const authenticatedUser = await getAuthenticatedUser({
      mastra,
      token: authHeader.startsWith('Bearer ')
        ? authHeader.slice('Bearer '.length)
        : '',
      request: c.req.raw,
    })

    if (requestContext?.set) {
      requestContext.set('userId', authenticatedUser?.user.id)
      requestContext.set(
        'role',
        authenticatedUser?.user.role === 'admin' ? 'admin' : 'user'
      )
      requestContext.set('language', 'en')
      requestContext.set('provider-id', 'google')
      requestContext.set(
        'model-id',
        'gemini-3.1-flash-lite-preview'
      )
    }

    await next()
  },
]

How it works:

  • Server-only request context: defined in src/mastra/agents/request-context.ts
  • Auth integration: src/mastra/auth.ts stores Better Auth data in LibSQL
  • Role-based access: role is either admin or user
  • Model overrides: provider-id and model-id can be passed through request context
  • Workspace identity: workspaceId, threadId, and resourceId are reserved for server-side routing and persistence
  • Localization: language and region can still be inferred server-side
  • LibSQL fallback: Turso URLs are optional; if missing, the app falls back to local file:./database.db

🔧 Harness - Multi-Mode Agent Orchestration (Alpha)

Advanced multi-mode agent orchestration with state persistence and workspace management:

// src/mastra/harness.ts - 8 specialized agent modes
export const mainHarness = new Harness({
    id: 'agentstack-harness',
    resourceId: 'agentstack',
    storage: pgStore,
    workspace: mainWorkspace,

    modes: [
        { id: 'plan', name: 'Planner', agent: codeArchitectAgent },
        { id: 'code', name: 'Builder', agent: codeArchitectAgent },
        { id: 'review', name: 'Reviewer', agent: codeReviewerAgent },
        { id: 'test', name: 'Tester', agent: testEngineerAgent },
        { id: 'refactor', name: 'Refactorer', agent: refactoringAgent },
        { id: 'research', name: 'Researcher', agent: researchAgent },
        { id: 'edit', name: 'Editor', agent: editorAgent },
        { id: 'report', name: 'Reporter', agent: reportAgent },
    ],
})

Available Modes:

  • 🏗️ Plan: Architecture and planning (codeArchitectAgent)
  • 💻 Code: Implementation and coding (codeArchitectAgent)
  • 🔍 Review: Code review and quality assessment (codeReviewerAgent)
  • 🧪 Test: Test generation and validation (testEngineerAgent)
  • 🔄 Refactor: Code refactoring and optimization (refactoringAgent)
  • 🔬 Research: Research and information gathering (researchAgent)
  • ✏️ Edit: Content editing and refinement (editorAgent)
  • 📊 Report: Report generation and synthesis (reportAgent)

Key Features:

  • State Persistence: Thread management with LibSQL storage
  • Workspace Integration: Full filesystem and sandbox access
  • Mode Switching: Dynamic agent mode transitions
  • Tool Approvals: Security controls for sensitive operations
  • Event Streaming: Real-time progress and result streaming

Usage (Alpha):

// Switch to planning mode
await harness.switchMode('plan')
await harness.execute('Design a new authentication system')

// Switch to implementation mode
await harness.switchMode('code')
await harness.execute('Implement the auth system using JWT')

// Switch to testing mode
await harness.switchMode('test')
await harness.execute('Generate comprehensive tests for auth')

⚠️ Alpha Status: The harness is currently in active development. APIs may change without notice.

🏗️ Workspace Management

Multi-provider workspace system with LSP support:

// src/mastra/workspaces.ts - 14 workspace variants
export const workspaceVariants = {
    mainWorkspace, // Local filesystem + sandbox
    agentFsWorkspace, // AgentFS integration
    daytonaWorkspace, // Daytona cloud sandboxes
    localReadOnlyWorkspace, // Read-only operations
    localApprovalWorkspace, // Manual approval required
    localLspWorkspace, // TypeScript/ESLint LSP
    // ... 8 more variants
}

Providers:

  • Local: Filesystem and sandbox with process management
  • AgentFS: Distributed filesystem with persistence
  • Daytona: Cloud-based development environments
  • LSP: TypeScript and ESLint language server integration
  • Approval: Security-controlled operations

Features:

  • Process Management: Spawn, kill, and monitor workspace processes
  • LSP Integration: Real-time TypeScript/ESLint diagnostics
  • Security Controls: Path validation and approval workflows
  • Multi-tenant: Isolated workspaces with proper boundaries

🌟 Feature Highlights

💰 Financial Intelligence Suite

Real-time market data from 30+ endpoints:

// Example: Multi-source stock analysis
const analysis = await stockAnalysisAgent.execute({
    symbol: 'AAPL',
    includeFundamentals: true,
    includeNews: true,
    timeRange: '1Y',
})
// → Combines Polygon quotes, Finnhub analysis, AlphaVantage indicators
// → Returns: Price action, valuation metrics, sentiment analysis

Supported Data Providers:

  • Polygon.io: Real-time quotes, historical aggregates, fundamentals
  • Finnhub: Company profiles, insider transactions, earnings surprises
  • Alpha Vantage: Technical indicators (RSI, MACD, Bollinger Bands)

🔍 Production RAG Pipeline

Zero-config semantic search with libSQL:

// 1. Index documents
await documentProcessingWorkflow.execute({
    documents: ['./annual-report.pdf', './market-data.csv'],
    chunkingStrategy: 'semantic',
    indexName: 'financial-reports',
})

// 2. Query with context
const answer = await governedRagAnswerWorkflow.execute({
    query: 'What were Q3 revenue drivers?',
    indexName: 'financial-reports',
    rerankTopK: 5,
})
// → Returns: Synthesized answer + source citations + confidence score

Features:

  • 10 Chunking Strategies: Semantic, recursive, markdown-aware
  • 3072D Embeddings: Gemini embedding-001
  • Hybrid Search: Vector similarity + BM25 reranking
  • Graph Traversal: Relationship-aware context expansion

🤖 Agent Networks (Supervisor Agents)

Supervisor agents that coordinate multiple specialized agents using delegation hooks:

// Networks are supervisor agents that route tasks to specialized subagents
const result = await agentNetwork.execute({
    query: 'Analyze renewable energy market trends',
    // Uses delegation hooks to route to researchAgent, learningAgent, etc.
})
// → Supervisor agent analyzes request and delegates to appropriate subagents
// → Results synthesized into unified response

Network Architecture:

  • Supervisor Pattern: Networks are supervisor agents, not parallel execution
  • Delegation Hooks: Use onDelegationStart/onDelegationComplete for coordination
  • Scoring System: Custom scorers ensure task completion and synthesis quality
  • Context Preservation: Maintain conversation context across delegations

Pre-configured Networks:

  • Primary Network: Routes to research, stock, weather, content, support agents
  • Coding Team Network: Architecture → Code Review → Testing → Refactoring
  • Financial Intelligence Network: Research → Analysis → Charts → Reports
  • Content Creation Network: Writing → Editing → Strategy → SEO

📊 Full Observability

Every operation traced with Langfuse:

// Traces automatically captured
const trace = await langfuse.getTrace(traceId)
// → Agent execution steps
// → Tool calls with latency
// → Token usage per step
// → Custom scorer results (quality, diversity, completeness)

Dashboard Views:

  • Real-time trace visualization
  • Performance metrics (latency, error rates)
  • Cost tracking by agent/workflow
  • Custom scorer analytics

🎨 AI Elements UI Library

50+ production-ready React components:

import { AgentArtifact, AgentChainOfThought, AgentSources } from '@/ai-elements'

// Render streaming AI responses
<AgentChainOfThought
  steps={reasoningSteps}
  isStreaming={true}
  duration={1500}
/>

// Display code artifacts with syntax highlighting
<AgentArtifact
  artifact={{
    type: 'code',
    language: 'typescript',
    content: generatedCode
  }}
  onCodeUpdate={handleUpdate}
/>

// Show source citations
<AgentSources
  sources={citedSources}
  maxVisible={5}
/>

🚀 What You Can Build

Real-world applications powered by AgentStack:

📈 Financial Analysis Platform

// Supervisor network coordinates specialized agents
const report = await financialIntelligenceNetwork.execute({
    symbol: 'TSLA',
    includeTechnicalAnalysis: true,
    includeNewsSentiment: true,
    generateCharts: true,
})
// → Supervisor network delegates to: researchAgent → stockAnalysisAgent → chartGeneratorAgent → reportAgent
// → Generates PDF report with charts and citations

Features:

  • Real-time market data from multiple providers
  • Automated technical analysis (RSI, MACD, Bollinger Bands)
  • News sentiment analysis with SerpAPI
  • Interactive chart generation
  • PDF report export with source citations

📚 Enterprise Knowledge Base

// Ingest and query company documents
await documentProcessingWorkflow.execute({
    source: 'https://company.com/docs',
    includeSubpages: true,
    chunkingStrategy: 'semantic',
    extractMetadata: true,
})

const answer = await knowledgeBaseAgent.execute({
    query: 'What is our refund policy?',
    includeSources: true,
    confidenceThreshold: 0.8,
})
// → Searches across all indexed documents
// → Returns answer with source URLs

Features:

  • Web scraping with recursive crawling
  • PDF/CSV/JSON document processing
  • Semantic chunking with 10 strategies
  • Hybrid search (vector + keyword)
  • Source attribution for every answer

🤖 AI Coding Assistant

// Supervisor network coordinates coding team
const result = await codingTeamNetwork.execute({
    task: 'Refactor authentication module',
    code: './src/auth/*',
    requirements: [
        'Improve security',
        'Add rate limiting',
        'Better error handling',
    ],
})
// → Supervisor network delegates: codeArchitectAgent → codeReviewerAgent → testEngineerAgent → refactoringAgent
// → Each agent handles specific aspect using delegation hooks

Features:

  • Multi-agent code review pipeline
  • Automatic test generation
  • Security vulnerability detection
  • TypeScript/React expertise
  • GitHub integration for PR automation

📊 Content Creation Studio

// Supervisor network orchestrates content pipeline
const content = await contentCreationNetwork.execute({
    topic: 'Sustainable investing trends',
    formats: ['blog', 'social', 'newsletter'],
    tone: 'professional',
    seoOptimize: true,
})
// → Supervisor network delegates: copywriterAgent → editorAgent → contentStrategistAgent → seoAgent
// → Each agent specializes in different aspect of content creation

Features:

  • Multi-format content generation
  • SEO optimization with keyword research
  • Tone and style consistency
  • Social media post generation
  • Editorial calendar integration

🔍 Research Synthesis Engine

// Supervisor network coordinates research pipeline
const research = await researchPipelineNetwork.execute({
    query: 'Latest advances in LLM safety',
    sources: ['arxiv', 'serpapi', 'web'],
    synthesizeFindings: true,
    generateReport: true,
})
// → Supervisor network delegates: researchAgent → documentProcessingAgent → knowledgeIndexingAgent → reportAgent
// → Research → Process → Index → Synthesize results

Features:

  • ArXiv paper analysis
  • Web scraping with content extraction
  • Citation tracking and verification
  • Consensus detection across sources
  • Automated report generation

🏗️ System Architecture

%%{init: {'theme': 'dark', 'themeVariables': { 'primaryColor': '#58a6ff', 'primaryTextColor': '#c9d1d9', 'primaryBorderColor': '#30363d', 'lineColor': '#58a6ff', 'sectionBkgColor': '#161b22', 'altSectionBkgColor': '#0d1117', 'sectionTextColor': '#c9d1d9', 'gridColor': '#30363d', 'tertiaryColor': '#161b22', 'fontFamily': 'JetBrains Mono, monospace' }}}%%
graph TB
    subgraph "🎨 Frontend Layer"
        direction TB
        UI[AI Elements Library<br/>• 50 Chat/Reasoning/Canvas Components<br/>• Real-time Streaming]
        Base[shadcn/ui Foundation<br/>• 55 Base Primitives<br/>• Accessible & Themable]
        App[Next.js 16 App Router<br/>• React 19 + Server Components<br/>• Tailwind CSS 4 + oklch]
        Query[TanStack Query<br/>• 1590+ Lines of Hooks<br/>• Type-Safe Data Fetching]
    end

    subgraph "🌐 External Interfaces"
        direction LR
        Client[MCP Clients<br/>Cursor / Claude / Windsurf]
        API[REST API<br/>OpenAPI + Typed SDK]
        SDK[MastraClient SDK<br/>Supervisor Agent Integration]
    end

    subgraph "⚡ AgentStack Runtime"
        direction TB
        Coord[A2A Coordinator<br/>Parallel Agent Orchestration]
        Supervisor[Supervisor Agents<br/>• Scoring & Delegation<br/>• Context-Aware Prompts]

        subgraph "Intelligent Agents"
            Agents[25+ Specialized Agents]
            Research[Research Suite]
            Financial[Financial Intelligence]
            Coding[Coding Team]
            Content[Content Creation]
        end

        subgraph "Tool Ecosystem"
            Tools[57 Enterprise Tools]
            APIs[Financial APIs<br/>Polygon / Finnhub / AlphaVantage]
            Search[Search & Research<br/>SerpAPI / ArXiv / Web Scraping]
            RAG[RAG Pipeline<br/>LibSQL + Embeddings]
        end

        subgraph "Workflow Engine"
            Workflows[10+ Multi-Step Workflows]
            Sequential[Sequential Execution]
            Parallel[Parallel Branches]
            Suspense[Suspend/Resume]
        end

        subgraph "Workspace Management"
            Workspaces[14 Workspace Variants<br/>• AgentFS • Daytona • Local]
            LSP[LSP Integration<br/>TypeScript • ESLint]
            Security[Security Controls<br/>Approval • Path Validation]
        end

        subgraph "Supervisor Networks"
            Networks[12+ Supervisor Networks]
            Routing[Delegation Hooks]
            Coordination[Subagent Orchestration]
        end
    end

    subgraph "🗄️ Data & Persistence Layer"
        direction TB
        VectorStore[(LibSQL<br/>3072D Embeddings<br/>HNSW/Flat Indexes)]
        Relational[(LibSQL<br/>Memory Threads<br/>Workflow State)]
        Cache[(Redis-ready<br/>Session Management)]
    end

    subgraph "📊 Observability Stack"
        direction LR
        Tracing[Langfuse Tracing<br/>100% Coverage]
        Metrics[Custom Scorers<br/>10+ Quality Metrics]
        Analytics[Performance Analytics<br/>Latency / Errors / Usage]
    end

    %% Connections
    UI --> App
    Base --> UI
    Query --> App
    App --> SDK
    SDK --> Coord

    Client --> Coord
    API --> Coord

    Coord --> Supervisor
    Supervisor --> Agents
    Coord --> Workflows
    Coord --> Networks

    Agents --> Tools
    Agents --> VectorStore
    Agents --> Relational
    Agents --> Workspaces

    Workflows --> Agents
    %% Networks (supervisors) delegate to subagents
    Networks --> Agents

    Tools --> VectorStore
    Tools --> Relational

    Workspaces --> LSP
    Workspaces --> Security

    Agents --> Tracing
    Workflows --> Tracing
    Networks --> Tracing
    Tools --> Tracing

    Tracing --> Metrics
    Tracing --> Analytics

    %% Styling
    classDef frontend fill:#1e3a5f,stroke:#58a6ff,stroke-width:3px,color:#fff
    classDef runtime fill:#2d4a22,stroke:#7ee787,stroke-width:3px,color:#fff
    classDef storage fill:#3d2817,stroke:#ffa657,stroke-width:3px,color:#fff
    classDef observe fill:#2a2a4a,stroke:#d2a8ff,stroke-width:3px,color:#fff
    classDef external fill:#3d3d3d,stroke:#8b949e,stroke-width:2px,color:#fff

    class UI,Base,App,Query frontend
    class Coord,Agents,Tools,Workflows,Networks,Research,Financial,Coding,Content,APIs,Search,RAG,Sequential,Parallel,Suspense,Routing,Coordination,Supervisor,Workspaces,LSP,Security runtime
    class VectorStore,Relational,Cache storage
    class Tracing,Metrics,Analytics observe
    class Client,API,SDK external

🔍 Chat UI-Backend Architecture

%%{init: {'theme': 'dark', 'themeVariables': { 'primaryColor': '#58a6ff', 'primaryTextColor': '#c9d1d9', 'primaryBorderColor': '#30363d', 'lineColor': '#58a6ff', 'sectionBkgColor': '#161b22', 'altSectionBkgColor': '#0d1117', 'sectionTextColor': '#c9d1d9', 'gridColor': '#30363d', 'tertiaryColor': '#161b22' }}}%%
sequenceDiagram
    participant UI as ChatUI
    participant Msg as MessageItem
    participant TG as TypeGuards
    participant ADS as AgentDataSection
    participant WDS as WorkflowDataSection
    participant NDS as NetworkDataSection
    participant AT as AgentTool

    UI->>Msg: render(message)
    Msg->>Msg: compute dataParts via useMemo

    loop for each part in dataParts
        Msg->>TG: isAgentDataPart(part)
        alt part is AgentDataPart
            Msg->>ADS: render part
            ADS-->>Msg: Agent execution collapsible
        else not AgentDataPart
            Msg->>TG: isWorkflowDataPart(part)
            alt part is WorkflowDataPart
                Msg->>WDS: render part
                WDS-->>Msg: Workflow execution collapsible
            else not WorkflowDataPart
                Msg->>TG: isNetworkDataPart(part)
                alt part is NetworkDataPart
                    Msg->>NDS: render part
                    NDS-->>Msg: Network execution collapsible
                else other data-tool-* part
                    alt part.type startsWith data-tool-
                        Msg->>AT: render custom tool UI
                        AT-->>Msg: Tool-specific panel
                    else generic data-* part
                        Msg-->>Msg: render generic Collapsible with JSON
                    end
                end
            end
        end
    end

    Msg-->>UI: message body with nested sections

📊 System Flowchart

%%{init: {'theme': 'dark', 'themeVariables': { 'primaryColor': '#58a6ff', 'primaryTextColor': '#c9d1d9', 'primaryBorderColor': '#30363d', 'lineColor': '#58a6ff', 'sectionBkgColor': '#161b22', 'altSectionBkgColor': '#0d1117', 'sectionTextColor': '#c9d1d9', 'gridColor': '#30363d', 'tertiaryColor': '#161b22' }}}%%
classDiagram
    direction LR

    class UIMessage {
      +string id
      +parts MastraDataPart[]
    }

    class MastraDataPart {
      +string type
      +string id
      +unknown data
    }

    class AgentDataPart {
      +string type
      +string id
      +AgentExecutionData data
    }

    class WorkflowDataPart {
      +string type
      +string id
      +WorkflowExecutionData data
    }

    class NetworkDataPart {
      +string type
      +string id
      +NetworkExecutionData data
    }

    class AgentExecutionData {
      +string text
      +unknown usage
      +toolResults unknown[]
    }

    class WorkflowExecutionData {
      +string name
      +string status
      +WorkflowStepMap steps
      +WorkflowOutput output
    }

    class NetworkExecutionData {
      +string name
      +string status
      +NetworkStep[] steps
      +NetworkUsage usage
      +unknown output
    }

    class WorkflowStepMap {
      <<map>>
      +string key
      +WorkflowStep value
    }

    class WorkflowStep {
      +string status
      +unknown input
      +unknown output
      +unknown suspendPayload
    }

    class NetworkStep {
      +string name
      +string status
      +unknown input
      +unknown output
    }

    class NetworkUsage {
      +number inputTokens
      +number outputTokens
      +number totalTokens
    }

    class MessageItem {
      +UIMessage message
      -MastraDataPart[] dataParts
      +render()
    }

    class AgentDataSection {
      +AgentDataPart part
      +render()
    }

    class WorkflowDataSection {
      +WorkflowDataPart part
      +render()
    }

    class NetworkDataSection {
      +NetworkDataPart part
      +render()
    }

    class AgentTool {
      +string id
      +string type
      +unknown data
      +render()
    }

    class TypeGuards {
      +bool hasStringType(unknown part)
      +bool isAgentDataPart(unknown part)
      +bool isWorkflowDataPart(unknown part)
      +bool isNetworkDataPart(unknown part)
    }

    class KeyHelpers {
      +string getToolCallId(unknown tool, number fallbackIndex)
    }

    UIMessage "1" o-- "*" MastraDataPart
    MastraDataPart <|-- AgentDataPart
    MastraDataPart <|-- WorkflowDataPart
    MastraDataPart <|-- NetworkDataPart

    MessageItem ..> MastraDataPart : filters dataParts
    MessageItem ..> AgentDataPart : uses when isAgentDataPart
    MessageItem ..> WorkflowDataPart : uses when isWorkflowDataPart
    MessageItem ..> NetworkDataPart : uses when isNetworkDataPart

    MessageItem --> AgentDataSection : renders nested agent
    MessageItem --> WorkflowDataSection : renders nested workflow
    MessageItem --> NetworkDataSection : renders nested network
    MessageItem --> AgentTool : renders other data-tool-* parts

    MessageItem ..> TypeGuards
    MessageItem ..> KeyHelpers

    AgentDataSection --> AgentExecutionData
    WorkflowDataSection --> WorkflowExecutionData
    NetworkDataSection --> NetworkExecutionData

    WorkflowExecutionData o-- WorkflowStepMap
    WorkflowStepMap o-- WorkflowStep
    NetworkExecutionData o-- NetworkStep
    NetworkExecutionData o-- NetworkUsage


    style UIMessage stroke:#64b5f6
    style MastraDataPart  stroke:#64b5f6
    style AgentDataPart stroke:#64b5f6
    style WorkflowDataPart stroke:#64b5f6
    style NetworkDataPart stroke:#64b5f6
    style AgentExecutionData stroke:#64b5f6
    style WorkflowExecutionData stroke:#64b5f6
    style NetworkExecutionData stroke:#64b5f6
    style MessageItem stroke:#64b5f6
    style TypeGuards stroke:#64b5f6
    style KeyHelpers stroke:#64b5f6
    style AgentDataSection stroke:#64b5f6
    style WorkflowDataSection stroke:#64b5f6
    style NetworkDataSection stroke:#64b5f6
    style AgentTool stroke:#64b5f6
    style NetworkUsage stroke:#64b5f6
    style NetworkStep stroke:#64b5f6
    style WorkflowStep stroke:#64b5f6
    style WorkflowStepMap stroke:#64b5f6
    style uses when stroke:#64b5f6

🔄 RAG Pipeline (Production-Grade)

%%{init: {'theme': 'dark', 'themeVariables': { 'primaryColor': '#58a6ff', 'primaryTextColor': '#c9d1d9', 'primaryBorderColor': '#30363d', 'lineColor': '#58a6ff', 'sectionBkgColor': '#161b22', 'altSectionBkgColor': '#0d1117', 'sectionTextColor': '#c9d1d9', 'gridColor': '#30363d', 'tertiaryColor': '#161b22' }}}%%
flowchart TB
    subgraph Indexing ["📥 Ingestion Pipeline"]
        A[Documents<br/>PDF/Web/MDX] --> B{MDocument<br/>Chunker}
        B -->|10 Strategies| C[Chunks +<br/>Metadata]
        C --> D[text-embedding-004<br/>3072D Vectors]
        D --> E[(LibSQL<br/>HNSW Index)]
    end

    subgraph Querying ["🔍 Retrieval Pipeline"]
        F[User Query] --> G[Query<br/>Embedding]
        G --> H{Vector<br/>Search}
        E -.->|Top-K| H
        H -->|Cosine Similarity| I[Candidates]
        I --> J[Rerank<br/>Cross-Encoder]
        J --> K[GraphRAG<br/>Relations]
        K --> L[Context<br/>Assembly]
    end

    subgraph Generation ["💬 Answer Pipeline"]
        L --> M[Supervisor Agent<br/>Scoring & Synthesis]
        M --> N[Generated<br/>Response]
        N --> O[Citations<br/>Verification]
        O --> P[Sources +<br/>Confidence Score]
    end

    subgraph Observability ["📊 Full Observability"]
        M -.->|Spans| Q[Langfuse<br/>Traces]
        E -.->|Usage| Q
        N -.->|Metrics| R[Custom Scorers<br/>10+ Metrics]
    end

    style A fill:#1a237e,color:#fff
    style B fill:#0d47a1,color:#fff
    style C fill:#1565c0,color:#fff
    style D fill:#1976d2,color:#fff
    style E fill:#2e7d32,color:#fff
    style F fill:#e65100,color:#fff
    style G fill:#ef6c00,color:#fff
    style H fill:#f57c00,color:#fff
    style I fill:#ff8f00,color:#fff
    style J fill:#ffa000,color:#000
    style K fill:#ffb300,color:#000
    style L fill:#4a148c,color:#fff
    style M fill:#6a1b9a,color:#fff
    style N fill:#8e24aa,color:#fff
    style O fill:#ab47bc,color:#fff
    style P fill:#ce93d8,color:#000
    style Q fill:#004d40,color:#fff
    style R fill:#00695c,color:#fff

🤝 Flowcharts

%%{init: {'theme': 'dark', 'themeVariables': { 'primaryColor': '#58a6ff', 'primaryTextColor': '#c9d1d9', 'primaryBorderColor': '#30363d', 'lineColor': '#58a6ff', 'sectionBkgColor': '#161b22', 'altSectionBkgColor': '#0d1117', 'sectionTextColor': '#c9d1d9', 'gridColor': '#30363d', 'tertiaryColor': '#161b22' }}}%%
sequenceDiagram
    actor User as User
    participant Assistant as Assistant_Message
    participant NetworkProvider as NetworkProvider
    participant WorkflowProvider as WorkflowProvider
    participant ProgressPanel as ProgressPanel

    User->>Assistant: Run network or workflow
    Assistant->>NetworkProvider: Stream messages with parts
    Assistant->>WorkflowProvider: Stream messages with parts

    loop For_each_assistant_message_in_network
        NetworkProvider->>NetworkProvider: Iterate parts with index partIndex
        NetworkProvider->>NetworkProvider: Build id using messageId_partType_partIndex
        NetworkProvider->>NetworkProvider: Append ProgressEvent to allProgressEvents
    end

    loop For_each_assistant_message_in_workflow
        WorkflowProvider->>WorkflowProvider: Iterate parts with index partIndex
        WorkflowProvider->>WorkflowProvider: Build id using messageId_partType_partIndex
        WorkflowProvider->>WorkflowProvider: Append ProgressEvent to allProgressEvents
    end

    NetworkProvider->>ProgressPanel: Provide progressEvents for network view
    WorkflowProvider->>ProgressPanel: Provide progressEvents for workflow view
    ProgressPanel->>User: Render grouped progress items with stable IDs

🚀 Hooks (5 Minutes to Production)

%%{init: {'theme': 'dark', 'themeVariables': { 'primaryColor': '#58a6ff', 'primaryTextColor': '#c9d1d9', 'primaryBorderColor': '#30363d', 'lineColor': '#58a6ff', 'sectionBkgColor': '#161b22', 'altSectionBkgColor': '#0d1117', 'sectionTextColor': '#c9d1d9', 'gridColor': '#30363d', 'tertiaryColor': '#161b22' }}}%%
classDiagram
  class MastraQueryHooks {
    <<interface>>
    %% Core access
    +useAgents()
    +useAgent(agentId, requestContext)
    +useAgentModelProviders()
    +useAgentSpeakers(agentId, requestContext)
    +useAgentListener(agentId, requestContext)

    %% Tools and processors
    +useTools(requestContext)
    +useTool(toolId, requestContext)
    +useToolProviders()
    +useToolProvider(providerId)
    +useToolProviderToolkits(providerId)
    +useToolProviderTools(providerId, params)
    +useToolProviderToolSchema(providerId, toolSlug)
    +useProcessors(requestContext)
    +useProcessor(processorId, requestContext)
    +useProcessorProviders()
    +useProcessorProvider(providerId)
    +useProcessorExecuteMutation(processorId)

    %% Workflows and