/** * Auto Account Machine - 主入口 * 工具注册和管理 */ const fs = require('fs'); const path = require('path'); const logger = require('./shared/logger'); class ToolRegistry { constructor() { this.tools = new Map(); } /** * 注册工具 * @param {Object} tool - 工具对象 */ register(tool) { if (!tool.name || !tool.execute) { throw new Error('Tool must have name and execute method'); } this.tools.set(tool.name, tool); if (tool.alias) { this.tools.set(tool.alias, tool); } } /** * 获取工具 * @param {string} name - 工具名称或别名 * @returns {Object|null} */ get(name) { return this.tools.get(name) || null; } /** * 获取所有工具 * @returns {Array} */ getAll() { const uniqueTools = new Map(); for (const [key, tool] of this.tools) { if (!uniqueTools.has(tool.name)) { uniqueTools.set(tool.name, tool); } } return Array.from(uniqueTools.values()); } /** * 自动发现并注册所有工具 * @param {string} toolsDir - 工具目录路径 */ autoDiscover(toolsDir) { try { const items = fs.readdirSync(toolsDir); items.forEach(item => { const itemPath = path.join(toolsDir, item); const stat = fs.statSync(itemPath); if (stat.isDirectory()) { try { const tool = require(itemPath); this.register(tool); logger.debug('registry', `Registered tool: ${tool.name}`); } catch (error) { logger.warn('registry', `Failed to load tool from ${item}: ${error.message}`); } } }); logger.debug('registry', `Total tools registered: ${this.getAll().length}`); } catch (error) { logger.error('registry', `Failed to discover tools: ${error.message}`); } } } // 创建全局注册表实例 const registry = new ToolRegistry(); // 自动发现工具 const toolsDir = path.join(__dirname, 'tools'); registry.autoDiscover(toolsDir); module.exports = registry;