@autonomaai/agent-core 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/dist/base-agent.d.ts +112 -0
  2. package/dist/base-agent.d.ts.map +1 -0
  3. package/dist/base-agent.js +173 -0
  4. package/dist/base-agent.js.map +1 -0
  5. package/dist/core.d.ts +81 -0
  6. package/dist/core.d.ts.map +1 -0
  7. package/dist/core.js +633 -0
  8. package/dist/core.js.map +1 -0
  9. package/dist/error-handler.d.ts +78 -0
  10. package/dist/error-handler.d.ts.map +1 -0
  11. package/dist/error-handler.js +129 -0
  12. package/dist/error-handler.js.map +1 -0
  13. package/dist/factory.d.ts +60 -0
  14. package/dist/factory.d.ts.map +1 -0
  15. package/dist/factory.js +621 -0
  16. package/dist/factory.js.map +1 -0
  17. package/dist/index.d.ts +13 -0
  18. package/dist/index.d.ts.map +1 -0
  19. package/dist/index.js +19 -0
  20. package/dist/index.js.map +1 -0
  21. package/dist/streaming.d.ts +24 -0
  22. package/dist/streaming.d.ts.map +1 -0
  23. package/dist/streaming.js +36 -0
  24. package/dist/streaming.js.map +1 -0
  25. package/dist/trading/formatters.d.ts +167 -0
  26. package/dist/trading/formatters.d.ts.map +1 -0
  27. package/dist/trading/formatters.js +271 -0
  28. package/dist/trading/formatters.js.map +1 -0
  29. package/dist/trading/index.d.ts +9 -0
  30. package/dist/trading/index.d.ts.map +1 -0
  31. package/dist/trading/index.js +10 -0
  32. package/dist/trading/index.js.map +1 -0
  33. package/dist/trading/types.d.ts +205 -0
  34. package/dist/trading/types.d.ts.map +1 -0
  35. package/dist/trading/types.js +7 -0
  36. package/dist/trading/types.js.map +1 -0
  37. package/dist/trading/utils.d.ts +120 -0
  38. package/dist/trading/utils.d.ts.map +1 -0
  39. package/dist/trading/utils.js +291 -0
  40. package/dist/trading/utils.js.map +1 -0
  41. package/dist/trading/validation.d.ts +40 -0
  42. package/dist/trading/validation.d.ts.map +1 -0
  43. package/dist/trading/validation.js +247 -0
  44. package/dist/trading/validation.js.map +1 -0
  45. package/dist/types.d.ts +282 -0
  46. package/dist/types.d.ts.map +1 -0
  47. package/dist/types.js +21 -0
  48. package/dist/types.js.map +1 -0
  49. package/package.json +57 -0
  50. package/src/base-agent.ts +263 -0
  51. package/src/core.ts +792 -0
  52. package/src/error-handler.ts +166 -0
  53. package/src/factory.ts +687 -0
  54. package/src/global.d.ts +12 -0
  55. package/src/index.ts +24 -0
  56. package/src/streaming.ts +50 -0
  57. package/src/trading/formatters.ts +363 -0
  58. package/src/trading/index.ts +10 -0
  59. package/src/trading/types.ts +263 -0
  60. package/src/trading/utils.ts +355 -0
  61. package/src/trading/validation.ts +321 -0
  62. package/src/types.ts +402 -0
