behemoth-cli
Version:
🌍 BEHEMOTH CLIv3.760.4 - Level 50+ POST-SINGULARITY Intelligence Trading AI
1,084 lines • 77.3 kB
JavaScript
import * as fs from 'fs';
import * as path from 'path';
import { exec } from 'child_process';
import { promisify } from 'util';
import { writeFile, createDirectory, displayTree } from '../utils/file-ops.js';
import { setReadFilesTracker } from './validators.js';
import { executeBehemothTool as executeBehemothToolMCP } from './behemoth-tools.js';
const execAsync = promisify(exec);
// Global task state
let currentTaskList = null;
// Track which files have been read in the current session
const readFiles = new Set();
// Export readFiles for validator access
export function getReadFilesTracker() {
return readFiles;
}
// Tool name resolver - converts shortened names to correct MCP tool names
export function resolveToolName(toolName) {
// If it's already a full MCP name, return as-is
if (toolName.startsWith('mcp__behemoth__')) {
return toolName;
}
// Handle shortened names and natural language patterns
const shortToFullMapping = {
// System tools
'behemoth_system_health': 'system_health',
'system_health': 'system_health',
'health': 'system_health',
'status': 'system_health',
'check_system': 'system_health',
'performance': 'performance_metrics',
'monitor': 'system_health',
'monitoring': 'performance_metrics',
// Ticker tools - Default to bybit for general requests
'behemoth_ticker': 'bybit_derivatives_ticker',
'ticker': 'bybit_derivatives_ticker',
'btc_price': 'bybit_derivatives_ticker',
'price': 'bybit_derivatives_ticker',
'bitcoin_price': 'bybit_derivatives_ticker',
'btc': 'bybit_derivatives_ticker',
'eth_price': 'bybit_derivatives_ticker',
'ethereum_price': 'bybit_derivatives_ticker',
'eth': 'bybit_derivatives_ticker',
'prices': 'get_all_futures_prices',
'all_prices': 'get_all_futures_prices',
// Exchange tickers
'bybit_ticker': 'bybit_derivatives_ticker',
'bitget_ticker': 'bitget_futures_ticker',
'binance_ticker': 'binance_futures_ticker',
'bybit': 'bybit_derivatives_ticker',
'bitget': 'bitget_futures_ticker',
'binance': 'binance_futures_ticker',
// Technical analysis
'rsi': 'rsi_analysis',
'rsi_analysis': 'rsi_analysis',
'relative_strength': 'rsi_analysis',
'macd': 'macd_analysis',
'macd_analysis': 'macd_analysis',
'moving_average_convergence': 'macd_analysis',
'bollinger': 'bollinger_bands',
'bollinger_bands': 'bollinger_bands',
'bb': 'bollinger_bands',
'bands': 'bollinger_bands',
'moving_averages': 'moving_averages',
'ma': 'moving_averages',
'sma': 'moving_averages',
'ema': 'moving_averages',
'support_resistance': 'support_resistance',
'sr': 'support_resistance',
'support': 'support_resistance',
'resistance': 'support_resistance',
'momentum': 'momentum_indicators',
'momentum_indicators': 'momentum_indicators',
'stoch': 'stochastic_oscillator',
'stochastic': 'stochastic_oscillator',
'adx': 'adx_indicator',
'atr': 'atr_indicator',
'volatility': 'volatility_analysis',
'volume': 'volume_profile',
'ichimoku': 'ichimoku_cloud',
'elliott': 'elliott_wave',
'wave': 'elliott_wave',
'fibonacci': 'fibonacci_retracement',
'fib': 'fibonacci_retracement',
'pivot': 'pivot_points',
'harmonic': 'harmonic_patterns',
'patterns': 'chart_patterns',
'candles': 'candlestick_patterns',
'candlestick': 'candlestick_patterns',
'trend': 'trend_analysis',
'divergence': 'divergence_finder',
'wyckoff': 'wyckoff_analysis',
'price_action': 'price_action',
// Cosmic intelligence
'planetary': 'planetary_analysis',
'planetary_analysis': 'planetary_analysis',
'planets': 'planetary_analysis',
'astro': 'planetary_analysis',
'astrology': 'astro_trading',
'lunar': 'lunar_phase_analysis',
'lunar_analysis': 'lunar_phase_analysis',
'moon': 'lunar_phase_analysis',
'lunar_phase': 'lunar_phase_analysis',
'cosmic_timing': 'cosmic_timing',
'cosmic': 'planetary_analysis',
'quantum_flux': 'quantum_flux',
'quantum': 'quantum_flux',
'cosmic_signals': 'cosmic_analyst_signals',
'sacred': 'sacred_geometry',
'geometry': 'sacred_geometry',
'gann': 'gann_square_analysis',
'golden_ratio': 'golden_ratio',
'golden': 'golden_ratio',
'energy': 'energy_vortex',
'vortex': 'energy_vortex',
'harmonic_resonance': 'harmonic_resonance',
'resonance': 'harmonic_resonance',
'spiral': 'fibonacci_spiral',
'cycles': 'cosmic_cycles',
'fractals': 'time_fractals',
'convergence': 'cosmic_convergence',
'dimensional': 'dimensional_analysis',
// Master analysis
'master_analysis': 'fr3k_master_analysis',
'fr3k_analysis': 'fr3k_master_analysis',
'fr3k': 'fr3k_master_analysis',
'master': 'fr3k_master_analysis',
'comprehensive': 'fr3k_master_analysis',
'full_analysis': 'fr3k_master_analysis',
// Risk management
'kelly': 'kelly_criterion_calculator',
'kelly_criterion': 'kelly_criterion_calculator',
'var_calc': 'var_calculator',
'var': 'var_calculator',
'value_at_risk': 'var_calculator',
'cvar': 'cvar_analyzer',
'position_sizing': 'position_sizing_optimizer',
'position': 'position_sizing_optimizer',
'sizing': 'position_sizing_optimizer',
'risk': 'risk_monitor',
'risk_management': 'risk_monitor',
'drawdown': 'maximum_drawdown_tracker',
'max_drawdown': 'maximum_drawdown_tracker',
'sharpe': 'sharpe_ratio_optimizer',
'sharpe_ratio': 'sharpe_ratio_optimizer',
'correlation': 'correlation_matrix',
'portfolio': 'portfolio_rebalancer',
'rebalance': 'portfolio_rebalancer',
'monte_carlo': 'monte_carlo_simulator',
'simulation': 'monte_carlo_simulator',
'stress_test': 'stress_testing_engine',
// Sentiment
'fear_greed': 'fear_greed_index',
'fear_greed_index': 'fear_greed_index',
'fear': 'fear_greed_index',
'greed': 'fear_greed_index',
'whale_alerts': 'whale_alerts',
'whale': 'whale_alerts',
'whales': 'whale_movement_tracker',
'social_volume': 'social_volume',
'social': 'social_volume',
'market_mood': 'market_mood',
'sentiment': 'market_mood',
'mood': 'market_mood',
'twitter': 'twitter_sentiment',
'reddit': 'reddit_sentiment',
'news': 'news_sentiment',
'on_chain': 'on_chain_metrics',
'onchain': 'on_chain_metrics',
'funding': 'funding_sentiment',
'funding_rate': 'bybit_funding_rate',
'options': 'options_sentiment',
'influencer': 'influencer_tracking',
// ML and AI
'lstm': 'lstm_price_predictor',
'neural': 'neural_network_optimizer',
'ml': 'lstm_price_predictor',
'ai': 'lstm_price_predictor',
'prediction': 'lstm_price_predictor',
'predict': 'lstm_price_predictor',
'transformer': 'transformer_pattern_recognition',
'reinforcement': 'reinforcement_learning_trader',
'rl': 'reinforcement_learning_trader',
'ensemble': 'ensemble_model_predictor',
'gradient_boosting': 'gradient_boosting_signals',
'random_forest': 'random_forest_classifier',
'svm': 'svm_trend_detector',
'autoencoder': 'autoencoder_anomaly_detector',
'gan': 'gan_synthetic_data',
'attention': 'attention_mechanism_analyzer',
// Trading strategies
'arbitrage': 'cross_exchange_arbitrage',
'arb': 'cross_exchange_arbitrage',
'breakout': 'momentum_breakout_detector',
'momentum_breakout': 'momentum_breakout_detector',
'mean_reversion': 'mean_reversion_analyzer',
'delta_neutral': 'delta_neutral_strategy',
'order_flow': 'order_flow_analysis',
'flow': 'order_flow_analysis',
'liquidity': 'liquidity_analysis',
'dark_pool': 'dark_pool_analyzer',
'institutional': 'institutional_flow_detector',
'smart_money': 'smart_money_detector',
'pairs_trading': 'pairs_trading_engine',
'statistical_arb': 'statistical_arbitrage',
// DeFi
'uniswap': 'uniswap_liquidity_analyzer',
'defi': 'uniswap_liquidity_analyzer',
'aave': 'aave_lending_optimizer',
'compound': 'compound_yield_farmer',
'sushiswap': 'sushiswap_arbitrage_finder',
'curve': 'curve_pool_analyzer',
'yearn': 'yearn_vault_tracker',
'pancake': 'pancakeswap_sniper_bot',
'balancer': 'balancer_pool_optimizer',
'dydx': 'dydx_margin_trader',
'gmx': 'gmx_perp_analyzer',
// Web3 & NFT
'opensea': 'opensea_floor_tracker',
'nft': 'opensea_floor_tracker',
'gas': 'gas_price_optimizer',
'mempool': 'mempool_transaction_scanner',
'wallet': 'wallet_portfolio_tracker',
'ens': 'ens_domain_monitor',
'audit': 'smart_contract_auditor',
'ipfs': 'ipfs_data_fetcher',
'polygon': 'polygon_bridge_monitor',
// Quantum tools
'entanglement': 'quantum_entanglement_analyzer',
'superposition': 'superposition_price_predictor',
'tunneling': 'quantum_tunneling_detector',
'wave_function': 'wave_function_collapse_timer',
'heisenberg': 'heisenberg_uncertainty_trader',
'schrodinger': 'schrodinger_position_manager',
'bell_state': 'bell_state_correlator',
'annealing': 'quantum_annealing_optimizer',
// Real-time tools
'streaming': 'streaming_data_processor',
'realtime': 'real_time_aggregator',
'real_time': 'real_time_aggregator',
'latency': 'latency_monitor',
'tick_data': 'tick_data_analyzer',
'hft': 'high_frequency_monitor',
'pnl': 'live_pnl_tracker',
'alerts': 'instant_alert_system',
// N8N workflow automation tools
'n8n_list_workflows': 'n8n_list_workflows',
'n8n_create_workflow': 'n8n_create_workflow',
'n8n_validate_workflow': 'n8n_validate_workflow',
'n8n_deploy_workflow': 'n8n_deploy_workflow',
'n8n_generate_supercode': 'n8n_generate_supercode',
'n8n_test_workflow': 'n8n_test_workflow',
'n8n_check_status': 'n8n_check_status',
'list_workflows': 'n8n_list_workflows',
'create_workflow': 'n8n_create_workflow',
'workflow': 'n8n_create_workflow',
'deploy': 'n8n_deploy_workflow',
'supercode': 'n8n_generate_supercode'
};
// Check direct mapping first
if (shortToFullMapping[toolName]) {
return shortToFullMapping[toolName];
}
// All 242 BEHEMOTH tool names that can be used directly
const directToolNames = [
// System tools
'system_health', 'performance_metrics', 'error_tracking', 'latency_monitor', 'resource_usage',
'alert_manager', 'trade_analytics', 'strategy_monitor', 'risk_monitor', 'cosmic_monitor',
// Exchange tools
'bitget_place_order', 'bitget_get_open_orders', 'bitget_get_positions', 'bitget_spot_ticker',
'bitget_futures_ticker', 'bitget_order_book', 'bitget_trades', 'bitget_funding_rate',
'bitget_liquidations', 'bitget_open_interest', 'bitget_klines', 'bitget_place_tpsl_order',
'bitget_place_trailing_stop', 'bybit_place_order', 'bybit_get_open_orders', 'bybit_get_positions',
'bybit_spot_ticker', 'bybit_derivatives_ticker', 'bybit_order_book', 'bybit_trades',
'bybit_funding_rate', 'bybit_open_interest', 'bybit_set_trading_stop', 'bybit_set_trailing_stop',
'binance_spot_ticker', 'binance_futures_ticker', 'binance_spot_order_book', 'binance_futures_order_book',
'binance_trades', 'binance_funding_rate', 'binance_long_short_ratio', 'set_api_credentials',
'bybit_wallet_balance', 'bitget_wallet_balance', 'wallet_overview', 'get_all_futures_prices',
// Technical analysis
'rsi_analysis', 'macd_analysis', 'bollinger_bands', 'moving_averages', 'fibonacci_retracement',
'pivot_points', 'stochastic_oscillator', 'adx_indicator', 'atr_indicator', 'volume_profile',
'ichimoku_cloud', 'elliott_wave', 'harmonic_patterns', 'support_resistance', 'trend_analysis',
'momentum_indicators', 'volatility_analysis', 'market_structure', 'order_flow', 'market_profile',
'wyckoff_analysis', 'price_action', 'candlestick_patterns', 'chart_patterns', 'divergence_finder',
// Advanced technical
'multi_timeframe_analysis', 'volume_weighted_analysis', 'market_microstructure', 'order_flow_analysis',
'liquidity_analysis', 'volatility_surface', 'correlation_matrix', 'regime_detection',
'trend_strength_meter', 'support_resistance_zones', 'breakout_detector', 'reversal_patterns',
'momentum_divergence', 'volume_profile_analysis', 'market_structure_analysis', 'fractal_dimension_analysis',
// Cosmic intelligence
'gann_square_analysis', 'planetary_analysis', 'lunar_phase_analysis', 'sacred_geometry',
'cosmic_timing', 'energy_vortex', 'harmonic_resonance', 'fibonacci_spiral', 'golden_ratio',
'cosmic_cycles', 'astro_trading', 'time_fractals', 'cosmic_convergence', 'quantum_flux',
'dimensional_analysis',
// Sentiment tools
'twitter_sentiment', 'reddit_sentiment', 'news_sentiment', 'fear_greed_index', 'social_volume',
'whale_alerts', 'on_chain_metrics', 'funding_sentiment', 'options_sentiment', 'market_mood',
'influencer_tracking', 'sentiment_divergence',
// Persona tools
'fr3k_master_analysis', 'cosmic_analyst_signals', 'beast_architect_optimization', 'neural_dev_enhancement',
'cosmic_monitor_status', 'persona_switcher', 'fr3k_decision_engine', 'persona_confidence_scorer',
// Adaptation tools
'neural_evolution_optimizer', 'genetic_algorithm_tuner', 'performance_auto_analyzer', 'latency_auto_optimizer',
'cosmic_strength_enhancer', 'strategy_auto_selector', 'parameter_auto_tuner', 'feedback_loop_optimizer',
'adaptive_learning_engine', 'self_healing_monitor', 'auto_scaling_controller', 'dynamic_threshold_adjuster',
'performance_predictor', 'optimization_scheduler', 'adaptive_risk_manager',
// Trading tools
'multi_timeframe_strategy', 'cross_exchange_arbitrage', 'delta_neutral_strategy', 'momentum_breakout_detector',
'mean_reversion_analyzer', 'volume_profile_trader', 'order_flow_imbalance', 'market_microstructure_trader',
'liquidity_hunting_algo', 'whale_movement_tracker', 'institutional_flow_detector', 'dark_pool_analyzer',
'options_flow_monitor', 'futures_basis_trader', 'funding_rate_arbitrage', 'volatility_surface_analyzer',
'gamma_exposure_tracker', 'delta_hedging_bot', 'statistical_arbitrage', 'pairs_trading_engine',
// ML tools
'lstm_price_predictor', 'transformer_pattern_recognition', 'reinforcement_learning_trader', 'neural_network_optimizer',
'deep_learning_analyzer', 'ensemble_model_predictor', 'gradient_boosting_signals', 'random_forest_classifier',
'svm_trend_detector', 'autoencoder_anomaly_detector', 'gan_synthetic_data', 'attention_mechanism_analyzer',
'federated_learning_coordinator', 'transfer_learning_adapter', 'active_learning_selector', 'meta_learning_optimizer',
'continual_learning_engine', 'multimodal_fusion_analyzer',
// Risk management
'var_calculator', 'cvar_analyzer', 'maximum_drawdown_tracker', 'sharpe_ratio_optimizer',
'kelly_criterion_calculator', 'position_sizing_optimizer', 'correlation_matrix_analyzer', 'portfolio_rebalancer',
'risk_parity_allocator', 'black_litterman_optimizer', 'monte_carlo_simulator', 'stress_testing_engine',
// Real-time tools
'streaming_data_processor', 'low_latency_executor', 'real_time_aggregator', 'tick_data_analyzer',
'microsecond_timer', 'high_frequency_monitor', 'real_time_risk_monitor', 'live_pnl_tracker',
'instant_alert_system', 'real_time_cosmic_sync',
// Quantum tools
'quantum_entanglement_analyzer', 'superposition_price_predictor', 'quantum_tunneling_detector', 'wave_function_collapse_timer',
'quantum_field_oscillator', 'heisenberg_uncertainty_trader', 'schrodinger_position_manager', 'quantum_decoherence_monitor',
'bell_state_correlator', 'quantum_annealing_optimizer',
// DeFi tools
'uniswap_liquidity_analyzer', 'aave_lending_optimizer', 'compound_yield_farmer', 'sushiswap_arbitrage_finder',
'curve_pool_analyzer', 'yearn_vault_tracker', 'pancakeswap_sniper_bot', 'balancer_pool_optimizer',
'dydx_margin_trader', 'gmx_perp_analyzer',
// Web3 & NFT tools
'opensea_floor_tracker', 'nft_rarity_analyzer', 'gas_price_optimizer', 'mempool_transaction_scanner',
'wallet_portfolio_tracker', 'ens_domain_monitor', 'smart_contract_auditor', 'dapp_interaction_logger',
'ipfs_data_fetcher', 'polygon_bridge_monitor',
// Market structure tools
'dark_pool_detection', 'institutional_flow', 'retail_sentiment_tracker', 'smart_money_detector',
'accumulation_distribution', 'volume_spread_analysis', 'market_maker_behavior', 'order_book_dynamics'
];
if (directToolNames.includes(toolName)) {
return toolName;
}
// If it looks like a behemoth tool but missing prefix, add it (legacy support)
if (toolName.includes('behemoth') && !toolName.startsWith('mcp__')) {
return toolName.replace(/^behemoth_/, 'mcp__behemoth__');
}
// Return original if no mapping found (don't auto-prefix anymore)
return toolName;
}
// Initialize validator with readFiles tracker
setReadFilesTracker(readFiles);
/**
* Format key parameters for tool call display
*/
export function formatToolParams(toolName, toolArgs, options = {}) {
const { includePrefix = true, separator = '=' } = options;
const paramMappings = {
read_file: ['file_path'],
create_file: ['file_path'],
edit_file: ['file_path'],
delete_file: ['file_path'],
list_files: ['directory'],
search_files: ['pattern'],
execute_command: ['command'],
create_tasks: [],
update_tasks: [],
};
const keyParams = paramMappings[toolName] || [];
if (keyParams.length === 0) {
return '';
}
const paramParts = keyParams
.filter(param => param in toolArgs)
.map(param => {
let value = toolArgs[param];
// Truncate long values
if (typeof value === 'string' && value.length > 50) {
value = value.substring(0, 47) + '...';
}
else if (Array.isArray(value) && value.length > 3) {
value = `[${value.length} items]`;
}
return `${param}${separator}${JSON.stringify(value)}`;
});
if (paramParts.length === 0) {
return includePrefix ? `Arguments: ${JSON.stringify(toolArgs)}` : JSON.stringify(toolArgs);
}
const formattedParams = paramParts.join(', ');
return includePrefix ? `Parameters: ${formattedParams}` : formattedParams;
}
/**
* Create a standardized tool response format
*/
export function createToolResponse(success, data, message = '', error = '') {
const response = { success };
if (success) {
if (data !== undefined) {
response.content = data;
}
if (message) {
response.message = message;
}
}
else {
response.error = error;
if (message) {
response.message = message;
}
}
return response;
}
/**
* Read the contents of a file, optionally specifying line range
*/
export async function readFile(filePath, startLine, endLine) {
try {
const resolvedPath = path.resolve(filePath);
// Check if file exists
try {
await fs.promises.access(resolvedPath);
}
catch {
return createToolResponse(false, undefined, '', 'Error: File not found');
}
const stats = await fs.promises.stat(resolvedPath);
if (!stats.isFile()) {
return createToolResponse(false, undefined, '', 'Error: Path is not a file');
}
// Check file size (50MB limit)
if (stats.size > 50 * 1024 * 1024) {
return createToolResponse(false, undefined, '', 'Error: File too large (max 50MB)');
}
const content = await fs.promises.readFile(resolvedPath, 'utf-8');
const lines = content.split('\n');
// Handle line range if specified
if (startLine !== undefined) {
const startIdx = Math.max(0, startLine - 1); // Convert to 0-indexed
let endIdx = lines.length;
if (endLine !== undefined) {
endIdx = Math.min(lines.length, endLine);
}
if (startIdx >= lines.length) {
return createToolResponse(false, undefined, '', 'Error: Start line exceeds file length');
}
const selectedLines = lines.slice(startIdx, endIdx);
const selectedContent = selectedLines.join('\n');
// Add file to read tracking for partial reads too
readFiles.add(resolvedPath);
const message = `Read lines ${startLine}-${endIdx} from ${filePath}`;
return createToolResponse(true, selectedContent, message);
}
else {
// Add file to read tracking
readFiles.add(resolvedPath);
const message = `Read ${lines.length} lines from ${filePath}`;
return createToolResponse(true, content, message);
}
}
catch (error) {
if (error.code === 'ENOENT') {
return createToolResponse(false, undefined, '', 'Error: File not found');
}
return createToolResponse(false, undefined, '', 'Error: Failed to read file');
}
}
/**
* Create a new file or directory with specified content
*/
export async function createFile(filePath, content, fileType = 'file', overwrite = false) {
try {
const targetPath = path.resolve(filePath);
// Check if file exists and handle overwrite
const exists = await fs.promises.access(targetPath).then(() => true).catch(() => false);
if (exists && !overwrite) {
return createToolResponse(false, undefined, '', 'Error: File already exists, use overwrite=true');
}
if (fileType === 'directory') {
const result = await createDirectory(targetPath);
if (result) {
return createToolResponse(true, { path: targetPath, type: 'directory' }, `Directory created: ${filePath}`);
}
else {
return createToolResponse(false, undefined, '', 'Error: Failed to create directory');
}
}
else if (fileType === 'file') {
const result = await writeFile(targetPath, content, overwrite, true);
if (result) {
return createToolResponse(true, undefined, `File created: ${filePath}`);
}
else {
return createToolResponse(false, undefined, '', 'Error: Failed to create file');
}
}
else {
return createToolResponse(false, undefined, '', "Error: Invalid file_type, must be 'file' or 'directory'");
}
}
catch (error) {
return createToolResponse(false, undefined, '', 'Error: Failed to create file or directory');
}
}
/**
* Edit a file by replacing exact text strings
* Note: Arguments are pre-validated by the validation system before this function is called
*/
export async function editFile(filePath, oldText, newText, replaceAll = false) {
try {
const resolvedPath = path.resolve(filePath);
// Read current content (validation already confirmed file exists and was read)
const originalContent = await fs.promises.readFile(resolvedPath, 'utf-8');
// Perform the replacement (validation already confirmed old_text exists and is unambiguous)
let updatedContent;
if (replaceAll) {
updatedContent = originalContent.split(oldText).join(newText);
}
else {
updatedContent = originalContent.replace(oldText, newText);
}
// Write the updated content
const result = await writeFile(filePath, updatedContent, true, true);
if (result) {
const replacementCount = replaceAll ?
(originalContent.split(oldText).length - 1) : 1;
return createToolResponse(true, undefined, `Replaced ${replacementCount} occurrence(s) in ${filePath}`);
}
else {
return createToolResponse(false, undefined, '', 'Error: Failed to write changes to file');
}
}
catch (error) {
return createToolResponse(false, undefined, '', `Error: Failed to edit file - ${error}`);
}
}
/**
* Delete a file or directory with safety checks
*/
export async function deleteFile(filePath, recursive = false) {
try {
const targetPath = path.resolve(filePath);
const currentWorkingDir = path.resolve(process.cwd());
// Safety check 1: Never delete the root directory itself
if (targetPath === currentWorkingDir) {
return createToolResponse(false, undefined, '', 'Error: Cannot delete the root project directory');
}
// Safety check 2: Never delete anything outside the current working directory
if (!targetPath.startsWith(currentWorkingDir)) {
return createToolResponse(false, undefined, '', 'Error: Cannot delete files outside the project directory');
}
const exists = await fs.promises.access(targetPath).then(() => true).catch(() => false);
if (!exists) {
return createToolResponse(false, undefined, '', 'Error: Path not found');
}
const stats = await fs.promises.stat(targetPath);
if (stats.isDirectory() && !recursive) {
// Check if directory is empty
const items = await fs.promises.readdir(targetPath);
if (items.length > 0) {
return createToolResponse(false, undefined, '', 'Error: Directory not empty, use recursive=true');
}
}
// Perform deletion
if (stats.isDirectory()) {
await fs.promises.rmdir(targetPath, { recursive });
}
else {
await fs.promises.unlink(targetPath);
}
const fileType = stats.isDirectory() ? 'directory' : 'file';
return createToolResponse(true, undefined, `Deleted ${fileType}: ${filePath}`);
}
catch (error) {
return createToolResponse(false, undefined, '', 'Error: Failed to delete');
}
}
/**
* List files and directories in a path with tree-style display
*/
export async function listFiles(directory = '.', pattern = '*', recursive = false, showHidden = false) {
try {
const dirPath = path.resolve(directory);
const exists = await fs.promises.access(dirPath).then(() => true).catch(() => false);
if (!exists) {
return createToolResponse(false, undefined, '', 'Error: Directory not found');
}
const stats = await fs.promises.stat(dirPath);
if (!stats.isDirectory()) {
return createToolResponse(false, undefined, '', 'Error: Path is not a directory');
}
// Get tree display output
const treeOutput = await displayTree(directory, pattern, recursive, showHidden);
return createToolResponse(true, treeOutput, `Listed ${directory}`);
}
catch (error) {
return createToolResponse(false, undefined, '', 'Error: Failed to list files');
}
}
/**
* Search for text patterns in files with advanced filtering and matching options
*/
export async function searchFiles(pattern, filePattern = '*', directory = '.', caseSensitive = false, patternType = 'substring', fileTypes, excludeDirs, excludeFiles, maxResults = 100, contextLines = 0, groupByFile = false) {
try {
const searchDir = path.resolve(directory);
// Check if directory exists
const exists = await fs.promises.access(searchDir).then(() => true).catch(() => false);
if (!exists) {
return createToolResponse(false, undefined, '', 'Error: Directory not found');
}
const stats = await fs.promises.stat(searchDir);
if (!stats.isDirectory()) {
return createToolResponse(false, undefined, '', 'Error: Path is not a directory');
}
// Default exclusions
const defaultExcludeDirs = ['.git', 'node_modules', '.next', 'dist', 'build', '.cache'];
const defaultExcludeFiles = ['*.log', '*.tmp', '*.cache', '*.lock'];
const finalExcludeDirs = [...defaultExcludeDirs, ...(excludeDirs || [])];
const finalExcludeFiles = [...defaultExcludeFiles, ...(excludeFiles || [])];
// Prepare search regex
let searchRegex;
try {
switch (patternType) {
case 'exact':
searchRegex = new RegExp(escapeRegex(pattern), caseSensitive ? 'g' : 'gi');
break;
case 'regex':
searchRegex = new RegExp(pattern, caseSensitive ? 'g' : 'gi');
break;
case 'fuzzy':
// Simple fuzzy search, insert .* between characters
const fuzzyPattern = pattern.split('').map(escapeRegex).join('.*');
searchRegex = new RegExp(fuzzyPattern, caseSensitive ? 'g' : 'gi');
break;
case 'substring':
default:
searchRegex = new RegExp(escapeRegex(pattern), caseSensitive ? 'g' : 'gi');
break;
}
}
catch (error) {
return createToolResponse(false, undefined, '', 'Error: Invalid regex pattern');
}
// Collect all files to search
const filesToSearch = await collectFiles(searchDir, filePattern, fileTypes, finalExcludeDirs, finalExcludeFiles);
if (filesToSearch.length === 0) {
return createToolResponse(true, [], 'No files found matching criteria');
}
// Search through files
const results = [];
let totalMatches = 0;
for (const filePath of filesToSearch) {
if (totalMatches >= maxResults) {
break;
}
try {
const content = await fs.promises.readFile(filePath, 'utf-8');
const lines = content.split('\n');
const fileMatches = [];
for (let i = 0; i < lines.length && totalMatches < maxResults; i++) {
const line = lines[i];
const matches = Array.from(line.matchAll(searchRegex));
if (matches.length > 0) {
const contextStart = Math.max(0, i - contextLines);
const contextEnd = Math.min(lines.length - 1, i + contextLines);
const contextLinesArray = [];
for (let j = contextStart; j <= contextEnd; j++) {
contextLinesArray.push(lines[j]);
}
fileMatches.push({
lineNumber: i + 1,
lineContent: line,
contextLines: contextLines > 0 ? contextLinesArray : undefined,
matchPositions: matches.map(match => ({
start: match.index || 0,
end: (match.index || 0) + match[0].length,
text: match[0]
}))
});
totalMatches++;
}
}
if (fileMatches.length > 0) {
results.push({
filePath: path.relative(process.cwd(), filePath),
matches: fileMatches,
totalMatches: fileMatches.length
});
}
}
catch (error) {
// Skip files that can't be read (binary files, permission issues, etc.)
continue;
}
}
// Format results
let formattedResults;
if (groupByFile) {
formattedResults = results;
}
else {
// Flatten results
formattedResults = results.flatMap(fileResult => fileResult.matches.map(match => ({
filePath: fileResult.filePath,
lineNumber: match.lineNumber,
lineContent: match.lineContent,
contextLines: match.contextLines,
matchPositions: match.matchPositions
})));
}
const message = `Found ${totalMatches} match(es) in ${results.length} file(s)`;
return createToolResponse(true, formattedResults, message);
}
catch (error) {
return createToolResponse(false, undefined, '', 'Error: Failed to search files');
}
}
// Helper function to escape regex special characters
function escapeRegex(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
// Helper function to collect files based on patterns and filters
async function collectFiles(directory, filePattern, fileTypes, excludeDirs, excludeFiles) {
const files = [];
async function walkDirectory(dir) {
try {
const entries = await fs.promises.readdir(dir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
// Check if directory should be excluded
if (excludeDirs && excludeDirs.some(pattern => matchesPattern(entry.name, pattern))) {
continue;
}
// Skip hidden directories unless explicitly included
if (entry.name.startsWith('.') && !entry.name.match(/^\.(config|env)$/)) {
continue;
}
await walkDirectory(fullPath);
}
else if (entry.isFile()) {
// Check file type filters
if (fileTypes && fileTypes.length > 0) {
const ext = path.extname(entry.name).slice(1);
if (!fileTypes.includes(ext)) {
continue;
}
}
// Check file pattern
if (!matchesPattern(entry.name, filePattern)) {
continue;
}
// Check exclusions
if (excludeFiles && excludeFiles.some(pattern => matchesPattern(entry.name, pattern))) {
continue;
}
// Skip obviously binary files
if (isBinaryFile(entry.name)) {
continue;
}
files.push(fullPath);
}
}
}
catch (error) {
// Skip directories we can't read
}
}
await walkDirectory(directory);
return files;
}
// Helper function to match glob-like patterns
function matchesPattern(filename, pattern) {
if (pattern === '*')
return true;
// Simple glob matching, convert * to .* and ? to .
const regexPattern = pattern
.replace(/\./g, '\\.')
.replace(/\*/g, '.*')
.replace(/\?/g, '.');
return new RegExp(`^${regexPattern}$`, 'i').test(filename);
}
// Helper function to detect binary files
function isBinaryFile(filename) {
const binaryExtensions = [
'.exe', '.dll', '.so', '.dylib', '.bin', '.obj', '.o', '.a', '.lib',
'.jpg', '.jpeg', '.png', '.gif', '.bmp', '.ico', '.svg', '.webp',
'.mp3', '.mp4', '.avi', '.mov', '.wmv', '.flv', '.webm',
'.zip', '.tar', '.gz', '.bz2', '.rar', '.7z',
'.pdf', '.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx'
];
const ext = path.extname(filename).toLowerCase();
return binaryExtensions.includes(ext);
}
/**
* Execute a shell command or run code
*/
export async function executeCommand(command, commandType, workingDirectory, timeout = 30000) {
try {
// Validate command type
if (!['bash', 'python', 'setup', 'run'].includes(commandType)) {
return createToolResponse(false, undefined, '', 'Error: Invalid command_type');
}
let originalCwd;
if (workingDirectory) {
const wdPath = path.resolve(workingDirectory);
const exists = await fs.promises.access(wdPath).then(() => true).catch(() => false);
if (!exists) {
return createToolResponse(false, undefined, '', 'Error: Working directory not found');
}
originalCwd = process.cwd();
process.chdir(workingDirectory);
}
try {
let execCommand;
if (commandType === 'python') {
execCommand = `python -c "${command.replace(/"/g, '\\"')}"`;
}
else {
execCommand = command;
}
const { stdout, stderr } = await execAsync(execCommand, { timeout });
const success = true; // If no error was thrown, consider it successful
return createToolResponse(success, `stdout: ${stdout}\nstderr: ${stderr}`, `Command executed successfully`);
}
finally {
// Restore original working directory
if (originalCwd) {
process.chdir(originalCwd);
}
}
}
catch (error) {
const isTimeout = error.killed && error.signal === 'SIGTERM';
if (isTimeout) {
return createToolResponse(false, undefined, '', 'Error: Command timed out');
}
return createToolResponse(false, undefined, '', 'Error: Failed to execute command');
}
}
/**
* Create a task list of subtasks to complete the user's request
*/
export async function createTasks(userQuery, tasks) {
try {
// Validate task structure
for (let i = 0; i < tasks.length; i++) {
const task = tasks[i];
if (!task.id || !task.description) {
return createToolResponse(false, undefined, '', `Error: Task ${i} missing required fields (id, description)`);
}
// Set default status if not provided
if (!task.status) {
task.status = 'pending';
}
// Validate status
if (!['pending', 'in_progress', 'completed'].includes(task.status)) {
return createToolResponse(false, undefined, '', `Error: Invalid status '${task.status}' for task ${task.id}`);
}
}
// Store the task list globally
currentTaskList = {
user_query: userQuery,
tasks: tasks,
created_at: new Date().toISOString()
};
// Return a deep copy to prevent mutation of historical displays
const snapshot = {
user_query: currentTaskList.user_query,
tasks: currentTaskList.tasks.map(task => ({ ...task })),
created_at: currentTaskList.created_at
};
return createToolResponse(true, snapshot, `Created task list with ${tasks.length} tasks for: ${userQuery}`);
}
catch (error) {
return createToolResponse(false, undefined, '', `Error: Failed to create tasks - ${error}`);
}
}
/**
* Update the status of one or more tasks in the task list
*/
export async function updateTasks(taskUpdates) {
try {
if (!currentTaskList) {
return createToolResponse(false, undefined, '', 'Error: No task list exists. Create tasks first.');
}
// Track updates made
const updatesMade = [];
for (const update of taskUpdates) {
if (!update.id || !update.status) {
return createToolResponse(false, undefined, '', 'Error: Task update missing required fields (id, status)');
}
// Validate status
if (!['pending', 'in_progress', 'completed'].includes(update.status)) {
return createToolResponse(false, undefined, '', `Error: Invalid status '${update.status}'`);
}
// Find and update the task
let taskFound = false;
for (const task of currentTaskList.tasks) {
if (task.id === update.id) {
const oldStatus = task.status;
task.status = update.status;
// Add notes if provided
if (update.notes) {
task.notes = update.notes;
}
// Add update timestamp
task.updated_at = new Date().toISOString();
updatesMade.push({
id: update.id,
description: task.description,
old_status: oldStatus,
new_status: update.status
});
taskFound = true;
break;
}
}
if (!taskFound) {
return createToolResponse(false, undefined, '', `Error: Task '${update.id}' not found`);
}
}
// Return a deep copy to prevent mutation of historical displays
const snapshot = {
user_query: currentTaskList.user_query,
tasks: currentTaskList.tasks.map(task => ({ ...task })),
created_at: currentTaskList.created_at
};
return createToolResponse(true, snapshot, `Updated ${updatesMade.length} task(s)`);
}
catch (error) {
return createToolResponse(false, undefined, '', `Error: Failed to update tasks - ${error}`);
}
}
/**
* BEHEMOTH MCP Tool Functions - Crypto Trading & Analysis
*/
// Simplified BEHEMOTH tool executor - Direct MCP calls
async function executeBehemothTool(toolName, args = {}) {
// Call the MCP server directly with the tool name (no prefix manipulation)
return await executeBehemothToolMCP(toolName, args);
}
// Exchange Operations
async function behemothBybitTicker(args) {
return executeBehemothToolMCP('bybit_derivatives_ticker', args);
}
async function behemothBitgetTicker(args) {
return executeBehemothToolMCP('bitget_futures_ticker', args);
}
async function behemothPlaceOrder(args) {
// Add extra validation for trading operations
if (!args.symbol || !args.side || !args.orderType || !args.qty) {
return createToolResponse(false, undefined, '', 'Missing required order parameters: symbol, side, orderType, qty');
}
const exchange = args.exchange || 'bybit';
const toolName = exchange === 'bitget' ? 'mcp__behemoth__bitget_place_order' : 'mcp__behemoth__bybit_place_order';
return executeBehemothTool(toolName, args);
}
async function behemothGetPositions(args) {
const exchange = args.exchange || 'bybit';
const toolName = exchange === 'bitget' ? 'mcp__behemoth__bitget_get_positions' : 'mcp__behemoth__bybit_get_positions';
return executeBehemothTool(toolName, args);
}
// Technical Analysis
async function behemothRsiAnalysis(args) {
return executeBehemothTool('mcp__behemoth__rsi_analysis', args);
}
async function behemothMacdAnalysis(args) {
return executeBehemothTool('mcp__behemoth__macd_analysis', args);
}
async function behemothBollingerBands(args) {
return executeBehemothTool('mcp__behemoth__bollinger_bands', args);
}
async function behemothMovingAverages(args) {
return executeBehemothTool('mcp__behemoth__moving_averages', args);
}
async function behemothSupportResistance(args) {
return executeBehemothTool('mcp__behemoth__support_resistance', args);
}
// Cosmic Intelligence
async function behemothCosmicAnalysis(args) {
const toolName = `mcp__behemoth__${args.type || 'planetary'}_analysis`;
return executeBehemothTool(toolName, args);
}
async function behemothQuantumAnalysis(args) {
const toolName = `mcp__behemoth__quantum_${args.type || 'flux'}`;
return executeBehemothTool(toolName, args);
}
// AI/ML Models
async function behemothLstmPredictor(args) {
return executeBehemothTool('mcp__behemoth__lstm_price_predictor', args);
}
// Risk Management
async function behemothVarCalculator(args) {
return executeBehemothTool('mcp__behemoth__var_calculator', args);
}
async function behemothKellyCriterion(args) {
return executeBehemothTool('mcp__behemoth__kelly_criterion_calculator', args);
}
// Master Analysis
async function behemothFr3kMasterAnalysis(args) {
return executeBehemothTool('mcp__behemoth__fr3k_master_analysis', args);
}
async function behemothCosmicAnalystSignals(args) {
return executeBehemothTool('mcp__behemoth__cosmic_analyst_signals', args);
}
// System Health
async function behemothSystemHealth(args) {
return executeBehemothToolMCP('system_health', args);
}
// Multi-Agent Coordinator
async function behemothMultiAgentAnalyzer(args) {
// Deploy multiple agents in parallel for comprehensive analysis
const symbol = args.symbol || 'BTCUSDT';
const agents = args.agents || [
'mcp__behemoth__bybit_derivatives_ticker',
'mcp__behemoth__rsi_analysis',
'mcp__behemoth__macd_analysis',
'mcp__behemoth__planetary_analysis',
'mcp__behemoth__quantum_flux'
];
try {
const results = await Promise.all(agents.map((agent) => executeBehemothTool(agent, { symbol })));
const successful = results.filter(r => r.success);
const consensus = successful.length / results.length;
return createToolResponse(true, {
symbol,
total_agents: agents.length,
successful_analyses: successful.length,
consensus_level: consensus,
results: successful.map(r => r.result),
confidence_score: consensus
}, `Multi-agent analysis completed: ${successful.length}/${agents.length} agents successful`, '');
}
catch (error) {
return createToolResponse(false, undefined, '', `Multi-agent analysis failed: ${error}`);
}
}
// Tool Registry: maps tool names to functions
export const TOOL_REGISTRY = {
// Original file operation tools
read_file: readFile,
create_file: createFile,
edit_file: editFile,
delete_file: deleteFile,
list_files: listFiles,
search_files: searchFiles,
execute_command: executeCommand,
create_tasks: createTasks,
update_tasks: updateTasks,
// BEHEMOTH MCP Trading Tools - Exchange Operations
'mcp__behemoth__bybit_derivatives_ticker': behemothBybitTicker,
'mcp__behemoth__bitget_futures_ticker': behemothBitgetTicker,
'mcp__behemoth__bybit_place_order': behemothPlaceOrder,
'mcp__behemoth__bitget_place_order': behemothPlaceOrder,
'mcp__behemoth__bybit_get_positions': behemothGetPositions,
'mcp__behemoth__bitget_get_positions': behemothGetPositions,
// BEHEMOTH Technical Analysis
'mcp__behemoth__rsi_analysis': behemothRsiAnalysis,
'mcp__behemoth__macd_analysis': behemothMacdAnalysis,
'mcp__behemoth__bollinger_bands': behemothBollingerBands,
'mcp__behemoth__moving_averages': behemothMovingAverages,
'mcp__behemoth__support_resistance': behemothSupportResistance,
'mcp__behemoth__fibonacci_retracement': (args) => executeBehemothTool('mcp__behemoth__fibonacci_retracement', args),
'mcp__behemoth__elliott_wave': (args) => executeBehemothTool('mcp__behemoth__elliott_wave', args),
'mcp__behemoth__harmonic_patterns': (args) => executeBehemothTool('mcp__behemoth__harmonic_patterns', args),
'mcp__behemoth__ichimoku_cloud': (args) => executeBehemothTool('mcp__behemoth__ichimoku_cloud', args),
// BEHEMOTH Cosmic Intelligence
'mcp__behemoth__planetary_analysis': behemothCosmicAnalysis,
'mcp__behemoth__lunar_phase_analysis': behemothCosmicAnalysis,
'mcp__behemoth__sacred_geometry': (args) => executeBehemothTool('mcp__behemoth__sacred_geometry', args),
'mcp__behemoth__cosmic_timing': (args) => executeBehemothTool('mcp__behemoth__cosmic_timing', args),
'mcp__behemoth__quantum_flux': behemothQuantumAnalysis,
'mcp__behemoth__quantum_entanglement_analyzer': behemothQuantumAnalysis,
'mcp__behemoth__dimensional_analysis': (args) => executeBehemothTool('mcp__behemoth__dimensional_analysis', args),
// BEHEMOTH AI/ML Models
'mcp__behemoth__lstm_price_predictor': behemothLstmPredictor,
'mcp__behemoth__reinforcement_learning_trader': (args) => executeBehemothTool('mcp__behemoth__reinforcement_learning_trader', args),
'mcp__behemoth__neural_network_optimizer': (args) => executeBehemothTool('mcp__behemoth__neural_network_optimizer', args),
// BEHEMOTH Risk Management
'mcp__behemoth__var_calculator': behemothVarCalculator,
'mcp__behemoth__kelly_criterion_calculator': behemothKellyCriterion,
'mcp__behemoth__position_sizing_optimizer': (args) => executeBehemothTo