claude-flow 2.7.26 → 2.7.28

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.
@@ -697,6 +697,9 @@ function showMemoryHelp() {
697
697
  console.log('Options:');
698
698
  console.log(' --namespace <ns> Specify namespace for operations');
699
699
  console.log(' --ns <ns> Short form of --namespace');
700
+ console.log(' --limit <n> Limit number of results (default: 10)');
701
+ console.log(' --sort <field> Sort results by: recent, oldest, key, value');
702
+ console.log(' --format <type> Export format: json, yaml');
700
703
  console.log(' --redact šŸ”’ Enable API key redaction (security feature)');
701
704
  console.log(' --secure Alias for --redact');
702
705
  console.log();
@@ -721,7 +724,9 @@ function showMemoryHelp() {
721
724
  console.log(' # ReasoningBank mode (AI-powered, opt-in)');
722
725
  console.log(' memory init --reasoningbank # One-time setup');
723
726
  console.log(' memory store api_pattern "Always use env vars" --reasoningbank');
724
- console.log(' memory query "API configuration" --reasoningbank # Semantic search!');
727
+ console.log(' memory query "API configuration" --reasoningbank --limit 5 # Semantic search!');
728
+ console.log(' memory list --reasoningbank --sort recent --limit 20');
729
+ console.log(' memory export backup.json --format json --reasoningbank');
725
730
  console.log(' memory status --reasoningbank # Show AI metrics');
726
731
  console.log();
727
732
  console.log(' # Auto-detect mode (smart selection)');
@@ -737,6 +742,16 @@ function showMemoryHelp() {
737
742
  console.log(' • JSON fallback: Always available, fast, simple key-value storage');
738
743
  console.log(' • Initialize ReasoningBank once: "memory init --reasoningbank"');
739
744
  console.log(' • Always use --redact when storing API keys or secrets!');
745
+ console.log();
746
+ console.log('šŸš€ Semantic Search (NEW in v2.7.25):');
747
+ console.log(' NPX Mode: Uses hash-based embeddings (text similarity)');
748
+ console.log(' • Fast, offline, zero dependencies');
749
+ console.log(' • Good for exact/partial text matching');
750
+ console.log(' Local Install: Uses transformer embeddings (semantic AI)');
751
+ console.log(' • Finds conceptually related content');
752
+ console.log(' • 384-dimensional vectors (Xenova/all-MiniLM-L6-v2)');
753
+ console.log(' • Install: npm install -g claude-flow@alpha');
754
+ console.log(' Both modes work perfectly - choose based on your needs!');
740
755
  }
741
756
 
742
757
  //# sourceMappingURL=memory.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/cli/simple-commands/memory.js"],"sourcesContent":["// memory.js - Memory management commands\nimport { printSuccess, printError, printWarning, printInfo } from '../utils.js';\nimport { promises as fs } from 'fs';\nimport { cwd, exit, existsSync } from '../node-compat.js';\nimport { getUnifiedMemory } from '../../memory/unified-memory-manager.js';\nimport { KeyRedactor } from '../../utils/key-redactor.js';\nimport { exec } from 'child_process';\nimport { promisify } from 'util';\n\nconst execAsync = promisify(exec);\n\nexport async function memoryCommand(subArgs, flags) {\n const memorySubcommand = subArgs[0];\n const memoryStore = './memory/memory-store.json';\n\n // Extract namespace from flags or subArgs\n const namespace = flags?.namespace || flags?.ns || getNamespaceFromArgs(subArgs) || 'default';\n\n // Check for redaction flag\n const enableRedaction = flags?.redact || subArgs.includes('--redact') || subArgs.includes('--secure');\n\n // NEW: Detect memory mode (basic, reasoningbank, auto)\n const mode = await detectMemoryMode(flags, subArgs);\n\n // Helper to load memory data\n async function loadMemory() {\n try {\n const content = await fs.readFile(memoryStore, 'utf8');\n return JSON.parse(content);\n } catch {\n return {};\n }\n }\n\n // Helper to save memory data\n async function saveMemory(data) {\n await fs.mkdir('./memory', { recursive: true });\n await fs.writeFile(memoryStore, JSON.stringify(data, null, 2, 'utf8'));\n }\n\n // NEW: Handle ReasoningBank-specific commands\n if (mode === 'reasoningbank' && ['init', 'status', 'consolidate', 'demo', 'test', 'benchmark'].includes(memorySubcommand)) {\n return await handleReasoningBankCommand(memorySubcommand, subArgs, flags);\n }\n\n // NEW: Handle new mode management commands\n if (['detect', 'mode', 'migrate'].includes(memorySubcommand)) {\n return await handleModeCommand(memorySubcommand, subArgs, flags);\n }\n\n // NEW: Delegate to ReasoningBank for regular commands if mode is set\n if (mode === 'reasoningbank' && ['store', 'query', 'list'].includes(memorySubcommand)) {\n return await handleReasoningBankCommand(memorySubcommand, subArgs, flags);\n }\n\n switch (memorySubcommand) {\n case 'store':\n await storeMemory(subArgs, loadMemory, saveMemory, namespace, enableRedaction);\n break;\n\n case 'query':\n await queryMemory(subArgs, loadMemory, namespace, enableRedaction);\n break;\n\n case 'stats':\n await showMemoryStats(loadMemory);\n break;\n\n case 'export':\n await exportMemory(subArgs, loadMemory, namespace);\n break;\n\n case 'import':\n await importMemory(subArgs, saveMemory, loadMemory);\n break;\n\n case 'clear':\n await clearMemory(subArgs, saveMemory, namespace);\n break;\n\n case 'list':\n await listNamespaces(loadMemory);\n break;\n\n default:\n showMemoryHelp();\n }\n}\n\nasync function storeMemory(subArgs, loadMemory, saveMemory, namespace, enableRedaction = false) {\n const key = subArgs[1];\n let value = subArgs.slice(2).join(' ');\n\n if (!key || !value) {\n printError('Usage: memory store <key> <value> [--namespace <ns>] [--redact]');\n return;\n }\n\n try {\n // Apply redaction if enabled\n let redactedValue = value;\n let securityWarnings = [];\n\n if (enableRedaction) {\n redactedValue = KeyRedactor.redact(value, true);\n const validation = KeyRedactor.validate(value);\n\n if (!validation.safe) {\n securityWarnings = validation.warnings;\n printWarning('šŸ”’ Redaction enabled: Sensitive data detected and redacted');\n securityWarnings.forEach(warning => console.log(` āš ļø ${warning}`));\n }\n } else {\n // Even if redaction is not explicitly enabled, validate and warn\n const validation = KeyRedactor.validate(value);\n if (!validation.safe) {\n printWarning('āš ļø Potential sensitive data detected! Use --redact flag for automatic redaction');\n validation.warnings.forEach(warning => console.log(` āš ļø ${warning}`));\n console.log(' šŸ’” Tip: Add --redact flag to automatically redact API keys');\n }\n }\n\n const data = await loadMemory();\n\n if (!data[namespace]) {\n data[namespace] = [];\n }\n\n // Remove existing entry with same key\n data[namespace] = data[namespace].filter((e) => e.key !== key);\n\n // Add new entry with redacted value\n data[namespace].push({\n key,\n value: redactedValue,\n namespace,\n timestamp: Date.now(),\n redacted: enableRedaction && securityWarnings.length > 0,\n });\n\n await saveMemory(data);\n printSuccess(enableRedaction && securityWarnings.length > 0 ? 'šŸ”’ Stored successfully (with redaction)' : 'āœ… Stored successfully');\n console.log(`šŸ“ Key: ${key}`);\n console.log(`šŸ“¦ Namespace: ${namespace}`);\n console.log(`šŸ’¾ Size: ${new TextEncoder().encode(redactedValue).length} bytes`);\n if (enableRedaction && securityWarnings.length > 0) {\n console.log(`šŸ”’ Security: ${securityWarnings.length} sensitive pattern(s) redacted`);\n }\n } catch (err) {\n printError(`Failed to store: ${err.message}`);\n }\n}\n\nasync function queryMemory(subArgs, loadMemory, namespace, enableRedaction = false) {\n const search = subArgs.slice(1).join(' ');\n\n if (!search) {\n printError('Usage: memory query <search> [--namespace <ns>] [--redact]');\n return;\n }\n\n try {\n const data = await loadMemory();\n const results = [];\n\n for (const [ns, entries] of Object.entries(data)) {\n if (namespace && ns !== namespace) continue;\n\n for (const entry of entries) {\n if (entry.key.includes(search) || entry.value.includes(search)) {\n results.push(entry);\n }\n }\n }\n\n if (results.length === 0) {\n printWarning('No results found');\n return;\n }\n\n printSuccess(`Found ${results.length} results:`);\n\n // Sort by timestamp (newest first)\n results.sort((a, b) => b.timestamp - a.timestamp);\n\n for (const entry of results.slice(0, 10)) {\n console.log(`\\nšŸ“Œ ${entry.key}`);\n console.log(` Namespace: ${entry.namespace}`);\n\n // Apply redaction to displayed value if requested\n let displayValue = entry.value;\n if (enableRedaction) {\n displayValue = KeyRedactor.redact(displayValue, true);\n }\n\n console.log(\n ` Value: ${displayValue.substring(0, 100)}${displayValue.length > 100 ? '...' : ''}`,\n );\n console.log(` Stored: ${new Date(entry.timestamp).toLocaleString()}`);\n\n // Show redaction status\n if (entry.redacted) {\n console.log(` šŸ”’ Status: Redacted on storage`);\n } else if (enableRedaction) {\n console.log(` šŸ”’ Status: Redacted for display`);\n }\n }\n\n if (results.length > 10) {\n console.log(`\\n... and ${results.length - 10} more results`);\n }\n } catch (err) {\n printError(`Failed to query: ${err.message}`);\n }\n}\n\nasync function showMemoryStats(loadMemory) {\n try {\n const data = await loadMemory();\n let totalEntries = 0;\n const namespaceStats = {};\n\n for (const [namespace, entries] of Object.entries(data)) {\n namespaceStats[namespace] = entries.length;\n totalEntries += entries.length;\n }\n\n printSuccess('Memory Bank Statistics:');\n console.log(` Total Entries: ${totalEntries}`);\n console.log(` Namespaces: ${Object.keys(data).length}`);\n console.log(\n ` Size: ${(new TextEncoder().encode(JSON.stringify(data)).length / 1024).toFixed(2)} KB`,\n );\n\n if (Object.keys(data).length > 0) {\n console.log('\\nšŸ“ Namespace Breakdown:');\n for (const [namespace, count] of Object.entries(namespaceStats)) {\n console.log(` ${namespace}: ${count} entries`);\n }\n }\n } catch (err) {\n printError(`Failed to get stats: ${err.message}`);\n }\n}\n\nasync function exportMemory(subArgs, loadMemory, namespace) {\n const filename = subArgs[1] || `memory-export-${Date.now()}.json`;\n\n try {\n const data = await loadMemory();\n\n let exportData = data;\n if (namespace) {\n exportData = { [namespace]: data[namespace] || [] };\n }\n\n await fs.writeFile(filename, JSON.stringify(exportData, null, 2, 'utf8'));\n printSuccess(`Memory exported to ${filename}`);\n\n let totalEntries = 0;\n for (const entries of Object.values(exportData)) {\n totalEntries += entries.length;\n }\n console.log(\n `šŸ“¦ Exported ${totalEntries} entries from ${Object.keys(exportData).length} namespace(s)`,\n );\n } catch (err) {\n printError(`Failed to export memory: ${err.message}`);\n }\n}\n\nasync function importMemory(subArgs, saveMemory, loadMemory) {\n const filename = subArgs[1];\n\n if (!filename) {\n printError('Usage: memory import <filename>');\n return;\n }\n\n try {\n const importContent = await fs.readFile(filename, 'utf8');\n const importData = JSON.parse(importContent);\n\n // Load existing memory\n const existingData = await loadMemory();\n\n // Merge imported data\n let totalImported = 0;\n for (const [namespace, entries] of Object.entries(importData)) {\n if (!existingData[namespace]) {\n existingData[namespace] = [];\n }\n\n // Add entries that don't already exist (by key)\n const existingKeys = new Set(existingData[namespace].map((e) => e.key));\n const newEntries = entries.filter((e) => !existingKeys.has(e.key));\n\n existingData[namespace].push(...newEntries);\n totalImported += newEntries.length;\n }\n\n await saveMemory(existingData);\n printSuccess(`Imported ${totalImported} new entries from ${filename}`);\n } catch (err) {\n printError(`Failed to import memory: ${err.message}`);\n }\n}\n\nasync function clearMemory(subArgs, saveMemory, namespace) {\n if (!namespace || namespace === 'default') {\n const nsFromArgs = getNamespaceFromArgs(subArgs);\n if (!nsFromArgs) {\n printError('Usage: memory clear --namespace <namespace>');\n printWarning('This will clear all entries in the specified namespace');\n return;\n }\n namespace = nsFromArgs;\n }\n\n try {\n // Helper to load memory data\n async function loadMemory() {\n try {\n const content = await fs.readFile('./memory/memory-store.json', 'utf8');\n return JSON.parse(content);\n } catch {\n return {};\n }\n }\n \n const data = await loadMemory();\n\n if (!data[namespace]) {\n printWarning(`Namespace '${namespace}' does not exist`);\n return;\n }\n\n const entryCount = data[namespace].length;\n delete data[namespace];\n\n await saveMemory(data);\n printSuccess(`Cleared ${entryCount} entries from namespace '${namespace}'`);\n } catch (err) {\n printError(`Failed to clear memory: ${err.message}`);\n }\n}\n\nasync function listNamespaces(loadMemory) {\n try {\n const data = await loadMemory();\n const namespaces = Object.keys(data);\n\n if (namespaces.length === 0) {\n printWarning('No namespaces found');\n return;\n }\n\n printSuccess('Available namespaces:');\n for (const namespace of namespaces) {\n const count = data[namespace].length;\n console.log(` ${namespace} (${count} entries)`);\n }\n } catch (err) {\n printError(`Failed to list namespaces: ${err.message}`);\n }\n}\n\nfunction getNamespaceFromArgs(subArgs) {\n const namespaceIndex = subArgs.indexOf('--namespace');\n if (namespaceIndex !== -1 && namespaceIndex + 1 < subArgs.length) {\n return subArgs[namespaceIndex + 1];\n }\n\n const nsIndex = subArgs.indexOf('--ns');\n if (nsIndex !== -1 && nsIndex + 1 < subArgs.length) {\n return subArgs[nsIndex + 1];\n }\n\n return null;\n}\n\n// Helper to load memory data (needed for import function)\nasync function loadMemory() {\n try {\n const content = await fs.readFile('./memory/memory-store.json', 'utf8');\n return JSON.parse(content);\n } catch {\n return {};\n }\n}\n\n// NEW: Mode detection function\nasync function detectMemoryMode(flags, subArgs) {\n // Explicit ReasoningBank flag takes precedence\n if (flags?.reasoningbank || flags?.rb || subArgs.includes('--reasoningbank') || subArgs.includes('--rb')) {\n return 'reasoningbank';\n }\n\n // Auto mode: detect if ReasoningBank is initialized\n if (flags?.auto || subArgs.includes('--auto')) {\n const initialized = await isReasoningBankInitialized();\n return initialized ? 'reasoningbank' : 'basic';\n }\n\n // Explicit basic mode flag\n if (flags?.basic || subArgs.includes('--basic')) {\n return 'basic';\n }\n\n // Default: AUTO MODE with SQLite preference\n // Try to use ReasoningBank (SQLite) by default, initialize if needed\n const initialized = await isReasoningBankInitialized();\n\n if (initialized) {\n return 'reasoningbank';\n }\n\n // Not initialized yet - try to auto-initialize on first use\n try {\n const { initializeReasoningBank } = await import('../../reasoningbank/reasoningbank-adapter.js');\n const initialized = await initializeReasoningBank();\n\n // Check if initialization succeeded (returns true) or failed (returns false)\n if (!initialized) {\n // Initialization failed but didn't throw - fall back to JSON\n const isNpx = process.env.npm_config_user_agent?.includes('npx') ||\n process.cwd().includes('_npx');\n if (isNpx) {\n console.log('\\nāœ… Automatically using JSON fallback for this command\\n');\n } else {\n printWarning(`āš ļø SQLite unavailable, using JSON fallback`);\n }\n return 'basic';\n }\n\n printInfo('šŸ—„ļø Initialized SQLite backend (.swarm/memory.db)');\n return 'reasoningbank';\n } catch (error) {\n // SQLite initialization failed - fall back to JSON\n const isSqliteError = error.message?.includes('BetterSqlite3') ||\n error.message?.includes('better-sqlite3') ||\n error.message?.includes('could not run migrations') ||\n error.message?.includes('ReasoningBank initialization failed');\n const isNpx = process.env.npm_config_user_agent?.includes('npx') ||\n process.cwd().includes('_npx');\n\n if (isSqliteError && isNpx) {\n // Silent fallback for npx - error already shown by adapter\n console.log('\\nāœ… Automatically using JSON fallback for this command\\n');\n return 'basic';\n } else {\n printWarning(`āš ļø SQLite unavailable, using JSON fallback`);\n printWarning(` Reason: ${error.message}`);\n return 'basic';\n }\n }\n}\n\n// NEW: Check if ReasoningBank is initialized\nasync function isReasoningBankInitialized() {\n try {\n // Check if .swarm/memory.db exists\n const dbPath = '.swarm/memory.db';\n await fs.access(dbPath);\n return true;\n } catch {\n return false;\n }\n}\n\n// NEW: Handle ReasoningBank commands\nasync function handleReasoningBankCommand(command, subArgs, flags) {\n const initialized = await isReasoningBankInitialized();\n\n // Lazy load the adapter (ES modules)\n const { initializeReasoningBank, storeMemory, queryMemories, listMemories, getStatus, checkReasoningBankTables, migrateReasoningBank, cleanup } = await import('../../reasoningbank/reasoningbank-adapter.js');\n\n // Special handling for 'init' command\n if (command === 'init') {\n const dbPath = '.swarm/memory.db';\n\n if (initialized) {\n // Database exists - check if migration is needed\n printInfo('šŸ” Checking existing database for ReasoningBank schema...\\n');\n\n try {\n // Set the database path for ReasoningBank\n process.env.CLAUDE_FLOW_DB_PATH = dbPath;\n\n const tableCheck = await checkReasoningBankTables();\n\n if (tableCheck.exists) {\n printSuccess('āœ… ReasoningBank already complete');\n console.log('Database: .swarm/memory.db');\n console.log('All ReasoningBank tables present\\n');\n console.log('Use --reasoningbank flag with memory commands to enable AI features');\n return;\n }\n\n // Missing tables found - run migration\n console.log(`šŸ”„ Migrating database: ${tableCheck.missingTables.length} tables missing`);\n console.log(` Missing: ${tableCheck.missingTables.join(', ')}\\n`);\n\n const migrationResult = await migrateReasoningBank();\n\n if (migrationResult.success) {\n printSuccess(`āœ“ Migration complete: added ${migrationResult.addedTables?.length || 0} tables`);\n console.log('\\nNext steps:');\n console.log(' 1. Store memories: memory store key \"value\" --reasoningbank');\n console.log(' 2. Query memories: memory query \"search\" --reasoningbank');\n console.log(' 3. Check status: memory status --reasoningbank');\n } else {\n printError(`āŒ Migration failed: ${migrationResult.message}`);\n console.log('Try running: init --force to reinitialize');\n }\n } catch (error) {\n printError('āŒ Migration check failed');\n console.error(error.message);\n console.log('\\nTry running: init --force to reinitialize');\n } finally {\n // Cleanup after migration check\n cleanup();\n // Force exit to prevent hanging from embedding cache timers\n setTimeout(() => process.exit(0), 100);\n }\n return;\n }\n\n // Fresh initialization\n printInfo('🧠 Initializing ReasoningBank...');\n console.log('This will create: .swarm/memory.db\\n');\n\n try {\n await initializeReasoningBank();\n printSuccess('āœ… ReasoningBank initialized successfully!');\n console.log('\\nNext steps:');\n console.log(' 1. Store memories: memory store key \"value\" --reasoningbank');\n console.log(' 2. Query memories: memory query \"search\" --reasoningbank');\n console.log(' 3. Check status: memory status --reasoningbank');\n } catch (error) {\n printError('āŒ Failed to initialize ReasoningBank');\n console.error(error.message);\n } finally {\n // Cleanup after init\n cleanup();\n // Force exit to prevent hanging from embedding cache timers\n setTimeout(() => process.exit(0), 100);\n }\n return;\n }\n\n // All other commands require initialization\n if (!initialized) {\n printError('āŒ ReasoningBank not initialized');\n console.log('\\nTo use ReasoningBank mode, first run:');\n console.log(' memory init --reasoningbank\\n');\n return;\n }\n\n printInfo(`🧠 Using ReasoningBank mode...`);\n\n try {\n // Handle different commands\n switch (command) {\n case 'store':\n await handleReasoningBankStore(subArgs, flags, storeMemory);\n break;\n\n case 'query':\n await handleReasoningBankQuery(subArgs, flags, queryMemories);\n break;\n\n case 'list':\n await handleReasoningBankList(subArgs, flags, listMemories);\n break;\n\n case 'status':\n await handleReasoningBankStatus(getStatus);\n break;\n\n case 'consolidate':\n case 'demo':\n case 'test':\n case 'benchmark':\n // These still use CLI commands\n const cmd = `npx agentic-flow reasoningbank ${command}`;\n const { stdout } = await execAsync(cmd, { timeout: 60000 });\n if (stdout) console.log(stdout);\n break;\n\n default:\n printError(`Unknown ReasoningBank command: ${command}`);\n }\n } catch (error) {\n printError(`āŒ ReasoningBank command failed`);\n console.error(error.message);\n } finally {\n // Always cleanup database connection\n cleanup();\n\n // Force process exit after cleanup (embedding cache timers prevent natural exit)\n // This is necessary because agentic-flow's embedding cache uses setTimeout\n // which keeps the event loop alive\n setTimeout(() => {\n process.exit(0);\n }, 100);\n }\n}\n\n// NEW: Handle ReasoningBank store\nasync function handleReasoningBankStore(subArgs, flags, storeMemory) {\n const key = subArgs[1];\n const value = subArgs.slice(2).join(' ');\n\n if (!key || !value) {\n printError('Usage: memory store <key> <value> --reasoningbank');\n return;\n }\n\n try {\n const namespace = flags?.namespace || flags?.ns || getArgValue(subArgs, '--namespace') || 'default';\n\n const memoryId = await storeMemory(key, value, {\n namespace,\n agent: 'memory-agent',\n domain: namespace,\n });\n\n printSuccess('āœ… Stored successfully in ReasoningBank');\n console.log(`šŸ“ Key: ${key}`);\n console.log(`🧠 Memory ID: ${memoryId}`);\n console.log(`šŸ“¦ Namespace: ${namespace}`);\n console.log(`šŸ’¾ Size: ${new TextEncoder().encode(value).length} bytes`);\n console.log(`šŸ” Semantic search: enabled`);\n } catch (error) {\n printError(`Failed to store: ${error.message}`);\n }\n}\n\n// NEW: Handle ReasoningBank query\nasync function handleReasoningBankQuery(subArgs, flags, queryMemories) {\n const search = subArgs.slice(1).join(' ');\n\n if (!search) {\n printError('Usage: memory query <search> --reasoningbank');\n return;\n }\n\n try {\n const namespace = flags?.namespace || flags?.ns || getArgValue(subArgs, '--namespace');\n const results = await queryMemories(search, {\n domain: namespace || 'general',\n limit: 10,\n });\n\n if (results.length === 0) {\n printWarning('No results found');\n return;\n }\n\n printSuccess(`Found ${results.length} results (semantic search):`);\n\n for (const entry of results) {\n console.log(`\\nšŸ“Œ ${entry.key}`);\n console.log(` Namespace: ${entry.namespace}`);\n console.log(` Value: ${entry.value.substring(0, 100)}${entry.value.length > 100 ? '...' : ''}`);\n console.log(` Confidence: ${(entry.confidence * 100).toFixed(1)}%`);\n console.log(` Usage: ${entry.usage_count} times`);\n if (entry.score) {\n console.log(` Match Score: ${(entry.score * 100).toFixed(1)}%`);\n }\n console.log(` Stored: ${new Date(entry.created_at).toLocaleString()}`);\n }\n } catch (error) {\n printError(`Failed to query: ${error.message}`);\n }\n}\n\n// NEW: Handle ReasoningBank list\nasync function handleReasoningBankList(subArgs, flags, listMemories) {\n try {\n const sort = flags?.sort || getArgValue(subArgs, '--sort') || 'created_at';\n const limit = parseInt(flags?.limit || getArgValue(subArgs, '--limit') || '10');\n\n const results = await listMemories({ sort, limit });\n\n if (results.length === 0) {\n printWarning('No memories found');\n return;\n }\n\n printSuccess(`ReasoningBank memories (${results.length} shown):`);\n\n for (const entry of results) {\n console.log(`\\nšŸ“Œ ${entry.key}`);\n console.log(` Value: ${entry.value.substring(0, 80)}${entry.value.length > 80 ? '...' : ''}`);\n console.log(` Confidence: ${(entry.confidence * 100).toFixed(1)}% | Usage: ${entry.usage_count}`);\n }\n } catch (error) {\n printError(`Failed to list: ${error.message}`);\n }\n}\n\n// NEW: Handle ReasoningBank status\nasync function handleReasoningBankStatus(getStatus) {\n try {\n const stats = await getStatus();\n\n printSuccess('šŸ“Š ReasoningBank Status:');\n console.log(` Total memories: ${stats.total_memories}`);\n console.log(` Average confidence: ${(stats.avg_confidence * 100).toFixed(1)}%`);\n console.log(` Total usage: ${stats.total_usage}`);\n console.log(` Embeddings: ${stats.total_embeddings}`);\n console.log(` Trajectories: ${stats.total_trajectories}`);\n } catch (error) {\n printError(`Failed to get status: ${error.message}`);\n }\n}\n\n// NEW: Build agentic-flow reasoningbank command\nfunction buildReasoningBankCommand(command, subArgs, flags) {\n const parts = ['npx', 'agentic-flow', 'reasoningbank'];\n\n // Map memory commands to reasoningbank commands\n const commandMap = {\n store: 'store',\n query: 'query',\n list: 'list',\n status: 'status',\n consolidate: 'consolidate',\n demo: 'demo',\n test: 'test',\n benchmark: 'benchmark',\n };\n\n parts.push(commandMap[command] || command);\n\n // Add arguments (skip the command itself)\n const args = subArgs.slice(1);\n args.forEach((arg) => {\n if (!arg.startsWith('--reasoningbank') && !arg.startsWith('--rb') && !arg.startsWith('--auto')) {\n parts.push(`\"${arg}\"`);\n }\n });\n\n // Add required --agent parameter\n parts.push('--agent', 'memory-agent');\n\n return parts.join(' ');\n}\n\n// NEW: Handle mode management commands\nasync function handleModeCommand(command, subArgs, flags) {\n switch (command) {\n case 'detect':\n await detectModes();\n break;\n\n case 'mode':\n await showCurrentMode();\n break;\n\n case 'migrate':\n await migrateMemory(subArgs, flags);\n break;\n\n default:\n printError(`Unknown mode command: ${command}`);\n }\n}\n\n// NEW: Detect and show available memory modes\nasync function detectModes() {\n printInfo('šŸ” Detecting memory modes...\\n');\n\n // Check basic mode\n const basicAvailable = await checkBasicMode();\n console.log(basicAvailable ? 'āœ… Basic Mode (active)' : 'āŒ Basic Mode (unavailable)');\n if (basicAvailable) {\n console.log(' Location: ./memory/memory-store.json');\n console.log(' Features: Simple key-value storage, fast');\n }\n\n console.log('');\n\n // Check ReasoningBank mode\n const rbAvailable = await isReasoningBankInitialized();\n console.log(rbAvailable ? 'āœ… ReasoningBank Mode (available)' : 'āš ļø ReasoningBank Mode (not initialized)');\n if (rbAvailable) {\n console.log(' Location: .swarm/memory.db');\n console.log(' Features: AI-powered semantic search, learning');\n } else {\n console.log(' To enable: memory init --reasoningbank');\n }\n\n console.log('\\nšŸ’” Usage:');\n console.log(' Basic: memory store key \"value\"');\n console.log(' ReasoningBank: memory store key \"value\" --reasoningbank');\n console.log(' Auto-detect: memory query search --auto');\n}\n\n// NEW: Check if basic mode is available\nasync function checkBasicMode() {\n try {\n const memoryDir = './memory';\n await fs.access(memoryDir);\n return true;\n } catch {\n // Create directory if it doesn't exist\n try {\n await fs.mkdir(memoryDir, { recursive: true });\n return true;\n } catch {\n return false;\n }\n }\n}\n\n// NEW: Show current default mode\nasync function showCurrentMode() {\n const rbInitialized = await isReasoningBankInitialized();\n\n printInfo('šŸ“Š Current Memory Configuration:\\n');\n console.log('Default Mode: AUTO (smart selection with JSON fallback)');\n console.log('Available Modes:');\n console.log(' • Basic Mode: Always available (JSON storage)');\n console.log(` • ReasoningBank Mode: ${rbInitialized ? 'Initialized āœ… (will be used by default)' : 'Not initialized āš ļø (JSON fallback active)'}`);\n\n console.log('\\nšŸ’” Mode Behavior:');\n console.log(' (no flag) → AUTO: Use ReasoningBank if initialized, else JSON');\n console.log(' --reasoningbank or --rb → Force ReasoningBank mode');\n console.log(' --basic → Force JSON mode');\n console.log(' --auto → Same as default (explicit)');\n}\n\n// NEW: Migrate memory between modes\nasync function migrateMemory(subArgs, flags) {\n const targetMode = flags?.to || getArgValue(subArgs, '--to');\n\n if (!targetMode || !['basic', 'reasoningbank'].includes(targetMode)) {\n printError('Usage: memory migrate --to <basic|reasoningbank>');\n return;\n }\n\n printInfo(`šŸ”„ Migrating to ${targetMode} mode...\\n`);\n\n if (targetMode === 'reasoningbank') {\n // Migrate basic → ReasoningBank\n const rbInitialized = await isReasoningBankInitialized();\n if (!rbInitialized) {\n printError('āŒ ReasoningBank not initialized');\n console.log('First run: memory init --reasoningbank\\n');\n return;\n }\n\n printWarning('āš ļø Migration from basic to ReasoningBank is not yet implemented');\n console.log('This feature is coming in v2.7.1\\n');\n console.log('For now, you can:');\n console.log(' 1. Export basic memory: memory export backup.json');\n console.log(' 2. Manually import to ReasoningBank');\n } else {\n // Migrate ReasoningBank → basic\n printWarning('āš ļø Migration from ReasoningBank to basic is not yet implemented');\n console.log('This feature is coming in v2.7.1\\n');\n }\n}\n\n// Helper to get argument value\nfunction getArgValue(args, flag) {\n const index = args.indexOf(flag);\n if (index !== -1 && index + 1 < args.length) {\n return args[index + 1];\n }\n return null;\n}\n\nfunction showMemoryHelp() {\n console.log('Memory commands:');\n console.log(' store <key> <value> Store a key-value pair');\n console.log(' query <search> Search for entries');\n console.log(' stats Show memory statistics');\n console.log(' export [filename] Export memory to file');\n console.log(' import <filename> Import memory from file');\n console.log(' clear --namespace <ns> Clear a namespace');\n console.log(' list List all namespaces');\n console.log();\n console.log('🧠 ReasoningBank Commands (NEW in v2.7.0):');\n console.log(' init --reasoningbank Initialize ReasoningBank (AI-powered memory)');\n console.log(' status --reasoningbank Show ReasoningBank statistics');\n console.log(' detect Show available memory modes');\n console.log(' mode Show current memory configuration');\n console.log(' migrate --to <mode> Migrate between basic/reasoningbank');\n console.log();\n console.log('Options:');\n console.log(' --namespace <ns> Specify namespace for operations');\n console.log(' --ns <ns> Short form of --namespace');\n console.log(' --redact šŸ”’ Enable API key redaction (security feature)');\n console.log(' --secure Alias for --redact');\n console.log();\n console.log('šŸŽÆ Mode Selection:');\n console.log(' (no flag) AUTO MODE (default) - Uses ReasoningBank if initialized, else JSON fallback');\n console.log(' --reasoningbank, --rb Force ReasoningBank mode (AI-powered)');\n console.log(' --basic Force Basic mode (JSON storage)');\n console.log(' --auto Explicit auto-detect (same as default)');\n console.log();\n console.log('šŸ”’ Security Features (v2.6.0):');\n console.log(' API Key Protection: Automatically detects and redacts sensitive data');\n console.log(' Patterns Detected: Anthropic, OpenRouter, Gemini, Bearer tokens, etc.');\n console.log(' Auto-Validation: Warns when storing unredacted sensitive data');\n console.log(' Display Redaction: Redact sensitive data when querying with --redact');\n console.log();\n console.log('Examples:');\n console.log(' # Basic mode (default - backward compatible)');\n console.log(' memory store previous_work \"Research findings from yesterday\"');\n console.log(' memory store api_config \"key=sk-ant-...\" --redact # šŸ”’ Redacts API key');\n console.log(' memory query research --namespace sparc');\n console.log();\n console.log(' # ReasoningBank mode (AI-powered, opt-in)');\n console.log(' memory init --reasoningbank # One-time setup');\n console.log(' memory store api_pattern \"Always use env vars\" --reasoningbank');\n console.log(' memory query \"API configuration\" --reasoningbank # Semantic search!');\n console.log(' memory status --reasoningbank # Show AI metrics');\n console.log();\n console.log(' # Auto-detect mode (smart selection)');\n console.log(' memory query config --auto # Uses ReasoningBank if available');\n console.log();\n console.log(' # Mode management');\n console.log(' memory detect # Show available modes');\n console.log(' memory mode # Show current configuration');\n console.log();\n console.log('šŸ’” Tips:');\n console.log(' • AUTO MODE (default): Automatically uses best available storage');\n console.log(' • ReasoningBank: AI-powered semantic search (learns from patterns)');\n console.log(' • JSON fallback: Always available, fast, simple key-value storage');\n console.log(' • Initialize ReasoningBank once: \"memory init --reasoningbank\"');\n console.log(' • Always use --redact when storing API keys or secrets!');\n}\n"],"names":["printSuccess","printError","printWarning","printInfo","promises","fs","KeyRedactor","exec","promisify","execAsync","memoryCommand","subArgs","flags","memorySubcommand","memoryStore","namespace","ns","getNamespaceFromArgs","enableRedaction","redact","includes","mode","detectMemoryMode","loadMemory","content","readFile","JSON","parse","saveMemory","data","mkdir","recursive","writeFile","stringify","handleReasoningBankCommand","handleModeCommand","storeMemory","queryMemory","showMemoryStats","exportMemory","importMemory","clearMemory","listNamespaces","showMemoryHelp","key","value","slice","join","redactedValue","securityWarnings","validation","validate","safe","warnings","forEach","warning","console","log","filter","e","push","timestamp","Date","now","redacted","length","TextEncoder","encode","err","message","search","results","entries","Object","entry","sort","a","b","displayValue","substring","toLocaleString","totalEntries","namespaceStats","keys","toFixed","count","filename","exportData","values","importContent","importData","existingData","totalImported","existingKeys","Set","map","newEntries","has","nsFromArgs","entryCount","namespaces","namespaceIndex","indexOf","nsIndex","reasoningbank","rb","auto","initialized","isReasoningBankInitialized","basic","initializeReasoningBank","isNpx","process","env","npm_config_user_agent","cwd","error","isSqliteError","dbPath","access","command","queryMemories","listMemories","getStatus","checkReasoningBankTables","migrateReasoningBank","cleanup","CLAUDE_FLOW_DB_PATH","tableCheck","exists","missingTables","migrationResult","success","addedTables","setTimeout","exit","handleReasoningBankStore","handleReasoningBankQuery","handleReasoningBankList","handleReasoningBankStatus","cmd","stdout","timeout","getArgValue","memoryId","agent","domain","limit","confidence","usage_count","score","created_at","parseInt","stats","total_memories","avg_confidence","total_usage","total_embeddings","total_trajectories","buildReasoningBankCommand","parts","commandMap","store","query","list","status","consolidate","demo","test","benchmark","args","arg","startsWith","detectModes","showCurrentMode","migrateMemory","basicAvailable","checkBasicMode","rbAvailable","memoryDir","rbInitialized","targetMode","to","flag","index"],"mappings":"AACA,SAASA,YAAY,EAAEC,UAAU,EAAEC,YAAY,EAAEC,SAAS,QAAQ,cAAc;AAChF,SAASC,YAAYC,EAAE,QAAQ,KAAK;AAGpC,SAASC,WAAW,QAAQ,8BAA8B;AAC1D,SAASC,IAAI,QAAQ,gBAAgB;AACrC,SAASC,SAAS,QAAQ,OAA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GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG;IACXD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;AACd"}
1
+ {"version":3,"sources":["../../../../src/cli/simple-commands/memory.js"],"sourcesContent":["// memory.js - Memory management commands\nimport { printSuccess, printError, printWarning, printInfo } from '../utils.js';\nimport { promises as fs } from 'fs';\nimport { cwd, exit, existsSync } from '../node-compat.js';\nimport { getUnifiedMemory } from '../../memory/unified-memory-manager.js';\nimport { KeyRedactor } from '../../utils/key-redactor.js';\nimport { exec } from 'child_process';\nimport { promisify } from 'util';\n\nconst execAsync = promisify(exec);\n\nexport async function memoryCommand(subArgs, flags) {\n const memorySubcommand = subArgs[0];\n const memoryStore = './memory/memory-store.json';\n\n // Extract namespace from flags or subArgs\n const namespace = flags?.namespace || flags?.ns || getNamespaceFromArgs(subArgs) || 'default';\n\n // Check for redaction flag\n const enableRedaction = flags?.redact || subArgs.includes('--redact') || subArgs.includes('--secure');\n\n // NEW: Detect memory mode (basic, reasoningbank, auto)\n const mode = await detectMemoryMode(flags, subArgs);\n\n // Helper to load memory data\n async function loadMemory() {\n try {\n const content = await fs.readFile(memoryStore, 'utf8');\n return JSON.parse(content);\n } catch {\n return {};\n }\n }\n\n // Helper to save memory data\n async function saveMemory(data) {\n await fs.mkdir('./memory', { recursive: true });\n await fs.writeFile(memoryStore, JSON.stringify(data, null, 2, 'utf8'));\n }\n\n // NEW: Handle ReasoningBank-specific commands\n if (mode === 'reasoningbank' && ['init', 'status', 'consolidate', 'demo', 'test', 'benchmark'].includes(memorySubcommand)) {\n return await handleReasoningBankCommand(memorySubcommand, subArgs, flags);\n }\n\n // NEW: Handle new mode management commands\n if (['detect', 'mode', 'migrate'].includes(memorySubcommand)) {\n return await handleModeCommand(memorySubcommand, subArgs, flags);\n }\n\n // NEW: Delegate to ReasoningBank for regular commands if mode is set\n if (mode === 'reasoningbank' && ['store', 'query', 'list'].includes(memorySubcommand)) {\n return await handleReasoningBankCommand(memorySubcommand, subArgs, flags);\n }\n\n switch (memorySubcommand) {\n case 'store':\n await storeMemory(subArgs, loadMemory, saveMemory, namespace, enableRedaction);\n break;\n\n case 'query':\n await queryMemory(subArgs, loadMemory, namespace, enableRedaction);\n break;\n\n case 'stats':\n await showMemoryStats(loadMemory);\n break;\n\n case 'export':\n await exportMemory(subArgs, loadMemory, namespace);\n break;\n\n case 'import':\n await importMemory(subArgs, saveMemory, loadMemory);\n break;\n\n case 'clear':\n await clearMemory(subArgs, saveMemory, namespace);\n break;\n\n case 'list':\n await listNamespaces(loadMemory);\n break;\n\n default:\n showMemoryHelp();\n }\n}\n\nasync function storeMemory(subArgs, loadMemory, saveMemory, namespace, enableRedaction = false) {\n const key = subArgs[1];\n let value = subArgs.slice(2).join(' ');\n\n if (!key || !value) {\n printError('Usage: memory store <key> <value> [--namespace <ns>] [--redact]');\n return;\n }\n\n try {\n // Apply redaction if enabled\n let redactedValue = value;\n let securityWarnings = [];\n\n if (enableRedaction) {\n redactedValue = KeyRedactor.redact(value, true);\n const validation = KeyRedactor.validate(value);\n\n if (!validation.safe) {\n securityWarnings = validation.warnings;\n printWarning('šŸ”’ Redaction enabled: Sensitive data detected and redacted');\n securityWarnings.forEach(warning => console.log(` āš ļø ${warning}`));\n }\n } else {\n // Even if redaction is not explicitly enabled, validate and warn\n const validation = KeyRedactor.validate(value);\n if (!validation.safe) {\n printWarning('āš ļø Potential sensitive data detected! Use --redact flag for automatic redaction');\n validation.warnings.forEach(warning => console.log(` āš ļø ${warning}`));\n console.log(' šŸ’” Tip: Add --redact flag to automatically redact API keys');\n }\n }\n\n const data = await loadMemory();\n\n if (!data[namespace]) {\n data[namespace] = [];\n }\n\n // Remove existing entry with same key\n data[namespace] = data[namespace].filter((e) => e.key !== key);\n\n // Add new entry with redacted value\n data[namespace].push({\n key,\n value: redactedValue,\n namespace,\n timestamp: Date.now(),\n redacted: enableRedaction && securityWarnings.length > 0,\n });\n\n await saveMemory(data);\n printSuccess(enableRedaction && securityWarnings.length > 0 ? 'šŸ”’ Stored successfully (with redaction)' : 'āœ… Stored successfully');\n console.log(`šŸ“ Key: ${key}`);\n console.log(`šŸ“¦ Namespace: ${namespace}`);\n console.log(`šŸ’¾ Size: ${new TextEncoder().encode(redactedValue).length} bytes`);\n if (enableRedaction && securityWarnings.length > 0) {\n console.log(`šŸ”’ Security: ${securityWarnings.length} sensitive pattern(s) redacted`);\n }\n } catch (err) {\n printError(`Failed to store: ${err.message}`);\n }\n}\n\nasync function queryMemory(subArgs, loadMemory, namespace, enableRedaction = false) {\n const search = subArgs.slice(1).join(' ');\n\n if (!search) {\n printError('Usage: memory query <search> [--namespace <ns>] [--redact]');\n return;\n }\n\n try {\n const data = await loadMemory();\n const results = [];\n\n for (const [ns, entries] of Object.entries(data)) {\n if (namespace && ns !== namespace) continue;\n\n for (const entry of entries) {\n if (entry.key.includes(search) || entry.value.includes(search)) {\n results.push(entry);\n }\n }\n }\n\n if (results.length === 0) {\n printWarning('No results found');\n return;\n }\n\n printSuccess(`Found ${results.length} results:`);\n\n // Sort by timestamp (newest first)\n results.sort((a, b) => b.timestamp - a.timestamp);\n\n for (const entry of results.slice(0, 10)) {\n console.log(`\\nšŸ“Œ ${entry.key}`);\n console.log(` Namespace: ${entry.namespace}`);\n\n // Apply redaction to displayed value if requested\n let displayValue = entry.value;\n if (enableRedaction) {\n displayValue = KeyRedactor.redact(displayValue, true);\n }\n\n console.log(\n ` Value: ${displayValue.substring(0, 100)}${displayValue.length > 100 ? '...' : ''}`,\n );\n console.log(` Stored: ${new Date(entry.timestamp).toLocaleString()}`);\n\n // Show redaction status\n if (entry.redacted) {\n console.log(` šŸ”’ Status: Redacted on storage`);\n } else if (enableRedaction) {\n console.log(` šŸ”’ Status: Redacted for display`);\n }\n }\n\n if (results.length > 10) {\n console.log(`\\n... and ${results.length - 10} more results`);\n }\n } catch (err) {\n printError(`Failed to query: ${err.message}`);\n }\n}\n\nasync function showMemoryStats(loadMemory) {\n try {\n const data = await loadMemory();\n let totalEntries = 0;\n const namespaceStats = {};\n\n for (const [namespace, entries] of Object.entries(data)) {\n namespaceStats[namespace] = entries.length;\n totalEntries += entries.length;\n }\n\n printSuccess('Memory Bank Statistics:');\n console.log(` Total Entries: ${totalEntries}`);\n console.log(` Namespaces: ${Object.keys(data).length}`);\n console.log(\n ` Size: ${(new TextEncoder().encode(JSON.stringify(data)).length / 1024).toFixed(2)} KB`,\n );\n\n if (Object.keys(data).length > 0) {\n console.log('\\nšŸ“ Namespace Breakdown:');\n for (const [namespace, count] of Object.entries(namespaceStats)) {\n console.log(` ${namespace}: ${count} entries`);\n }\n }\n } catch (err) {\n printError(`Failed to get stats: ${err.message}`);\n }\n}\n\nasync function exportMemory(subArgs, loadMemory, namespace) {\n const filename = subArgs[1] || `memory-export-${Date.now()}.json`;\n\n try {\n const data = await loadMemory();\n\n let exportData = data;\n if (namespace) {\n exportData = { [namespace]: data[namespace] || [] };\n }\n\n await fs.writeFile(filename, JSON.stringify(exportData, null, 2, 'utf8'));\n printSuccess(`Memory exported to ${filename}`);\n\n let totalEntries = 0;\n for (const entries of Object.values(exportData)) {\n totalEntries += entries.length;\n }\n console.log(\n `šŸ“¦ Exported ${totalEntries} entries from ${Object.keys(exportData).length} namespace(s)`,\n );\n } catch (err) {\n printError(`Failed to export memory: ${err.message}`);\n }\n}\n\nasync function importMemory(subArgs, saveMemory, loadMemory) {\n const filename = subArgs[1];\n\n if (!filename) {\n printError('Usage: memory import <filename>');\n return;\n }\n\n try {\n const importContent = await fs.readFile(filename, 'utf8');\n const importData = JSON.parse(importContent);\n\n // Load existing memory\n const existingData = await loadMemory();\n\n // Merge imported data\n let totalImported = 0;\n for (const [namespace, entries] of Object.entries(importData)) {\n if (!existingData[namespace]) {\n existingData[namespace] = [];\n }\n\n // Add entries that don't already exist (by key)\n const existingKeys = new Set(existingData[namespace].map((e) => e.key));\n const newEntries = entries.filter((e) => !existingKeys.has(e.key));\n\n existingData[namespace].push(...newEntries);\n totalImported += newEntries.length;\n }\n\n await saveMemory(existingData);\n printSuccess(`Imported ${totalImported} new entries from ${filename}`);\n } catch (err) {\n printError(`Failed to import memory: ${err.message}`);\n }\n}\n\nasync function clearMemory(subArgs, saveMemory, namespace) {\n if (!namespace || namespace === 'default') {\n const nsFromArgs = getNamespaceFromArgs(subArgs);\n if (!nsFromArgs) {\n printError('Usage: memory clear --namespace <namespace>');\n printWarning('This will clear all entries in the specified namespace');\n return;\n }\n namespace = nsFromArgs;\n }\n\n try {\n // Helper to load memory data\n async function loadMemory() {\n try {\n const content = await fs.readFile('./memory/memory-store.json', 'utf8');\n return JSON.parse(content);\n } catch {\n return {};\n }\n }\n \n const data = await loadMemory();\n\n if (!data[namespace]) {\n printWarning(`Namespace '${namespace}' does not exist`);\n return;\n }\n\n const entryCount = data[namespace].length;\n delete data[namespace];\n\n await saveMemory(data);\n printSuccess(`Cleared ${entryCount} entries from namespace '${namespace}'`);\n } catch (err) {\n printError(`Failed to clear memory: ${err.message}`);\n }\n}\n\nasync function listNamespaces(loadMemory) {\n try {\n const data = await loadMemory();\n const namespaces = Object.keys(data);\n\n if (namespaces.length === 0) {\n printWarning('No namespaces found');\n return;\n }\n\n printSuccess('Available namespaces:');\n for (const namespace of namespaces) {\n const count = data[namespace].length;\n console.log(` ${namespace} (${count} entries)`);\n }\n } catch (err) {\n printError(`Failed to list namespaces: ${err.message}`);\n }\n}\n\nfunction getNamespaceFromArgs(subArgs) {\n const namespaceIndex = subArgs.indexOf('--namespace');\n if (namespaceIndex !== -1 && namespaceIndex + 1 < subArgs.length) {\n return subArgs[namespaceIndex + 1];\n }\n\n const nsIndex = subArgs.indexOf('--ns');\n if (nsIndex !== -1 && nsIndex + 1 < subArgs.length) {\n return subArgs[nsIndex + 1];\n }\n\n return null;\n}\n\n// Helper to load memory data (needed for import function)\nasync function loadMemory() {\n try {\n const content = await fs.readFile('./memory/memory-store.json', 'utf8');\n return JSON.parse(content);\n } catch {\n return {};\n }\n}\n\n// NEW: Mode detection function\nasync function detectMemoryMode(flags, subArgs) {\n // Explicit ReasoningBank flag takes precedence\n if (flags?.reasoningbank || flags?.rb || subArgs.includes('--reasoningbank') || subArgs.includes('--rb')) {\n return 'reasoningbank';\n }\n\n // Auto mode: detect if ReasoningBank is initialized\n if (flags?.auto || subArgs.includes('--auto')) {\n const initialized = await isReasoningBankInitialized();\n return initialized ? 'reasoningbank' : 'basic';\n }\n\n // Explicit basic mode flag\n if (flags?.basic || subArgs.includes('--basic')) {\n return 'basic';\n }\n\n // Default: AUTO MODE with SQLite preference\n // Try to use ReasoningBank (SQLite) by default, initialize if needed\n const initialized = await isReasoningBankInitialized();\n\n if (initialized) {\n return 'reasoningbank';\n }\n\n // Not initialized yet - try to auto-initialize on first use\n try {\n const { initializeReasoningBank } = await import('../../reasoningbank/reasoningbank-adapter.js');\n const initialized = await initializeReasoningBank();\n\n // Check if initialization succeeded (returns true) or failed (returns false)\n if (!initialized) {\n // Initialization failed but didn't throw - fall back to JSON\n const isNpx = process.env.npm_config_user_agent?.includes('npx') ||\n process.cwd().includes('_npx');\n if (isNpx) {\n console.log('\\nāœ… Automatically using JSON fallback for this command\\n');\n } else {\n printWarning(`āš ļø SQLite unavailable, using JSON fallback`);\n }\n return 'basic';\n }\n\n printInfo('šŸ—„ļø Initialized SQLite backend (.swarm/memory.db)');\n return 'reasoningbank';\n } catch (error) {\n // SQLite initialization failed - fall back to JSON\n const isSqliteError = error.message?.includes('BetterSqlite3') ||\n error.message?.includes('better-sqlite3') ||\n error.message?.includes('could not run migrations') ||\n error.message?.includes('ReasoningBank initialization failed');\n const isNpx = process.env.npm_config_user_agent?.includes('npx') ||\n process.cwd().includes('_npx');\n\n if (isSqliteError && isNpx) {\n // Silent fallback for npx - error already shown by adapter\n console.log('\\nāœ… Automatically using JSON fallback for this command\\n');\n return 'basic';\n } else {\n printWarning(`āš ļø SQLite unavailable, using JSON fallback`);\n printWarning(` Reason: ${error.message}`);\n return 'basic';\n }\n }\n}\n\n// NEW: Check if ReasoningBank is initialized\nasync function isReasoningBankInitialized() {\n try {\n // Check if .swarm/memory.db exists\n const dbPath = '.swarm/memory.db';\n await fs.access(dbPath);\n return true;\n } catch {\n return false;\n }\n}\n\n// NEW: Handle ReasoningBank commands\nasync function handleReasoningBankCommand(command, subArgs, flags) {\n const initialized = await isReasoningBankInitialized();\n\n // Lazy load the adapter (ES modules)\n const { initializeReasoningBank, storeMemory, queryMemories, listMemories, getStatus, checkReasoningBankTables, migrateReasoningBank, cleanup } = await import('../../reasoningbank/reasoningbank-adapter.js');\n\n // Special handling for 'init' command\n if (command === 'init') {\n const dbPath = '.swarm/memory.db';\n\n if (initialized) {\n // Database exists - check if migration is needed\n printInfo('šŸ” Checking existing database for ReasoningBank schema...\\n');\n\n try {\n // Set the database path for ReasoningBank\n process.env.CLAUDE_FLOW_DB_PATH = dbPath;\n\n const tableCheck = await checkReasoningBankTables();\n\n if (tableCheck.exists) {\n printSuccess('āœ… ReasoningBank already complete');\n console.log('Database: .swarm/memory.db');\n console.log('All ReasoningBank tables present\\n');\n console.log('Use --reasoningbank flag with memory commands to enable AI features');\n return;\n }\n\n // Missing tables found - run migration\n console.log(`šŸ”„ Migrating database: ${tableCheck.missingTables.length} tables missing`);\n console.log(` Missing: ${tableCheck.missingTables.join(', ')}\\n`);\n\n const migrationResult = await migrateReasoningBank();\n\n if (migrationResult.success) {\n printSuccess(`āœ“ Migration complete: added ${migrationResult.addedTables?.length || 0} tables`);\n console.log('\\nNext steps:');\n console.log(' 1. Store memories: memory store key \"value\" --reasoningbank');\n console.log(' 2. Query memories: memory query \"search\" --reasoningbank');\n console.log(' 3. Check status: memory status --reasoningbank');\n } else {\n printError(`āŒ Migration failed: ${migrationResult.message}`);\n console.log('Try running: init --force to reinitialize');\n }\n } catch (error) {\n printError('āŒ Migration check failed');\n console.error(error.message);\n console.log('\\nTry running: init --force to reinitialize');\n } finally {\n // Cleanup after migration check\n cleanup();\n // Force exit to prevent hanging from embedding cache timers\n setTimeout(() => process.exit(0), 100);\n }\n return;\n }\n\n // Fresh initialization\n printInfo('🧠 Initializing ReasoningBank...');\n console.log('This will create: .swarm/memory.db\\n');\n\n try {\n await initializeReasoningBank();\n printSuccess('āœ… ReasoningBank initialized successfully!');\n console.log('\\nNext steps:');\n console.log(' 1. Store memories: memory store key \"value\" --reasoningbank');\n console.log(' 2. Query memories: memory query \"search\" --reasoningbank');\n console.log(' 3. Check status: memory status --reasoningbank');\n } catch (error) {\n printError('āŒ Failed to initialize ReasoningBank');\n console.error(error.message);\n } finally {\n // Cleanup after init\n cleanup();\n // Force exit to prevent hanging from embedding cache timers\n setTimeout(() => process.exit(0), 100);\n }\n return;\n }\n\n // All other commands require initialization\n if (!initialized) {\n printError('āŒ ReasoningBank not initialized');\n console.log('\\nTo use ReasoningBank mode, first run:');\n console.log(' memory init --reasoningbank\\n');\n return;\n }\n\n printInfo(`🧠 Using ReasoningBank mode...`);\n\n try {\n // Handle different commands\n switch (command) {\n case 'store':\n await handleReasoningBankStore(subArgs, flags, storeMemory);\n break;\n\n case 'query':\n await handleReasoningBankQuery(subArgs, flags, queryMemories);\n break;\n\n case 'list':\n await handleReasoningBankList(subArgs, flags, listMemories);\n break;\n\n case 'status':\n await handleReasoningBankStatus(getStatus);\n break;\n\n case 'consolidate':\n case 'demo':\n case 'test':\n case 'benchmark':\n // These still use CLI commands\n const cmd = `npx agentic-flow reasoningbank ${command}`;\n const { stdout } = await execAsync(cmd, { timeout: 60000 });\n if (stdout) console.log(stdout);\n break;\n\n default:\n printError(`Unknown ReasoningBank command: ${command}`);\n }\n } catch (error) {\n printError(`āŒ ReasoningBank command failed`);\n console.error(error.message);\n } finally {\n // Always cleanup database connection\n cleanup();\n\n // Force process exit after cleanup (embedding cache timers prevent natural exit)\n // This is necessary because agentic-flow's embedding cache uses setTimeout\n // which keeps the event loop alive\n setTimeout(() => {\n process.exit(0);\n }, 100);\n }\n}\n\n// NEW: Handle ReasoningBank store\nasync function handleReasoningBankStore(subArgs, flags, storeMemory) {\n const key = subArgs[1];\n const value = subArgs.slice(2).join(' ');\n\n if (!key || !value) {\n printError('Usage: memory store <key> <value> --reasoningbank');\n return;\n }\n\n try {\n const namespace = flags?.namespace || flags?.ns || getArgValue(subArgs, '--namespace') || 'default';\n\n const memoryId = await storeMemory(key, value, {\n namespace,\n agent: 'memory-agent',\n domain: namespace,\n });\n\n printSuccess('āœ… Stored successfully in ReasoningBank');\n console.log(`šŸ“ Key: ${key}`);\n console.log(`🧠 Memory ID: ${memoryId}`);\n console.log(`šŸ“¦ Namespace: ${namespace}`);\n console.log(`šŸ’¾ Size: ${new TextEncoder().encode(value).length} bytes`);\n console.log(`šŸ” Semantic search: enabled`);\n } catch (error) {\n printError(`Failed to store: ${error.message}`);\n }\n}\n\n// NEW: Handle ReasoningBank query\nasync function handleReasoningBankQuery(subArgs, flags, queryMemories) {\n const search = subArgs.slice(1).join(' ');\n\n if (!search) {\n printError('Usage: memory query <search> --reasoningbank');\n return;\n }\n\n try {\n const namespace = flags?.namespace || flags?.ns || getArgValue(subArgs, '--namespace');\n const results = await queryMemories(search, {\n domain: namespace || 'general',\n limit: 10,\n });\n\n if (results.length === 0) {\n printWarning('No results found');\n return;\n }\n\n printSuccess(`Found ${results.length} results (semantic search):`);\n\n for (const entry of results) {\n console.log(`\\nšŸ“Œ ${entry.key}`);\n console.log(` Namespace: ${entry.namespace}`);\n console.log(` Value: ${entry.value.substring(0, 100)}${entry.value.length > 100 ? '...' : ''}`);\n console.log(` Confidence: ${(entry.confidence * 100).toFixed(1)}%`);\n console.log(` Usage: ${entry.usage_count} times`);\n if (entry.score) {\n console.log(` Match Score: ${(entry.score * 100).toFixed(1)}%`);\n }\n console.log(` Stored: ${new Date(entry.created_at).toLocaleString()}`);\n }\n } catch (error) {\n printError(`Failed to query: ${error.message}`);\n }\n}\n\n// NEW: Handle ReasoningBank list\nasync function handleReasoningBankList(subArgs, flags, listMemories) {\n try {\n const sort = flags?.sort || getArgValue(subArgs, '--sort') || 'created_at';\n const limit = parseInt(flags?.limit || getArgValue(subArgs, '--limit') || '10');\n\n const results = await listMemories({ sort, limit });\n\n if (results.length === 0) {\n printWarning('No memories found');\n return;\n }\n\n printSuccess(`ReasoningBank memories (${results.length} shown):`);\n\n for (const entry of results) {\n console.log(`\\nšŸ“Œ ${entry.key}`);\n console.log(` Value: ${entry.value.substring(0, 80)}${entry.value.length > 80 ? '...' : ''}`);\n console.log(` Confidence: ${(entry.confidence * 100).toFixed(1)}% | Usage: ${entry.usage_count}`);\n }\n } catch (error) {\n printError(`Failed to list: ${error.message}`);\n }\n}\n\n// NEW: Handle ReasoningBank status\nasync function handleReasoningBankStatus(getStatus) {\n try {\n const stats = await getStatus();\n\n printSuccess('šŸ“Š ReasoningBank Status:');\n console.log(` Total memories: ${stats.total_memories}`);\n console.log(` Average confidence: ${(stats.avg_confidence * 100).toFixed(1)}%`);\n console.log(` Total usage: ${stats.total_usage}`);\n console.log(` Embeddings: ${stats.total_embeddings}`);\n console.log(` Trajectories: ${stats.total_trajectories}`);\n } catch (error) {\n printError(`Failed to get status: ${error.message}`);\n }\n}\n\n// NEW: Build agentic-flow reasoningbank command\nfunction buildReasoningBankCommand(command, subArgs, flags) {\n const parts = ['npx', 'agentic-flow', 'reasoningbank'];\n\n // Map memory commands to reasoningbank commands\n const commandMap = {\n store: 'store',\n query: 'query',\n list: 'list',\n status: 'status',\n consolidate: 'consolidate',\n demo: 'demo',\n test: 'test',\n benchmark: 'benchmark',\n };\n\n parts.push(commandMap[command] || command);\n\n // Add arguments (skip the command itself)\n const args = subArgs.slice(1);\n args.forEach((arg) => {\n if (!arg.startsWith('--reasoningbank') && !arg.startsWith('--rb') && !arg.startsWith('--auto')) {\n parts.push(`\"${arg}\"`);\n }\n });\n\n // Add required --agent parameter\n parts.push('--agent', 'memory-agent');\n\n return parts.join(' ');\n}\n\n// NEW: Handle mode management commands\nasync function handleModeCommand(command, subArgs, flags) {\n switch (command) {\n case 'detect':\n await detectModes();\n break;\n\n case 'mode':\n await showCurrentMode();\n break;\n\n case 'migrate':\n await migrateMemory(subArgs, flags);\n break;\n\n default:\n printError(`Unknown mode command: ${command}`);\n }\n}\n\n// NEW: Detect and show available memory modes\nasync function detectModes() {\n printInfo('šŸ” Detecting memory modes...\\n');\n\n // Check basic mode\n const basicAvailable = await checkBasicMode();\n console.log(basicAvailable ? 'āœ… Basic Mode (active)' : 'āŒ Basic Mode (unavailable)');\n if (basicAvailable) {\n console.log(' Location: ./memory/memory-store.json');\n console.log(' Features: Simple key-value storage, fast');\n }\n\n console.log('');\n\n // Check ReasoningBank mode\n const rbAvailable = await isReasoningBankInitialized();\n console.log(rbAvailable ? 'āœ… ReasoningBank Mode (available)' : 'āš ļø ReasoningBank Mode (not initialized)');\n if (rbAvailable) {\n console.log(' Location: .swarm/memory.db');\n console.log(' Features: AI-powered semantic search, learning');\n } else {\n console.log(' To enable: memory init --reasoningbank');\n }\n\n console.log('\\nšŸ’” Usage:');\n console.log(' Basic: memory store key \"value\"');\n console.log(' ReasoningBank: memory store key \"value\" --reasoningbank');\n console.log(' Auto-detect: memory query search --auto');\n}\n\n// NEW: Check if basic mode is available\nasync function checkBasicMode() {\n try {\n const memoryDir = './memory';\n await fs.access(memoryDir);\n return true;\n } catch {\n // Create directory if it doesn't exist\n try {\n await fs.mkdir(memoryDir, { recursive: true });\n return true;\n } catch {\n return false;\n }\n }\n}\n\n// NEW: Show current default mode\nasync function showCurrentMode() {\n const rbInitialized = await isReasoningBankInitialized();\n\n printInfo('šŸ“Š Current Memory Configuration:\\n');\n console.log('Default Mode: AUTO (smart selection with JSON fallback)');\n console.log('Available Modes:');\n console.log(' • Basic Mode: Always available (JSON storage)');\n console.log(` • ReasoningBank Mode: ${rbInitialized ? 'Initialized āœ… (will be used by default)' : 'Not initialized āš ļø (JSON fallback active)'}`);\n\n console.log('\\nšŸ’” Mode Behavior:');\n console.log(' (no flag) → AUTO: Use ReasoningBank if initialized, else JSON');\n console.log(' --reasoningbank or --rb → Force ReasoningBank mode');\n console.log(' --basic → Force JSON mode');\n console.log(' --auto → Same as default (explicit)');\n}\n\n// NEW: Migrate memory between modes\nasync function migrateMemory(subArgs, flags) {\n const targetMode = flags?.to || getArgValue(subArgs, '--to');\n\n if (!targetMode || !['basic', 'reasoningbank'].includes(targetMode)) {\n printError('Usage: memory migrate --to <basic|reasoningbank>');\n return;\n }\n\n printInfo(`šŸ”„ Migrating to ${targetMode} mode...\\n`);\n\n if (targetMode === 'reasoningbank') {\n // Migrate basic → ReasoningBank\n const rbInitialized = await isReasoningBankInitialized();\n if (!rbInitialized) {\n printError('āŒ ReasoningBank not initialized');\n console.log('First run: memory init --reasoningbank\\n');\n return;\n }\n\n printWarning('āš ļø Migration from basic to ReasoningBank is not yet implemented');\n console.log('This feature is coming in v2.7.1\\n');\n console.log('For now, you can:');\n console.log(' 1. Export basic memory: memory export backup.json');\n console.log(' 2. Manually import to ReasoningBank');\n } else {\n // Migrate ReasoningBank → basic\n printWarning('āš ļø Migration from ReasoningBank to basic is not yet implemented');\n console.log('This feature is coming in v2.7.1\\n');\n }\n}\n\n// Helper to get argument value\nfunction getArgValue(args, flag) {\n const index = args.indexOf(flag);\n if (index !== -1 && index + 1 < args.length) {\n return args[index + 1];\n }\n return null;\n}\n\nfunction showMemoryHelp() {\n console.log('Memory commands:');\n console.log(' store <key> <value> Store a key-value pair');\n console.log(' query <search> Search for entries');\n console.log(' stats Show memory statistics');\n console.log(' export [filename] Export memory to file');\n console.log(' import <filename> Import memory from file');\n console.log(' clear --namespace <ns> Clear a namespace');\n console.log(' list List all namespaces');\n console.log();\n console.log('🧠 ReasoningBank Commands (NEW in v2.7.0):');\n console.log(' init --reasoningbank Initialize ReasoningBank (AI-powered memory)');\n console.log(' status --reasoningbank Show ReasoningBank statistics');\n console.log(' detect Show available memory modes');\n console.log(' mode Show current memory configuration');\n console.log(' migrate --to <mode> Migrate between basic/reasoningbank');\n console.log();\n console.log('Options:');\n console.log(' --namespace <ns> Specify namespace for operations');\n console.log(' --ns <ns> Short form of --namespace');\n console.log(' --limit <n> Limit number of results (default: 10)');\n console.log(' --sort <field> Sort results by: recent, oldest, key, value');\n console.log(' --format <type> Export format: json, yaml');\n console.log(' --redact šŸ”’ Enable API key redaction (security feature)');\n console.log(' --secure Alias for --redact');\n console.log();\n console.log('šŸŽÆ Mode Selection:');\n console.log(' (no flag) AUTO MODE (default) - Uses ReasoningBank if initialized, else JSON fallback');\n console.log(' --reasoningbank, --rb Force ReasoningBank mode (AI-powered)');\n console.log(' --basic Force Basic mode (JSON storage)');\n console.log(' --auto Explicit auto-detect (same as default)');\n console.log();\n console.log('šŸ”’ Security Features (v2.6.0):');\n console.log(' API Key Protection: Automatically detects and redacts sensitive data');\n console.log(' Patterns Detected: Anthropic, OpenRouter, Gemini, Bearer tokens, etc.');\n console.log(' Auto-Validation: Warns when storing unredacted sensitive data');\n console.log(' Display Redaction: Redact sensitive data when querying with --redact');\n console.log();\n console.log('Examples:');\n console.log(' # Basic mode (default - backward compatible)');\n console.log(' memory store previous_work \"Research findings from yesterday\"');\n console.log(' memory store api_config \"key=sk-ant-...\" --redact # šŸ”’ Redacts API key');\n console.log(' memory query research --namespace sparc');\n console.log();\n console.log(' # ReasoningBank mode (AI-powered, opt-in)');\n console.log(' memory init --reasoningbank # One-time setup');\n console.log(' memory store api_pattern \"Always use env vars\" --reasoningbank');\n console.log(' memory query \"API configuration\" --reasoningbank --limit 5 # Semantic search!');\n console.log(' memory list --reasoningbank --sort recent --limit 20');\n console.log(' memory export backup.json --format json --reasoningbank');\n console.log(' memory status --reasoningbank # Show AI metrics');\n console.log();\n console.log(' # Auto-detect mode (smart selection)');\n console.log(' memory query config --auto # Uses ReasoningBank if available');\n console.log();\n console.log(' # Mode management');\n console.log(' memory detect # Show available modes');\n console.log(' memory mode # Show current configuration');\n console.log();\n console.log('šŸ’” Tips:');\n console.log(' • AUTO MODE (default): Automatically uses best available storage');\n console.log(' • ReasoningBank: AI-powered semantic search (learns from patterns)');\n console.log(' • JSON fallback: Always available, fast, simple key-value storage');\n console.log(' • Initialize ReasoningBank once: \"memory init --reasoningbank\"');\n console.log(' • Always use --redact when storing API keys or secrets!');\n console.log();\n console.log('šŸš€ Semantic Search (NEW in v2.7.25):');\n console.log(' NPX Mode: Uses hash-based embeddings (text similarity)');\n console.log(' • Fast, offline, zero dependencies');\n console.log(' • Good for exact/partial text matching');\n console.log(' Local Install: Uses transformer embeddings (semantic AI)');\n console.log(' • Finds conceptually related content');\n console.log(' • 384-dimensional vectors (Xenova/all-MiniLM-L6-v2)');\n console.log(' • Install: npm install -g claude-flow@alpha');\n console.log(' Both modes work perfectly - choose based on your needs!');\n}\n"],"names":["printSuccess","printError","printWarning","printInfo","promises","fs","KeyRedactor","exec","promisify","execAsync","memoryCommand","subArgs","flags","memorySubcommand","memoryStore","namespace","ns","getNamespaceFromArgs","enableRedaction","redact","includes","mode","detectMemoryMode","loadMemory","content","readFile","JSON","parse","saveMemory","data","mkdir","recursive","writeFile","stringify","handleReasoningBankCommand","handleModeCommand","storeMemory","queryMemory","showMemoryStats","exportMemory","importMemory","clearMemory","listNamespaces","showMemoryHelp","key","value","slice","join","redactedValue","securityWarnings","validation","validate","safe","warnings","forEach","warning","console","log","filter","e","push","timestamp","Date","now","redacted","length","TextEncoder","encode","err","message","search","results","entries","Object","entry","sort","a","b","displayValue","substring","toLocaleString","totalEntries","namespaceStats","keys","toFixed","count","filename","exportData","values","importContent","importData","existingData","totalImported","existingKeys","Set","map","newEntries","has","nsFromArgs","entryCount","namespaces","namespaceIndex","indexOf","nsIndex","reasoningbank","rb","auto","initialized","isReasoningBankInitialized","basic","initializeReasoningBank","isNpx","process","env","npm_config_user_agent","cwd","error","isSqliteError","dbPath","access","command","queryMemories","listMemories","getStatus","checkReasoningBankTables","migrateReasoningBank","cleanup","CLAUDE_FLOW_DB_PATH","tableCheck","exists","missingTables","migrationResult","success","addedTables","setTimeout","exit","handleReasoningBankStore","handleReasoningBankQuery","handleReasoningBankList","handleReasoningBankStatus","cmd","stdout","timeout","getArgValue","memoryId","agent","domain","limit","confidence","usage_count","score","created_at","parseInt","stats","total_memories","avg_confidence","total_usage","total_embeddings","total_trajectories","buildReasoningBankCommand","parts","commandMap","store","query","list","status","consolidate","demo","test","benchmark","args","arg","startsWith","detectModes","showCurrentMode","migrateMemory","basicAvailable","checkBasicMode","rbAvailable","memoryDir","rbInitialized","targetMode","to","flag","index"],"mappings":"AACA,SAASA,YAAY,EAAEC,UAAU,EAAEC,YAAY,EAAEC,SAAS,QAAQ,cAAc;AAChF,SAASC,YAAYC,EAAE,QAAQ,KAAK;AAGpC,SAASC,WAAW,QAAQ,8BAA8B;AAC1D,SAASC,IAAI,QAAQ,gBAAgB;AACrC,SAASC,SAAS,QAAQ,OAAO;AAEjC,MAAMC,YAAYD,UAAUD;AAE5B,OAAO,eAAeG,cAAcC,OAAO,EAAEC,KAAK;IAChD,MAAMC,mBAAmBF,OAAO,CAAC,EAAE;IACnC,MAAMG,cAAc;IAGpB,MAAMC,YAAYH,OAAOG,aAAaH,OAAOI,MAAMC,qBAAqBN,YAAY;IAGpF,MAAMO,kBAAkBN,OAAOO,UAAUR,QAAQS,QAAQ,CAAC,eAAeT,QAAQS,QAAQ,CAAC;IAG1F,MAAMC,OAAO,MAAMC,iBAAiBV,OAAOD;IAG3C,eAAeY;QACb,IAAI;YACF,MAAMC,UAAU,MAAMnB,GAAGoB,QAAQ,CAACX,aAAa;YAC/C,OAAOY,KAAKC,KAAK,CAACH;QACpB,EAAE,OAAM;YACN,OAAO,CAAC;QACV;IACF;IAGA,eAAeI,WAAWC,IAAI;QAC5B,MAAMxB,GAAGyB,KAAK,CAAC,YAAY;YAAEC,WAAW;QAAK;QAC7C,MAAM1B,GAAG2B,SAAS,CAAClB,aAAaY,KAAKO,SAAS,CAACJ,MAAM,MAAM,GAAG;IAChE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ACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG;IACXD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG;IACXD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG;IACXD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG;IACXD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG;IACXD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG;IACXD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG;IACXD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;AACd"}
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/cli/validation-helper.ts"],"sourcesContent":["/**\n * CLI Parameter Validation Helper\n * Provides standardized error messages for invalid parameters\n */\n\nimport { HelpFormatter } from './help-formatter.js';\n\nexport class ValidationHelper {\n /**\n * Validate enum parameter\n */\n static validateEnum(\n value: string,\n paramName: string,\n validOptions: string[],\n commandPath: string,\n ): void {\n if (!validOptions.includes(value)) {\n console.error(\n HelpFormatter.formatValidationError(value, paramName, validOptions, commandPath),\n );\n process.exit(1);\n }\n }\n\n /**\n * Validate numeric parameter\n */\n static validateNumber(\n value: string,\n paramName: string,\n min?: number,\n max?: number,\n commandPath?: string,\n ): number {\n const num = parseInt(value, 10);\n\n if (isNaN(num)) {\n console.error(\n HelpFormatter.formatError(\n `'${value}' is not a valid number for ${paramName}.`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n\n if (min !== undefined && num < min) {\n console.error(\n HelpFormatter.formatError(\n `${paramName} must be at least ${min}. Got: ${num}`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n\n if (max !== undefined && num > max) {\n console.error(\n HelpFormatter.formatError(\n `${paramName} must be at most ${max}. Got: ${num}`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n\n return num;\n }\n\n /**\n * Validate required parameter\n */\n static validateRequired(value: any, paramName: string, commandPath?: string): void {\n if (!value || (typeof value === 'string' && value.trim() === '')) {\n console.error(\n HelpFormatter.formatError(\n `Missing required parameter: ${paramName}`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n }\n\n /**\n * Validate file path exists\n */\n static async validateFilePath(\n path: string,\n paramName: string,\n commandPath?: string,\n ): Promise<void> {\n try {\n const fs = await import('fs/promises');\n await fs.access(path);\n } catch (error) {\n console.error(\n HelpFormatter.formatError(\n `File not found for ${paramName}: ${path}`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n }\n\n /**\n * Validate boolean flag\n */\n static validateBoolean(value: string, paramName: string, commandPath?: string): boolean {\n const lowerValue = value.toLowerCase();\n if (lowerValue === 'true' || lowerValue === '1' || lowerValue === 'yes') {\n return true;\n }\n if (lowerValue === 'false' || lowerValue === '0' || lowerValue === 'no') {\n return false;\n }\n\n console.error(\n HelpFormatter.formatError(\n `'${value}' is not a valid boolean for ${paramName}. Use: true, false, yes, no, 1, or 0.`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n}\n"],"names":["HelpFormatter","ValidationHelper","validateEnum","value","paramName","validOptions","commandPath","includes","console","error","formatValidationError","process","exit","validateNumber","min","max","num","parseInt","isNaN","formatError","undefined","validateRequired","trim","validateFilePath","path","fs","access","validateBoolean","lowerValue","toLowerCase"],"mappings":"AAKA,SAASA,aAAa,QAAQ,sBAAsB;AAEpD,OAAO,MAAMC;IAIX,OAAOC,aACLC,KAAa,EACbC,SAAiB,EACjBC,YAAsB,EACtBC,WAAmB,EACb;QACN,IAAI,CAACD,aAAaE,QAAQ,CAACJ,QAAQ;YACjCK,QAAQC,KAAK,CACXT,cAAcU,qBAAqB,CAACP,OAAOC,WAAWC,cAAcC;YAEtEK,QAAQC,IAAI,CAAC;QACf;IACF;IAKA,OAAOC,eACLV,KAAa,EACbC,SAAiB,EACjBU,GAAY,EACZC,GAAY,EACZT,WAAoB,EACZ;QACR,MAAMU,MAAMC,SAASd,OAAO;QAE5B,IAAIe,MAAMF,MAAM;YACdR,QAAQC,KAAK,CACXT,cAAcmB,WAAW,CACvB,CAAC,CAAC,EAAEhB,MAAM,4BAA4B,EAAEC,UAAU,CAAC,CAAC,EACpDE,eAAe;YAGnBK,QAAQC,IAAI,CAAC;QACf;QAEA,IAAIE,QAAQM,aAAaJ,MAAMF,KAAK;YAClCN,QAAQC,KAAK,CACXT,cAAcmB,WAAW,CACvB,GAAGf,UAAU,kBAAkB,EAAEU,IAAI,OAAO,EAAEE,KAAK,EACnDV,eAAe;YAGnBK,QAAQC,IAAI,CAAC;QACf;QAEA,IAAIG,QAAQK,aAAaJ,MAAMD,KAAK;YAClCP,QAAQC,KAAK,CACXT,cAAcmB,WAAW,CACvB,GAAGf,UAAU,iBAAiB,EAAEW,IAAI,OAAO,EAAEC,KAAK,EAClDV,eAAe;YAGnBK,QAAQC,IAAI,CAAC;QACf;QAEA,OAAOI;IACT;IAKA,OAAOK,iBAAiBlB,KAAU,EAAEC,SAAiB,EAAEE,WAAoB,EAAQ;QACjF,IAAI,CAACH,SAAU,OAAOA,UAAU,YAAYA,MAAMmB,IAAI,OAAO,IAAK;YAChEd,QAAQC,KAAK,CACXT,cAAcmB,WAAW,CACvB,CAAC,4BAA4B,EAAEf,WAAW,EAC1CE,eAAe;YAGnBK,QAAQC,IAAI,CAAC;QACf;IACF;IAKA,aAAaW,iBACXC,IAAY,EACZpB,SAAiB,EACjBE,WAAoB,EACL;QACf,IAAI;YACF,MAAMmB,KAAK,MAAM,MAAM,CAAC;YACxB,MAAMA,GAAGC,MAAM,CAACF;QAClB,EAAE,OAAOf,OAAO;YACdD,QAAQC,KAAK,CACXT,cAAcmB,WAAW,CACvB,CAAC,mBAAmB,EAAEf,UAAU,EAAE,EAAEoB,MAAM,EAC1ClB,eAAe;YAGnBK,QAAQC,IAAI,CAAC;QACf;IACF;IAKA,OAAOe,gBAAgBxB,KAAa,EAAEC,SAAiB,EAAEE,WAAoB,EAAW;QACtF,MAAMsB,aAAazB,MAAM0B,WAAW;QACpC,IAAID,eAAe,UAAUA,eAAe,OAAOA,eAAe,OAAO;YACvE,OAAO;QACT;QACA,IAAIA,eAAe,WAAWA,eAAe,OAAOA,eAAe,MAAM;YACvE,OAAO;QACT;QAEApB,QAAQC,KAAK,CACXT,cAAcmB,WAAW,CACvB,CAAC,CAAC,EAAEhB,MAAM,6BAA6B,EAAEC,UAAU,qCAAqC,CAAC,EACzFE,eAAe;QAGnBK,QAAQC,IAAI,CAAC;IACf;AACF"}
1
+ {"version":3,"sources":["../../../src/cli/validation-helper.js"],"sourcesContent":["/**\n * CLI Parameter Validation Helper\n * Provides standardized error messages for invalid parameters\n */\n\nimport { HelpFormatter } from './help-formatter.js';\n\nexport class ValidationHelper {\n /**\n * Validate enum parameter\n */\n static validateEnum(value, paramName, validOptions, commandPath) {\n if (!validOptions.includes(value)) {\n console.error(\n HelpFormatter.formatValidationError(value, paramName, validOptions, commandPath),\n );\n process.exit(1);\n }\n }\n\n /**\n * Validate numeric parameter\n */\n static validateNumber(value, paramName, min, max, commandPath) {\n const num = parseInt(value, 10);\n\n if (isNaN(num)) {\n console.error(\n HelpFormatter.formatError(\n `'${value}' is not a valid number for ${paramName}.`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n\n if (min !== undefined && num < min) {\n console.error(\n HelpFormatter.formatError(\n `${paramName} must be at least ${min}. Got: ${num}`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n\n if (max !== undefined && num > max) {\n console.error(\n HelpFormatter.formatError(\n `${paramName} must be at most ${max}. Got: ${num}`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n\n return num;\n }\n\n /**\n * Validate required parameter\n */\n static validateRequired(value, paramName, commandPath) {\n if (!value || (typeof value === 'string' && value.trim() === '')) {\n console.error(\n HelpFormatter.formatError(\n `Missing required parameter: ${paramName}`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n }\n\n /**\n * Validate file path exists\n */\n static async validateFilePath(path, paramName, commandPath) {\n try {\n const fs = await import('fs/promises');\n await fs.access(path);\n } catch (error) {\n console.error(\n HelpFormatter.formatError(\n `File not found for ${paramName}: ${path}`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n }\n\n /**\n * Validate boolean flag\n */\n static validateBoolean(value, paramName, commandPath) {\n const lowerValue = value.toLowerCase();\n if (lowerValue === 'true' || lowerValue === '1' || lowerValue === 'yes') {\n return true;\n }\n if (lowerValue === 'false' || lowerValue === '0' || lowerValue === 'no') {\n return false;\n }\n\n console.error(\n HelpFormatter.formatError(\n `'${value}' is not a valid boolean for ${paramName}. Use: true, false, yes, no, 1, or 0.`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n}\n"],"names":["HelpFormatter","ValidationHelper","validateEnum","value","paramName","validOptions","commandPath","includes","console","error","formatValidationError","process","exit","validateNumber","min","max","num","parseInt","isNaN","formatError","undefined","validateRequired","trim","validateFilePath","path","fs","access","validateBoolean","lowerValue","toLowerCase"],"mappings":"AAKA,SAASA,aAAa,QAAQ,sBAAsB;AAEpD,OAAO,MAAMC;IAIX,OAAOC,aAAaC,KAAK,EAAEC,SAAS,EAAEC,YAAY,EAAEC,WAAW,EAAE;QAC/D,IAAI,CAACD,aAAaE,QAAQ,CAACJ,QAAQ;YACjCK,QAAQC,KAAK,CACXT,cAAcU,qBAAqB,CAACP,OAAOC,WAAWC,cAAcC;YAEtEK,QAAQC,IAAI,CAAC;QACf;IACF;IAKA,OAAOC,eAAeV,KAAK,EAAEC,SAAS,EAAEU,GAAG,EAAEC,GAAG,EAAET,WAAW,EAAE;QAC7D,MAAMU,MAAMC,SAASd,OAAO;QAE5B,IAAIe,MAAMF,MAAM;YACdR,QAAQC,KAAK,CACXT,cAAcmB,WAAW,CACvB,CAAC,CAAC,EAAEhB,MAAM,4BAA4B,EAAEC,UAAU,CAAC,CAAC,EACpDE,eAAe;YAGnBK,QAAQC,IAAI,CAAC;QACf;QAEA,IAAIE,QAAQM,aAAaJ,MAAMF,KAAK;YAClCN,QAAQC,KAAK,CACXT,cAAcmB,WAAW,CACvB,GAAGf,UAAU,kBAAkB,EAAEU,IAAI,OAAO,EAAEE,KAAK,EACnDV,eAAe;YAGnBK,QAAQC,IAAI,CAAC;QACf;QAEA,IAAIG,QAAQK,aAAaJ,MAAMD,KAAK;YAClCP,QAAQC,KAAK,CACXT,cAAcmB,WAAW,CACvB,GAAGf,UAAU,iBAAiB,EAAEW,IAAI,OAAO,EAAEC,KAAK,EAClDV,eAAe;YAGnBK,QAAQC,IAAI,CAAC;QACf;QAEA,OAAOI;IACT;IAKA,OAAOK,iBAAiBlB,KAAK,EAAEC,SAAS,EAAEE,WAAW,EAAE;QACrD,IAAI,CAACH,SAAU,OAAOA,UAAU,YAAYA,MAAMmB,IAAI,OAAO,IAAK;YAChEd,QAAQC,KAAK,CACXT,cAAcmB,WAAW,CACvB,CAAC,4BAA4B,EAAEf,WAAW,EAC1CE,eAAe;YAGnBK,QAAQC,IAAI,CAAC;QACf;IACF;IAKA,aAAaW,iBAAiBC,IAAI,EAAEpB,SAAS,EAAEE,WAAW,EAAE;QAC1D,IAAI;YACF,MAAMmB,KAAK,MAAM,MAAM,CAAC;YACxB,MAAMA,GAAGC,MAAM,CAACF;QAClB,EAAE,OAAOf,OAAO;YACdD,QAAQC,KAAK,CACXT,cAAcmB,WAAW,CACvB,CAAC,mBAAmB,EAAEf,UAAU,EAAE,EAAEoB,MAAM,EAC1ClB,eAAe;YAGnBK,QAAQC,IAAI,CAAC;QACf;IACF;IAKA,OAAOe,gBAAgBxB,KAAK,EAAEC,SAAS,EAAEE,WAAW,EAAE;QACpD,MAAMsB,aAAazB,MAAM0B,WAAW;QACpC,IAAID,eAAe,UAAUA,eAAe,OAAOA,eAAe,OAAO;YACvE,OAAO;QACT;QACA,IAAIA,eAAe,WAAWA,eAAe,OAAOA,eAAe,MAAM;YACvE,OAAO;QACT;QAEApB,QAAQC,KAAK,CACXT,cAAcmB,WAAW,CACvB,CAAC,CAAC,EAAEhB,MAAM,6BAA6B,EAAEC,UAAU,qCAAqC,CAAC,EACzFE,eAAe;QAGnBK,QAAQC,IAAI,CAAC;IACf;AACF"}
@@ -151,105 +151,6 @@ export class MCPIntegrator {
151
151
  ],
152
152
  status: 'disconnected'
153
153
  });
154
- this.tools.set('agentic-payments', {
155
- name: 'agentic-payments',
156
- server: 'npx agentic-payments@latest mcp',
157
- functions: [
158
- {
159
- name: 'create_active_mandate',
160
- description: 'Create Active Mandate for autonomous payment authorization',
161
- parameters: {
162
- agent: 'string',
163
- holder: 'string',
164
- amount: 'number',
165
- currency: 'string',
166
- period: 'string',
167
- kind: 'string'
168
- },
169
- required: [
170
- 'agent',
171
- 'holder',
172
- 'amount',
173
- 'currency',
174
- 'period',
175
- 'kind'
176
- ]
177
- },
178
- {
179
- name: 'sign_mandate',
180
- description: 'Sign mandate with Ed25519 cryptographic proof',
181
- parameters: {
182
- mandate: 'object',
183
- private_key: 'string'
184
- },
185
- required: [
186
- 'mandate',
187
- 'private_key'
188
- ]
189
- },
190
- {
191
- name: 'verify_mandate',
192
- description: 'Verify mandate signature and execution guards',
193
- parameters: {
194
- signed_mandate: 'object',
195
- check_guards: 'boolean'
196
- },
197
- required: [
198
- 'signed_mandate'
199
- ]
200
- },
201
- {
202
- name: 'revoke_mandate',
203
- description: 'Revoke mandate by ID',
204
- parameters: {
205
- mandate_id: 'string',
206
- reason: 'string'
207
- },
208
- required: [
209
- 'mandate_id'
210
- ]
211
- },
212
- {
213
- name: 'generate_agent_identity',
214
- description: 'Generate Ed25519 keypair for agent',
215
- parameters: {
216
- include_private_key: 'boolean'
217
- },
218
- required: []
219
- },
220
- {
221
- name: 'create_intent_mandate',
222
- description: 'Create intent-based payment mandate',
223
- parameters: {
224
- merchant_id: 'string',
225
- customer_id: 'string',
226
- intent: 'string',
227
- max_amount: 'number'
228
- },
229
- required: [
230
- 'merchant_id',
231
- 'customer_id',
232
- 'intent',
233
- 'max_amount'
234
- ]
235
- },
236
- {
237
- name: 'create_cart_mandate',
238
- description: 'Create cart-based payment mandate',
239
- parameters: {
240
- merchant_id: 'string',
241
- customer_id: 'string',
242
- items: 'array'
243
- },
244
- required: [
245
- 'merchant_id',
246
- 'customer_id',
247
- 'items'
248
- ]
249
- }
250
- ],
251
- status: 'disconnected'
252
- });
253
154
  }
254
155
  async discoverTools() {
255
156
  for (const [name, tool] of this.tools){
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/core/MCPIntegrator.ts"],"sourcesContent":["/**\n * MCPIntegrator - Manages MCP tool coordination\n * Provides integration with external MCP tools and orchestration services\n */\n\nexport interface MCPTool {\n name: string;\n server: string;\n functions: MCPFunction[];\n status: 'connected' | 'disconnected' | 'error';\n lastPing?: Date;\n}\n\nexport interface MCPFunction {\n name: string;\n description: string;\n parameters: any;\n required: string[];\n}\n\nexport interface MCPCommand {\n tool: string;\n function: string;\n parameters: any;\n timeout?: number;\n}\n\nexport interface MCPResult {\n success: boolean;\n data?: any;\n error?: string;\n metadata?: {\n executionTime: number;\n tool: string;\n function: string;\n };\n}\n\nexport class MCPIntegrator {\n private tools: Map<string, MCPTool> = new Map();\n private initialized: boolean = false;\n\n constructor() {\n this.registerDefaultTools();\n }\n\n /**\n * Initialize MCP integrator and discover available tools\n */\n async initialize(): Promise<void> {\n await this.discoverTools();\n await this.testConnections();\n this.initialized = true;\n }\n\n /**\n * Register default MCP tools\n */\n private registerDefaultTools(): void {\n // Claude Flow MCP tools\n this.tools.set('claude-flow', {\n name: 'claude-flow',\n server: 'npx claude-flow@alpha mcp start',\n functions: [\n {\n name: 'swarm_init',\n description: 'Initialize swarm with topology',\n parameters: { topology: 'string', maxAgents: 'number', strategy: 'string' },\n required: ['topology']\n },\n {\n name: 'agent_spawn',\n description: 'Spawn specialized agents',\n parameters: { type: 'string', capabilities: 'array', name: 'string' },\n required: ['type']\n },\n {\n name: 'task_orchestrate',\n description: 'Orchestrate complex tasks',\n parameters: { task: 'string', strategy: 'string', priority: 'string' },\n required: ['task']\n },\n {\n name: 'memory_usage',\n description: 'Manage coordination memory',\n parameters: { action: 'string', key: 'string', value: 'string', namespace: 'string' },\n required: ['action']\n },\n {\n name: 'swarm_status',\n description: 'Get swarm status and metrics',\n parameters: { detailed: 'boolean' },\n required: []\n }\n ],\n status: 'disconnected'\n });\n\n // ruv-swarm MCP tools (optional)\n this.tools.set('ruv-swarm', {\n name: 'ruv-swarm',\n server: 'npx ruv-swarm mcp start',\n functions: [\n {\n name: 'swarm_init',\n description: 'Initialize RUV swarm',\n parameters: { topology: 'string', maxAgents: 'number', strategy: 'string' },\n required: ['topology']\n },\n {\n name: 'neural_status',\n description: 'Get neural network status',\n parameters: { agentId: 'string' },\n required: []\n },\n {\n name: 'benchmark_run',\n description: 'Run performance benchmarks',\n parameters: { type: 'string', iterations: 'number' },\n required: []\n }\n ],\n status: 'disconnected'\n });\n\n // Flow Nexus MCP tools (optional)\n this.tools.set('flow-nexus', {\n name: 'flow-nexus',\n server: 'npx flow-nexus@latest mcp start',\n functions: [\n {\n name: 'swarm_init',\n description: 'Initialize Flow Nexus swarm',\n parameters: { topology: 'string', maxAgents: 'number', strategy: 'string' },\n required: ['topology']\n },\n {\n name: 'sandbox_create',\n description: 'Create execution sandbox',\n parameters: { template: 'string', env_vars: 'object' },\n required: ['template']\n },\n {\n name: 'neural_train',\n description: 'Train neural networks',\n parameters: { config: 'object', tier: 'string' },\n required: ['config']\n }\n ],\n status: 'disconnected'\n });\n\n // Agentic Payments MCP tools (optional)\n this.tools.set('agentic-payments', {\n name: 'agentic-payments',\n server: 'npx agentic-payments@latest mcp',\n functions: [\n {\n name: 'create_active_mandate',\n description: 'Create Active Mandate for autonomous payment authorization',\n parameters: { agent: 'string', holder: 'string', amount: 'number', currency: 'string', period: 'string', kind: 'string' },\n required: ['agent', 'holder', 'amount', 'currency', 'period', 'kind']\n },\n {\n name: 'sign_mandate',\n description: 'Sign mandate with Ed25519 cryptographic proof',\n parameters: { mandate: 'object', private_key: 'string' },\n required: ['mandate', 'private_key']\n },\n {\n name: 'verify_mandate',\n description: 'Verify mandate signature and execution guards',\n parameters: { signed_mandate: 'object', check_guards: 'boolean' },\n required: ['signed_mandate']\n },\n {\n name: 'revoke_mandate',\n description: 'Revoke mandate by ID',\n parameters: { mandate_id: 'string', reason: 'string' },\n required: ['mandate_id']\n },\n {\n name: 'generate_agent_identity',\n description: 'Generate Ed25519 keypair for agent',\n parameters: { include_private_key: 'boolean' },\n required: []\n },\n {\n name: 'create_intent_mandate',\n description: 'Create intent-based payment mandate',\n parameters: { merchant_id: 'string', customer_id: 'string', intent: 'string', max_amount: 'number' },\n required: ['merchant_id', 'customer_id', 'intent', 'max_amount']\n },\n {\n name: 'create_cart_mandate',\n description: 'Create cart-based payment mandate',\n parameters: { merchant_id: 'string', customer_id: 'string', items: 'array' },\n required: ['merchant_id', 'customer_id', 'items']\n }\n ],\n status: 'disconnected'\n });\n }\n\n /**\n * Discover available MCP tools\n */\n private async discoverTools(): Promise<void> {\n // In a real implementation, this would probe for available MCP servers\n // For now, we'll simulate the discovery process\n\n for (const [name, tool] of this.tools) {\n try {\n // Simulate tool discovery\n const isAvailable = await this.checkToolAvailability(name);\n tool.status = isAvailable ? 'connected' : 'disconnected';\n tool.lastPing = new Date();\n } catch (error) {\n tool.status = 'error';\n console.warn(`Failed to discover MCP tool ${name}:`, error);\n }\n }\n }\n\n /**\n * Check if a specific tool is available\n */\n private async checkToolAvailability(toolName: string): Promise<boolean> {\n // Simulate availability check\n // In real implementation, this would try to connect to the MCP server\n return Math.random() > 0.3; // 70% availability simulation\n }\n\n /**\n * Test connections to all tools\n */\n private async testConnections(): Promise<void> {\n for (const [name, tool] of this.tools) {\n if (tool.status === 'connected') {\n try {\n // Simulate connection test\n await new Promise(resolve => setTimeout(resolve, 100));\n console.log(`āœ“ MCP tool ${name} connected successfully`);\n } catch (error) {\n tool.status = 'error';\n console.warn(`āœ— MCP tool ${name} connection failed:`, error);\n }\n }\n }\n }\n\n /**\n * Execute MCP command\n */\n async executeCommand(command: MCPCommand): Promise<MCPResult> {\n const startTime = Date.now();\n\n try {\n const tool = this.tools.get(command.tool);\n if (!tool) {\n return {\n success: false,\n error: `Unknown MCP tool: ${command.tool}`,\n metadata: {\n executionTime: Date.now() - startTime,\n tool: command.tool,\n function: command.function\n }\n };\n }\n\n if (tool.status !== 'connected') {\n return {\n success: false,\n error: `MCP tool ${command.tool} is not connected (status: ${tool.status})`,\n metadata: {\n executionTime: Date.now() - startTime,\n tool: command.tool,\n function: command.function\n }\n };\n }\n\n // Validate function exists\n const func = tool.functions.find(f => f.name === command.function);\n if (!func) {\n return {\n success: false,\n error: `Function ${command.function} not found in tool ${command.tool}`,\n metadata: {\n executionTime: Date.now() - startTime,\n tool: command.tool,\n function: command.function\n }\n };\n }\n\n // Validate required parameters\n const missingParams = func.required.filter(param => !(param in command.parameters));\n if (missingParams.length > 0) {\n return {\n success: false,\n error: `Missing required parameters: ${missingParams.join(', ')}`,\n metadata: {\n executionTime: Date.now() - startTime,\n tool: command.tool,\n function: command.function\n }\n };\n }\n\n // Execute the command (simulation)\n const result = await this.simulateCommandExecution(command);\n\n return {\n success: true,\n data: result,\n metadata: {\n executionTime: Date.now() - startTime,\n tool: command.tool,\n function: command.function\n }\n };\n\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n metadata: {\n executionTime: Date.now() - startTime,\n tool: command.tool,\n function: command.function\n }\n };\n }\n }\n\n /**\n * Simulate command execution (replace with real MCP calls in production)\n */\n private async simulateCommandExecution(command: MCPCommand): Promise<any> {\n // Simulate processing time\n await new Promise(resolve => setTimeout(resolve, 200 + Math.random() * 800));\n\n // Return different results based on function\n switch (command.function) {\n case 'swarm_init':\n return {\n swarmId: `swarm-${Date.now()}`,\n topology: command.parameters.topology,\n maxAgents: command.parameters.maxAgents || 8,\n status: 'initialized'\n };\n\n case 'agent_spawn':\n return {\n agentId: `agent-${Date.now()}`,\n type: command.parameters.type,\n capabilities: command.parameters.capabilities || [],\n status: 'spawned'\n };\n\n case 'task_orchestrate':\n return {\n taskId: `task-${Date.now()}`,\n task: command.parameters.task,\n strategy: command.parameters.strategy || 'adaptive',\n status: 'orchestrating'\n };\n\n case 'memory_usage':\n if (command.parameters.action === 'store') {\n return { stored: true, key: command.parameters.key };\n } else if (command.parameters.action === 'retrieve') {\n return { found: Math.random() > 0.3, value: 'simulated-value' };\n }\n return { action: command.parameters.action, success: true };\n\n case 'swarm_status':\n return {\n activeAgents: Math.floor(Math.random() * 8) + 1,\n topology: 'mesh',\n health: 'good',\n metrics: {\n throughput: Math.random() * 100,\n latency: Math.random() * 50 + 10\n }\n };\n\n case 'neural_status':\n return {\n modelLoaded: true,\n accuracy: 0.85 + Math.random() * 0.1,\n trainingProgress: Math.random() * 100\n };\n\n case 'benchmark_run':\n return {\n benchmarks: [\n { name: 'cpu', value: Math.random() * 100, unit: 'ms' },\n { name: 'memory', value: Math.random() * 512, unit: 'MB' },\n { name: 'network', value: Math.random() * 50, unit: 'ms' }\n ]\n };\n\n default:\n return { function: command.function, executed: true };\n }\n }\n\n /**\n * Get available tools\n */\n getAvailableTools(): MCPTool[] {\n return Array.from(this.tools.values());\n }\n\n /**\n * Get connected tools\n */\n getConnectedTools(): MCPTool[] {\n return Array.from(this.tools.values()).filter(tool => tool.status === 'connected');\n }\n\n /**\n * Get tool by name\n */\n getTool(name: string): MCPTool | undefined {\n return this.tools.get(name);\n }\n\n /**\n * Check if a tool is available\n */\n isToolAvailable(name: string): boolean {\n const tool = this.tools.get(name);\n return tool?.status === 'connected' || false;\n }\n\n /**\n * Get tool functions\n */\n getToolFunctions(toolName: string): MCPFunction[] {\n const tool = this.tools.get(toolName);\n return tool?.functions || [];\n }\n\n /**\n * Initialize swarm coordination using MCP tools\n */\n async initializeSwarmCoordination(config: {\n topology: string;\n maxAgents: number;\n strategy: string;\n }): Promise<MCPResult> {\n // Try claude-flow first, then fallback to other tools\n const toolPriority = ['claude-flow', 'ruv-swarm', 'flow-nexus'];\n\n for (const toolName of toolPriority) {\n if (this.isToolAvailable(toolName)) {\n return await this.executeCommand({\n tool: toolName,\n function: 'swarm_init',\n parameters: config\n });\n }\n }\n\n return {\n success: false,\n error: 'No MCP tools available for swarm initialization',\n metadata: {\n executionTime: 0,\n tool: 'none',\n function: 'swarm_init'\n }\n };\n }\n\n /**\n * Coordinate memory across swarm using MCP tools\n */\n async coordinateMemory(action: string, key: string, value?: string, namespace?: string): Promise<MCPResult> {\n const command: MCPCommand = {\n tool: 'claude-flow',\n function: 'memory_usage',\n parameters: { action, key, value, namespace: namespace || 'coordination' }\n };\n\n return await this.executeCommand(command);\n }\n\n /**\n * Spawn agents using MCP tools\n */\n async spawnAgent(type: string, capabilities?: string[], name?: string): Promise<MCPResult> {\n const command: MCPCommand = {\n tool: 'claude-flow',\n function: 'agent_spawn',\n parameters: { type, capabilities, name }\n };\n\n return await this.executeCommand(command);\n }\n\n /**\n * Orchestrate tasks using MCP tools\n */\n async orchestrateTask(task: string, strategy?: string, priority?: string): Promise<MCPResult> {\n const command: MCPCommand = {\n tool: 'claude-flow',\n function: 'task_orchestrate',\n parameters: { task, strategy, priority }\n };\n\n return await this.executeCommand(command);\n }\n\n /**\n * Get swarm status using MCP tools\n */\n async getSwarmStatus(detailed: boolean = false): Promise<MCPResult> {\n const command: MCPCommand = {\n tool: 'claude-flow',\n function: 'swarm_status',\n parameters: { detailed }\n };\n\n return await this.executeCommand(command);\n }\n\n /**\n * Refresh tool connections\n */\n async refreshConnections(): Promise<void> {\n await this.discoverTools();\n await this.testConnections();\n }\n\n /**\n * Register a custom tool\n */\n registerTool(tool: MCPTool): void {\n this.tools.set(tool.name, tool);\n }\n\n /**\n * Unregister a tool\n */\n unregisterTool(name: string): boolean {\n return this.tools.delete(name);\n }\n\n /**\n * Get integration status\n */\n getIntegrationStatus(): {\n initialized: boolean;\n totalTools: number;\n connectedTools: number;\n availableFunctions: number;\n } {\n const tools = Array.from(this.tools.values());\n const connectedTools = tools.filter(tool => tool.status === 'connected');\n const availableFunctions = connectedTools.reduce((sum, tool) => sum + tool.functions.length, 0);\n\n return {\n initialized: this.initialized,\n totalTools: tools.length,\n connectedTools: connectedTools.length,\n availableFunctions\n };\n }\n}"],"names":["MCPIntegrator","tools","Map","initialized","registerDefaultTools","initialize","discoverTools","testConnections","set","name","server","functions","description","parameters","topology","maxAgents","strategy","required","type","capabilities","task","priority","action","key","value","namespace","detailed","status","agentId","iterations","template","env_vars","config","tier","agent","holder","amount","currency","period","kind","mandate","private_key","signed_mandate","check_guards","mandate_id","reason","include_private_key","merchant_id","customer_id","intent","max_amount","items","tool","isAvailable","checkToolAvailability","lastPing","Date","error","console","warn","toolName","Math","random","Promise","resolve","setTimeout","log","executeCommand","command","startTime","now","get","success","metadata","executionTime","function","func","find","f","missingParams","filter","param","length","join","result","simulateCommandExecution","data","Error","message","String","swarmId","taskId","stored","found","activeAgents","floor","health","metrics","throughput","latency","modelLoaded","accuracy","trainingProgress","benchmarks","unit","executed","getAvailableTools","Array","from","values","getConnectedTools","getTool","isToolAvailable","getToolFunctions","initializeSwarmCoordination","toolPriority","coordinateMemory","spawnAgent","orchestrateTask","getSwarmStatus","refreshConnections","registerTool","unregisterTool","delete","getIntegrationStatus","connectedTools","availableFunctions","reduce","sum","totalTools"],"mappings":"AAsCA,OAAO,MAAMA;IACHC,QAA8B,IAAIC,MAAM;IACxCC,cAAuB,MAAM;IAErC,aAAc;QACZ,IAAI,CAACC,oBAAoB;IAC3B;IAKA,MAAMC,aAA4B;QAChC,MAAM,IAAI,CAACC,aAAa;QACxB,MAAM,IAAI,CAACC,eAAe;QAC1B,IAAI,CAACJ,WAAW,GAAG;IACrB;IAKQC,uBAA6B;QAEnC,IAAI,CAACH,KAAK,CAACO,GAAG,CAAC,eAAe;YAC5BC,MAAM;YACNC,QAAQ;YACRC,WAAW;gBACT;oBACEF,MAAM;oBACNG,aAAa;oBACbC,YAAY;wBAAEC,UAAU;wBAAUC,WAAW;wBAAUC,UAAU;oBAAS;oBAC1EC,UAAU;wBAAC;qBAAW;gBACxB;gBACA;oBACER,MAAM;oBACNG,aAAa;oBACbC,YAAY;wBAAEK,MAAM;wBAAUC,cAAc;wBAASV,MAAM;oBAAS;oBACpEQ,UAAU;wBAAC;qBAAO;gBACpB;gBACA;oBACER,MAAM;oBACNG,aAAa;oBACbC,YAAY;wBAAEO,MAAM;wBAAUJ,UAAU;wBAAUK,UAAU;oBAAS;oBACrEJ,UAAU;wBAAC;qBAAO;gBACpB;gBACA;oBACER,MAAM;oBACNG,aAAa;oBACbC,YAAY;wBAAES,QAAQ;wBAAUC,KAAK;wBAAUC,OAAO;wBAAUC,WAAW;oBAAS;oBACpFR,UAAU;wBAAC;qBAAS;gBACtB;gBACA;oBAC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S;QACzB;QAEA,OAAO,MAAM,IAAI,CAACyC,cAAc,CAACC;IACnC;IAKA,MAAMoD,qBAAoC;QACxC,MAAM,IAAI,CAAClH,aAAa;QACxB,MAAM,IAAI,CAACC,eAAe;IAC5B;IAKAkH,aAAarE,IAAa,EAAQ;QAChC,IAAI,CAACnD,KAAK,CAACO,GAAG,CAAC4C,KAAK3C,IAAI,EAAE2C;IAC5B;IAKAsE,eAAejH,IAAY,EAAW;QACpC,OAAO,IAAI,CAACR,KAAK,CAAC0H,MAAM,CAAClH;IAC3B;IAKAmH,uBAKE;QACA,MAAM3H,QAAQ0G,MAAMC,IAAI,CAAC,IAAI,CAAC3G,KAAK,CAAC4G,MAAM;QAC1C,MAAMgB,iBAAiB5H,MAAM+E,MAAM,CAAC5B,CAAAA,OAAQA,KAAKzB,MAAM,KAAK;QAC5D,MAAMmG,qBAAqBD,eAAeE,MAAM,CAAC,CAACC,KAAK5E,OAAS4E,MAAM5E,KAAKzC,SAAS,CAACuE,MAAM,EAAE;QAE7F,OAAO;YACL/E,aAAa,IAAI,CAACA,WAAW;YAC7B8H,YAAYhI,MAAMiF,MAAM;YACxB2C,gBAAgBA,eAAe3C,MAAM;YACrC4C;QACF;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/core/MCPIntegrator.ts"],"sourcesContent":["/**\n * MCPIntegrator - Manages MCP tool coordination\n * Provides integration with external MCP tools and orchestration services\n */\n\nexport interface MCPTool {\n name: string;\n server: string;\n functions: MCPFunction[];\n status: 'connected' | 'disconnected' | 'error';\n lastPing?: Date;\n}\n\nexport interface MCPFunction {\n name: string;\n description: string;\n parameters: any;\n required: string[];\n}\n\nexport interface MCPCommand {\n tool: string;\n function: string;\n parameters: any;\n timeout?: number;\n}\n\nexport interface MCPResult {\n success: boolean;\n data?: any;\n error?: string;\n metadata?: {\n executionTime: number;\n tool: string;\n function: string;\n };\n}\n\nexport class MCPIntegrator {\n private tools: Map<string, MCPTool> = new Map();\n private initialized: boolean = false;\n\n constructor() {\n this.registerDefaultTools();\n }\n\n /**\n * Initialize MCP integrator and discover available tools\n */\n async initialize(): Promise<void> {\n await this.discoverTools();\n await this.testConnections();\n this.initialized = true;\n }\n\n /**\n * Register default MCP tools\n */\n private registerDefaultTools(): void {\n // Claude Flow MCP tools\n this.tools.set('claude-flow', {\n name: 'claude-flow',\n server: 'npx claude-flow@alpha mcp start',\n functions: [\n {\n name: 'swarm_init',\n description: 'Initialize swarm with topology',\n parameters: { topology: 'string', maxAgents: 'number', strategy: 'string' },\n required: ['topology']\n },\n {\n name: 'agent_spawn',\n description: 'Spawn specialized agents',\n parameters: { type: 'string', capabilities: 'array', name: 'string' },\n required: ['type']\n },\n {\n name: 'task_orchestrate',\n description: 'Orchestrate complex tasks',\n parameters: { task: 'string', strategy: 'string', priority: 'string' },\n required: ['task']\n },\n {\n name: 'memory_usage',\n description: 'Manage coordination memory',\n parameters: { action: 'string', key: 'string', value: 'string', namespace: 'string' },\n required: ['action']\n },\n {\n name: 'swarm_status',\n description: 'Get swarm status and metrics',\n parameters: { detailed: 'boolean' },\n required: []\n }\n ],\n status: 'disconnected'\n });\n\n // ruv-swarm MCP tools (optional)\n this.tools.set('ruv-swarm', {\n name: 'ruv-swarm',\n server: 'npx ruv-swarm mcp start',\n functions: [\n {\n name: 'swarm_init',\n description: 'Initialize RUV swarm',\n parameters: { topology: 'string', maxAgents: 'number', strategy: 'string' },\n required: ['topology']\n },\n {\n name: 'neural_status',\n description: 'Get neural network status',\n parameters: { agentId: 'string' },\n required: []\n },\n {\n name: 'benchmark_run',\n description: 'Run performance benchmarks',\n parameters: { type: 'string', iterations: 'number' },\n required: []\n }\n ],\n status: 'disconnected'\n });\n\n // Flow Nexus MCP tools (optional)\n this.tools.set('flow-nexus', {\n name: 'flow-nexus',\n server: 'npx flow-nexus@latest mcp start',\n functions: [\n {\n name: 'swarm_init',\n description: 'Initialize Flow Nexus swarm',\n parameters: { topology: 'string', maxAgents: 'number', strategy: 'string' },\n required: ['topology']\n },\n {\n name: 'sandbox_create',\n description: 'Create execution sandbox',\n parameters: { template: 'string', env_vars: 'object' },\n required: ['template']\n },\n {\n name: 'neural_train',\n description: 'Train neural networks',\n parameters: { config: 'object', tier: 'string' },\n required: ['config']\n }\n ],\n status: 'disconnected'\n });\n }\n\n /**\n * Discover available MCP tools\n */\n private async discoverTools(): Promise<void> {\n // In a real implementation, this would probe for available MCP servers\n // For now, we'll simulate the discovery process\n\n for (const [name, tool] of this.tools) {\n try {\n // Simulate tool discovery\n const isAvailable = await this.checkToolAvailability(name);\n tool.status = isAvailable ? 'connected' : 'disconnected';\n tool.lastPing = new Date();\n } catch (error) {\n tool.status = 'error';\n console.warn(`Failed to discover MCP tool ${name}:`, error);\n }\n }\n }\n\n /**\n * Check if a specific tool is available\n */\n private async checkToolAvailability(toolName: string): Promise<boolean> {\n // Simulate availability check\n // In real implementation, this would try to connect to the MCP server\n return Math.random() > 0.3; // 70% availability simulation\n }\n\n /**\n * Test connections to all tools\n */\n private async testConnections(): Promise<void> {\n for (const [name, tool] of this.tools) {\n if (tool.status === 'connected') {\n try {\n // Simulate connection test\n await new Promise(resolve => setTimeout(resolve, 100));\n console.log(`āœ“ MCP tool ${name} connected successfully`);\n } catch (error) {\n tool.status = 'error';\n console.warn(`āœ— MCP tool ${name} connection failed:`, error);\n }\n }\n }\n }\n\n /**\n * Execute MCP command\n */\n async executeCommand(command: MCPCommand): Promise<MCPResult> {\n const startTime = Date.now();\n\n try {\n const tool = this.tools.get(command.tool);\n if (!tool) {\n return {\n success: false,\n error: `Unknown MCP tool: ${command.tool}`,\n metadata: {\n executionTime: Date.now() - startTime,\n tool: command.tool,\n function: command.function\n }\n };\n }\n\n if (tool.status !== 'connected') {\n return {\n success: false,\n error: `MCP tool ${command.tool} is not connected (status: ${tool.status})`,\n metadata: {\n executionTime: Date.now() - startTime,\n tool: command.tool,\n function: command.function\n }\n };\n }\n\n // Validate function exists\n const func = tool.functions.find(f => f.name === command.function);\n if (!func) {\n return {\n success: false,\n error: `Function ${command.function} not found in tool ${command.tool}`,\n metadata: {\n executionTime: Date.now() - startTime,\n tool: command.tool,\n function: command.function\n }\n };\n }\n\n // Validate required parameters\n const missingParams = func.required.filter(param => !(param in command.parameters));\n if (missingParams.length > 0) {\n return {\n success: false,\n error: `Missing required parameters: ${missingParams.join(', ')}`,\n metadata: {\n executionTime: Date.now() - startTime,\n tool: command.tool,\n function: command.function\n }\n };\n }\n\n // Execute the command (simulation)\n const result = await this.simulateCommandExecution(command);\n\n return {\n success: true,\n data: result,\n metadata: {\n executionTime: Date.now() - startTime,\n tool: command.tool,\n function: command.function\n }\n };\n\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n metadata: {\n executionTime: Date.now() - startTime,\n tool: command.tool,\n function: command.function\n }\n };\n }\n }\n\n /**\n * Simulate command execution (replace with real MCP calls in production)\n */\n private async simulateCommandExecution(command: MCPCommand): Promise<any> {\n // Simulate processing time\n await new Promise(resolve => setTimeout(resolve, 200 + Math.random() * 800));\n\n // Return different results based on function\n switch (command.function) {\n case 'swarm_init':\n return {\n swarmId: `swarm-${Date.now()}`,\n topology: command.parameters.topology,\n maxAgents: command.parameters.maxAgents || 8,\n status: 'initialized'\n };\n\n case 'agent_spawn':\n return {\n agentId: `agent-${Date.now()}`,\n type: command.parameters.type,\n capabilities: command.parameters.capabilities || [],\n status: 'spawned'\n };\n\n case 'task_orchestrate':\n return {\n taskId: `task-${Date.now()}`,\n task: command.parameters.task,\n strategy: command.parameters.strategy || 'adaptive',\n status: 'orchestrating'\n };\n\n case 'memory_usage':\n if (command.parameters.action === 'store') {\n return { stored: true, key: command.parameters.key };\n } else if (command.parameters.action === 'retrieve') {\n return { found: Math.random() > 0.3, value: 'simulated-value' };\n }\n return { action: command.parameters.action, success: true };\n\n case 'swarm_status':\n return {\n activeAgents: Math.floor(Math.random() * 8) + 1,\n topology: 'mesh',\n health: 'good',\n metrics: {\n throughput: Math.random() * 100,\n latency: Math.random() * 50 + 10\n }\n };\n\n case 'neural_status':\n return {\n modelLoaded: true,\n accuracy: 0.85 + Math.random() * 0.1,\n trainingProgress: Math.random() * 100\n };\n\n case 'benchmark_run':\n return {\n benchmarks: [\n { name: 'cpu', value: Math.random() * 100, unit: 'ms' },\n { name: 'memory', value: Math.random() * 512, unit: 'MB' },\n { name: 'network', value: Math.random() * 50, unit: 'ms' }\n ]\n };\n\n default:\n return { function: command.function, executed: true };\n }\n }\n\n /**\n * Get available tools\n */\n getAvailableTools(): MCPTool[] {\n return Array.from(this.tools.values());\n }\n\n /**\n * Get connected tools\n */\n getConnectedTools(): MCPTool[] {\n return Array.from(this.tools.values()).filter(tool => tool.status === 'connected');\n }\n\n /**\n * Get tool by name\n */\n getTool(name: string): MCPTool | undefined {\n return this.tools.get(name);\n }\n\n /**\n * Check if a tool is available\n */\n isToolAvailable(name: string): boolean {\n const tool = this.tools.get(name);\n return tool?.status === 'connected' || false;\n }\n\n /**\n * Get tool functions\n */\n getToolFunctions(toolName: string): MCPFunction[] {\n const tool = this.tools.get(toolName);\n return tool?.functions || [];\n }\n\n /**\n * Initialize swarm coordination using MCP tools\n */\n async initializeSwarmCoordination(config: {\n topology: string;\n maxAgents: number;\n strategy: string;\n }): Promise<MCPResult> {\n // Try claude-flow first, then fallback to other tools\n const toolPriority = ['claude-flow', 'ruv-swarm', 'flow-nexus'];\n\n for (const toolName of toolPriority) {\n if (this.isToolAvailable(toolName)) {\n return await this.executeCommand({\n tool: toolName,\n function: 'swarm_init',\n parameters: config\n });\n }\n }\n\n return {\n success: false,\n error: 'No MCP tools available for swarm initialization',\n metadata: {\n executionTime: 0,\n tool: 'none',\n function: 'swarm_init'\n }\n };\n }\n\n /**\n * Coordinate memory across swarm using MCP tools\n */\n async coordinateMemory(action: string, key: string, value?: string, namespace?: string): Promise<MCPResult> {\n const command: MCPCommand = {\n tool: 'claude-flow',\n function: 'memory_usage',\n parameters: { action, key, value, namespace: namespace || 'coordination' }\n };\n\n return await this.executeCommand(command);\n }\n\n /**\n * Spawn agents using MCP tools\n */\n async spawnAgent(type: string, capabilities?: string[], name?: string): Promise<MCPResult> {\n const command: MCPCommand = {\n tool: 'claude-flow',\n function: 'agent_spawn',\n parameters: { type, capabilities, name }\n };\n\n return await this.executeCommand(command);\n }\n\n /**\n * Orchestrate tasks using MCP tools\n */\n async orchestrateTask(task: string, strategy?: string, priority?: string): Promise<MCPResult> {\n const command: MCPCommand = {\n tool: 'claude-flow',\n function: 'task_orchestrate',\n parameters: { task, strategy, priority }\n };\n\n return await this.executeCommand(command);\n }\n\n /**\n * Get swarm status using MCP tools\n */\n async getSwarmStatus(detailed: boolean = false): Promise<MCPResult> {\n const command: MCPCommand = {\n tool: 'claude-flow',\n function: 'swarm_status',\n parameters: { detailed }\n };\n\n return await this.executeCommand(command);\n }\n\n /**\n * Refresh tool connections\n */\n async refreshConnections(): Promise<void> {\n await this.discoverTools();\n await this.testConnections();\n }\n\n /**\n * Register a custom tool\n */\n registerTool(tool: MCPTool): void {\n this.tools.set(tool.name, tool);\n }\n\n /**\n * Unregister a tool\n */\n unregisterTool(name: string): boolean {\n return this.tools.delete(name);\n }\n\n /**\n * Get integration status\n */\n getIntegrationStatus(): {\n initialized: boolean;\n totalTools: number;\n connectedTools: number;\n availableFunctions: number;\n } {\n const tools = Array.from(this.tools.values());\n const connectedTools = tools.filter(tool => tool.status === 'connected');\n const availableFunctions = connectedTools.reduce((sum, tool) => sum + tool.functions.length, 0);\n\n return {\n initialized: this.initialized,\n totalTools: tools.length,\n connectedTools: connectedTools.length,\n availableFunctions\n };\n }\n}"],"names":["MCPIntegrator","tools","Map","initialized","registerDefaultTools","initialize","discoverTools","testConnections","set","name","server","functions","description","parameters","topology","maxAgents","strategy","required","type","capabilities","task","priority","action","key","value","namespace","detailed","status","agentId","iterations","template","env_vars","config","tier","tool","isAvailable","checkToolAvailability","lastPing","Date","error","console","warn","toolName","Math","random","Promise","resolve","setTimeout","log","executeCommand","command","startTime","now","get","success","metadata","executionTime","function","func","find","f","missingParams","filter","param","length","join","result","simulateCommandExecution","data","Error","message","String","swarmId","taskId","stored","found","activeAgents","floor","health","metrics","throughput","latency","modelLoaded","accuracy","trainingProgress","benchmarks","unit","executed","getAvailableTools","Array","from","values","getConnectedTools","getTool","isToolAvailable","getToolFunctions","initializeSwarmCoordination","toolPriority","coordinateMemory","spawnAgent","orchestrateTask","getSwarmStatus","refreshConnections","registerTool","unregisterTool","delete","getIntegrationStatus","connectedTools","availableFunctions","reduce","sum","totalTools"],"mappings":"AAsCA,OAAO,MAAMA;IACHC,QAA8B,IAAIC,MAAM;IACxCC,cAAuB,MAAM;IAErC,aAAc;QACZ,IAAI,CAACC,oBAAoB;IAC3B;IAKA,MAAMC,aAA4B;QAChC,MAAM,IAAI,CAACC,aAAa;QACxB,MAAM,IAAI,CAACC,eAAe;QAC1B,IAAI,CAACJ,WAAW,GAAG;IACrB;IAKQC,uBAA6B;QAEnC,IAAI,CAACH,KAAK,CAACO,GAAG,CAAC,eAAe;YAC5BC,MAAM;YACNC,QAAQ;YACRC,WAAW;gBACT;oBACEF,MAAM;oBACNG,aAAa;oBACbC,YAAY;wBAAEC,UAAU;wBAAUC,WAAW;wBAAUC,UAAU;oBAAS;oBAC1EC,UAAU;wBAAC;qBAAW;gBACxB;gBACA;oBACER,MAAM;oBACNG,aAAa;oBACbC,YAAY;wBAAEK,MAAM;wBAAUC,cAAc;wBAASV,MAAM;oBAAS;oBACpEQ,UAAU;wBAAC;qBAAO;gBACpB;gBACA;oBACER,MAAM;oBACNG,aAAa;oBACbC,YAAY;wBAAEO,MAAM;wBAAUJ,UAAU;wBAAUK,UAAU;oBAAS;oBACrEJ,UAAU;wBAAC;qBAAO;gBACpB;gBACA;oBACER,MAAM;oBACNG,aAAa;oBACbC,YAAY;wBAAES,QAAQ;wBAAUC,KAAK;wBAAUC,OAAO;wBAAUC,WAAW;oBAAS;oBACpFR,UAAU;wBAAC;qBAAS;gBACtB;gBACA;oBACER,MAAM;oBACNG,aAAa;oBACbC,YA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