🚀 AgentStack 的
配置
发展
AgentStack 的 是一个 生产级AI代理平台 以Mastra为基础,交付 57个企业工具, 25+专业代理商, 10+工作流程, 12+主管网络, 105个UI组件 (50+AI元素+55+基础),以及 A2A/MCP编排 用于可扩展的AI系统。特性 带有委派挂钩的主管网络, 工作空间管理 (代理商/代托纳/当地), TanStack查询集成,以及 LibSQL支持的持久性 用于代理、工作区、主管网络和身份验证。专注于 金融情报, RAG管道, 企业可观察性, 安全治理,以及 AI聊天界面.
🎯 为什么选择AgentStack?
AgentStack弥合了基本AI聊天机器人和企业级多代理编排之间的差距。虽然其他AI代理平台提供简单的自动化,但AgentStack提供了生产部署所需的可观察性、安全性和可扩展性。
| 功能 | 代理堆叠 | 羊毛AI | 植酸酶 | 丝绒AI |
|---|---|---|---|---|
| 生产可观察性 | ✅ 通过TanStack+Langfuse进行实时跟踪 | ⚠️ 基础 | ⚠️ 基础 | ✅ 部分 |
| 数据集管理 | ✅ 完整数据集/评估/实验API(带版本控制) | ❌ 无 | ❌ 无 | ⚠️ 基础 |
| 主管网络 | ✅ 12+带委派挂钩的协调员代理 | ❌ 无 | ❌ 无 | ❌ 没有 |
| 金融情报 | ✅ Polygon/Finnhub/AlphaVantage(30+端点) | ❌ 无 | ❌ 无 | ❌ 没有 |
| RAG 流程 | ✅ LibSQL HNSW+重新存储+图形RAG | ⚠️ 基础 | ⚠️ 基础 | ✅ 外部 |
| 多代理编排 | ✅ A2A MCP+监控网络(25+代理) | ✅ 高级 | ✅ 基础 | ✅ 部分 |
| 实时浏览器自动化 | ✅ 本地Chrome/CDP浏览器代理+共享运行时 | ⚠️ 基础 | ⚠️ 部分 | ⚠️ 部分 |
| 工作区/沙盒 | ✅ AgentFS+代托纳+本地沙盒+持久化 | ⚠️ 基础 | ❌ 无 | ⚠️ 部分 |
| 企业安全 | ✅ 更好的Auth+RBAC+路径遍历保护+HTML净化 | ⚠️ 部分 | ⚠️ 部分 | ✅ 部分 |
| 类型安全 | ✅ Zod模式无处不在(57个工具) | ⚠️ 有限 | ⚠️ 有限 | ✅ 部分 |
| UI组件 | ✅ 105个组件(AI元素+shadcn/ui) | ✅ 30+ | ✅ 50+ | ✅ 30+ |
| 测试 | ✅ Vitest+97%覆盖率+全面模拟 | ⚠️ 部分 | ⚠️ 部分 | ✅ 部分 |
🚀 从第一天开始生产准备就绪
虽然其他AI代理平台提供基本的聊天机器人功能,但AgentStack提供企业级多代理编排:
- 零配置RAG:带有3072D嵌入的LibSQL开箱即用
- 主管网络:12名以上具有代表团挂钩和计分功能的协调员
- 工作空间管理:支持LSP和LibSQL支持持久性的AgentFS、Daytona和本地沙盒
- 金融情报:Polygon、Finnhub、AlphaVantage,拥有30多个端点
- 完全可观察性:跟踪每个代理调用、工具执行和工作流步骤
- 企业安全:更好的身份验证、RBAC、路径验证、HTML净化、LibSQL会话存储
✨ 核心能力
- 💰 金融情报:30多种工具(多边形报价/标记/基本面、Finnhub分析、AlphaVantage指标)
- 🔍 语义RAG:LibSQL(3072D嵌入)+MDocument分块+重排序+图遍历
- 📊 数据集管理:完整的数据集API,包含版本控制、实验和评估
- 🤖 25+代理:个人专业代理(研究、股票分析、文案撰写等)
- 📋 10+工作流程:多步骤编排流程(天气分析、内容创建、财务报告)
- 🌐 12+主管网络:使用委托挂钩将任务路由到专门代理的协调代理(主路由器、编码团队、金融情报、内容创建等)
- 🧭 实时浏览器自动化:共享Chrome/CDP浏览器运行时,用于本地验证、截图和交互测试
- 🧩 工作区和沙盒:AgentFS、Daytona和本地沙盒支持,具有持久的LibSQL支持状态
- 🔌 A2A/MCP:MCP服务器协调并行代理(研究+股票→报告),A2A跨代理通信协调员
- 🎨 105个UI组件:AI元素(50个聊天/推理/画布组件)+shadcn/ui(55个基本图元)
- 📊 企业可观察性:默认跟踪+Langfuse集成+10+自定义评分器+中间件日志
- 🛡️ 企业安全:JWT身份验证、RBAC、路径验证、HTML净化、秘密屏蔽、中间件保护
- ⚡ 可扩展:模型注册表(Gemini/OpenAI/Anthropic/OpenRouter),Zod模式无处不在,MastraClient SDK集成
⚛️ TanStack查询集成
使用全面的React钩子获取生产级数据:```typescript
// 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
}
**主要特点:**
- **1590+条线路**:全面覆盖所有Mastra API
- **类型安全**:带Zod模式验证的完整TypeScript
- **缓存**:使用React Query进行智能缓存管理
- **实时**:自动背景更新和无效
- **开发者工具**:与@tanstack/react-query开发工具集成
## 📊 **数据集管理与评估**
完整的数据集和评估流程,包括版本控制和实验:```typescript
// 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()
特征:
- 数据集版本控制:完整的历史跟踪和回滚功能
- 实验管理:比较不同数据集的模型性能
- 评估评分员:用于质量评估的自定义评分功能
- 批量操作:高效的批量数据操作
- 类型安全:通过Zod验证完全支持TypeScript
🔍 可观测性和监测
企业级可观察性,易于Langfuse集成:```typescript
// 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({...})],
}
}
})
**特征:**
- **默认跟踪**:内置可观察性,无需设置
- **实时跟踪查看**:通过TanStack查询钩子实时查看跟踪
- **廊坊准备就绪**:直接集成高级分析和持久性
- **自定义评分器**:10多个代理绩效评估指标
- **敏感数据保护**:自动编辑凭据
- **性能监控**:延迟、令牌使用、错误跟踪
**实时跟踪监控:**```typescript
// 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 })
🌐 中间件和请求上下文
AgentStack使用服务器端Mastra中间件为代理、工具、工作流和主管路由填充请求上下文。前端不会直接导入这些助手。```typescript
// 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()
},
]
**它是如何工作的:**
- **仅服务器请求上下文**:定义于 `src/mastra/agents/request-context.ts`
- **身份验证集成**: `src/mastra/auth.ts` 在LibSQL中存储更好的身份验证数据
- **基于角色的访问**: `role` 要么 `admin` 或 `user`
- **模型覆盖**: `provider-id` 和 `model-id` 可以通过请求上下文传递
- **工作区标识**: `workspaceId`, `threadId`,以及 `resourceId` 保留用于服务器端路由和持久性
- **本地化**:仍然可以在服务器端推断语言和地区
- **LibSQL回退**:Turso URL是可选的;如果丢失,应用程序将回退到本地 `file:./database.db`
## 🔧 **线束-多模式代理编排** (阿尔法)
具有状态持久性和工作区管理的高级多模式代理编排:```typescript
// 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 },
],
})
可用模式:
- 🏗️ 计划:架构和规划(codeArchitectAgent)
- 💻 代码:实现和编码(codeArchitectAgent)
- 🔍 审查:代码审查和质量评估(codeReviewerAgent)
- 🧪 测试:测试生成和验证(testEngineerAgent)
- 🔄 重构:代码重构和优化(reformingAgent)
- 🔬 研究:研究和信息收集(researchAgent)
- ✏️ 编辑:内容编辑和优化(editorAgent)
- 📊 报告:报告生成和合成(reportAgent)
主要特点:
- 状态持久性:使用LibSQL存储进行线程管理
- 工作空间集成:完整的文件系统和沙盒访问
- 模式切换:动态代理模式转换
- 工具批准:敏感行动的安全控制
- 事件流:实时进度和结果流
用法(Alpha):```typescript
// 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状态**:该线束目前正在积极开发中。API可能会更改,恕不另行通知。
## 🏗️ **工作空间管理**
支持LSP的多提供商工作空间系统:```typescript
// 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
}
供应商:
- 本地:具有进程管理的文件系统和沙盒
- AgentFS:具有持久性的分布式文件系统
- 代托纳:基于云的开发环境
- 语言服务器协议:TypeScript和ESLint语言服务器集成
- 批准:安保控制行动
特征:
- 进程管理:生成、终止和监视工作区进程
- LSP集成:实时TypeScript/ESLint诊断
- 安全控制:路径验证和审批工作流
- 多用户:具有适当边界的隔离工作区
🌟 功能亮点
💰 金融智能套件
来自30多个端点的实时市场数据:```typescript
// 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
**支持的数据提供程序:**
- **Polygon.io**:实时报价、历史汇总、基本面
- **Finnhub**:公司简介、内幕交易、收益惊喜
- **阿尔法Vantage**:技术指标(RSI、MACD、布林带)
### 🔍 **RAG生产管道**
使用libSQL进行零配置语义搜索:```typescript
// 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
特征:
- 10分块策略:语义、递归、标记感知
- 3072D嵌入:双子座嵌入-001
- 混合搜索:向量相似度+BM25重新排序
- 图遍历:关系感知上下文扩展
🤖 代理网络(监督代理)
使用委托挂钩协调多个专业代理的主管代理:```typescript
// 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
**网络架构:**
- **主管模式**:网络是监督代理,而不是并行执行
- **代表团挂钩**:使用 `onDelegationStart`/`onDelegationComplete` 为了协调
- **评分系统**:自定义评分器确保任务完成和综合质量
- **上下文保护**:保持各代表团之间的对话背景
**预配置网络:**
- **主要网络**:研究路线、库存、天气、内容、支持代理
- **编码团队网络**:建筑→ 代码审查→ 测试→ 重构
- **金融情报网**:研究→ 分析→ 图表→ 报告
- **内容创作网络**:写作→ 编辑→ 策略→ SEO
### 📊 **完全可观察性**
与Langfuse追踪的每一次操作:```typescript
// 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)
仪表板视图:
- 实时跟踪可视化
- 性能指标(延迟、错误率)
- 按代理/工作流进行成本跟踪
- 自定义评分分析
🎨 AI元素UI库
50+生产就绪的React组件:```tsx
import { AgentArtifact, AgentChainOfThought, AgentSources } from '@/ai-elements'
// Render streaming AI responses
// Display code artifacts with syntax highlighting
// Show source citations
## 🚀 **你能建造什么**
由AgentStack支持的现实世界应用程序:
### 📈 **财务分析平台**```typescript
// 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
特征:
- 来自多个提供商的实时市场数据
- 自动技术分析(RSI、MACD、布林带)
- 基于SerpAPI的新闻情绪分析
- 交互式图表生成
- 带源引用的PDF报告导出
📚 企业知识库```typescript
// 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
**特征:**
- 使用递归爬行进行Web抓取
- PDF/CSV/JSON文档处理
- 语义组块的10种策略
- 混合搜索(矢量+关键字)
- 每个答案的来源归因
### 🤖 **AI编程助手**```typescript
// 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
特征:
- 多代理代码审查管道
- 自动测试生成
- 安全漏洞检测
- Types/React专业知识
- GitHub集成用于PR自动化
📊 内容创作工作室```typescript
// 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
**特征:**
- 多格式内容生成
- 搜索引擎优化与关键字研究
- 色调和风格的一致性
- 社交媒体后一代
- 编辑日历集成
### 🔍 **研究合成发动机**```typescript
// 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
特征:
- ArXiv论文分析
- 带有内容提取的网络抓取
- 引文跟踪和验证
- 跨来源的共识检测
- 自动生成报告
🏗️ 系统架构```mermaid
%%{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
• 50 Chat/Reasoning/Canvas Components
• Real-time Streaming]
Base[shadcn/ui Foundation
• 55 Base Primitives
• Accessible & Themable]
App[Next.js 16 App Router
• React 19 + Server Components
• Tailwind CSS 4 + oklch]
Query[TanStack Query
• 1590+ Lines of Hooks
• Type-Safe Data Fetching]
end
subgraph "🌐 External Interfaces"
direction LR
Client[MCP Clients
Cursor / Claude / Windsurf]
API[REST API
OpenAPI + Typed SDK]
SDK[MastraClient SDK
Supervisor Agent Integration]
end
subgraph "⚡ AgentStack Runtime"
direction TB
Coord[A2A Coordinator
Parallel Agent Orchestration]
Supervisor[Supervisor Agents
• Scoring & Delegation
• 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
Polygon / Finnhub / AlphaVantage]
Search[Search & Research
SerpAPI / ArXiv / Web Scraping]
RAG[RAG Pipeline
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
• AgentFS • Daytona • Local]
LSP[LSP Integration
TypeScript • ESLint]
Security[Security Controls
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
3072D Embeddings
HNSW/Flat Indexes)]
Relational[(LibSQL
Memory Threads
Workflow State)]
Cache[(Redis-ready
Session Management)]
end
subgraph "📊 Observability Stack"
direction LR
Tracing[Langfuse Tracing
100% Coverage]
Metrics[Custom Scorers
10+ Quality Metrics]
Analytics[Performance Analytics
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
## 🔍 **聊天UI后端架构**```mermaid
%%{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
📊 系统流程图```mermaid
%%{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 {
<>
+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管道(生产级)**```mermaid
%%{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
PDF/Web/MDX] --> B{MDocument
Chunker}
B -->|10 Strategies| C[Chunks +
Metadata]
C --> D[text-embedding-004
3072D Vectors]
D --> E[(LibSQL
HNSW Index)]
end
subgraph Querying ["🔍 Retrieval Pipeline"]
F[User Query] --> G[Query
Embedding]
G --> H{Vector
Search}
E -.->|Top-K| H
H -->|Cosine Similarity| I[Candidates]
I --> J[Rerank
Cross-Encoder]
J --> K[GraphRAG
Relations]
K --> L[Context
Assembly]
end
subgraph Generation ["💬 Answer Pipeline"]
L --> M[Supervisor Agent
Scoring & Synthesis]
M --> N[Generated
Response]
N --> O[Citations
Verification]
O --> P[Sources +
Confidence Score]
end
subgraph Observability ["📊 Full Observability"]
M -.->|Spans| Q[Langfuse
Traces]
E -.->|Usage| Q
N -.->|Metrics| R[Custom Scorers
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
🤝 流程图```mermaid
%%{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
## 🚀 **钩子** (制作前5分钟)```mermaid
%%{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 {
<>
%% 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 runs
+useWorkflows(requestContext, partial)
+useWorkflow(workflowId, requestContext)
+useWorkflowRun(workflowId, runId, options)
+useWorkflowRuns(workflowId, params, requestContext)
+useWorkflowSchema(workflowId)
+useWorkflowStartMutation(workflowId)
+useWorkflowStartAsyncMutation(workflowId)
+useWorkflowDeleteRunMutation(workflowId)
+useWorkflowResumeMutation(workflowId)
+useWorkflowResumeAsyncMutation(workflowId)
+useWorkflowCancelMutation(workflowId)
+useWorkflowRestartMutation(workflowId)
+useWorkflowRestartAsyncMutation(workflowId)
+useWorkflowTimeTravelMutation(workflowId)
+useWorkflowTimeTravelAsyncMutation(workflowId)
%% Memory and threads
+useThreads(params)
+useThread(threadId, agentId, requestContext)
+useThreadMessages(threadId, opts)
+useThreadMessagesPaginated(threadId, opts)
+useWorkingMemory(params)
+useMemorySearch(params)
+useMemoryStatus(agentId, requestContext, opts)
+useMemoryConfig(params)
+useObservationalMemory(params)
+useAwaitBufferStatus(params)
+useCreateThreadMutation()
+useDeleteThreadMutation()
+useUpdateMemoryThreadMutation(threadId, agentId)
+useUpdateWorkingMemoryMutation(agentId, threadId)
+useSaveMessageToMemoryMutation()
+useDeleteThreadMessagesMutation(threadId, agentId)
+useCloneThreadMutation(threadId, agentId)
%% Stored agents and versions
+useStoredAgents(params)
+useStoredAgent(id, requestContext, options)
+useStoredAgentVersions(storedAgentId, params, requestContext)
+useStoredAgentVersion(storedAgentId, versionId, requestContext)
+useCompareStoredAgentVersions(storedAgentId, fromId, toId, requestContext)
+useCreateStoredAgentMutation()
+useUpdateStoredAgentMutation(storedAgentId)
+useDeleteStoredAgentMutation(storedAgentId)
+useCreateStoredAgentVersionMutation(storedAgentId)
+useActivateStoredAgentVersionMutation(storedAgentId)
+useRestoreStoredAgentVersionMutation(storedAgentId)
+useDeleteStoredAgentVersionMutation(storedAgentId)
%% Stored prompt blocks
+useStoredPromptBlocks(params)
+useStoredPromptBlock(id, requestContext, options)
+useStoredPromptBlockVersions(storedPromptBlockId, params, requestContext)
+useStoredPromptBlockVersion(storedPromptBlockId, versionId, requestContext)
+useCompareStoredPromptBlockVersions(storedPromptBlockId, fromId, toId, requestContext)
+useCreateStoredPromptBlockMutation()
+useUpdateStoredPromptBlockMutation(storedPromptBlockId)
+useDeleteStoredPromptBlockMutation(storedPromptBlockId)
+useCreateStoredPromptBlockVersionMutation(storedPromptBlockId)
+useActivateStoredPromptBlockVersionMutation(storedPromptBlockId)
+useRestoreStoredPromptBlockVersionMutation(storedPromptBlockId)
+useDeleteStoredPromptBlockVersionMutation(storedPromptBlockId)
%% Stored scorers
+useStoredScorers(params)
+useStoredScorer(id, requestContext, options)
+useStoredScorerVersions(storedScorerId, params, requestContext)
+useStoredScorerVersion(storedScorerId, versionId, requestContext)
+useCompareStoredScorerVersions(storedScorerId, fromId, toId, requestContext)
+useCreateStoredScorerMutation()
+useUpdateStoredScorerMutation(storedScorerId)
+useDeleteStoredScorerMutation(storedScorerId)
+useCreateStoredScorerVersionMutation(storedScorerId)
+useActivateStoredScorerVersionMutation(storedScorerId)
+useRestoreStoredScorerVersionMutation(storedScorerId)
+useDeleteStoredScorerVersionMutation(storedScorerId)
%% Stored MCP clients and skills
+useStoredMcpClients(params)
+useStoredMcpClient(id, requestContext)
+useCreateStoredMcpClientMutation()
+useUpdateStoredMcpClientMutation(storedMcpClientId)
+useDeleteStoredMcpClientMutation(storedMcpClientId)
+useStoredSkills(params)
+useStoredSkill(id, requestContext)
+useCreateStoredSkillMutation()
+useUpdateStoredSkillMutation(storedSkillId)
+useDeleteStoredSkillMutation(storedSkillId)
%% Vectors and embedders
+useVectorIndexes()
+useVectorDetails(indexName)
+useVectors()
+useEmbedders()
+useVectorQueryMutation(vectorName, indexName)
+useVectorUpsertMutation(vectorName, indexName)
%% Workspaces and skills
+useWorkspaces()
+useWorkspace(id)
+useWorkspaceInfo(id)
+useWorkspaceFiles(id, params)
+useWorkspaceReadFile(id, path)
+useWorkspaceSearch(id, params)
+useWorkspaceSkills(id)
…(正文过长,页面只展示前面部分,完整内容见仓库)