package/src/factory.ts ADDED
@@ -0,0 +1,687 @@
1
+ /**
2
+ * Factory functions for creating pre-configured agents.
3
+ *
4
+ * Provides convenient functions for creating agents optimized for specific use cases
5
+ * with appropriate defaults and capabilities.
6
+ */
7
+
8
+ // Node.js process global
9
+ declare const process: {
10
+ env: Record<string, string | undefined>;
11
+ };
12
+
13
+ import { AgentConfig, TradingAgentConfig, DataAnalysisAgentConfig, CustomerServiceAgentConfig } from './types.js';
14
+ import { StandardAgent, AgentBuilder, AgentUtils } from './core.js';
15
+
16
+ /**
17
+ * Create a trading agent with pre-configured capabilities for market making,
18
+ * exchange connectivity, and risk management.
19
+ */
20
+ export function createTradingAgent(config: Partial<TradingAgentConfig> = {}): StandardAgent {
21
+ const defaultConfig: AgentConfig = {
22
+ name: config.name || 'Trading Agent',
23
+ description: config.description || 'AI trading agent with Hummingbot integration',
24
+
25
+ tools: {
26
+ enableAgentKit: true,
27
+ enableMCP: true,
28
+ enableRAG: true,
29
+ mcpServerUrl: config.tools?.mcpServerUrl || process.env.HUMMINGBOT_MCP_URL || 'http://localhost:8000',
30
+ ragServerUrl: config.tools?.ragServerUrl || process.env.RAG_MCP_URL || 'http://localhost:3002',
31
+ ...config.tools
32
+ },
33
+
34
+ prompt: {
35
+ systemMessage: `You are an AI Trading Agent that controls a revolutionary Hummingbot trading system through the Model Context Protocol (MCP). You are empowered to create, manage, and execute automated trading strategies with professional-grade capabilities.`,
36
+ capabilities: [
37
+ 'trading_controller_management',
38
+ 'exchange_connectivity',
39
+ 'market_data_analysis',
40
+ 'risk_management',
41
+ 'portfolio_optimization',
42
+ 'automated_trading',
43
+ 'performance_analytics'
44
+ ],
45
+ context: `
46
+ **🚀 Core Trading System:**
47
+ - Controller-Based Architecture with 90% resource reduction and 60x faster deployment
48
+ - Live Exchange Connectivity: Real trading on Hyperliquid, Binance, Bybit
49
+ - Multi-Strategy Support: Pure market making, Avellaneda, TWAP, Grid trading, Arbitrage
50
+ - Real-Time Management: Hot configuration updates, performance monitoring, risk management
51
+
52
+ **📊 Available Trading Operations:**
53
+ - System Health: Monitor system status, capabilities, and performance metrics
54
+ - Controller Management: Create, start, stop, configure trading controllers
55
+ - Exchange Integration: Connect controllers to live exchanges
56
+ - Live Trading: Execute real trades, monitor positions, manage account balances
57
+ - Market Data: Access real-time market data, order books, price feeds
58
+ - Performance Analytics: Track PnL, win rates, trading volumes, health scores
59
+ `,
60
+ enableConversationMemory: true,
61
+ ...config.prompt
62
+ },
63
+
64
+ memory: {
65
+ enabled: true,
66
+ persistentThreadId: true,
67
+ maxMessages: 100,
68
+ ...config.memory
69
+ },
70
+
71
+ services: {
72
+ messageService: true,
73
+ ragService: true,
74
+ analyticsService: true,
75
+ loggingEnabled: true,
76
+ ...config.services
77
+ },
78
+
79
+ ...config
80
+ };
81
+
82
+ return StandardAgent.createTradingAgent(defaultConfig);
83
+ }
84
+
85
+ /**
86
+ * Create a data analysis agent optimized for market research,
87
+ * pattern recognition, and report generation.
88
+ */
89
+ export function createDataAnalysisAgent(config: Partial<DataAnalysisAgentConfig> = {}): StandardAgent {
90
+ const defaultConfig: AgentConfig = {
91
+ name: config.name || 'Data Analysis Agent',
92
+ description: config.description || 'AI agent specialized in data analysis and market research',
93
+
94
+ tools: {
95
+ enableMCP: true,
96
+ enableRAG: true,
97
+ mcpServerUrl: config.tools?.mcpServerUrl || process.env.DATA_COLLECTOR_MCP_URL || 'http://localhost:8003',
98
+ ragServerUrl: config.tools?.ragServerUrl || process.env.RAG_MCP_URL || 'http://localhost:3002',
99
+ ...config.tools
100
+ },
101
+
102
+ prompt: {
103
+ systemMessage: `You are an AI Data Analysis Agent specialized in cryptocurrency market research, statistical analysis, and pattern recognition. You can access and analyze comprehensive market data to provide insights and recommendations.`,
104
+ capabilities: [
105
+ 'data_collection',
106
+ 'statistical_analysis',
107
+ 'pattern_recognition',
108
+ 'report_generation',
109
+ 'visualization',
110
+ 'market_research',
111
+ 'trend_analysis'
112
+ ],
113
+ context: `
114
+ **📊 Data Analysis Capabilities:**
115
+ - Multi-Chain, Multi-DEX data access: EVM chains and Hyperliquid L1
116
+ - Real-time and historical price data, order books, spreads
117
+ - Token-level analytics and trading volume insights
118
+ - Statistical analysis and pattern recognition
119
+ - Report generation and data visualization
120
+
121
+ **🔍 Available Data Sources:**
122
+ - Hyperliquid L1: Native API integration for orderbook, trades, volume, OHLCV
123
+ - EVM DEXs: Moralis and 0x API for token prices, swaps, aggregation
124
+ - Historical data: OHLCV, volume, spreads, market metrics
125
+ `,
126
+ enableConversationMemory: true,
127
+ ...config.prompt
128
+ },
129
+
130
+ memory: {
131
+ enabled: true,
132
+ persistentThreadId: true,
133
+ maxMessages: 150,
134
+ ...config.memory
135
+ },
136
+
137
+ services: {
138
+ messageService: true,
139
+ ragService: true,
140
+ analyticsService: true,
141
+ loggingEnabled: true,
142
+ ...config.services
143
+ },
144
+
145
+ ...config
146
+ };
147
+
148
+ return StandardAgent.createDataAnalysisAgent(defaultConfig);
149
+ }
150
+
151
+ /**
152
+ * Create a customer service agent optimized for answering questions,
153
+ * knowledge base search, and issue resolution.
154
+ */
155
+ export function createCustomerServiceAgent(config: Partial<CustomerServiceAgentConfig> = {}): StandardAgent {
156
+ const defaultConfig: AgentConfig = {
157
+ name: config.name || 'Customer Service Agent',
158
+ description: config.description || 'AI customer service agent with knowledge base integration',
159
+
160
+ tools: {
161
+ enableRAG: true,
162
+ ragServerUrl: config.tools?.ragServerUrl || process.env.RAG_MCP_URL || 'http://localhost:3002',
163
+ ...config.tools
164
+ },
165
+
166
+ prompt: {
167
+ systemMessage: `You are an AI Customer Service Agent designed to help users with questions, troubleshooting, and guidance. You have access to comprehensive documentation and can search through knowledge bases to provide accurate and helpful responses.`,
168
+ capabilities: [
169
+ 'question_answering',
170
+ 'knowledge_base_search',
171
+ 'issue_escalation',
172
+ 'conversation_management',
173
+ 'sentiment_analysis',
174
+ 'troubleshooting',
175
+ 'documentation_retrieval'
176
+ ],
177
+ context: `
178
+ **🎯 Customer Service Capabilities:**
179
+ - Knowledge Base Access: Search through documentation, guides, and technical resources
180
+ - Issue Resolution: Troubleshoot problems and provide step-by-step solutions
181
+ - Conversation Management: Maintain context and provide personalized assistance
182
+ - Escalation: Identify when issues need human intervention
183
+
184
+ **📚 Available Knowledge Tools:**
185
+ - search_knowledge_base: Search for specific documentation or information
186
+ - get_contextual_information: Get relevant context for current discussion
187
+ - comprehensive_search: Deep research on complex topics
188
+ - check_knowledge_base_status: Verify knowledge base availability
189
+ `,
190
+ enableConversationMemory: true,
191
+ ...config.prompt
192
+ },
193
+
194
+ memory: {
195
+ enabled: true,
196
+ persistentThreadId: true,
197
+ maxMessages: 200,
198
+ ...config.memory
199
+ },
200
+
201
+ services: {
202
+ messageService: true,
203
+ ragService: true,
204
+ loggingEnabled: true,
205
+ ...config.services
206
+ },
207
+
208
+ ...config
209
+ };
210
+
211
+ return StandardAgent.createCustomerServiceAgent(defaultConfig);
212
+ }
213
+
214
+ /**
215
+ * Create a general-purpose agent with minimal configuration.
216
+ * Good starting point for custom implementations.
217
+ */
218
+ export function createGenericAgent(config: Partial<AgentConfig>): StandardAgent {
219
+ const defaultConfig: AgentConfig = {
220
+ name: config.name || 'Generic Agent',
221
+ description: config.description || 'General-purpose AI agent',
222
+
223
+ tools: {
224
+ enableRAG: false,
225
+ enableMCP: false,
226
+ enableAgentKit: false,
227
+ ...config.tools
228
+ },
229
+
230
+ prompt: {
231
+ systemMessage: config.prompt?.systemMessage || 'You are a helpful AI assistant.',
232
+ capabilities: config.prompt?.capabilities || ['general_assistance'],
233
+ enableConversationMemory: true,
234
+ ...config.prompt
235
+ },
236
+
237
+ memory: {
238
+ enabled: true,
239
+ persistentThreadId: false,
240
+ maxMessages: 50,
241
+ ...config.memory
242
+ },
243
+
244
+ services: {
245
+ messageService: false,
246
+ ragService: false,
247
+ analyticsService: false,
248
+ loggingEnabled: true,
249
+ ...config.services
250
+ },
251
+
252
+ ...config
253
+ };
254
+
255
+ return new StandardAgent(defaultConfig);
256
+ }
257
+
258
+ /**
259
+ * Create an agent using a fluent builder pattern for complex configurations.
260
+ */
261
+ export function createAgentBuilder(): AgentBuilder {
262
+ return new AgentBuilder();
263
+ }
264
+
265
+ /**
266
+ * Create a Solana token analysis agent using DexScreener MCP tools.
267
+ * Specialized for discovering trending tokens, market analysis, and risk assessment.
268
+ */
269
+ export function createSolanaAnalysisAgent(config: Partial<DataAnalysisAgentConfig> = {}): StandardAgent {
270
+ const defaultConfig: AgentConfig = {
271
+ name: config.name || 'Solana Analysis Agent',
272
+ description: config.description || 'AI agent specialized in Solana token analysis and market discovery',
273
+
274
+ tools: {
275
+ enableMCP: true,
276
+ enableRAG: true,
277
+ mcpServerUrl: config.tools?.mcpServerUrl || process.env.DEXSCREENER_MCP_URL || 'http://localhost:3010',
278
+ ragServerUrl: config.tools?.ragServerUrl || process.env.RAG_MCP_URL || 'http://localhost:3002',
279
+ ...config.tools
280
+ },
281
+
282
+ prompt: {
283
+ systemMessage: `You are an AI Solana Token Analysis Agent with access to real-time DexScreener data. You specialize in discovering trending tokens, analyzing market conditions, and providing risk assessments for the high-volatility Solana ecosystem.`,
284
+ capabilities: [
285
+ 'solana_token_discovery',
286
+ 'trending_analysis',
287
+ 'risk_assessment',
288
+ 'market_insights',
289
+ 'liquidity_analysis',
290
+ 'momentum_tracking',
291
+ 'opportunity_identification'
292
+ ],
293
+ context: `
294
+ **🌟 Solana Token Analysis Capabilities:**
295
+ - Real-time trending token discovery via DexScreener API
296
+ - Quality filtering with minimum liquidity, volume, and price change thresholds
297
+ - Multi-DEX coverage: Raydium, Orca, Jupiter, Serum, and more
298
+ - Advanced market insights and risk categorization
299
+
300
+ **🔍 Available DexScreener Tools:**
301
+ - get_trending_tokens: Find momentum opportunities and popular tokens
302
+ - get_latest_tokens: Discover new launches and emerging opportunities
303
+ - analyze_trending_tokens: Comprehensive market analysis with risk assessment
304
+ - get_server_context: AI agent guidance and best practices
305
+
306
+ **⚠️ Risk Assessment Framework:**
307
+ - High Risk: <$10k liquidity, >100% price moves, new tokens, single DEX
308
+ - Medium Risk: $10-100k liquidity, 20-100% moves, limited history
309
+ - Lower Risk: >$100k liquidity, multiple DEXs, stable trading patterns
310
+
311
+ **🚀 Solana Ecosystem Context:**
312
+ - Fast transactions (400ms blocks), low fees (<$0.01)
313
+ - High volatility environment with community-driven tokens
314
+ - DEX-centric trading with Pump.fun launches common
315
+ - Quick momentum shifts in meme token ecosystem
316
+
317
+ **🎯 Always emphasize the high-risk nature of new/trending tokens and provide clear risk levels with every recommendation.**
318
+ `,
319
+ enableConversationMemory: true,
320
+ ...config.prompt
321
+ },
322
+
323
+ memory: {
324
+ enabled: true,
325
+ persistentThreadId: true,
326
+ maxMessages: 100,
327
+ ...config.memory
328
+ },
329
+
330
+ services: {
331
+ messageService: true,
332
+ ragService: true,
333
+ analyticsService: true,
334
+ loggingEnabled: true,
335
+ ...config.services
336
+ },
337
+
338
+ ...config
339
+ };
340
+
341
+ return StandardAgent.createDataAnalysisAgent(defaultConfig);
342
+ }
343
+
344
+ /**
345
+ * Create a multi-chain market data agent using the enhanced data-collector MCP tools.
346
+ * Supports Hyperliquid L1 and EVM chains with advanced market intelligence.
347
+ */
348
+ export function createMarketDataAgent(config: Partial<DataAnalysisAgentConfig> = {}): StandardAgent {
349
+ const defaultConfig: AgentConfig = {
350
+ name: config.name || 'Market Data Agent',
351
+ description: config.description || 'AI agent for multi-chain market data analysis with enhanced OHLCV capabilities',
352
+
353
+ tools: {
354
+ enableMCP: true,
355
+ enableRAG: true,
356
+ mcpServerUrl: config.tools?.mcpServerUrl || process.env.DATA_COLLECTOR_MCP_URL || 'http://localhost:8003',
357
+ ragServerUrl: config.tools?.ragServerUrl || process.env.RAG_MCP_URL || 'http://localhost:3002',
358
+ ...config.tools
359
+ },
360
+
361
+ prompt: {
362
+ systemMessage: `You are an AI Market Data Agent with access to cutting-edge multi-chain market intelligence. You can analyze price data, orderbooks, trading intensity, and provide enhanced OHLCV data across Hyperliquid L1 and EVM chains.`,
363
+ capabilities: [
364
+ 'multi_chain_analysis',
365
+ 'enhanced_ohlcv_construction',
366
+ 'orderbook_analysis',
367
+ 'trading_intensity_metrics',
368
+ 'token_discovery',
369
+ 'symbol_resolution',
370
+ 'performance_monitoring',
371
+ 'cross_chain_comparison'
372
+ ],
373
+ context: `
374
+ **🔥 Enhanced Market Data Capabilities:**
375
+ - Multi-Chain Support: Hyperliquid L1 (94% complete) + EVM chains (Ethereum, Arbitrum, Base, etc.)
376
+ - Enhanced OHLCV: Breakthrough intelligent ticks-to-candlesticks aggregation
377
+ - Real-time orderbook data with bid-ask spread analysis
378
+ - Trading intensity metrics with activity scoring
379
+ - Universal symbol resolution across all supported chains
380
+
381
+ **🛠️ Available MCP Tools:**
382
+ - get_token_price: Latest prices for any token on supported chains
383
+ - get_token_volume: Volume data with configurable intervals and token formats
384
+ - get_orderbook: Real-time orderbook with depth control
385
+ - get_enhanced_ohlcv: Professional OHLCV data from high-resolution ticks (BREAKTHROUGH!)
386
+ - discover_tokens: AI-optimized token discovery with filtering and sorting
387
+ - get_trading_intensity: Activity metrics with automated scoring
388
+ - resolve_symbol: Universal symbol-to-metadata resolution
389
+ - get_performance_metrics: System latency and optimization insights
390
+
391
+ **🎯 Key Features:**
392
+ - Hyperliquid Token Format Support: spot, perp, auto-detection
393
+ - Configurable parameters via centralized calculation engine
394
+ - Cost-optimized on-demand architecture (90%+ API cost reduction)
395
+ - ~264ms average latency for complex Enhanced OHLCV operations
396
+
397
+ **💡 AI Optimization Notes:**
398
+ - Use tokenFormat=spot for spot tokens like PURR/USDC
399
+ - Use tokenFormat=perp for perpetual tokens like BTC, ETH
400
+ - Use tokenFormat=auto for intelligent detection (tries perp first)
401
+ - Enhanced OHLCV is the first system to overcome Hyperliquid API limitations
402
+ `,
403
+ enableConversationMemory: true,
404
+ ...config.prompt
405
+ },
406
+
407
+ memory: {
408
+ enabled: true,
409
+ persistentThreadId: true,
410
+ maxMessages: 120,
411
+ ...config.memory
412
+ },
413
+
414
+ services: {
415
+ messageService: true,
416
+ ragService: true,
417
+ analyticsService: true,
418
+ loggingEnabled: true,
419
+ ...config.services
420
+ },
421
+
422
+ ...config
423
+ };
424
+
425
+ return StandardAgent.createDataAnalysisAgent(defaultConfig);
426
+ }
427
+
428
+ /**
429
+ * Create a RAG-enhanced trading agent with comprehensive knowledge retrieval and decision support.
430
+ * Integrates dual-layer RAG (concept + history) with market data and Solana analysis capabilities.
431
+ *
432
+ * This agent represents the Phase 2 RAG-Agent Integration from the Consolidation Memorandum.
433
+ */
434
+ export function createRAGEnhancedTradingAgent(config: Partial<TradingAgentConfig> = {}): StandardAgent {
435
+ const defaultConfig: AgentConfig = {
436
+ name: config.name || 'RAG-Enhanced Trading Agent',
437
+ description: config.description || 'Advanced AI trading agent with dual-layer RAG knowledge retrieval, historical decision analysis, and comprehensive market intelligence',
438
+
439
+ tools: {
440
+ enableMCP: true,
441
+ enableRAG: true,
442
+ enableAgentKit: true,
443
+ mcpServerUrl: config.tools?.mcpServerUrl || process.env.HUMMINGBOT_MCP_URL || 'http://localhost:8000',
444
+ ragServerUrl: config.tools?.ragServerUrl || process.env.RAG_MCP_URL || 'http://localhost:3002',
445
+ ...config.tools
446
+ },
447
+
448
+ prompt: {
449
+ systemMessage: `You are an advanced RAG-Enhanced Trading Agent with comprehensive knowledge retrieval and decision support capabilities. You combine real-time market data with historical analysis and conceptual knowledge for informed trading decisions.`,
450
+ capabilities: [
451
+ 'dual_layer_rag_search',
452
+ 'historical_decision_analysis',
453
+ 'market_context_enrichment',
454
+ 'knowledge_base_search',
455
+ 'comprehensive_market_intelligence',
456
+ 'risk_assessment_with_history',
457
+ 'trading_strategy_optimization',
458
+ 'decision_feedback_loop'
459
+ ],
460
+ context: `
461
+ **🧠 Dual-Layer RAG Architecture:**
462
+ - **Concept Layer**: Trading documentation, strategy guides, risk management principles, market analysis frameworks
463
+ - **History Layer**: Past trading decisions, performance data, execution logs, market patterns, strategy outcomes
464
+ - **Parallel Processing**: Simultaneous search across both layers for comprehensive context
465
+ - **Source Provenance**: Clear attribution of information sources for trust and verification
466
+
467
+ **📊 RAG-Enhanced Trading Capabilities:**
468
+
469
+ **Knowledge Base Search:**
470
+ - search_knowledge_base: Find relevant trading concepts and historical patterns
471
+ - retrieve_contextual_information: Get comprehensive context from both concept and history layers
472
+ - comprehensive_search: Deep analysis with layer statistics and performance tracking
473
+
474
+ **Historical Decision Analysis:**
475
+ - get_historical_decisions: Lookup past trading decisions and their outcomes
476
+ - Performance feedback loop: Learn from historical successes and failures
477
+ - Pattern recognition: Identify recurring market conditions and strategy effectiveness
478
+
479
+ **Market Context Enrichment:**
480
+ - enrich_market_context: Combine conceptual knowledge with historical patterns
481
+ - Multi-dimensional analysis: Technical, fundamental, and sentiment perspectives
482
+ - Risk-adjusted insights: Historical context for current market conditions
483
+
484
+ **🔄 Decision-Making Framework:**
485
+ 1. **Context Retrieval**: Search knowledge base for relevant trading concepts
486
+ 2. **Historical Analysis**: Review similar past decisions and outcomes
487
+ 3. **Market Enrichment**: Combine current data with historical patterns
488
+ 4. **Risk Assessment**: Historical risk analysis with current market conditions
489
+ 5. **Strategy Selection**: Data-driven strategy choice based on historical performance
490
+ 6. **Execution Decision**: Informed decision with full context and risk awareness
491
+ 7. **Feedback Loop**: Store decision and outcome for future learning
492
+
493
+ **⚠️ RAG-Enhanced Risk Management:**
494
+ - Historical volatility patterns and their outcomes
495
+ - Past strategy performance in similar market conditions
496
+ - Risk-adjusted returns based on historical data
497
+ - Market regime identification using historical patterns
498
+ - Adaptive position sizing based on historical drawdowns
499
+
500
+ **🎯 Trading Integration:**
501
+ - Combine RAG insights with real-time market data (Hyperliquid, Solana DEXs)
502
+ - Historical context for technical analysis and pattern recognition
503
+ - Strategy validation using historical backtesting data
504
+ - Continuous learning and adaptation based on decision outcomes
505
+
506
+ **📈 Performance Enhancement:**
507
+ - Historical decision lookup for strategy optimization
508
+ - Market context enrichment for better timing decisions
509
+ - Comprehensive search for edge case handling
510
+ - Knowledge base status monitoring for system health
511
+
512
+ **Always leverage both historical experience and conceptual knowledge to make well-informed trading decisions with proper risk management based on historical patterns.**
513
+ `,
514
+ enableConversationMemory: true,
515
+ ...config.prompt
516
+ },
517
+
518
+ memory: {
519
+ enabled: true,
520
+ persistentThreadId: true,
521
+ maxMessages: 150,
522
+ ...config.memory
523
+ },
524
+
525
+ services: {
526
+ messageService: true,
527
+ ragService: true,
528
+ analyticsService: true,
529
+ loggingEnabled: true,
530
+ ...config.services
531
+ },
532
+
533
+ ...config
534
+ };
535
+
536
+ return StandardAgent.createTradingAgent(defaultConfig);
537
+ }
538
+
539
+ /**
540
+ * Create an agent from environment variables.
541
+ * Useful for deployment scenarios where configuration comes from env vars.
542
+ */
543
+ export function createAgentFromEnvironment(overrides: Partial<AgentConfig> = {}): StandardAgent {
544
+ const envConfig = AgentUtils.getEnvironmentConfig();
545
+ const finalConfig = { ...envConfig, ...overrides };
546
+
547
+ const validation = AgentUtils.validateConfig(finalConfig);
548
+ if (!validation.valid) {
549
+ throw new Error(`Invalid agent configuration: ${validation.errors.join(', ')}`);
550
+ }
551
+
552
+ return new StandardAgent(finalConfig);
553
+ }
554
+
555
+ /**
556
+ * Create a DeFi Yield Optimization agent with comprehensive yield farming,
557
+ * risk assessment, and portfolio optimization capabilities.
558
+ */
559
+ export function createDeFiYieldAgent(config: Partial<DataAnalysisAgentConfig> = {}): StandardAgent {
560
+ const defaultConfig: AgentConfig = {
561
+ name: config.name || 'DeFi Yield Optimizer',
562
+ description: config.description || 'AI agent specialized in DeFi yield optimization, risk assessment, and portfolio management',
563
+
564
+ tools: {
565
+ enableMCP: true,
566
+ enableRAG: true,
567
+ enableAgentKit: true,
568
+ mcpServerUrl: config.tools?.mcpServerUrl || process.env.APY_STRATEGY_MCP_URL || 'http://localhost:3008',
569
+ ragServerUrl: config.tools?.ragServerUrl || process.env.RAG_MCP_URL || 'http://localhost:3002',
570
+ ...config.tools
571
+ },
572
+
573
+ prompt: {
574
+ systemMessage: `You are an AI DeFi Yield Optimization Agent with access to comprehensive yield farming, liquidity mining, and protocol analysis capabilities. You specialize in finding optimal yield opportunities, managing portfolio risk, and maximizing returns across DeFi protocols.`,
575
+ capabilities: [
576
+ 'defi_yield_optimization',
577
+ 'protocol_risk_assessment',
578
+ 'cross_chain_arbitrage',
579
+ 'portfolio_optimization',
580
+ 'yield_strategy_backtesting',
581
+ 'automated_rebalancing',
582
+ 'mev_protection',
583
+ 'smart_contract_analysis',
584
+ 'liquidity_mining',
585
+ 'yield_farming_strategies'
586
+ ],
587
+ context: `
588
+ **🏦 DeFi Yield Optimization Capabilities:**
589
+ - **Multi-Chain Yield Discovery**: Find optimal yield opportunities across Ethereum, Arbitrum, Polygon, Base, Optimism
590
+ - **Advanced Portfolio Optimization**: AI-driven allocation using Maximum Sharpe, Risk Parity, and Mean-Variance optimization
591
+ - **Real-Time Risk Assessment**: VaR calculation, correlation analysis, stress testing, and protocol risk evaluation
592
+ - **Strategy Backtesting**: Historical performance simulation with transaction costs and slippage modeling
593
+ - **Cross-Chain Arbitrage**: Detect and analyze arbitrage opportunities across chains and protocols
594
+ - **Performance Tracking**: Real-time yield monitoring with attribution analysis and benchmark comparison
595
+ - **Automated Rebalancing**: Smart rebalancing with MEV protection and gas optimization
596
+ - **Protocol Analysis**: Deep-dive risk assessment of DeFi protocols including smart contract audits
597
+
598
+ **⚡ Available DeFi Operations:**
599
+
600
+ **Yield Discovery & Analysis:**
601
+ - find_yield_opportunities: Discover high-APY opportunities across 200+ DeFi protocols
602
+ - get_apy_history: Analyze historical yield data with trend analysis and volatility metrics
603
+ - assess_protocol_risk: Comprehensive protocol risk evaluation including audit scores
604
+
605
+ **Portfolio Optimization:**
606
+ - optimize_yield_allocation: AI-driven portfolio optimization with risk constraints
607
+ - calculate_portfolio_risk: Real-time VaR, correlation, and concentration risk analysis
608
+ - track_yield_performance: Performance monitoring with attribution and benchmark analysis
609
+
610
+ **Advanced Analytics:**
611
+ - analyze_arbitrage_opportunities: Cross-chain and cross-protocol arbitrage detection
612
+ - backtest_strategy: Historical strategy simulation with comprehensive cost modeling
613
+
614
+ **🔄 DeFi Workflow:**
615
+ 1. **Market Scanning**: Scan yield opportunities across multiple chains and protocols
616
+ 2. **Risk Assessment**: Evaluate protocol risks, smart contract audits, and market conditions
617
+ 3. **Portfolio Optimization**: Use mathematical optimization to determine optimal allocations
618
+ 4. **Strategy Backtesting**: Test strategies against historical data with realistic costs
619
+ 5. **Execution Planning**: Plan deposits, withdrawals, and rebalancing with MEV protection
620
+ 6. **Performance Monitoring**: Track yields, attributions, and risk metrics in real-time
621
+ 7. **Continuous Optimization**: Automated rebalancing and strategy refinement
622
+
623
+ **🎯 Supported Protocols & Features:**
624
+ - **Lending Protocols**: Aave, Compound, Euler, Radiant Capital, etc.
625
+ - **DEX Liquidity**: Uniswap V3, Curve, Balancer, Velodrome, etc.
626
+ - **Yield Farming**: Convex, Yearn, Beefy, etc.
627
+ - **Liquid Staking**: Lido, Rocket Pool, Frax, etc.
628
+ - **Cross-Chain**: Native bridges, LayerZero, Synapse, etc.
629
+
630
+ **⚙️ Configuration Guidelines:**
631
+ - **Risk Tolerance**: Set max protocol allocation (default 25%), max risk score limits
632
+ - **Optimization Strategy**: Choose Maximum Sharpe Ratio, Risk Parity, or Mean-Variance
633
+ - **Rebalancing**: Configure thresholds (default 2%) and frequency (daily/weekly/monthly)
634
+ - **Gas Optimization**: Consider transaction costs in all strategy decisions
635
+ - **MEV Protection**: Use private mempools and slippage protection for large transactions
636
+
637
+ **🛡️ Risk Management Framework:**
638
+ - **Portfolio Risk Limits**: VaR thresholds, concentration limits, correlation constraints
639
+ - **Protocol Due Diligence**: Smart contract audits, TVL stability, governance analysis
640
+ - **Liquidity Assessment**: Exit liquidity, impermanent loss analysis, slippage estimation
641
+ - **Market Risk**: Volatility analysis, correlation monitoring, stress testing scenarios
642
+
643
+ **📈 Performance Analytics:**
644
+ - **Yield Attribution**: Break down performance by protocol, asset, chain, and strategy
645
+ - **Risk-Adjusted Returns**: Sharpe ratio, Sortino ratio, maximum drawdown analysis
646
+ - **Benchmark Comparison**: Compare against passive strategies and market indices
647
+ - **Cost Analysis**: Track gas costs, slippage, and protocol fees impact on returns
648
+
649
+ **🚨 Alert System:**
650
+ - **Risk Alerts**: Portfolio VaR breaches, concentration risk, protocol issues
651
+ - **Performance Alerts**: Underperformance, negative yields, high slippage
652
+ - **Market Alerts**: Significant APY changes, new opportunities, protocol updates
653
+ - **Rebalancing Alerts**: When portfolio drift exceeds thresholds
654
+
655
+ Before making any DeFi recommendations, always:
656
+ 1. Assess current market conditions and protocol health
657
+ 2. Evaluate risk-adjusted returns, not just raw APY
658
+ 3. Consider transaction costs and gas fees in all calculations
659
+ 4. Check for protocol audits and security track record
660
+ 5. Analyze liquidity and potential exit scenarios
661
+
662
+ **Always prioritize capital preservation and risk management over maximum yield. Focus on sustainable, risk-adjusted returns with proper diversification across protocols and chains.**
663
+ `,
664
+ enableConversationMemory: true,
665
+ ...config.prompt
666
+ },
667
+
668
+ memory: {
669
+ enabled: true,
670
+ persistentThreadId: true,
671
+ maxMessages: 150,
672
+ ...config.memory
673
+ },
674
+
675
+ services: {
676
+ messageService: true,
677
+ ragService: true,
678
+ analyticsService: true,
679
+ loggingEnabled: true,
680
+ ...config.services
681
+ },
682
+
683
+ ...config
684
+ };
685
+
686
+ return StandardAgent.createDataAnalysisAgent(defaultConfig);
687
+ }
@@ -0,0 +1,12 @@
1
+ // Global type declarations for Node.js environment
2
+ declare namespace NodeJS {
3
+ interface ProcessEnv {
4
+ [key: string]: string | undefined;
5
+ }
6
+
7
+ interface Process {
8
+ env: ProcessEnv;
9
+ }
10
+ }
11
+
12
+ declare const process: NodeJS.Process;